feat: create template with problem url and code snippet

This commit is contained in:
Yiyang Kang 2026-02-26 17:43:43 +09:00
parent 8a95ea80a7
commit ec5559f877
3 changed files with 70 additions and 9 deletions

View file

@ -1,21 +1,42 @@
#!/bin/bash
num=$1
id=$1
echo "$num" | grep -q "^[1-9][0-9]\{,4\}$" || {
echo "Err: no valid number given" >&2
echo "$id" | grep -q "^[1-9][0-9]\{,4\}$" || {
echo "Err: no valid problem ID provided." >&2
exit 1
}
parent=$((num / 100))
pdir="solutions/${parent}/q${num}"
parent=$((id / 100))
pdir="solutions/${parent}/q${id}"
sol_file="${pdir}/solution.go"
if [ -f "$sol_file" ]; then
exit 0
fi
echo "Creating template for question No. $num" >&2
title_slug=$(jq -r "select(.id == $id) | .titleSlug" ./problemset.jsonl)
[ -n "$title_slug" ] || {
echo "Err: problem $id not found in the problem set." >&2
exit 1
}
problem_url="https://leetcode.com/problems/$title_slug/"
echo -e "Creating template for problem \033[32m${id}: $title_slug\033[0m" >&2
mkdir -pv "$pdir"
echo "package q$num" > "$sol_file"
echo "Created $sol_file"
echo "// Package q$id implements a solution for $problem_url" > "$sol_file"
echo -e "package q$id\n" >> "$sol_file"
echo "Created: $sol_file"
echo "Fetching code snippet for Go ..."
curl -sSLf "${problem_url}description/" \
-H 'accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8' \
-H 'accept-language: en-US,en;q=0.5' \
-H 'user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36' \
| grep -o 'NEXT_DATA[^>]*>.*' \
| sed 's/^[^>]*>//;s/<\/script.*//' \
| jq -r '[ .props.pageProps.dehydratedState.queries[].state.data.question.codeSnippets | select( . != null) | .[] | select(.langSlug == "golang") ][0].code' \
>> "$sol_file"
echo "Done."