|
| 1 | +#!/usr/bin/env bash |
| 2 | + |
| 3 | +# Extract the title-slug from the LeetCode URL |
| 4 | +function extract_problem_name() { |
| 5 | + local url="$1" |
| 6 | + echo "$url" | sed -n 's/.*\/problems\/\([^/]*\)\/.*/\1/p' |
| 7 | +} |
| 8 | + |
| 9 | +# Generates the GraphQL query to fetch problem details based on the provided title-slug |
| 10 | +function make_query() { |
| 11 | + local question_slug=$1 |
| 12 | + # shellcheck disable=SC2016 |
| 13 | + local query='{ |
| 14 | + "query": "query selectProblem($titleSlug: String!) { question(titleSlug: $titleSlug) { questionFrontendId title titleSlug codeSnippets { langSlug code } } }", |
| 15 | + "variables": { |
| 16 | + "titleSlug": "'"$question_slug"'" |
| 17 | + } |
| 18 | +}' |
| 19 | + echo "$query" |
| 20 | +} |
| 21 | + |
| 22 | +# Sends a POST request to the LeetCode GraphQL API with the generated query |
| 23 | +function request() { |
| 24 | + local query="$1" |
| 25 | + local response |
| 26 | + response=$(curl -s -X POST -H "Content-Type: application/json" --data "$query" https://leetcode.com/graphql) |
| 27 | + echo -E "$response" |
| 28 | +} |
| 29 | + |
| 30 | +# Creates a file for the LeetCode problem |
| 31 | +# |
| 32 | +# Parses the JSON response from the LeetCode API, extracts relevant problem details, |
| 33 | +# generates the solution code template using the `make_solution_code()` function, |
| 34 | +# and saves the file using the `save_file()` function. |
| 35 | +function create_file() { |
| 36 | + local json_data="$1" |
| 37 | + local question_id |
| 38 | + local title |
| 39 | + local title_slug |
| 40 | + local code_snippet |
| 41 | + local content |
| 42 | + |
| 43 | + question_id=$(echo -E "$json_data" | jq -r '.data.question.questionFrontendId') |
| 44 | + title=$(echo -E "$json_data" | jq -r '.data.question.title') |
| 45 | + title_slug=$(echo -E "$json_data" | jq -r '.data.question.titleSlug') |
| 46 | + |
| 47 | + # Generate the code snippet |
| 48 | + code_snippet=$(echo -E "$json_data" | jq -r ".data.question.codeSnippets[] | select(.langSlug == \"$LANGUAGE\") | .code") |
| 49 | + |
| 50 | + # Generate the entire code |
| 51 | + content=$(make_solution_code "$question_id" "$title" "https://leetcode.com/problems/$title_slug/description/" "$code_snippet") |
| 52 | + |
| 53 | + save_file "$title_slug" "$content" |
| 54 | +} |
0 commit comments