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:
2026-10-20 11:29:39 +01:00
co-authored by Claude Opus 5.5
parent c972fa9fd9
commit af070ffcf9
9 changed files with 337 additions and 2 deletions
+70
View File
@@ -0,0 +1,70 @@
package handlers
import (
"context"
"log"
"net/http"
"time"
"github.com/gin-gonic/gin"
"adam-french.co.uk/usaco-site/internal/leetcode"
)
// LeetCode is the part of leetcode.Importer the handlers use, so tests can
// fake LeetCode and the import script.
type LeetCode interface {
Daily(ctx context.Context) (string, error)
Import(ctx context.Context, root, slug string) error
}
func (s *Server) leetcode() LeetCode {
if s.LeetCode != nil {
return s.LeetCode
}
return &leetcode.Importer{}
}
// startDaily is `usaco daily`: it imports today's LeetCode daily question
// into solving/ and commits it, and answers its name for the page to open.
// A daily question already in the repo (started yesterday from the CLI, or
// solved months ago) is only named, never imported again.
func (s *Server) startDaily(ctx *gin.Context) {
c, cancel := context.WithTimeout(ctx.Request.Context(), 60*time.Second)
defer cancel()
lc := s.leetcode()
slug, err := lc.Daily(c)
if err != nil {
log.Printf("[daily] %v", err)
ctx.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
return
}
// The slug becomes a directory name.
if !validName.MatchString(slug) {
ctx.JSON(http.StatusBadGateway, gin.H{"error": "LeetCode named the daily question " + slug + ", which is not a usable name"})
return
}
if idx := s.Index(); idx != nil {
if _, ok := idx.Problems[slug]; ok {
ctx.JSON(http.StatusOK, gin.H{"name": slug, "created": false})
return
}
}
created := false
err = s.Repo.Mutate(c, "Start "+slug, func(dir string) error {
if _, err := findOnDisk(dir, slug); err == nil {
created = false
return nil
}
created = true
if err := lc.Import(c, dir, slug); err != nil {
return &requestError{http.StatusBadGateway, err.Error()}
}
return nil
})
if err != nil {
editFailed(ctx, "Start "+slug, err)
return
}
ctx.JSON(http.StatusOK, gin.H{"name": slug, "created": created})
}
+86
View File
@@ -0,0 +1,86 @@
package handlers
import (
"context"
"encoding/json"
"errors"
"os"
"path/filepath"
"testing"
)
// fakeLeetCode names slug as the daily question, and imports it by writing a
// main.cpp, as lib/leetcode.py would (much more fully).
type fakeLeetCode struct {
slug string
err error
imports int
}
func (f *fakeLeetCode) Daily(context.Context) (string, error) { return f.slug, nil }
func (f *fakeLeetCode) Import(_ context.Context, root, slug string) error {
f.imports++
if f.err != nil {
return f.err
}
dir := filepath.Join(root, "solving", slug)
os.MkdirAll(dir, 0o755)
return os.WriteFile(filepath.Join(dir, "main.cpp"), []byte("class Solution {};\n"), 0o644)
}
type dailyReply struct {
Name string `json:"name"`
Created bool `json:"created"`
}
func TestDailyImports(t *testing.T) {
r, repo, _ := setup(t)
lc := &fakeLeetCode{slug: "two-sum"}
repo.srv.LeetCode = lc
if rec := do(r, "POST", "/usaco/api/leetcode/daily", "", false); rec.Code != 401 {
t.Fatalf("non-admin = %d, want 401", rec.Code)
}
rec := do(r, "POST", "/usaco/api/leetcode/daily", "", true)
var got dailyReply
json.Unmarshal(rec.Body.Bytes(), &got)
if rec.Code != 200 || got != (dailyReply{"two-sum", true}) {
t.Fatalf("daily = %d %s", rec.Code, rec.Body)
}
if len(repo.msg) != 1 || repo.msg[0] != "Start two-sum" {
t.Fatalf("commits = %v", repo.msg)
}
if _, ok := repo.srv.Index().Problems["two-sum"]; !ok {
t.Fatal("two-sum is not in the index after the import")
}
// The second press only names it.
rec = do(r, "POST", "/usaco/api/leetcode/daily", "", true)
got = dailyReply{}
json.Unmarshal(rec.Body.Bytes(), &got)
if rec.Code != 200 || got != (dailyReply{"two-sum", false}) || lc.imports != 1 {
t.Fatalf("second daily = %d %s after %d imports", rec.Code, rec.Body, lc.imports)
}
}
// A daily question that is already a problem, whatever its status, is not
// imported over.
func TestDailyExisting(t *testing.T) {
r, repo, _ := setup(t)
lc := &fakeLeetCode{slug: "moocast"}
repo.srv.LeetCode = lc
rec := do(r, "POST", "/usaco/api/leetcode/daily", "", true)
if rec.Code != 200 || lc.imports != 0 || len(repo.msg) != 0 {
t.Fatalf("daily = %d %s, %d imports, commits %v", rec.Code, rec.Body, lc.imports, repo.msg)
}
}
func TestDailyImportFails(t *testing.T) {
r, repo, _ := setup(t)
repo.srv.LeetCode = &fakeLeetCode{slug: "paid-only", err: errors.New("LeetCode returned no statement for 'paid-only' (a premium problem?)")}
rec := do(r, "POST", "/usaco/api/leetcode/daily", "", true)
if rec.Code != 502 || len(repo.msg) != 0 {
t.Fatalf("daily = %d %s, commits %v", rec.Code, rec.Body, repo.msg)
}
}
+4
View File
@@ -53,6 +53,9 @@ type Server struct {
// Statements reads a statement from the problem's judge; nil means the
// real judges.
Statements Fetcher
// LeetCode starts the daily question; nil means the real API and the
// clone's lib/leetcode.py.
LeetCode LeetCode
// Transcriber turns review recordings into text; nil when
// TRANSCRIBE_API_KEY is not set, which turns reviews off.
Transcriber Transcriber
@@ -108,6 +111,7 @@ func (s *Server) Routes(api *gin.RouterGroup) {
admin.PUT("/problems/:name/code", s.saveCode)
admin.POST("/problems/:name/run", s.run)
admin.POST("/problems/:name/lint", s.lint)
admin.POST("/leetcode/daily", s.startDaily)
api.POST("/hooks/gitea", s.webhook)
}