Start the LeetCode daily question from the site
A "Today's LeetCode" button on the problem list (admin only) does what `usaco daily` does: it asks LeetCode for the daily question, runs the clone's lib/leetcode.py to import it into solving/ (statement, starter, driver.h and the examples as tests), commits it as "Start <slug>" and opens its solve page. A daily question already in the repo is only opened. The importer stays the CLI's one script rather than a Go copy of its driver generator, so the site image now has python3. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -0,0 +1,96 @@
|
||||
// Package leetcode starts LeetCode problems from the site the way `usaco
|
||||
// daily` does from the CLI. The import itself is the CLI's: lib/leetcode.py
|
||||
// in the clone writes problem.md, main.cpp, the generated driver.h and the
|
||||
// examples as tests. Rewriting its driver generator in Go would leave two
|
||||
// copies to drift apart, so the site image carries python3 to run it.
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Importer asks LeetCode for the daily question and runs the CLI's importer.
|
||||
// The zero value talks to the real API with python3 from PATH; tests point
|
||||
// API at an httptest server.
|
||||
type Importer struct {
|
||||
Client *http.Client
|
||||
API string // default https://leetcode.com/graphql
|
||||
Python string // default python3
|
||||
}
|
||||
|
||||
// Daily is the slug of today's daily question.
|
||||
func (i *Importer) Daily(ctx context.Context) (string, error) {
|
||||
body, _ := json.Marshal(map[string]string{
|
||||
"query": "query { activeDailyCodingChallengeQuestion { question { titleSlug } } }",
|
||||
})
|
||||
api := i.API
|
||||
if api == "" {
|
||||
api = "https://leetcode.com/graphql"
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, api, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Referer", "https://leetcode.com")
|
||||
client := i.Client
|
||||
if client == nil {
|
||||
client = &http.Client{Timeout: 15 * time.Second}
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("could not reach LeetCode")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("LeetCode answered %s", resp.Status)
|
||||
}
|
||||
var out struct {
|
||||
Data struct {
|
||||
Daily *struct {
|
||||
Question struct {
|
||||
Slug string `json:"titleSlug"`
|
||||
} `json:"question"`
|
||||
} `json:"activeDailyCodingChallengeQuestion"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&out); err != nil {
|
||||
return "", fmt.Errorf("LeetCode answered with something other than JSON")
|
||||
}
|
||||
if out.Data.Daily == nil || out.Data.Daily.Question.Slug == "" {
|
||||
return "", fmt.Errorf("LeetCode named no daily question")
|
||||
}
|
||||
return out.Data.Daily.Question.Slug, nil
|
||||
}
|
||||
|
||||
// Import runs `lib/leetcode.py root slug` in the clone at root, which
|
||||
// creates solving/<slug>. The script reports a failure as "Error: ..." on
|
||||
// stderr, which is what the admin is shown.
|
||||
func (i *Importer) Import(ctx context.Context, root, slug string) error {
|
||||
python := i.Python
|
||||
if python == "" {
|
||||
python = "python3"
|
||||
}
|
||||
var stderr bytes.Buffer
|
||||
cmd := exec.CommandContext(ctx, python, "-I", filepath.Join(root, "lib", "leetcode.py"), root, slug)
|
||||
cmd.Stderr = &stderr
|
||||
if err := cmd.Run(); err != nil {
|
||||
for _, line := range strings.Split(stderr.String(), "\n") {
|
||||
if msg, ok := strings.CutPrefix(line, "Error: "); ok {
|
||||
return errors.New(msg)
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("the LeetCode import failed: %v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDaily(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte(`{"data":{"activeDailyCodingChallengeQuestion":{"question":{"titleSlug":"two-sum"}}}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
slug, err := (&Importer{API: srv.URL}).Daily(context.Background())
|
||||
if err != nil || slug != "two-sum" {
|
||||
t.Fatalf("Daily = %q, %v; want two-sum", slug, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDailyMissing(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte(`{"data":{"activeDailyCodingChallengeQuestion":null}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
if _, err := (&Importer{API: srv.URL}).Daily(context.Background()); err == nil {
|
||||
t.Fatal("Daily with no question succeeded")
|
||||
}
|
||||
}
|
||||
|
||||
// The script's own "Error: ..." line is the message, not the exit status.
|
||||
func TestImportError(t *testing.T) {
|
||||
if _, err := exec.LookPath("python3"); err != nil {
|
||||
t.Skip("no python3")
|
||||
}
|
||||
root := t.TempDir()
|
||||
os.MkdirAll(filepath.Join(root, "lib"), 0o755)
|
||||
script := "import sys\nprint('Error: LeetCode has no problem ' + repr(sys.argv[2]), file=sys.stderr)\nsys.exit(1)\n"
|
||||
os.WriteFile(filepath.Join(root, "lib", "leetcode.py"), []byte(script), 0o644)
|
||||
err := (&Importer{}).Import(context.Background(), root, "nope")
|
||||
if err == nil || !strings.Contains(err.Error(), "LeetCode has no problem 'nope'") {
|
||||
t.Fatalf("Import = %v, want the script's message", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user