A standalone container for web_server, shaped like job-tracker: serves /usaco/ with solved problems public and solving/skipped plus edits (status, link, notes) for the site admin. Git is the only store: the server clones adamf/usaco from Gitea, pulls on the push webhook, and commits edits back. CI builds the image only when site/ changes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
425 lines
11 KiB
Go
425 lines
11 KiB
Go
// Package index reads a clone of the usaco repository into memory: every
|
|
// problem, its files and tests, and the dates git knows about it.
|
|
//
|
|
// The layout is the CLI's (README.md at the repo root): solving/, solved/
|
|
// and skipped/<name>/, each with a solution (main.cpp, sol.py...), an <io>.in
|
|
// the CLI wires up, tests/N.in + N.out, an optional .url and an optional
|
|
// notes.md. The repo is small, so everything, file contents included, is
|
|
// read on each rebuild, and a rebuild only happens when the clone changes.
|
|
package index
|
|
|
|
import (
|
|
"bufio"
|
|
"bytes"
|
|
"fmt"
|
|
"io"
|
|
"net/url"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// The three status directories, in the order the CLI searches them.
|
|
const (
|
|
Solving = "solving"
|
|
Solved = "solved"
|
|
Skipped = "skipped"
|
|
)
|
|
|
|
var Statuses = []string{Solving, Solved, Skipped}
|
|
|
|
// MaxFileSize caps what is held for one file. Test inputs can be large and
|
|
// nobody reads a megabyte in a browser; the rest is cut and marked.
|
|
const MaxFileSize = 64 << 10
|
|
|
|
// File is a solution file or a test half.
|
|
type File struct {
|
|
Name string `json:"name"`
|
|
Lang string `json:"lang,omitempty"`
|
|
Content string `json:"content"`
|
|
Truncated bool `json:"truncated,omitempty"`
|
|
}
|
|
|
|
// Test is one saved case. Output is nil when the expected output is missing
|
|
// (tests/*.out were gitignored before the site existed).
|
|
type Test struct {
|
|
Name string `json:"name"`
|
|
Input File `json:"input"`
|
|
Output *File `json:"output,omitempty"`
|
|
}
|
|
|
|
// Commit is one entry of a problem's history.
|
|
type Commit struct {
|
|
Hash string `json:"hash"`
|
|
Date time.Time `json:"date"`
|
|
Subject string `json:"subject"`
|
|
}
|
|
|
|
// Summary is what the list shows.
|
|
type Summary struct {
|
|
Name string `json:"name"`
|
|
Status string `json:"status"`
|
|
URL string `json:"url,omitempty"`
|
|
Source string `json:"source,omitempty"`
|
|
Langs []string `json:"langs"`
|
|
Tests int `json:"tests"`
|
|
HasNotes bool `json:"hasNotes"`
|
|
FirstSeen *time.Time `json:"firstSeen,omitempty"`
|
|
SolvedAt *time.Time `json:"solvedAt,omitempty"`
|
|
LastTouched *time.Time `json:"lastTouched,omitempty"`
|
|
}
|
|
|
|
// Problem is everything known about one problem.
|
|
type Problem struct {
|
|
Summary
|
|
IO string `json:"io,omitempty"`
|
|
Notes string `json:"notes"`
|
|
Files []File `json:"files"`
|
|
Sample *File `json:"sample,omitempty"`
|
|
TestSet []Test `json:"testCases"`
|
|
History []Commit `json:"history"`
|
|
}
|
|
|
|
// Index is one snapshot of the clone.
|
|
type Index struct {
|
|
Head string
|
|
Built time.Time
|
|
Problems map[string]*Problem
|
|
}
|
|
|
|
// Build reads dir, a git work tree.
|
|
func Build(dir string) (*Index, error) {
|
|
idx := &Index{Built: time.Now(), Problems: map[string]*Problem{}}
|
|
for _, status := range Statuses {
|
|
entries, err := os.ReadDir(filepath.Join(dir, status))
|
|
if os.IsNotExist(err) {
|
|
continue
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for _, e := range entries {
|
|
if !e.IsDir() || strings.HasPrefix(e.Name(), ".") {
|
|
continue
|
|
}
|
|
// The CLI never lets one name exist in two status dirs; if a
|
|
// hand edit did it anyway, the first in search order wins, as
|
|
// in find_problem.
|
|
if _, dup := idx.Problems[e.Name()]; dup {
|
|
continue
|
|
}
|
|
p, err := readProblem(filepath.Join(dir, status, e.Name()), status)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%s/%s: %w", status, e.Name(), err)
|
|
}
|
|
idx.Problems[p.Name] = p
|
|
}
|
|
}
|
|
head, err := gitOut(dir, "rev-parse", "HEAD")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
idx.Head = strings.TrimSpace(head)
|
|
if err := addHistory(dir, idx); err != nil {
|
|
return nil, err
|
|
}
|
|
return idx, nil
|
|
}
|
|
|
|
// solution languages, by extension. Anything else at the top of a problem
|
|
// dir (binaries, .bak, the .in/.out) is not a solution.
|
|
var langs = map[string]string{
|
|
".cpp": "cpp", ".cc": "cpp", ".c": "c", ".h": "cpp", ".hpp": "cpp",
|
|
".py": "python", ".java": "java", ".rs": "rust", ".go": "go",
|
|
}
|
|
|
|
func readProblem(pdir, status string) (*Problem, error) {
|
|
p := &Problem{Summary: Summary{Name: filepath.Base(pdir), Status: status, Langs: []string{}}, Files: []File{}, TestSet: []Test{}, History: []Commit{}}
|
|
|
|
entries, err := os.ReadDir(pdir)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
seenLang := map[string]bool{}
|
|
for _, e := range entries {
|
|
name := e.Name()
|
|
if e.IsDir() {
|
|
continue
|
|
}
|
|
switch {
|
|
case name == ".url":
|
|
b, _ := os.ReadFile(filepath.Join(pdir, name))
|
|
p.URL = strings.TrimSpace(string(b))
|
|
case name == "notes.md":
|
|
b, _ := os.ReadFile(filepath.Join(pdir, name))
|
|
p.Notes = string(b)
|
|
case strings.HasSuffix(name, ".in") && p.IO == "":
|
|
// The first *.in, as detect_io in lib/common.sh picks it.
|
|
p.IO = strings.TrimSuffix(name, ".in")
|
|
f, err := readFile(filepath.Join(pdir, name), "")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
p.Sample = &f
|
|
default:
|
|
if lang, ok := langs[filepath.Ext(name)]; ok {
|
|
f, err := readFile(filepath.Join(pdir, name), lang)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
p.Files = append(p.Files, f)
|
|
if !seenLang[lang] {
|
|
seenLang[lang] = true
|
|
p.Langs = append(p.Langs, lang)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
// main.cpp first: it is the CLI's solution, anything else is a side
|
|
// experiment (sol.py) or a helper.
|
|
sort.SliceStable(p.Files, func(i, j int) bool {
|
|
return p.Files[i].Name == "main.cpp" && p.Files[j].Name != "main.cpp"
|
|
})
|
|
if p.Sample != nil && strings.TrimSpace(p.Sample.Content) == "" {
|
|
p.Sample = nil
|
|
}
|
|
|
|
tests, err := readTests(filepath.Join(pdir, "tests"))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
p.TestSet = tests
|
|
p.Tests = len(tests)
|
|
p.HasNotes = strings.TrimSpace(p.Notes) != ""
|
|
p.Source = Source(p.URL)
|
|
return p, nil
|
|
}
|
|
|
|
// readTests pairs tests/N.in with tests/N.out, numerically ordered as
|
|
// `usaco test` runs them.
|
|
func readTests(tdir string) ([]Test, error) {
|
|
entries, err := os.ReadDir(tdir)
|
|
if os.IsNotExist(err) {
|
|
return []Test{}, nil
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
tests := []Test{}
|
|
for _, e := range entries {
|
|
base, ok := strings.CutSuffix(e.Name(), ".in")
|
|
if !ok || e.IsDir() {
|
|
continue
|
|
}
|
|
in, err := readFile(filepath.Join(tdir, e.Name()), "")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
t := Test{Name: base, Input: in}
|
|
if out, err := readFile(filepath.Join(tdir, base+".out"), ""); err == nil {
|
|
t.Output = &out
|
|
}
|
|
tests = append(tests, t)
|
|
}
|
|
sort.Slice(tests, func(i, j int) bool {
|
|
a, aerr := strconv.Atoi(tests[i].Name)
|
|
b, berr := strconv.Atoi(tests[j].Name)
|
|
if aerr == nil && berr == nil {
|
|
return a < b
|
|
}
|
|
return tests[i].Name < tests[j].Name
|
|
})
|
|
return tests, nil
|
|
}
|
|
|
|
func readFile(path, lang string) (File, error) {
|
|
f, err := os.Open(path)
|
|
if err != nil {
|
|
return File{}, err
|
|
}
|
|
defer f.Close()
|
|
b, err := io.ReadAll(io.LimitReader(f, MaxFileSize+1))
|
|
if err != nil {
|
|
return File{}, err
|
|
}
|
|
file := File{Name: filepath.Base(path), Lang: lang}
|
|
if len(b) > MaxFileSize {
|
|
b = b[:MaxFileSize]
|
|
file.Truncated = true
|
|
}
|
|
file.Content = string(b)
|
|
return file, nil
|
|
}
|
|
|
|
// Source names the judge a problem URL points at, for the list's badge.
|
|
func Source(raw string) string {
|
|
if raw == "" {
|
|
return ""
|
|
}
|
|
u, err := url.Parse(raw)
|
|
if err != nil || u.Host == "" {
|
|
return ""
|
|
}
|
|
host := strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.")
|
|
known := map[string]string{
|
|
"usaco.org": "USACO",
|
|
"usaco.guide": "USACO Guide",
|
|
"cses.fi": "CSES",
|
|
"leetcode.com": "LeetCode",
|
|
"codeforces.com": "Codeforces",
|
|
"atcoder.jp": "AtCoder",
|
|
"kattis.com": "Kattis",
|
|
"open.kattis.com": "Kattis",
|
|
"hackerrank.com": "HackerRank",
|
|
"spoj.com": "SPOJ",
|
|
"onlinejudge.org": "UVa",
|
|
}
|
|
if s, ok := known[host]; ok {
|
|
return s
|
|
}
|
|
return host
|
|
}
|
|
|
|
// addHistory walks the whole log once, oldest first, and gives each problem
|
|
// its commits, first and last dates, and solve date.
|
|
//
|
|
// The solve date is the last time the problem's solved/<name>/ went from
|
|
// empty to non-empty: `usaco done` (a move into solved/) and a reopen +
|
|
// re-solve both count, adding a test to an already solved problem does not.
|
|
// It is taken from git rather than file mtimes (what `usaco stats` uses)
|
|
// because a fresh clone has every mtime set to the clone time.
|
|
func addHistory(dir string, idx *Index) error {
|
|
// --no-renames: a move between status dirs is then a delete plus an
|
|
// add, which is exactly what the solved-file counting below wants.
|
|
out, err := gitOut(dir, "-c", "core.quotePath=false", "log", "--reverse", "--no-renames",
|
|
"--format=%x00%H%x09%aI%x09%s", "--name-status")
|
|
if err != nil {
|
|
// A repository with no commits yet has no history to add.
|
|
if strings.Contains(err.Error(), "does not have any commits") {
|
|
return nil
|
|
}
|
|
return err
|
|
}
|
|
|
|
solvedFiles := map[string]map[string]bool{} // name -> paths under solved/<name>/
|
|
var c Commit
|
|
touched := map[string]bool{}
|
|
becameSolved := map[string]bool{}
|
|
|
|
flush := func() {
|
|
for name := range touched {
|
|
p, ok := idx.Problems[name]
|
|
if !ok {
|
|
continue
|
|
}
|
|
d := c.Date
|
|
if p.FirstSeen == nil {
|
|
p.FirstSeen = &d
|
|
}
|
|
p.LastTouched = &d
|
|
p.History = append(p.History, c)
|
|
}
|
|
for name := range becameSolved {
|
|
if p, ok := idx.Problems[name]; ok && len(solvedFiles[name]) > 0 {
|
|
d := c.Date
|
|
p.SolvedAt = &d
|
|
}
|
|
}
|
|
touched = map[string]bool{}
|
|
becameSolved = map[string]bool{}
|
|
}
|
|
|
|
sc := bufio.NewScanner(bytes.NewReader([]byte(out)))
|
|
sc.Buffer(make([]byte, 1<<20), 1<<20)
|
|
started := false
|
|
for sc.Scan() {
|
|
line := sc.Text()
|
|
if rest, ok := strings.CutPrefix(line, "\x00"); ok {
|
|
if started {
|
|
flush()
|
|
}
|
|
started = true
|
|
parts := strings.SplitN(rest, "\t", 3)
|
|
if len(parts) != 3 {
|
|
return fmt.Errorf("unexpected git log line %q", line)
|
|
}
|
|
date, err := time.Parse(time.RFC3339, parts[1])
|
|
if err != nil {
|
|
return err
|
|
}
|
|
c = Commit{Hash: parts[0][:min(len(parts[0]), 12)], Date: date, Subject: parts[2]}
|
|
continue
|
|
}
|
|
if line == "" {
|
|
continue
|
|
}
|
|
fields := strings.Split(line, "\t")
|
|
if len(fields) < 2 {
|
|
continue
|
|
}
|
|
kind, path := fields[0], fields[len(fields)-1]
|
|
segs := strings.SplitN(path, "/", 3)
|
|
if len(segs) < 3 || !isStatus(segs[0]) {
|
|
continue
|
|
}
|
|
name := segs[1]
|
|
touched[name] = true
|
|
if segs[0] != Solved {
|
|
continue
|
|
}
|
|
set := solvedFiles[name]
|
|
if set == nil {
|
|
set = map[string]bool{}
|
|
solvedFiles[name] = set
|
|
}
|
|
wasEmpty := len(set) == 0
|
|
switch kind[0] {
|
|
case 'D':
|
|
delete(set, path)
|
|
default: // A, M, T (and C if it ever appears)
|
|
set[path] = true
|
|
}
|
|
if wasEmpty && len(set) > 0 {
|
|
becameSolved[name] = true
|
|
}
|
|
}
|
|
if started {
|
|
flush()
|
|
}
|
|
if err := sc.Err(); err != nil {
|
|
return err
|
|
}
|
|
|
|
for _, p := range idx.Problems {
|
|
// Newest first for display.
|
|
for i, j := 0, len(p.History)-1; i < j; i, j = i+1, j-1 {
|
|
p.History[i], p.History[j] = p.History[j], p.History[i]
|
|
}
|
|
// A problem that is solved on disk but whose solved/ files never
|
|
// showed up in the log (uncommitted, in development) has no date.
|
|
if p.Status != Solved {
|
|
p.SolvedAt = nil
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func isStatus(s string) bool {
|
|
return s == Solving || s == Solved || s == Skipped
|
|
}
|
|
|
|
func gitOut(dir string, args ...string) (string, error) {
|
|
cmd := exec.Command("git", args...)
|
|
cmd.Dir = dir
|
|
var out, errb bytes.Buffer
|
|
cmd.Stdout, cmd.Stderr = &out, &errb
|
|
if err := cmd.Run(); err != nil {
|
|
return "", fmt.Errorf("git %s: %w: %s", args[0], err, strings.TrimSpace(errb.String()))
|
|
}
|
|
return out.String(), nil
|
|
}
|