Files
usaco/site/internal/repo/repo.go
T
adamfandClaude Opus 5.5 6d956f1c76 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]>
2026-10-14 21:51:34 +01:00

238 lines
6.9 KiB
Go

// 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")
}