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
+237
View File
@@ -0,0 +1,237 @@
// Package repo keeps the server's clone of the usaco repository in step with
// the remote, and turns edits from the web into commits pushed back to it.
//
// Git is the only store: the remote (adamf/usaco on the site's Gitea) is the
// source of truth and the clone is a cache of it. So a sync is fetch + hard
// reset, never a merge, and an edit is "sync, change files, commit, push"
// under one lock. If the push is refused because someone pushed in between
// (the CLI's `usaco sync`), the edit is replayed once on the new tip.
//
// It shells out to the git binary rather than using a Go git library: fetch,
// reset and push over HTTP with a token are one line each that way, and the
// behaviour is exactly what the CLI side sees.
package repo
import (
"bytes"
"context"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
)
// ErrRejected means the push was refused twice, normally because the remote
// kept moving. The caller should ask the user to try again.
var ErrRejected = errors.New("push rejected by the remote")
// Config says where the clone lives and how to talk to the remote.
type Config struct {
Dir string // the working clone, e.g. /data/repo
Remote string // clone URL; a file:// URL works for development
Branch string
// Token, when set, is given to git as the password for HTTP remotes
// (through GIT_ASKPASS), so it never lands in .git/config or a URL.
User string
Token string
AuthorName string
AuthorEmail string
// Push false keeps commits local. Syncs then rebase onto the remote
// instead of resetting, so those commits survive.
Push bool
}
// Repo serializes every git operation on the clone.
type Repo struct {
cfg Config
askpass string
// onChange runs under the lock after every sync or edit, with the clone
// in a consistent state, so the index is never built from a half-reset
// tree.
onChange func(dir string) error
mu sync.Mutex
}
// New prepares a Repo. Nothing touches the network until Sync.
func New(cfg Config, onChange func(dir string) error) (*Repo, error) {
if cfg.Branch == "" {
cfg.Branch = "main"
}
r := &Repo{cfg: cfg, onChange: onChange}
if cfg.Token != "" {
// The script reads the secret from its environment, so the file
// itself holds nothing sensitive.
f, err := os.CreateTemp("", "usaco-askpass-*")
if err != nil {
return nil, err
}
script := "#!/bin/sh\ncase \"$1\" in Username*) echo \"$USACO_GIT_USER\" ;; *) echo \"$USACO_GIT_TOKEN\" ;; esac\n"
if _, err := f.WriteString(script); err != nil {
return nil, err
}
f.Close()
if err := os.Chmod(f.Name(), 0o700); err != nil {
return nil, err
}
r.askpass = f.Name()
}
return r, nil
}
// Dir is the clone's path.
func (r *Repo) Dir() string { return r.cfg.Dir }
func (r *Repo) git(ctx context.Context, args ...string) (string, error) {
cmd := exec.CommandContext(ctx, "git", args...)
cmd.Dir = r.cfg.Dir
cmd.Env = append(os.Environ(),
"GIT_TERMINAL_PROMPT=0",
"GIT_AUTHOR_NAME="+r.cfg.AuthorName,
"GIT_AUTHOR_EMAIL="+r.cfg.AuthorEmail,
"GIT_COMMITTER_NAME="+r.cfg.AuthorName,
"GIT_COMMITTER_EMAIL="+r.cfg.AuthorEmail,
)
if r.askpass != "" {
cmd.Env = append(cmd.Env,
"GIT_ASKPASS="+r.askpass,
"USACO_GIT_USER="+r.cfg.User,
"USACO_GIT_TOKEN="+r.cfg.Token,
)
}
var out, errb bytes.Buffer
cmd.Stdout, cmd.Stderr = &out, &errb
if err := cmd.Run(); err != nil {
return out.String(), fmt.Errorf("git %s: %w: %s", args[0], err, strings.TrimSpace(errb.String()))
}
return out.String(), nil
}
// Sync brings the clone up to the remote's tip, cloning it first if needed.
func (r *Repo) Sync(ctx context.Context) error {
r.mu.Lock()
defer r.mu.Unlock()
if err := r.syncLocked(ctx); err != nil {
return err
}
return r.changed()
}
func (r *Repo) syncLocked(ctx context.Context) error {
if _, err := os.Stat(filepath.Join(r.cfg.Dir, ".git")); errors.Is(err, os.ErrNotExist) {
if err := os.MkdirAll(r.cfg.Dir, 0o755); err != nil {
return err
}
if _, err := r.git(ctx, "clone", "--quiet", "--branch", r.cfg.Branch, r.cfg.Remote, "."); err != nil {
return err
}
return nil
}
// Set every time, so a changed GIT_REMOTE_URL applies to an existing
// clone.
if _, err := r.git(ctx, "remote", "set-url", "origin", r.cfg.Remote); err != nil {
return err
}
if _, err := r.git(ctx, "fetch", "--quiet", "--prune", "origin", r.cfg.Branch); err != nil {
return err
}
if !r.cfg.Push {
if _, err := r.git(ctx, "rebase", "--quiet", "origin/"+r.cfg.Branch); err != nil {
r.git(ctx, "rebase", "--abort")
return err
}
return nil
}
if _, err := r.git(ctx, "checkout", "--quiet", "-B", r.cfg.Branch, "origin/"+r.cfg.Branch); err != nil {
return err
}
if _, err := r.git(ctx, "reset", "--quiet", "--hard", "origin/"+r.cfg.Branch); err != nil {
return err
}
_, err := r.git(ctx, "clean", "-ffdq")
return err
}
func (r *Repo) changed() error {
if r.onChange == nil {
return nil
}
return r.onChange(r.cfg.Dir)
}
// Mutate syncs, lets edit change files in the clone, and commits the result
// as message, pushing it when Push is on. An error from edit is returned as
// is and nothing is committed. If edit changes nothing, nothing is
// committed either and Mutate succeeds.
//
// edit may run twice: a rejected push re-syncs and replays it on the new
// tip, so it must decide what to do from the files on disk, not from
// anything it saw before.
func (r *Repo) Mutate(ctx context.Context, message string, edit func(dir string) error) error {
r.mu.Lock()
defer r.mu.Unlock()
var pushErr error
for attempt := 0; attempt < 2; attempt++ {
if err := r.syncLocked(ctx); err != nil {
return err
}
if err := edit(r.cfg.Dir); err != nil {
r.discardLocked(ctx)
return err
}
if _, err := r.git(ctx, "add", "-A"); err != nil {
r.discardLocked(ctx)
return err
}
if _, err := r.git(ctx, "diff", "--cached", "--quiet"); err == nil {
return r.changed()
}
if _, err := r.git(ctx, "commit", "--quiet", "-m", message); err != nil {
r.discardLocked(ctx)
return err
}
if !r.cfg.Push {
return r.changed()
}
// Not --quiet: that would also drop the "[rejected]" line that
// isRejection looks for.
_, pushErr = r.git(ctx, "push", "origin", "HEAD:"+r.cfg.Branch)
if pushErr == nil {
return r.changed()
}
if !isRejection(pushErr) {
break
}
}
// Drop the unpushed commit, so the clone matches the remote again.
if err := r.syncLocked(ctx); err == nil {
r.changed()
}
if isRejection(pushErr) {
return fmt.Errorf("%w: %v", ErrRejected, pushErr)
}
return pushErr
}
// discardLocked throws away uncommitted changes after a failed edit.
func (r *Repo) discardLocked(ctx context.Context) {
r.git(ctx, "reset", "--quiet", "--hard", "HEAD")
r.git(ctx, "clean", "-ffdq")
}
func isRejection(err error) bool {
if err == nil {
return false
}
s := err.Error()
return strings.Contains(s, "[rejected]") || strings.Contains(s, "non-fast-forward") || strings.Contains(s, "fetch first") ||
strings.Contains(s, "Updates were rejected")
}
+218
View File
@@ -0,0 +1,218 @@
package repo
import (
"context"
"errors"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
// run is git in dir, failing the test on error.
func run(t *testing.T, dir string, args ...string) 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")
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("git %v: %v\n%s", args, err, out)
}
return strings.TrimSpace(string(out))
}
// remote makes a bare repo with one commit on main, and a second clone of it
// ("the laptop") for pushing from outside.
func remote(t *testing.T) (bare, laptop string) {
t.Helper()
root := t.TempDir()
bare = filepath.Join(root, "remote.git")
laptop = filepath.Join(root, "laptop")
run(t, root, "init", "--quiet", "--bare", "--initial-branch=main", bare)
run(t, root, "clone", "--quiet", bare, laptop)
os.MkdirAll(filepath.Join(laptop, "solving", "moocast"), 0o755)
os.WriteFile(filepath.Join(laptop, "solving", "moocast", "main.cpp"), []byte("int main(){}\n"), 0o644)
run(t, laptop, "add", "-A")
run(t, laptop, "commit", "--quiet", "-m", "first")
run(t, laptop, "push", "--quiet", "origin", "HEAD:main")
return bare, laptop
}
func newRepo(t *testing.T, bare string, push bool) (*Repo, *int) {
t.Helper()
changes := 0
r, err := New(Config{
Dir: filepath.Join(t.TempDir(), "clone"), Remote: "file://" + bare, Branch: "main",
AuthorName: "site", AuthorEmail: "[email protected]", Push: push,
}, func(string) error { changes++; return nil })
if err != nil {
t.Fatal(err)
}
return r, &changes
}
func laptopCommit(t *testing.T, laptop, file, msg string) {
t.Helper()
run(t, laptop, "pull", "--quiet", "--rebase")
os.WriteFile(filepath.Join(laptop, file), []byte(msg+"\n"), 0o644)
run(t, laptop, "add", "-A")
run(t, laptop, "commit", "--quiet", "-m", msg)
run(t, laptop, "push", "--quiet")
}
func TestSyncClonesThenFollowsRemote(t *testing.T) {
bare, laptop := remote(t)
r, changes := newRepo(t, bare, true)
ctx := context.Background()
if err := r.Sync(ctx); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(filepath.Join(r.Dir(), "solving", "moocast", "main.cpp")); err != nil {
t.Fatal("clone is missing the problem:", err)
}
laptopCommit(t, laptop, "README.md", "from laptop")
// Stray local junk must not survive a sync: the remote always wins.
os.WriteFile(filepath.Join(r.Dir(), "junk"), []byte("x"), 0o644)
if err := r.Sync(ctx); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(filepath.Join(r.Dir(), "README.md")); err != nil {
t.Fatal("sync did not bring in the laptop's commit")
}
if _, err := os.Stat(filepath.Join(r.Dir(), "junk")); err == nil {
t.Fatal("sync left an untracked file behind")
}
if *changes != 2 {
t.Fatalf("onChange ran %d times, want 2", *changes)
}
}
func TestMutateCommitsAndPushes(t *testing.T) {
bare, _ := remote(t)
r, _ := newRepo(t, bare, true)
ctx := context.Background()
err := r.Mutate(ctx, "Solve moocast", func(dir string) error {
os.MkdirAll(filepath.Join(dir, "solved"), 0o755)
return os.Rename(filepath.Join(dir, "solving", "moocast"), filepath.Join(dir, "solved", "moocast"))
})
if err != nil {
t.Fatal(err)
}
if got := run(t, bare, "log", "-1", "--format=%s %an", "main"); got != "Solve moocast site" {
t.Fatalf("remote head = %q, want the site's commit", got)
}
if got := run(t, bare, "ls-tree", "-r", "--name-only", "main"); got != "solved/moocast/main.cpp" {
t.Fatalf("remote tree = %q", got)
}
}
func TestMutateNoChangeMakesNoCommit(t *testing.T) {
bare, _ := remote(t)
r, _ := newRepo(t, bare, true)
before := run(t, bare, "rev-parse", "main")
if err := r.Mutate(context.Background(), "Nothing", func(string) error { return nil }); err != nil {
t.Fatal(err)
}
if after := run(t, bare, "rev-parse", "main"); after != before {
t.Fatal("an edit that changed nothing was committed")
}
}
func TestMutateEditErrorDiscards(t *testing.T) {
bare, _ := remote(t)
r, _ := newRepo(t, bare, true)
boom := errors.New("boom")
err := r.Mutate(context.Background(), "Broken", func(dir string) error {
os.WriteFile(filepath.Join(dir, "half-done"), []byte("x"), 0o644)
return boom
})
if !errors.Is(err, boom) {
t.Fatalf("err = %v, want the edit's own error", err)
}
if _, err := os.Stat(filepath.Join(r.Dir(), "half-done")); err == nil {
t.Fatal("a failed edit left its files behind")
}
}
// An outside push between the site's sync and its push is the normal race
// with `usaco sync` on the laptop. The edit is replayed on the new tip.
func TestMutateReplaysAfterRejectedPush(t *testing.T) {
bare, laptop := remote(t)
r, _ := newRepo(t, bare, true)
ctx := context.Background()
if err := r.Sync(ctx); err != nil {
t.Fatal(err)
}
calls := 0
err := r.Mutate(ctx, "Update moocast", func(dir string) error {
calls++
if calls == 1 {
// Sneak a push in after this attempt's sync.
laptopCommit(t, laptop, "laptop.txt", "laptop wins the race")
}
return os.WriteFile(filepath.Join(dir, "solving", "moocast", "notes.md"), []byte("notes\n"), 0o644)
})
if err != nil {
t.Fatal(err)
}
if calls != 2 {
t.Fatalf("edit ran %d times, want 2 (once, then a replay)", calls)
}
log := run(t, bare, "log", "--format=%s", "main")
if !strings.HasPrefix(log, "Update moocast\nlaptop wins the race") {
t.Fatalf("remote log =\n%s\nwant the site's commit on top of the laptop's", log)
}
}
func TestMutateGivesUpAfterTwoRejections(t *testing.T) {
bare, laptop := remote(t)
r, _ := newRepo(t, bare, true)
ctx := context.Background()
if err := r.Sync(ctx); err != nil {
t.Fatal(err)
}
n := 0
err := r.Mutate(ctx, "Update moocast", func(dir string) error {
n++
laptopCommit(t, laptop, "laptop.txt", "race "+string(rune('0'+n)))
return os.WriteFile(filepath.Join(dir, "solving", "moocast", "notes.md"), []byte("notes\n"), 0o644)
})
if !errors.Is(err, ErrRejected) {
t.Fatalf("err = %v, want ErrRejected", err)
}
// And the clone is back on the remote's tip, without the lost commit.
if got, want := run(t, r.Dir(), "rev-parse", "HEAD"), run(t, bare, "rev-parse", "main"); got != want {
t.Fatal("clone was left on an unpushed commit")
}
}
func TestNoPushKeepsLocalCommitsAcrossSyncs(t *testing.T) {
bare, laptop := remote(t)
r, _ := newRepo(t, bare, false)
ctx := context.Background()
before := run(t, bare, "rev-parse", "main")
err := r.Mutate(ctx, "Update moocast", func(dir string) error {
return os.WriteFile(filepath.Join(dir, "solving", "moocast", "notes.md"), []byte("notes\n"), 0o644)
})
if err != nil {
t.Fatal(err)
}
if run(t, bare, "rev-parse", "main") != before {
t.Fatal("pushed with Push off")
}
laptopCommit(t, laptop, "laptop.txt", "laptop")
if err := r.Sync(ctx); err != nil {
t.Fatal(err)
}
if got := run(t, r.Dir(), "log", "--format=%s", "-2"); got != "Update moocast\nlaptop" {
t.Fatalf("local log = %q, want the local commit rebased onto the laptop's", got)
}
}