Add the website: Go server + Vue SPA in site/, with CI

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]>
This commit is contained in:
2026-10-14 21:51:34 +01:00
co-authored by Claude Opus 5.5
parent 440d51caba
commit 6d956f1c76
39 changed files with 6285 additions and 0 deletions
+424
View File
@@ -0,0 +1,424 @@
// 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
}
+138
View File
@@ -0,0 +1,138 @@
package index
import (
"os"
"os/exec"
"path/filepath"
"testing"
"time"
)
// fixture builds a repo the way the CLI would have, with fixed commit dates:
//
// day 1 new moocast (solving), new watermelon (solving)
// day 2 done moocast -> solved
// day 3 skip watermelon -> skipped
// day 4 add a test to moocast (must not move its solve date)
func fixture(t *testing.T) string {
t.Helper()
dir := t.TempDir()
day := func(n int) string { return time.Date(2026, 9, n, 12, 0, 0, 0, time.UTC).Format(time.RFC3339) }
git := func(date string, args ...string) {
t.Helper()
cmd := exec.Command("git", args...)
cmd.Dir = dir
cmd.Env = append(os.Environ(),
"GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@t", "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@t",
"GIT_AUTHOR_DATE="+date, "GIT_COMMITTER_DATE="+date)
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git %v: %v\n%s", args, err, out)
}
}
write := func(path, content string) {
t.Helper()
p := filepath.Join(dir, path)
os.MkdirAll(filepath.Dir(p), 0o755)
if err := os.WriteFile(p, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
commit := func(n int, msg string) {
git(day(n), "add", "-A")
git(day(n), "commit", "--quiet", "-m", msg)
}
move := func(from, to string) {
os.MkdirAll(filepath.Join(dir, filepath.Dir(to)), 0o755)
if err := os.Rename(filepath.Join(dir, from), filepath.Join(dir, to)); err != nil {
t.Fatal(err)
}
}
git(day(1), "init", "--quiet", "--initial-branch=main")
write("template.cpp", "// template\n")
write("solving/moocast/main.cpp", "int main() {}\n")
write("solving/moocast/moocast.in", "4\n1 2 3\n")
write("solving/moocast/sol.py", "print(1)\n")
write("solving/moocast/.url", "https://usaco.org/index.php?page=viewproblem2&cpid=668\n")
write("solving/moocast/tests/1.in", "a\n")
write("solving/moocast/tests/1.out", "b\n")
write("solving/moocast/tests/10.in", "c\n")
write("solving/moocast/tests/2.in", "d\n")
write("solving/watermelon/main.cpp", "int main() {}\n")
write("solving/watermelon/watermelon.in", "")
commit(1, "new problems")
move("solving/moocast", "solved/moocast")
commit(2, "Solve moocast")
move("solving/watermelon", "skipped/watermelon")
commit(3, "Skip watermelon")
write("solved/moocast/tests/3.in", "e\n")
write("solved/moocast/notes.md", "union find\n")
commit(4, "Add a test")
return dir
}
func TestBuild(t *testing.T) {
idx, err := Build(fixture(t))
if err != nil {
t.Fatal(err)
}
if len(idx.Problems) != 2 {
t.Fatalf("got %d problems, want 2", len(idx.Problems))
}
m := idx.Problems["moocast"]
if m.Status != Solved || m.IO != "moocast" || m.Source != "USACO" || !m.HasNotes {
t.Fatalf("moocast summary wrong: %+v", m.Summary)
}
if len(m.Files) != 2 || m.Files[0].Name != "main.cpp" || m.Files[1].Lang != "python" {
t.Fatalf("moocast files = %+v, want main.cpp then sol.py", m.Files)
}
if m.Sample == nil || m.Sample.Content != "4\n1 2 3\n" {
t.Fatalf("moocast sample = %+v", m.Sample)
}
var names []string
for _, tc := range m.TestSet {
names = append(names, tc.Name)
}
if got := len(names); got != 4 || names[0] != "1" || names[1] != "2" || names[2] != "3" || names[3] != "10" {
t.Fatalf("test order = %v, want numeric 1 2 3 10", names)
}
if m.TestSet[0].Output == nil || m.TestSet[1].Output != nil {
t.Fatal("test outputs not paired: 1 has one, 2 does not")
}
day := func(n int) time.Time { return time.Date(2026, 9, n, 12, 0, 0, 0, time.UTC) }
if m.SolvedAt == nil || !m.SolvedAt.Equal(day(2)) {
t.Fatalf("moocast solvedAt = %v, want day 2 (adding a test later does not count)", m.SolvedAt)
}
if !m.FirstSeen.Equal(day(1)) || !m.LastTouched.Equal(day(4)) {
t.Fatalf("moocast first/last = %v / %v", m.FirstSeen, m.LastTouched)
}
if len(m.History) != 3 || m.History[0].Subject != "Add a test" {
t.Fatalf("moocast history = %+v, want 3 commits newest first", m.History)
}
w := idx.Problems["watermelon"]
if w.Status != Skipped || w.SolvedAt != nil || w.Sample != nil {
t.Fatalf("watermelon = %+v, want skipped, unsolved, no sample (empty .in)", w.Summary)
}
}
func TestSource(t *testing.T) {
cases := map[string]string{
"": "",
"not a url": "",
"https://cses.fi/problemset/task/1": "CSES",
"https://www.usaco.org/index.php": "USACO",
"https://leetcode.com/problems/x/": "LeetCode",
"https://example.com/problem/1": "example.com",
}
for in, want := range cases {
if got := Source(in); got != want {
t.Errorf("Source(%q) = %q, want %q", in, got, want)
}
}
}