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:
@@ -0,0 +1,135 @@
|
||||
// Package auth decides whether a request comes from the site's admin.
|
||||
//
|
||||
// Copied from the job tracker (adamf/job-tracker, internal/auth), which has
|
||||
// the same arrangement: no users or passwords here. The site runs behind the
|
||||
// main site's nginx and borrows that site's session: the browser already
|
||||
// carries the site's HTTP-only auth cookies on every request to /usaco/, so
|
||||
// the Cookie header is forwarded to the site backend's
|
||||
// GET /auth/validate-admin and a 2xx means "admin". Logging in and out happen
|
||||
// on the main site; this only ever asks.
|
||||
//
|
||||
// Unlike the tracker, most of this site is public: the verdict decides what a
|
||||
// visitor sees (solved problems only, or everything) as well as guarding the
|
||||
// edit routes.
|
||||
//
|
||||
// Two consequences worth knowing:
|
||||
// - validate-admin falls back to the refresh token when the access token has
|
||||
// expired, and answers with fresh cookies. Those Set-Cookie headers are
|
||||
// relayed onto this response, or the browser would keep presenting the
|
||||
// expired token and every request would refresh again.
|
||||
// - The answer is cached for a short while per cookie. Only "yes" is
|
||||
// cached: a refusal is re-asked, so logging in takes effect at once.
|
||||
// Logging out takes up to cacheTTL to reach this site.
|
||||
//
|
||||
// Mode "dev" admits everyone. It exists for the standalone docker-compose,
|
||||
// which has no site backend to ask, and main refuses it unless DEV_MODE=true.
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"log"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// cacheTTL is how long a "yes" from the site backend is trusted.
|
||||
const cacheTTL = 30 * time.Second
|
||||
|
||||
// Checker answers whether the request is the admin's. It may write headers
|
||||
// (the relayed Set-Cookie) onto w, which is why it gets the writer.
|
||||
type Checker interface {
|
||||
IsAdmin(w http.ResponseWriter, r *http.Request) bool
|
||||
}
|
||||
|
||||
// AllowAll is the "dev" mode checker.
|
||||
type AllowAll struct{}
|
||||
|
||||
func (AllowAll) IsAdmin(http.ResponseWriter, *http.Request) bool { return true }
|
||||
|
||||
// Forward asks the site backend at URL, forwarding the request's cookies.
|
||||
type Forward struct {
|
||||
URL string
|
||||
Client *http.Client
|
||||
|
||||
mu sync.Mutex
|
||||
cache map[string]time.Time // sha256(Cookie header) -> when it was confirmed
|
||||
}
|
||||
|
||||
// NewForward builds a Forward checker for validateURL, normally
|
||||
// http://backend:8080/auth/validate-admin on the Docker network.
|
||||
func NewForward(validateURL string) *Forward {
|
||||
return &Forward{
|
||||
URL: validateURL,
|
||||
// Short: this sits in front of every request that has cookies, and a
|
||||
// backend that does not answer in a few seconds should be a refusal,
|
||||
// not a hang.
|
||||
Client: &http.Client{Timeout: 5 * time.Second},
|
||||
cache: map[string]time.Time{},
|
||||
}
|
||||
}
|
||||
|
||||
func (f *Forward) IsAdmin(w http.ResponseWriter, r *http.Request) bool {
|
||||
cookie := r.Header.Get("Cookie")
|
||||
if cookie == "" {
|
||||
return false
|
||||
}
|
||||
sum := sha256.Sum256([]byte(cookie))
|
||||
key := hex.EncodeToString(sum[:])
|
||||
|
||||
f.mu.Lock()
|
||||
confirmed, ok := f.cache[key]
|
||||
f.mu.Unlock()
|
||||
if ok && time.Since(confirmed) < cacheTTL {
|
||||
return true
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, f.URL, nil)
|
||||
if err != nil {
|
||||
log.Printf("[auth] building validate request: %v", err)
|
||||
return false
|
||||
}
|
||||
req.Header.Set("Cookie", cookie)
|
||||
resp, err := f.Client.Do(req)
|
||||
if err != nil {
|
||||
log.Printf("[auth] site backend unreachable: %v", err)
|
||||
return false
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Relayed whatever the verdict: a refresh that rotated the cookies is
|
||||
// worth keeping even on a 403.
|
||||
for _, c := range resp.Header.Values("Set-Cookie") {
|
||||
w.Header().Add("Set-Cookie", c)
|
||||
}
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode > 299 {
|
||||
return false
|
||||
}
|
||||
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
// Pruned on the way through; the map only grows with distinct admin
|
||||
// sessions, so this is plenty.
|
||||
for k, t := range f.cache {
|
||||
if time.Since(t) >= cacheTTL {
|
||||
delete(f.cache, k)
|
||||
}
|
||||
}
|
||||
f.cache[key] = time.Now()
|
||||
return true
|
||||
}
|
||||
|
||||
// Require refuses a non-admin with 401. It guards the REST admin routes.
|
||||
func Require(c Checker) gin.HandlerFunc {
|
||||
return func(ctx *gin.Context) {
|
||||
if !c.IsAdmin(ctx.Writer, ctx.Request) {
|
||||
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "admin access required"})
|
||||
return
|
||||
}
|
||||
ctx.Next()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// site fakes the backend's validate-admin: 200 for the "admin" session,
|
||||
// 403 for any other cookie, 401 for none, and a rotated cookie on "stale".
|
||||
func site(t *testing.T, calls *atomic.Int32) *httptest.Server {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
c, err := r.Cookie("access_token")
|
||||
switch {
|
||||
case err != nil:
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
case c.Value == "admin":
|
||||
w.WriteHeader(http.StatusOK)
|
||||
case c.Value == "stale":
|
||||
http.SetCookie(w, &http.Cookie{Name: "access_token", Value: "fresh"})
|
||||
w.WriteHeader(http.StatusOK)
|
||||
default:
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
return srv
|
||||
}
|
||||
|
||||
func ask(f *Forward, cookie string) (bool, *httptest.ResponseRecorder) {
|
||||
r := httptest.NewRequest(http.MethodPost, "/usaco/api/problems", nil)
|
||||
if cookie != "" {
|
||||
r.Header.Set("Cookie", cookie)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
return f.IsAdmin(w, r), w
|
||||
}
|
||||
|
||||
func TestForwardVerdicts(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
f := NewForward(site(t, &calls).URL)
|
||||
|
||||
cases := []struct {
|
||||
name, cookie string
|
||||
want bool
|
||||
}{
|
||||
{"admin session", "access_token=admin", true},
|
||||
{"signed in, not admin", "access_token=someone", false},
|
||||
{"cookies but no session", "theme=dark", false},
|
||||
{"no cookies at all", "", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got, _ := ask(f, c.cookie); got != c.want {
|
||||
t.Fatalf("IsAdmin = %v, want %v", got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestForwardCachesOnlyYes(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
f := NewForward(site(t, &calls).URL)
|
||||
|
||||
ask(f, "access_token=admin")
|
||||
ask(f, "access_token=admin")
|
||||
if n := calls.Load(); n != 1 {
|
||||
t.Fatalf("admin checked %d times, want 1 (second answer from cache)", n)
|
||||
}
|
||||
|
||||
calls.Store(0)
|
||||
ask(f, "access_token=someone")
|
||||
ask(f, "access_token=someone")
|
||||
if n := calls.Load(); n != 2 {
|
||||
t.Fatalf("refusal checked %d times, want 2 (refusals are not cached)", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestForwardRelaysRefreshedCookies(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
f := NewForward(site(t, &calls).URL)
|
||||
|
||||
ok, w := ask(f, "access_token=stale")
|
||||
if !ok {
|
||||
t.Fatal("refreshed session refused")
|
||||
}
|
||||
if got := w.Header().Get("Set-Cookie"); got != "access_token=fresh" {
|
||||
t.Fatalf("Set-Cookie = %q, want the backend's rotated cookie", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestForwardBackendDownRefuses(t *testing.T) {
|
||||
f := NewForward("http://127.0.0.1:1/auth/validate-admin")
|
||||
if ok, _ := ask(f, "access_token=admin"); ok {
|
||||
t.Fatal("admitted while the site backend was unreachable")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
// Package handlers is the site's REST API: the problem list and pages (public
|
||||
// for solved problems, everything for the admin), the admin's edits, and the
|
||||
// Gitea webhook that tells the server to pull.
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"adam-french.co.uk/usaco-site/internal/auth"
|
||||
"adam-french.co.uk/usaco-site/internal/index"
|
||||
"adam-french.co.uk/usaco-site/internal/repo"
|
||||
)
|
||||
|
||||
// Repo is the part of repo.Repo the handlers use, so tests can fake it.
|
||||
type Repo interface {
|
||||
Mutate(ctx context.Context, message string, edit func(dir string) error) error
|
||||
}
|
||||
|
||||
// Server holds the current index and what is needed to change it.
|
||||
type Server struct {
|
||||
Repo Repo
|
||||
Checker auth.Checker
|
||||
WebhookSecret string
|
||||
// Pull asks for a sync. It must not block: the webhook answers at once
|
||||
// and the sync runs in the background.
|
||||
Pull func()
|
||||
|
||||
idx atomic.Pointer[index.Index]
|
||||
}
|
||||
|
||||
// SetIndex swaps in a freshly built index. repo.Repo calls it (through
|
||||
// Reload) under its lock after every sync and edit.
|
||||
func (s *Server) SetIndex(idx *index.Index) { s.idx.Store(idx) }
|
||||
|
||||
// Reload rebuilds the index from dir. It has repo.Repo's onChange signature.
|
||||
func (s *Server) Reload(dir string) error {
|
||||
idx, err := index.Build(dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.SetIndex(idx)
|
||||
log.Printf("[index] %d problems at %.12s", len(idx.Problems), idx.Head)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Index is the current snapshot; nil until the first sync has finished.
|
||||
func (s *Server) Index() *index.Index { return s.idx.Load() }
|
||||
|
||||
// Routes registers everything under api.
|
||||
func (s *Server) Routes(api *gin.RouterGroup) {
|
||||
admin := api.Group("", auth.Require(s.Checker))
|
||||
|
||||
api.GET("/health", s.health)
|
||||
api.GET("/me", s.me)
|
||||
api.GET("/problems", s.list)
|
||||
api.GET("/problems/:name", s.get)
|
||||
admin.PUT("/problems/:name/meta", s.updateMeta)
|
||||
admin.POST("/problems/:name/status", s.setStatus)
|
||||
api.POST("/hooks/gitea", s.webhook)
|
||||
}
|
||||
|
||||
func (s *Server) health(ctx *gin.Context) {
|
||||
idx := s.Index()
|
||||
if idx == nil {
|
||||
ctx.JSON(http.StatusServiceUnavailable, gin.H{"status": "repository not loaded yet"})
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, gin.H{"status": "ok", "head": idx.Head})
|
||||
}
|
||||
|
||||
func (s *Server) me(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusOK, gin.H{"admin": s.isAdmin(ctx)})
|
||||
}
|
||||
|
||||
// visible says whether a problem may be shown to this caller: solved ones
|
||||
// to anyone, the rest only to the admin.
|
||||
func visible(p *index.Problem, admin bool) bool {
|
||||
return admin || p.Status == index.Solved
|
||||
}
|
||||
|
||||
// isAdmin asks the checker. auth.Forward answers a request with no cookies
|
||||
// (nearly every public visitor) without asking the site backend.
|
||||
func (s *Server) isAdmin(ctx *gin.Context) bool {
|
||||
return s.Checker.IsAdmin(ctx.Writer, ctx.Request)
|
||||
}
|
||||
|
||||
func (s *Server) list(ctx *gin.Context) {
|
||||
idx := s.Index()
|
||||
if idx == nil {
|
||||
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "repository not loaded yet"})
|
||||
return
|
||||
}
|
||||
admin := s.isAdmin(ctx)
|
||||
out := []index.Summary{}
|
||||
for _, p := range idx.Problems {
|
||||
if visible(p, admin) {
|
||||
out = append(out, p.Summary)
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
|
||||
ctx.JSON(http.StatusOK, gin.H{"head": idx.Head, "admin": admin, "problems": out})
|
||||
}
|
||||
|
||||
// The CLI's names are slugs. Checking the shape before any lookup keeps
|
||||
// anything path-like ("..", "a/b") away from the filesystem.
|
||||
var validName = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]*$`)
|
||||
|
||||
// lookup finds a problem the caller may see. A problem the caller may not
|
||||
// see is a 404 like a missing one, so its existence does not leak.
|
||||
func (s *Server) lookup(ctx *gin.Context, admin bool) (*index.Problem, bool) {
|
||||
name := ctx.Param("name")
|
||||
idx := s.Index()
|
||||
if idx == nil {
|
||||
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "repository not loaded yet"})
|
||||
return nil, false
|
||||
}
|
||||
if !validName.MatchString(name) {
|
||||
ctx.JSON(http.StatusNotFound, gin.H{"error": "no such problem"})
|
||||
return nil, false
|
||||
}
|
||||
p, ok := idx.Problems[name]
|
||||
if !ok || !visible(p, admin) {
|
||||
ctx.JSON(http.StatusNotFound, gin.H{"error": "no such problem"})
|
||||
return nil, false
|
||||
}
|
||||
return p, true
|
||||
}
|
||||
|
||||
func (s *Server) get(ctx *gin.Context) {
|
||||
if p, ok := s.lookup(ctx, s.isAdmin(ctx)); ok {
|
||||
ctx.JSON(http.StatusOK, p)
|
||||
}
|
||||
}
|
||||
|
||||
// requestError is an edit that cannot be made, with the status to send.
|
||||
type requestError struct {
|
||||
status int
|
||||
msg string
|
||||
}
|
||||
|
||||
func (e *requestError) Error() string { return e.msg }
|
||||
|
||||
// mutate runs an edit through the repo and answers with the problem as it
|
||||
// is afterwards (under its possibly new status).
|
||||
func (s *Server) mutate(ctx *gin.Context, name, message string, edit func(dir string) error) {
|
||||
c, cancel := context.WithTimeout(ctx.Request.Context(), 60*time.Second)
|
||||
defer cancel()
|
||||
err := s.Repo.Mutate(c, message, edit)
|
||||
var re *requestError
|
||||
switch {
|
||||
case err == nil:
|
||||
if p, ok := s.Index().Problems[name]; ok {
|
||||
ctx.JSON(http.StatusOK, p)
|
||||
} else {
|
||||
ctx.JSON(http.StatusOK, gin.H{})
|
||||
}
|
||||
case errors.As(err, &re):
|
||||
ctx.JSON(re.status, gin.H{"error": re.msg})
|
||||
case errors.Is(err, repo.ErrRejected):
|
||||
ctx.JSON(http.StatusConflict, gin.H{"error": "the repository changed while saving; try again"})
|
||||
default:
|
||||
log.Printf("[edit] %s: %v", message, err)
|
||||
ctx.JSON(http.StatusBadGateway, gin.H{"error": "could not save to git"})
|
||||
}
|
||||
}
|
||||
|
||||
// findOnDisk locates a problem in the freshly synced clone. Edits decide
|
||||
// from the disk, not the index, because Mutate may replay them on a newer
|
||||
// tip than the one the index was built from.
|
||||
func findOnDisk(dir, name string) (status string, err error) {
|
||||
for _, st := range index.Statuses {
|
||||
if info, err := os.Stat(filepath.Join(dir, st, name)); err == nil && info.IsDir() {
|
||||
return st, nil
|
||||
}
|
||||
}
|
||||
return "", &requestError{http.StatusNotFound, "no such problem"}
|
||||
}
|
||||
|
||||
type metaBody struct {
|
||||
URL *string `json:"url"`
|
||||
Notes *string `json:"notes"`
|
||||
}
|
||||
|
||||
const maxNotes = 64 << 10
|
||||
|
||||
func (s *Server) updateMeta(ctx *gin.Context) {
|
||||
p, ok := s.lookup(ctx, true)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var body metaBody
|
||||
if err := ctx.ShouldBindJSON(&body); err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON"})
|
||||
return
|
||||
}
|
||||
if body.URL != nil {
|
||||
u := strings.TrimSpace(*body.URL)
|
||||
if u != "" {
|
||||
parsed, err := url.Parse(u)
|
||||
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" || len(u) > 2048 {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "url must be an http(s) link"})
|
||||
return
|
||||
}
|
||||
}
|
||||
body.URL = &u
|
||||
}
|
||||
if body.Notes != nil && len(*body.Notes) > maxNotes {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "notes are too long"})
|
||||
return
|
||||
}
|
||||
|
||||
name := p.Name
|
||||
s.mutate(ctx, name, "Update "+name, func(dir string) error {
|
||||
status, err := findOnDisk(dir, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pdir := filepath.Join(dir, status, name)
|
||||
if body.URL != nil {
|
||||
// Same format `usaco new --url` writes: the link and a newline.
|
||||
if err := writeOrRemove(filepath.Join(pdir, ".url"), *body.URL); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if body.Notes != nil {
|
||||
if err := writeOrRemove(filepath.Join(pdir, "notes.md"), *body.Notes); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// writeOrRemove writes content plus a trailing newline, or removes the file
|
||||
// when content is blank, so clearing a field leaves no empty file behind.
|
||||
func writeOrRemove(path, content string) error {
|
||||
content = strings.TrimRight(content, " \t\r\n")
|
||||
if content == "" {
|
||||
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return os.WriteFile(path, []byte(content+"\n"), 0o644)
|
||||
}
|
||||
|
||||
type statusBody struct {
|
||||
To string `json:"to"`
|
||||
}
|
||||
|
||||
// The commit subjects match the CLI's: `usaco done` commits "Solve <name>".
|
||||
var statusVerb = map[string]string{
|
||||
index.Solved: "Solve",
|
||||
index.Skipped: "Skip",
|
||||
index.Solving: "Reopen",
|
||||
}
|
||||
|
||||
func (s *Server) setStatus(ctx *gin.Context) {
|
||||
p, ok := s.lookup(ctx, true)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var body statusBody
|
||||
if err := ctx.ShouldBindJSON(&body); err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON"})
|
||||
return
|
||||
}
|
||||
verb, ok := statusVerb[body.To]
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "to must be solving, solved or skipped"})
|
||||
return
|
||||
}
|
||||
name := p.Name
|
||||
s.mutate(ctx, name, verb+" "+name, func(dir string) error {
|
||||
from, err := findOnDisk(dir, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if from == body.To {
|
||||
return nil
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Join(dir, body.To), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(filepath.Join(dir, from, name), filepath.Join(dir, body.To, name))
|
||||
})
|
||||
}
|
||||
|
||||
// webhook accepts Gitea's push hook. Gitea signs the body with the shared
|
||||
// secret (HMAC-SHA256, hex, in X-Gitea-Signature). The body itself is not
|
||||
// read beyond that: any push to the repo is a reason to pull.
|
||||
func (s *Server) webhook(ctx *gin.Context) {
|
||||
if s.WebhookSecret == "" {
|
||||
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "webhook not configured"})
|
||||
return
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(ctx.Request.Body, 5<<20))
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "unreadable body"})
|
||||
return
|
||||
}
|
||||
if !validSignature(s.WebhookSecret, body, ctx.GetHeader("X-Gitea-Signature")) {
|
||||
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "bad signature"})
|
||||
return
|
||||
}
|
||||
s.Pull()
|
||||
ctx.JSON(http.StatusAccepted, gin.H{"status": "pull queued"})
|
||||
}
|
||||
|
||||
func validSignature(secret string, body []byte, sig string) bool {
|
||||
got, err := hex.DecodeString(strings.TrimPrefix(sig, "sha256="))
|
||||
if err != nil || len(got) == 0 {
|
||||
return false
|
||||
}
|
||||
mac := hmac.New(sha256.New, []byte(secret))
|
||||
mac.Write(body)
|
||||
return hmac.Equal(got, mac.Sum(nil))
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// cookieChecker: the admin is whoever sends the cookie "admin=1".
|
||||
type cookieChecker struct{}
|
||||
|
||||
func (cookieChecker) IsAdmin(_ http.ResponseWriter, r *http.Request) bool {
|
||||
c, err := r.Cookie("admin")
|
||||
return err == nil && c.Value == "1"
|
||||
}
|
||||
|
||||
// dirRepo applies edits straight to a work tree and reindexes, standing in
|
||||
// for repo.Repo without a remote.
|
||||
type dirRepo struct {
|
||||
dir string
|
||||
srv *Server
|
||||
msg []string
|
||||
}
|
||||
|
||||
func (d *dirRepo) Mutate(_ context.Context, message string, edit func(string) error) error {
|
||||
if err := edit(d.dir); err != nil {
|
||||
return err
|
||||
}
|
||||
d.msg = append(d.msg, message)
|
||||
return d.srv.Reload(d.dir)
|
||||
}
|
||||
|
||||
func setup(t *testing.T) (*gin.Engine, *dirRepo, *int) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
dir := t.TempDir()
|
||||
for _, p := range []string{"solved/moocast/main.cpp", "solving/watermelon/main.cpp"} {
|
||||
os.MkdirAll(filepath.Join(dir, filepath.Dir(p)), 0o755)
|
||||
os.WriteFile(filepath.Join(dir, p), []byte("int main() {}\n"), 0o644)
|
||||
}
|
||||
for _, args := range [][]string{{"init", "--quiet"}, {"add", "-A"}, {"-c", "user.name=t", "-c", "user.email=t@t", "commit", "--quiet", "-m", "init"}} {
|
||||
cmd := exec.Command("git", args...)
|
||||
cmd.Dir = dir
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("git %v: %v\n%s", args, err, out)
|
||||
}
|
||||
}
|
||||
|
||||
pulls := 0
|
||||
srv := &Server{Checker: cookieChecker{}, WebhookSecret: "s3cret", Pull: func() { pulls++ }}
|
||||
repo := &dirRepo{dir: dir, srv: srv}
|
||||
srv.Repo = repo
|
||||
if err := srv.Reload(dir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := gin.New()
|
||||
srv.Routes(r.Group("/usaco/api"))
|
||||
return r, repo, &pulls
|
||||
}
|
||||
|
||||
func do(r *gin.Engine, method, path, body string, admin bool, headers ...string) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
if admin {
|
||||
req.Header.Set("Cookie", "admin=1")
|
||||
}
|
||||
for i := 0; i+1 < len(headers); i += 2 {
|
||||
req.Header.Set(headers[i], headers[i+1])
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
func names(t *testing.T, rec *httptest.ResponseRecorder) []string {
|
||||
t.Helper()
|
||||
var body struct {
|
||||
Problems []struct{ Name string } `json:"problems"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out []string
|
||||
for _, p := range body.Problems {
|
||||
out = append(out, p.Name)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestVisibility(t *testing.T) {
|
||||
r, _, _ := setup(t)
|
||||
|
||||
if got := names(t, do(r, "GET", "/usaco/api/problems", "", false)); len(got) != 1 || got[0] != "moocast" {
|
||||
t.Fatalf("public list = %v, want only the solved problem", got)
|
||||
}
|
||||
if got := names(t, do(r, "GET", "/usaco/api/problems", "", true)); len(got) != 2 {
|
||||
t.Fatalf("admin list = %v, want both", got)
|
||||
}
|
||||
if rec := do(r, "GET", "/usaco/api/problems/watermelon", "", false); rec.Code != 404 {
|
||||
t.Fatalf("public GET of an unsolved problem = %d, want 404", rec.Code)
|
||||
}
|
||||
if rec := do(r, "GET", "/usaco/api/problems/watermelon", "", true); rec.Code != 200 {
|
||||
t.Fatalf("admin GET of an unsolved problem = %d, want 200", rec.Code)
|
||||
}
|
||||
if rec := do(r, "GET", "/usaco/api/problems/moocast", "", false); rec.Code != 200 {
|
||||
t.Fatalf("public GET of a solved problem = %d, want 200", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNameValidation(t *testing.T) {
|
||||
r, _, _ := setup(t)
|
||||
for _, name := range []string{"..", ".git", "Moocast", "%2e%2e", "a%2Fb"} {
|
||||
if rec := do(r, "GET", "/usaco/api/problems/"+name, "", true); rec.Code != 404 {
|
||||
t.Errorf("GET %q = %d, want 404", name, rec.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWritesNeedAdmin(t *testing.T) {
|
||||
r, repo, _ := setup(t)
|
||||
if rec := do(r, "POST", "/usaco/api/problems/moocast/status", `{"to":"skipped"}`, false); rec.Code != 401 {
|
||||
t.Fatalf("anonymous status change = %d, want 401", rec.Code)
|
||||
}
|
||||
if rec := do(r, "PUT", "/usaco/api/problems/moocast/meta", `{"notes":"x"}`, false); rec.Code != 401 {
|
||||
t.Fatalf("anonymous meta edit = %d, want 401", rec.Code)
|
||||
}
|
||||
if len(repo.msg) != 0 {
|
||||
t.Fatalf("refused writes still committed %v", repo.msg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusChange(t *testing.T) {
|
||||
r, repo, _ := setup(t)
|
||||
rec := do(r, "POST", "/usaco/api/problems/watermelon/status", `{"to":"solved"}`, true)
|
||||
if rec.Code != 200 || !strings.Contains(rec.Body.String(), `"status":"solved"`) {
|
||||
t.Fatalf("solve = %d %s", rec.Code, rec.Body)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(repo.dir, "solved", "watermelon", "main.cpp")); err != nil {
|
||||
t.Fatal("directory was not moved")
|
||||
}
|
||||
if len(repo.msg) != 1 || repo.msg[0] != "Solve watermelon" {
|
||||
t.Fatalf("commit messages = %v, want the CLI's \"Solve watermelon\"", repo.msg)
|
||||
}
|
||||
if rec := do(r, "POST", "/usaco/api/problems/watermelon/status", `{"to":"elsewhere"}`, true); rec.Code != 400 {
|
||||
t.Fatalf("bad status = %d, want 400", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetaEdit(t *testing.T) {
|
||||
r, repo, _ := setup(t)
|
||||
pdir := filepath.Join(repo.dir, "solved", "moocast")
|
||||
|
||||
rec := do(r, "PUT", "/usaco/api/problems/moocast/meta", `{"url":" https://usaco.org/x ","notes":"# idea\n"}`, true)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("meta = %d %s", rec.Code, rec.Body)
|
||||
}
|
||||
if b, _ := os.ReadFile(filepath.Join(pdir, ".url")); string(b) != "https://usaco.org/x\n" {
|
||||
t.Fatalf(".url = %q", b)
|
||||
}
|
||||
if b, _ := os.ReadFile(filepath.Join(pdir, "notes.md")); string(b) != "# idea\n" {
|
||||
t.Fatalf("notes.md = %q", b)
|
||||
}
|
||||
|
||||
// Clearing a field removes its file; leaving one out leaves it alone.
|
||||
do(r, "PUT", "/usaco/api/problems/moocast/meta", `{"notes":""}`, true)
|
||||
if _, err := os.Stat(filepath.Join(pdir, "notes.md")); err == nil {
|
||||
t.Fatal("clearing notes left notes.md")
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(pdir, ".url")); err != nil {
|
||||
t.Fatal("an edit without url removed .url")
|
||||
}
|
||||
|
||||
if rec := do(r, "PUT", "/usaco/api/problems/moocast/meta", `{"url":"javascript:alert(1)"}`, true); rec.Code != 400 {
|
||||
t.Fatalf("javascript: url = %d, want 400", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebhookSignature(t *testing.T) {
|
||||
r, _, pulls := setup(t)
|
||||
body := `{"ref":"refs/heads/main"}`
|
||||
mac := hmac.New(sha256.New, []byte("s3cret"))
|
||||
mac.Write([]byte(body))
|
||||
good := hex.EncodeToString(mac.Sum(nil))
|
||||
|
||||
if rec := do(r, "POST", "/usaco/api/hooks/gitea", body, false, "X-Gitea-Signature", "00"+good[2:]); rec.Code != 401 {
|
||||
t.Fatalf("bad signature = %d, want 401", rec.Code)
|
||||
}
|
||||
if rec := do(r, "POST", "/usaco/api/hooks/gitea", body, false); rec.Code != 401 {
|
||||
t.Fatalf("no signature = %d, want 401", rec.Code)
|
||||
}
|
||||
if *pulls != 0 {
|
||||
t.Fatal("an unsigned hook triggered a pull")
|
||||
}
|
||||
if rec := do(r, "POST", "/usaco/api/hooks/gitea", body, false, "X-Gitea-Signature", good); rec.Code != 202 {
|
||||
t.Fatalf("good signature = %d, want 202", rec.Code)
|
||||
}
|
||||
if *pulls != 1 {
|
||||
t.Fatalf("pulls = %d, want 1", *pulls)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// SPA serves the built Vue app from dir for every GET under base that no API
|
||||
// route claimed. It is installed as gin's NoRoute handler rather than as a
|
||||
// base+"/*path" route because gin will not let a catch-all sit beside the
|
||||
// /api routes at the same level.
|
||||
//
|
||||
// History-mode routing means a path such as /usaco/p/moocast is a page of the app,
|
||||
// not a file, so anything that is not a file in dir gets index.html — except
|
||||
// under /api/ and /assets/, where a miss is a real 404: an API typo should
|
||||
// not come back as a page of HTML, and neither should a stale asset hash.
|
||||
//
|
||||
// Caching: Vite fingerprints everything under assets/, so those are cached
|
||||
// for a year; index.html is never cached, so a deploy is picked up on the
|
||||
// next load.
|
||||
func SPA(dir, base string) gin.HandlerFunc {
|
||||
return func(ctx *gin.Context) {
|
||||
p := ctx.Request.URL.Path
|
||||
if ctx.Request.Method != http.MethodGet && ctx.Request.Method != http.MethodHead {
|
||||
ctx.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||||
return
|
||||
}
|
||||
if p == base {
|
||||
ctx.Redirect(http.StatusMovedPermanently, base+"/")
|
||||
return
|
||||
}
|
||||
rel, ok := strings.CutPrefix(p, base+"/")
|
||||
if !ok || strings.HasPrefix(rel, "api/") {
|
||||
ctx.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||||
return
|
||||
}
|
||||
|
||||
// path.Clean on a rooted path cannot climb above the root, so the
|
||||
// result always stays inside dir.
|
||||
rel = strings.TrimPrefix(path.Clean("/"+rel), "/")
|
||||
if rel != "" {
|
||||
file := filepath.Join(dir, filepath.FromSlash(rel))
|
||||
if info, err := os.Stat(file); err == nil && !info.IsDir() {
|
||||
if strings.HasPrefix(rel, "assets/") {
|
||||
ctx.Header("Cache-Control", "public, max-age=31536000, immutable")
|
||||
} else {
|
||||
ctx.Header("Cache-Control", "no-cache")
|
||||
}
|
||||
ctx.File(file)
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(rel, "assets/") {
|
||||
ctx.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
}
|
||||
ctx.Header("Cache-Control", "no-cache")
|
||||
ctx.File(filepath.Join(dir, "index.html"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func TestSPA(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
dir := t.TempDir()
|
||||
os.MkdirAll(filepath.Join(dir, "assets"), 0o755)
|
||||
os.WriteFile(filepath.Join(dir, "index.html"), []byte("index"), 0o644)
|
||||
os.WriteFile(filepath.Join(dir, "assets", "app-1a2b.js"), []byte("js"), 0o644)
|
||||
os.WriteFile(filepath.Join(dir, "robots.txt"), []byte("robots"), 0o644)
|
||||
// Outside dir: must never be reachable.
|
||||
os.WriteFile(filepath.Join(filepath.Dir(dir), "secret"), []byte("secret"), 0o644)
|
||||
|
||||
r := gin.New()
|
||||
r.GET("/usaco/api/health", func(c *gin.Context) { c.String(http.StatusOK, "ok") })
|
||||
r.NoRoute(SPA(dir, "/usaco"))
|
||||
|
||||
cases := []struct {
|
||||
method, path string
|
||||
code int
|
||||
body string
|
||||
cache string
|
||||
}{
|
||||
{"GET", "/usaco/", 200, "index", "no-cache"},
|
||||
{"GET", "/usaco/p/moocast", 200, "index", "no-cache"},
|
||||
{"GET", "/usaco/stats/anything", 200, "index", "no-cache"},
|
||||
{"GET", "/usaco/assets/app-1a2b.js", 200, "js", "public, max-age=31536000, immutable"},
|
||||
{"GET", "/usaco/robots.txt", 200, "robots", "no-cache"},
|
||||
{"GET", "/usaco/api/health", 200, "ok", ""},
|
||||
{"GET", "/usaco/api/nope", 404, `{"error":"not found"}`, ""},
|
||||
{"GET", "/usaco/assets/gone.js", 404, "404 page not found", ""},
|
||||
// net/http refuses a path that climbs, before anything is read.
|
||||
{"GET", "/usaco/../secret", 400, "invalid URL path\n", ""},
|
||||
{"GET", "/usaco/%2e%2e/secret", 400, "invalid URL path\n", ""},
|
||||
{"POST", "/usaco/p/moocast", 404, `{"error":"not found"}`, ""},
|
||||
{"GET", "/elsewhere", 404, `{"error":"not found"}`, ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, httptest.NewRequest(c.method, c.path, nil))
|
||||
if rec.Code != c.code || rec.Body.String() != c.body || rec.Header().Get("Cache-Control") != c.cache {
|
||||
t.Errorf("%s %s = %d %q (cache %q), want %d %q (cache %q)",
|
||||
c.method, c.path, rec.Code, rec.Body, rec.Header().Get("Cache-Control"), c.code, c.body, c.cache)
|
||||
}
|
||||
}
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, httptest.NewRequest("GET", "/usaco", nil))
|
||||
if rec.Code != http.StatusMovedPermanently || rec.Header().Get("Location") != "/usaco/" {
|
||||
t.Errorf("GET /usaco = %d to %q, want a redirect to /usaco/", rec.Code, rec.Header().Get("Location"))
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user