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,147 @@
|
||||
# =============================================================================
|
||||
# ci.yaml — test the site (site/) on every push that changes it; publish an
|
||||
# image for such pushes to main that pass. Copied from job-tracker's ci.yaml,
|
||||
# with the same runner and constraints: a self-hosted act_runner on the Pi in
|
||||
# HOST mode, with git and docker and no other toolchain. So Go and Node run
|
||||
# in `docker run` containers, and the source is fetched with plain git rather
|
||||
# than actions/checkout (which needs Node on the host).
|
||||
#
|
||||
# PATHS
|
||||
# Most pushes here are problems ("Solve moocast", from the CLI or from the
|
||||
# site itself) and must not rebuild anything: the running site picks those
|
||||
# up through the Gitea webhook. Only changes to site/ or this workflow run
|
||||
# it.
|
||||
#
|
||||
# TWO JOBS
|
||||
# test go vet + go test, and a vite build of site/web. The same checks
|
||||
# as `make check` in site/.
|
||||
# publish main only, after test: builds the image, pushes it to this
|
||||
# Gitea's container registry as :<sha> and :latest, then pulls it
|
||||
# into the web_server stack (its `usaco` service) and waits for it
|
||||
# to be healthy — see "Deploying" in site/README.md.
|
||||
#
|
||||
# SECRETS (repo settings -> Actions -> Secrets)
|
||||
# REGISTRY_USER a Gitea user that can write packages for adamf
|
||||
# REGISTRY_TOKEN that user's access token with the write:package scope
|
||||
# =============================================================================
|
||||
name: Test and publish the site
|
||||
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- "site/**"
|
||||
- ".gitea/workflows/**"
|
||||
|
||||
env:
|
||||
IMAGE: adam-french.co.uk/adamf/usaco
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: self-hosted
|
||||
env:
|
||||
SHA: ${{ github.sha }}
|
||||
REF: ${{ github.ref }}
|
||||
REMOTE: ssh://git@localhost:2222/adamf/usaco.git
|
||||
GIT_SSH_COMMAND: "ssh -o StrictHostKeyChecking=no"
|
||||
CACHE: /home/adamf/.cache/usaco-ci/repo.git
|
||||
SRC: /home/adamf/.cache/usaco-ci/src-${{ github.sha }}
|
||||
steps:
|
||||
- name: Export the pushed commit's site/ to a scratch directory
|
||||
shell: bash
|
||||
run: |
|
||||
set -eu
|
||||
mkdir -p "$(dirname "$CACHE")"
|
||||
[ -d "$CACHE" ] || git init --quiet --bare "$CACHE"
|
||||
git --git-dir="$CACHE" fetch --quiet --no-tags "$REMOTE" "$REF"
|
||||
rm -rf "$SRC"
|
||||
mkdir -p "$SRC"
|
||||
git --git-dir="$CACHE" archive --format=tar "$SHA" site | tar -x -C "$SRC"
|
||||
test -f "$SRC/site/go.mod"
|
||||
|
||||
# Read-only source, and named volumes for the module and build
|
||||
# caches, for the reasons given in web_server's deploy.yaml. git
|
||||
# is installed because internal/repo and internal/index test
|
||||
# against real repositories.
|
||||
- name: Go - vet and test
|
||||
shell: bash
|
||||
run: |
|
||||
set -eu
|
||||
docker run --rm \
|
||||
-v "$SRC/site":/src:ro -w /src \
|
||||
-v usaco_ci_gomod:/go/pkg/mod \
|
||||
-v usaco_ci_gobuild:/root/.cache/go-build \
|
||||
golang:1.26 \
|
||||
sh -c 'go vet ./... && go test ./...'
|
||||
|
||||
# Built in the container's own copy: node_modules and dist must not
|
||||
# be written into $SRC, which is mounted read-only.
|
||||
- name: Web - vite build
|
||||
shell: bash
|
||||
run: |
|
||||
set -eu
|
||||
docker run --rm \
|
||||
-v "$SRC/site/web":/src:ro \
|
||||
-v usaco_ci_npm:/root/.npm \
|
||||
node:22-alpine \
|
||||
sh -c 'cp -r /src /build && cd /build && npm ci --no-audit --no-fund && npx vite build'
|
||||
|
||||
- name: Remove the scratch directory
|
||||
if: always()
|
||||
shell: bash
|
||||
run: rm -rf "$SRC"
|
||||
|
||||
publish:
|
||||
needs: test
|
||||
if: github.ref == 'refs/heads/main'
|
||||
runs-on: self-hosted
|
||||
env:
|
||||
SHA: ${{ github.sha }}
|
||||
CACHE: /home/adamf/.cache/usaco-ci/repo.git
|
||||
SRC: /home/adamf/.cache/usaco-ci/publish-${{ github.sha }}
|
||||
REGISTRY_USER: ${{ secrets.REGISTRY_USER }}
|
||||
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
|
||||
# The Pi's Docker is 20.10, where plain `docker build` still uses
|
||||
# the legacy builder, and that rejects the Dockerfile's
|
||||
# `RUN --mount=type=cache` lines. This switches on BuildKit.
|
||||
DOCKER_BUILDKIT: "1"
|
||||
steps:
|
||||
- name: Build and push the image
|
||||
shell: bash
|
||||
run: |
|
||||
set -eu
|
||||
rm -rf "$SRC" && mkdir -p "$SRC"
|
||||
git --git-dir="$CACHE" archive --format=tar "$SHA" site | tar -x -C "$SRC"
|
||||
printf '%s' "$REGISTRY_TOKEN" | docker login adam-french.co.uk -u "$REGISTRY_USER" --password-stdin
|
||||
# Built natively on the Pi, so the image is arm64 — the only
|
||||
# platform it runs on.
|
||||
docker build -t "$IMAGE:$SHA" -t "$IMAGE:latest" "$SRC/site"
|
||||
docker push "$IMAGE:$SHA"
|
||||
docker push "$IMAGE:latest"
|
||||
|
||||
- name: Remove the scratch directory
|
||||
if: always()
|
||||
shell: bash
|
||||
run: rm -rf "$SRC"
|
||||
|
||||
# Put the new image live, exactly as job-tracker's workflow does
|
||||
# for `jobs`: pull + up of the one service, under the lock that
|
||||
# web_server's deploy.yaml and env-apply hold, then wait for the
|
||||
# image's HEALTHCHECK (process up, repository cloned and indexed).
|
||||
# Pinning USACO_IMAGE_TAG in the site's .env makes this a no-op.
|
||||
- name: Roll the site onto the new image
|
||||
working-directory: /home/adamf/deploy/web_server
|
||||
env:
|
||||
DOCKER_API_VERSION: "1.41"
|
||||
shell: bash
|
||||
run: |
|
||||
set -eu
|
||||
flock env-apply/run/lock sh -c 'docker compose pull usaco && docker compose up -d --no-deps usaco'
|
||||
for i in $(seq 1 30); do
|
||||
status=$(docker inspect -f '{{.State.Health.Status}}' usaco)
|
||||
echo "usaco: $status"
|
||||
[ "$status" = healthy ] && exit 0
|
||||
[ "$status" = unhealthy ] && break
|
||||
sleep 5
|
||||
done
|
||||
docker logs --tail 50 usaco
|
||||
exit 1
|
||||
@@ -0,0 +1,4 @@
|
||||
web/node_modules
|
||||
web/dist
|
||||
.env
|
||||
*.log
|
||||
@@ -0,0 +1,42 @@
|
||||
# Every variable the server reads. In production these are set by the main
|
||||
# site's docker-compose.yml (see README.md); for standalone development,
|
||||
# docker-compose.yml here sets what it needs.
|
||||
|
||||
# --- Core -------------------------------------------------------------------
|
||||
# URL prefix everything is served under. The SPA is built for /usaco.
|
||||
BASE_PATH=
|
||||
# The clone lives in $DATA_DIR/repo (default /data).
|
||||
DATA_DIR=
|
||||
# Listen port (default 8080).
|
||||
PORT=
|
||||
# "true" enables gin debug logging, and is required for AUTH_MODE=dev.
|
||||
DEV_MODE=
|
||||
|
||||
# --- Git --------------------------------------------------------------------
|
||||
# What to clone. Production: http://gitea:3000/adamf/usaco.git (Gitea on the
|
||||
# Docker network). Required.
|
||||
GIT_REMOTE_URL=
|
||||
# Default main.
|
||||
GIT_BRANCH=
|
||||
# HTTP credentials: a Gitea access token with read and write on the repo.
|
||||
# Given to git through GIT_ASKPASS, never written into .git/config.
|
||||
# GIT_USER defaults to adamf.
|
||||
GIT_USER=
|
||||
GIT_TOKEN=
|
||||
# Who the site's commits are by. Defaults: "usaco site" / [email protected].
|
||||
GIT_AUTHOR_NAME=
|
||||
GIT_AUTHOR_EMAIL=
|
||||
# "false" keeps edits as local commits (development). Default true.
|
||||
GIT_PUSH=
|
||||
# Fallback pull interval, a Go duration. Default 10m; the webhook is the
|
||||
# normal trigger.
|
||||
PULL_INTERVAL=
|
||||
# Shared secret of the Gitea push webhook. Blank turns the hook off.
|
||||
WEBHOOK_SECRET=
|
||||
|
||||
# --- Auth -------------------------------------------------------------------
|
||||
# "forward" (default): ask the main site's backend. "dev": admit everyone.
|
||||
AUTH_MODE=
|
||||
# The site backend's validate-admin route, on the Docker network
|
||||
# (default http://backend:8080/auth/validate-admin).
|
||||
AUTH_VALIDATE_URL=
|
||||
@@ -0,0 +1,3 @@
|
||||
web/node_modules/
|
||||
web/dist/
|
||||
.env
|
||||
@@ -0,0 +1,26 @@
|
||||
# CLAUDE.md
|
||||
|
||||
Guidance for Claude Code in `site/`. README.md has the full picture (routes, git sync, deployment).
|
||||
|
||||
## Commands
|
||||
|
||||
```
|
||||
make check # go vet ./... && go test ./..., then a vite build of web/ into a temp dir
|
||||
make dev # docker compose up --build: this checkout's problems, AUTH_MODE=dev, GIT_PUSH=false
|
||||
cd web && npm run dev # SPA hot reload; proxies /usaco/api to localhost:8080
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
One Go binary (`cmd/usacosite`) that serves a REST API and the built Vue SPA, all under `/usaco`. It is deployed as one container inside the `web_server` stack, behind its nginx. It has the same shape as `../job-tracker`, from which `internal/auth` and `handlers.SPA` were copied.
|
||||
|
||||
- **Git is the only store.** `internal/repo` owns the clone and serializes every git command. A sync is fetch + hard reset (the remote wins). `Mutate` does sync, edit, commit and push, and replays the edit once if the push is rejected. Its `onChange` callback (`Server.Reload`) rebuilds the index under the same lock.
|
||||
- **The index is an immutable snapshot**, swapped in through an `atomic.Pointer`. Handlers read `s.Index()` once per request.
|
||||
- **Visibility is decided server-side.** Non-admins see only `solved/`, and an unsolved problem is a 404, not a 403. `auth.Forward` returns false for a request with no cookies without a network call.
|
||||
|
||||
## Conventions
|
||||
|
||||
- **Comments explain why, not what.** Preserve them, and update them when behaviour changes.
|
||||
- **Edits look at the disk.** An edit func passed to `Mutate` may run twice, so it must locate the problem with `findOnDisk`, never from the index.
|
||||
- **Commit subjects match the CLI's** (`lib/cmd/done.sh`): "Solve <name>" and so on.
|
||||
- **The problem layout belongs to the CLI** in the repo root (`lib/`). When the CLI's layout changes, update `internal/index`.
|
||||
@@ -0,0 +1,47 @@
|
||||
# =============================================================================
|
||||
# The USACO site: one image, one process. Same three stages as the job
|
||||
# tracker's Dockerfile, which this is copied from:
|
||||
#
|
||||
# web builds the Vue SPA (web/) with Vite. Only package*.json is copied
|
||||
# before `npm ci`, so the dependency layer is cached across edits.
|
||||
# build compiles the Go server. Same trick with go.mod/go.sum.
|
||||
# runtime alpine with the binary and the built SPA, which the server serves
|
||||
# from /app/static (STATIC_DIR) for every non-API path under /usaco/.
|
||||
#
|
||||
# The build context is site/, so the problems themselves are never in the
|
||||
# image: the server clones them from Gitea at runtime into DATA_DIR.
|
||||
#
|
||||
# The runtime runs as uid 1000, not root. DATA_DIR (/data) must be writable by
|
||||
# it: with a bind mount, `chown 1000 <dir>` on the host. git is the server's
|
||||
# storage layer (internal/repo shells out to it); wget is for the healthcheck.
|
||||
# =============================================================================
|
||||
FROM node:22-alpine AS web
|
||||
WORKDIR /web
|
||||
COPY web/package.json web/package-lock.json ./
|
||||
RUN npm ci --no-audit --no-fund
|
||||
COPY web/ ./
|
||||
RUN npm run build
|
||||
|
||||
FROM golang:1.26 AS build
|
||||
WORKDIR /src
|
||||
COPY go.mod go.sum ./
|
||||
RUN --mount=type=cache,target=/go/pkg/mod go mod download
|
||||
COPY cmd ./cmd
|
||||
COPY internal ./internal
|
||||
RUN --mount=type=cache,target=/go/pkg/mod \
|
||||
--mount=type=cache,target=/root/.cache/go-build \
|
||||
CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/usacosite ./cmd/usacosite
|
||||
|
||||
FROM alpine:3.22
|
||||
RUN apk add --no-cache ca-certificates git wget \
|
||||
&& adduser -D -H -u 1000 app \
|
||||
&& mkdir /data && chown app /data
|
||||
COPY --from=build /out/usacosite /app/usacosite
|
||||
COPY --from=web /web/dist /app/static
|
||||
USER app
|
||||
VOLUME /data
|
||||
EXPOSE 8080
|
||||
# start-period covers the first clone, which /api/health waits for.
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \
|
||||
CMD wget -qO- http://localhost:8080/usaco/api/health || exit 1
|
||||
CMD ["/app/usacosite"]
|
||||
@@ -0,0 +1,31 @@
|
||||
# =============================================================================
|
||||
# Makefile — the commands that verify and run the site. `make check` is the
|
||||
# thing to run before pushing; .gitea/workflows/ci.yaml (at the repo root)
|
||||
# runs the same checks in containers before it publishes an image.
|
||||
#
|
||||
# Needs on the host: Go (the version in go.mod) for check-go, Node with
|
||||
# `npm install` done in web/ for check-web, Docker for dev.
|
||||
# =============================================================================
|
||||
|
||||
.DEFAULT_GOAL := help
|
||||
|
||||
.PHONY: help check check-go check-web dev
|
||||
|
||||
help:
|
||||
@echo "Targets:"
|
||||
@echo " make check run every check below"
|
||||
@echo " make check-go go vet + go test"
|
||||
@echo " make check-web vite build of web/ into a throwaway directory"
|
||||
@echo " make dev build and run the standalone site (http://localhost:8080/usaco/)"
|
||||
|
||||
check: check-go check-web
|
||||
|
||||
check-go:
|
||||
go vet ./... && go test ./...
|
||||
|
||||
# Built into a temporary directory so a check never replaces web/dist.
|
||||
check-web:
|
||||
cd web && npx vite build --outDir "$$(mktemp -d)" --emptyOutDir
|
||||
|
||||
dev:
|
||||
docker compose up --build
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
# USACO site
|
||||
|
||||
The public face of this repo, served at `/usaco/` on adam-french.co.uk. It shows the solved problems: each solution, its sample input, saved tests and notes, and its git history, plus a stats page with a solve calendar. When the site's admin is logged in, it also shows problems in `solving/` and `skipped/`, and lets them:
|
||||
|
||||
- mark a problem solved, skipped or back in progress
|
||||
- set its link
|
||||
- write notes
|
||||
|
||||
It is one Go binary that serves a REST API and the built Vue SPA. It runs as one container behind the site's nginx and borrows the site's login, the same arrangement as job-tracker (adamf/job-tracker), which it is modelled on.
|
||||
|
||||
## Git is the store
|
||||
|
||||
There is no database. The CLI's layout is the data model (see the root README.md):
|
||||
|
||||
- `solving/`, `solved/` and `skipped/<name>/`, each holding the solution files
|
||||
- `<io>.in` for the sample input
|
||||
- `tests/N.in` and `N.out`
|
||||
- `.url` for the problem link
|
||||
- `notes.md` for notes
|
||||
|
||||
The server keeps a clone of adamf/usaco in `$DATA_DIR/repo` and indexes it into memory.
|
||||
|
||||
- **Reading.** A Gitea push webhook triggers a fetch and hard reset, then a re-index, so a `usaco done && usaco sync` is live in seconds. A pull every `PULL_INTERVAL` (10m) catches missed hooks. The clone is a cache: the remote always wins.
|
||||
- **Writing.** An admin edit runs under one lock:
|
||||
1. sync
|
||||
2. change the files
|
||||
3. commit as `GIT_AUTHOR_NAME`
|
||||
4. push
|
||||
|
||||
The commit subjects match the CLI's: "Solve <name>", "Skip <name>", "Reopen <name>" and "Update <name>". If someone pushed in between and the push is rejected, the edit is replayed once on the new tip. A second rejection returns 409.
|
||||
- **Dates come from git, not mtimes.** A problem's solve date is the commit that moved it into `solved/`. Its first and last dates are its first and last commits.
|
||||
|
||||
The site commits, so the laptop must pull before pushing. `usaco sync` does `pull --rebase --autostash` and then `push`.
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
cmd/usacosite/ main: reads the environment, wires everything, registers routes
|
||||
internal/auth/ is this request the admin? (asks the site backend; copied from job-tracker)
|
||||
internal/repo/ the clone: sync, and edit-commit-push with one replay on rejection
|
||||
internal/index/ reads the clone into memory: problems, files, tests, git dates
|
||||
internal/handlers/ REST API, Gitea webhook, SPA file server
|
||||
web/ Vue 3 + Vite SPA, built for base /usaco/
|
||||
```
|
||||
|
||||
## Routes
|
||||
|
||||
Everything is served under `BASE_PATH` (`/usaco`). nginx proxies the prefix through unchanged.
|
||||
|
||||
| Path | Auth | What |
|
||||
|---|---|---|
|
||||
| `/usaco/`, `/usaco/p/<name>`, `/usaco/stats` | none | SPA |
|
||||
| `GET /usaco/api/problems` | open; the admin also gets unsolved problems | the list |
|
||||
| `GET /usaco/api/problems/<name>` | open for solved problems; 404 for others unless admin | one problem, with files, tests and history |
|
||||
| `GET /usaco/api/me` | open | `{admin}`, so the SPA knows whether to show the edit controls |
|
||||
| `PUT /usaco/api/problems/<name>/meta` | admin | `{url?, notes?}`: writes `.url` and `notes.md` (blank removes the file) |
|
||||
| `POST /usaco/api/problems/<name>/status` | admin | `{to: solving\|solved\|skipped}`: moves the directory |
|
||||
| `POST /usaco/api/hooks/gitea` | HMAC (`X-Gitea-Signature`) | queue a pull |
|
||||
| `GET /usaco/api/health` | open | 200 once the clone is indexed |
|
||||
|
||||
Auth works as in job-tracker:
|
||||
|
||||
- `internal/auth` forwards the browser's cookies to the site backend's `/auth/validate-admin`.
|
||||
- A "yes" is cached for 30 seconds.
|
||||
- A refused admin action sends the browser to `/admin/login?redirect=…`.
|
||||
|
||||
## Development
|
||||
|
||||
```
|
||||
make check # go vet + go test, and a vite build
|
||||
make dev # docker compose up --build: this checkout's problems, no login
|
||||
```
|
||||
|
||||
Then open http://localhost:8080/usaco/.
|
||||
|
||||
**`make dev`.** The dev compose clones the repo root, mounted read-only, and sets `GIT_PUSH=false`. Edits made in the browser become commits in the container's clone and nowhere else. Only committed work shows up.
|
||||
|
||||
**Hot reload.** Run the server with `make dev`, then run `cd web && npm run dev`. Vite proxies `/usaco/api` to `localhost:8080`.
|
||||
|
||||
**Without Docker:**
|
||||
```
|
||||
go build -o /tmp/usacosite ./cmd/usacosite && (cd web && npx vite build)
|
||||
DEV_MODE=true AUTH_MODE=dev GIT_PUSH=false GIT_REMOTE_URL=file://$PWD/.. \
|
||||
DATA_DIR=/tmp/usaco-data STATIC_DIR=$PWD/web/dist /tmp/usacosite
|
||||
```
|
||||
|
||||
Every variable is listed and explained in `.env.example`.
|
||||
|
||||
## Running inside web_server
|
||||
|
||||
The site's `docker-compose.yml` runs the published image as service `usaco`, with an explicit `environment:` list. The site's nginx routes `/usaco/` to it. `./usaco-data` is mounted at `/data` and holds only the clone, so deleting it is safe: the next start re-clones. The container runs as uid 1000, so run `chown 1000 usaco-data` on the host.
|
||||
|
||||
### Deploying
|
||||
|
||||
A push to `main` that touches `site/` or `.gitea/workflows/` runs `.gitea/workflows/ci.yaml` at the repo root. It does the following:
|
||||
|
||||
1. Tests.
|
||||
2. Builds the image from `site/` and pushes it as `adam-french.co.uk/adamf/usaco:<sha>` and `:latest`.
|
||||
3. Rolls the site onto the new image and waits for the healthcheck.
|
||||
|
||||
Problem commits don't match the path filter, so they never rebuild the image. The webhook brings them in.
|
||||
|
||||
By hand on the Pi:
|
||||
|
||||
```
|
||||
cd ~/deploy/web_server && docker compose pull usaco && docker compose up -d --no-deps usaco
|
||||
```
|
||||
|
||||
To pin a version, set `USACO_IMAGE_TAG=<sha>` in the site's `.env`.
|
||||
|
||||
### One-off setup
|
||||
|
||||
The registry setup is shared with job-tracker (see its README, "One-off: registry setup"). The Pi is already logged in, and the same `REGISTRY_USER` and `REGISTRY_TOKEN` work here.
|
||||
|
||||
1. **CI secrets.** In this repo's Settings → Actions → Secrets, add `REGISTRY_USER` and `REGISTRY_TOKEN`. Use the same values as job-tracker.
|
||||
2. **A git token for the server.** In Gitea, go to Settings → Applications and create a token with **repository: read and write**. Put it in the site's `.env` as `USACO_GIT_TOKEN`.
|
||||
3. **The data directory.** On the Pi, in `~/deploy/web_server`, run `mkdir usaco-data && sudo chown 1000:1000 usaco-data`.
|
||||
4. **A webhook secret.** Generate one, for example with `openssl rand -hex 32`, and put it in the site's `.env` as `USACO_WEBHOOK_SECRET`.
|
||||
5. **Deploy web_server** with the `usaco` service and the `/usaco/` route. Then push this repo, so CI publishes the first image.
|
||||
6. **The webhook.** In this repo's Settings → Webhooks → Add webhook → Gitea, set:
|
||||
- Target URL: `http://usaco:8080/usaco/api/hooks/gitea`
|
||||
- Method: POST
|
||||
- Content type: application/json
|
||||
- Secret: the value of `USACO_WEBHOOK_SECRET`
|
||||
- Trigger: push events
|
||||
|
||||
Gitea only delivers to Docker-network hosts that are on `[webhook] ALLOWED_HOST_LIST`. web_server's compose sets that to `external,usaco`. Use "Test delivery": the response should be `202`, and `docker logs usaco` should show a new `[index]` line.
|
||||
|
||||
## Things that are easy to get wrong
|
||||
|
||||
- **`BASE_PATH` and Vite's `base` must agree.** The SPA's asset URLs and router base are fixed at build time.
|
||||
- **Edits must decide from disk, not the index.** `repo.Mutate` may run an edit twice, the second time on a newer tip. The handlers re-locate the problem in the clone each time with `findOnDisk`.
|
||||
- **`tests/*.out` used to be gitignored** by the root `*.out` rule. The root `.gitignore` now re-includes `**/tests/*.out`. A test whose expected output is shown as "Not saved." predates that change or never had one.
|
||||
@@ -0,0 +1,159 @@
|
||||
// Command usacosite serves the USACO practice log at /usaco/: the problems
|
||||
// from adamf/usaco on the site's Gitea, their solutions and tests, and a few
|
||||
// admin edits (problem link, notes, status) that it commits back to git.
|
||||
//
|
||||
// It is built to sit behind adam-french.co.uk's nginx and borrow its login
|
||||
// (internal/auth), like the job tracker. There is no database: the server
|
||||
// keeps a clone of the repository in DATA_DIR and pulls it when Gitea's push
|
||||
// webhook fires, and every PULL_INTERVAL in case a hook was missed. main
|
||||
// reads every setting from the environment (all listed in .env.example),
|
||||
// wires the pieces together and registers the routes.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"adam-french.co.uk/usaco-site/internal/auth"
|
||||
"adam-french.co.uk/usaco-site/internal/handlers"
|
||||
"adam-french.co.uk/usaco-site/internal/repo"
|
||||
)
|
||||
|
||||
func main() {
|
||||
devMode := os.Getenv("DEV_MODE") == "true"
|
||||
if !devMode {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
}
|
||||
|
||||
// Everything is served under basePath, and nginx proxies it without
|
||||
// stripping the prefix. The SPA is built for /usaco/ (web/vite.config.js),
|
||||
// so changing this means rebuilding it with a matching base.
|
||||
basePath := strings.TrimRight(getenv("BASE_PATH", "/usaco"), "/")
|
||||
dataDir := getenv("DATA_DIR", "/data")
|
||||
staticDir := getenv("STATIC_DIR", "/app/static")
|
||||
|
||||
// AUTH
|
||||
// "forward" (the default) asks the main site; "dev" admits everyone and
|
||||
// is refused outside DEV_MODE, so a stray setting cannot open the edits
|
||||
// in production.
|
||||
var checker auth.Checker
|
||||
switch mode := getenv("AUTH_MODE", "forward"); mode {
|
||||
case "forward":
|
||||
checker = auth.NewForward(getenv("AUTH_VALIDATE_URL", "http://backend:8080/auth/validate-admin"))
|
||||
case "dev":
|
||||
if !devMode {
|
||||
log.Fatal("AUTH_MODE=dev is only allowed with DEV_MODE=true")
|
||||
}
|
||||
log.Println("[auth] AUTH_MODE=dev: every request is treated as the admin")
|
||||
checker = auth.AllowAll{}
|
||||
default:
|
||||
log.Fatalf("unknown AUTH_MODE %q (want forward or dev)", mode)
|
||||
}
|
||||
|
||||
remote := os.Getenv("GIT_REMOTE_URL")
|
||||
if remote == "" {
|
||||
log.Fatal("GIT_REMOTE_URL is not set")
|
||||
}
|
||||
|
||||
srv := &handlers.Server{Checker: checker, WebhookSecret: os.Getenv("WEBHOOK_SECRET")}
|
||||
if srv.WebhookSecret == "" {
|
||||
log.Println("[webhook] WEBHOOK_SECRET is not set: the push hook is off, pulls happen on the interval only")
|
||||
}
|
||||
|
||||
rp, err := repo.New(repo.Config{
|
||||
Dir: filepath.Join(dataDir, "repo"),
|
||||
Remote: remote,
|
||||
Branch: getenv("GIT_BRANCH", "main"),
|
||||
User: getenv("GIT_USER", "adamf"),
|
||||
Token: os.Getenv("GIT_TOKEN"),
|
||||
AuthorName: getenv("GIT_AUTHOR_NAME", "usaco site"),
|
||||
AuthorEmail: getenv("GIT_AUTHOR_EMAIL", "[email protected]"),
|
||||
Push: getenv("GIT_PUSH", "true") == "true",
|
||||
}, srv.Reload)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
srv.Repo = rp
|
||||
|
||||
// SYNC LOOP
|
||||
// One goroutine does every pull, so webhook bursts coalesce: a trigger
|
||||
// that arrives while a pull is running queues exactly one more. Until
|
||||
// the first pull succeeds (Gitea may still be starting), it retries
|
||||
// every 30 seconds and /api/health reports not ready.
|
||||
trigger := make(chan struct{}, 1)
|
||||
srv.Pull = func() {
|
||||
select {
|
||||
case trigger <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
go syncLoop(rp, srv, trigger, duration("PULL_INTERVAL", 10*time.Minute))
|
||||
|
||||
r := gin.New()
|
||||
r.Use(gin.Logger(), gin.Recovery())
|
||||
// Nothing here keys on the client's IP, so no proxy is trusted to
|
||||
// report one.
|
||||
if err := r.SetTrustedProxies(nil); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
srv.Routes(r.Group(basePath + "/api"))
|
||||
r.NoRoute(handlers.SPA(staticDir, basePath))
|
||||
|
||||
addr := ":" + getenv("PORT", "8080")
|
||||
log.Printf("listening on %s%s/", addr, basePath)
|
||||
if err := r.Run(addr); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func syncLoop(rp *repo.Repo, srv *handlers.Server, trigger <-chan struct{}, interval time.Duration) {
|
||||
pull := func() bool {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||
defer cancel()
|
||||
if err := rp.Sync(ctx); err != nil {
|
||||
log.Printf("[sync] %v", err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
for !pull() {
|
||||
time.Sleep(30 * time.Second)
|
||||
}
|
||||
tick := time.NewTicker(interval)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-tick.C:
|
||||
case <-trigger:
|
||||
}
|
||||
pull()
|
||||
}
|
||||
}
|
||||
|
||||
func getenv(key, def string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
// duration reads a Go duration; an unparseable value is logged and the
|
||||
// default stands.
|
||||
func duration(key string, def time.Duration) time.Duration {
|
||||
v := os.Getenv(key)
|
||||
if v == "" {
|
||||
return def
|
||||
}
|
||||
d, err := time.ParseDuration(v)
|
||||
if err != nil || d <= 0 {
|
||||
log.Printf("%s=%q is not a duration; using %s", key, v, def)
|
||||
return def
|
||||
}
|
||||
return d
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
# Standalone development: the site serving THIS checkout's problems, with no
|
||||
# login (AUTH_MODE=dev, everyone is the admin). http://localhost:8080/usaco/
|
||||
#
|
||||
# docker compose up --build
|
||||
#
|
||||
# The repo root is mounted read-only at /seed and cloned from there, and
|
||||
# GIT_PUSH=false keeps edits made in the browser as commits in the
|
||||
# container's own clone (docker compose exec usaco git -C /data/repo log),
|
||||
# so nothing here can touch your working tree or the real remote. Only
|
||||
# committed work shows up: it is a clone, not the working tree.
|
||||
#
|
||||
# This is NOT how it runs in production. There it is one service in the main
|
||||
# site's docker-compose.yml, behind its nginx, cloning from Gitea and
|
||||
# borrowing the site's login; see README.md.
|
||||
services:
|
||||
usaco:
|
||||
build: .
|
||||
ports:
|
||||
- "8080:8080"
|
||||
environment:
|
||||
DEV_MODE: "true"
|
||||
AUTH_MODE: dev
|
||||
GIT_REMOTE_URL: file:///seed
|
||||
GIT_PUSH: "false"
|
||||
# The checkout belongs to your host user, which git refuses to read
|
||||
# from as a different uid unless told it is safe.
|
||||
GIT_CONFIG_COUNT: "1"
|
||||
GIT_CONFIG_KEY_0: safe.directory
|
||||
GIT_CONFIG_VALUE_0: "*"
|
||||
volumes:
|
||||
- ..:/seed:ro
|
||||
- usaco-data:/data
|
||||
|
||||
volumes:
|
||||
usaco-data:
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
module adam-french.co.uk/usaco-site
|
||||
|
||||
go 1.26
|
||||
|
||||
require github.com/gin-gonic/gin v1.11.0
|
||||
|
||||
require (
|
||||
github.com/bytedance/sonic v1.14.0 // indirect
|
||||
github.com/bytedance/sonic/loader v0.3.0 // indirect
|
||||
github.com/cloudwego/base64x v0.1.6 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.8 // indirect
|
||||
github.com/gin-contrib/sse v1.1.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.27.0 // indirect
|
||||
github.com/goccy/go-json v0.10.2 // indirect
|
||||
github.com/goccy/go-yaml v1.18.0 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
||||
github.com/quic-go/qpack v0.5.1 // indirect
|
||||
github.com/quic-go/quic-go v0.54.0 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.3.0 // indirect
|
||||
go.uber.org/mock v0.5.0 // indirect
|
||||
golang.org/x/arch v0.20.0 // indirect
|
||||
golang.org/x/crypto v0.40.0 // indirect
|
||||
golang.org/x/mod v0.25.0 // indirect
|
||||
golang.org/x/net v0.42.0 // indirect
|
||||
golang.org/x/sync v0.16.0 // indirect
|
||||
golang.org/x/sys v0.35.0 // indirect
|
||||
golang.org/x/text v0.27.0 // indirect
|
||||
golang.org/x/tools v0.34.0 // indirect
|
||||
google.golang.org/protobuf v1.36.9 // indirect
|
||||
)
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ=
|
||||
github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA=
|
||||
github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA=
|
||||
github.com/bytedance/sonic/loader v0.3.0/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI=
|
||||
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
|
||||
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=
|
||||
github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8=
|
||||
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
|
||||
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
|
||||
github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk=
|
||||
github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.27.0 h1:w8+XrWVMhGkxOaaowyKH35gFydVHOvC0/uWoy2Fzwn4=
|
||||
github.com/go-playground/validator/v10 v10.27.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo=
|
||||
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
||||
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
||||
github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw=
|
||||
github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI=
|
||||
github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg=
|
||||
github.com/quic-go/quic-go v0.54.0 h1:6s1YB9QotYI6Ospeiguknbp2Znb/jZYjZLRXn9kMQBg=
|
||||
github.com/quic-go/quic-go v0.54.0/go.mod h1:e68ZEaCdyviluZmy44P6Iey98v/Wfz6HCjQEm+l8zTY=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA=
|
||||
github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
|
||||
go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=
|
||||
go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM=
|
||||
golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c=
|
||||
golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk=
|
||||
golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM=
|
||||
golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY=
|
||||
golang.org/x/mod v0.25.0 h1:n7a+ZbQKQA/Ysbyb0/6IbB1H/X41mKgbhfv7AfG/44w=
|
||||
golang.org/x/mod v0.25.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww=
|
||||
golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs=
|
||||
golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=
|
||||
golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
|
||||
golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
|
||||
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4=
|
||||
golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU=
|
||||
golang.org/x/tools v0.34.0 h1:qIpSLOxeCYGg9TrcJokLBG4KFA6d795g0xkBkiESGlo=
|
||||
golang.org/x/tools v0.34.0/go.mod h1:pAP9OwEaY1CAW3HOmg3hLZC5Z0CCmzjAF2UQMSqNARg=
|
||||
google.golang.org/protobuf v1.36.9 h1:w2gp2mA27hUeUzj9Ex9FBjsBm40zfaDtEWow293U7Iw=
|
||||
google.golang.org/protobuf v1.36.9/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="description" content="Competitive programming practice: USACO and friends, with solutions." />
|
||||
<title>USACO practice</title>
|
||||
<link rel="icon" href="/img/favicon.ico" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+2177
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "usaco-site-web",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"highlight.js": "^11.11.1",
|
||||
"markdown-it": "^14.1.0",
|
||||
"vue": "^3.5.22",
|
||||
"vue-router": "^4.6.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/vite": "^4.1.18",
|
||||
"@vitejs/plugin-vue": "^6.0.1",
|
||||
"tailwindcss": "^4.1.18",
|
||||
"vite": "^7.3.2"
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,62 @@
|
||||
<script setup>
|
||||
/**
|
||||
* Root: the header with the page links, and the outlet.
|
||||
*/
|
||||
import { RouterLink, RouterView } from "vue-router";
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="shell">
|
||||
<header class="top">
|
||||
<RouterLink to="/" class="brand">USACO practice</RouterLink>
|
||||
<nav>
|
||||
<RouterLink to="/" exact-active-class="on">Problems</RouterLink>
|
||||
<RouterLink to="/stats" active-class="on">Stats</RouterLink>
|
||||
<a href="/">adam-french.co.uk</a>
|
||||
</nav>
|
||||
</header>
|
||||
<main>
|
||||
<RouterView />
|
||||
</main>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.shell {
|
||||
max-width: 1100px;
|
||||
margin: 0 auto;
|
||||
padding: 0 16px 48px;
|
||||
}
|
||||
.top {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 8px 24px;
|
||||
padding: 24px 0 16px;
|
||||
border-bottom: 1px solid var(--color-line);
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
.brand {
|
||||
font-family: var(--font-heading);
|
||||
font-size: 2.25rem;
|
||||
line-height: 1;
|
||||
letter-spacing: 0.02em;
|
||||
color: var(--color-ink);
|
||||
text-decoration: none;
|
||||
}
|
||||
nav {
|
||||
display: flex;
|
||||
gap: 20px;
|
||||
}
|
||||
nav a {
|
||||
color: var(--color-ink-muted);
|
||||
text-decoration: none;
|
||||
}
|
||||
nav a:hover,
|
||||
nav a.on {
|
||||
color: var(--color-ink);
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 4px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* The server's REST API (internal/handlers). Every call goes through
|
||||
* request(), which turns an error response into a thrown Error carrying the
|
||||
* server's message, and sends a refused admin action to the site's login.
|
||||
*/
|
||||
|
||||
import { goToLogin } from "./session";
|
||||
|
||||
const BASE = `${import.meta.env.BASE_URL}api`;
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(status, message) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
async function request(method, path, body) {
|
||||
const res = await fetch(BASE + path, {
|
||||
method,
|
||||
credentials: "same-origin",
|
||||
headers: body === undefined ? {} : { "Content-Type": "application/json" },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
if (res.status === 401) goToLogin();
|
||||
throw new ApiError(res.status, data.error || `request failed (${res.status})`);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
export const listProblems = () => request("GET", "/problems");
|
||||
export const getProblem = (name) => request("GET", `/problems/${encodeURIComponent(name)}`);
|
||||
export const updateMeta = (name, meta) => request("PUT", `/problems/${encodeURIComponent(name)}/meta`, meta);
|
||||
export const setStatus = (name, to) => request("POST", `/problems/${encodeURIComponent(name)}/status`, { to });
|
||||
export const getMe = () => request("GET", "/me");
|
||||
@@ -0,0 +1,215 @@
|
||||
/*
|
||||
* Global stylesheet: tokens, base elements, shared bits (badges, buttons)
|
||||
* and the code-highlighting colours.
|
||||
*
|
||||
* The palette and fonts are the job tracker's paper look (same fonts, copied
|
||||
* into public/fonts), so the two read as parts of one site. Tailwind is here
|
||||
* for its preflight reset; components use their own scoped <style> blocks.
|
||||
*/
|
||||
|
||||
@import "tailwindcss";
|
||||
|
||||
@font-face {
|
||||
font-family: "big_noodle_titling";
|
||||
src: url("/usaco/fonts/big_noodle_titling.woff2") format("woff2");
|
||||
font-weight: normal;
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "CreatoDisplay";
|
||||
src: url("/usaco/fonts/CreatoDisplay-Bold.woff2") format("woff2");
|
||||
font-weight: normal;
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
/* `static` = always emit these variables, because component <style> blocks
|
||||
reference them with var(). */
|
||||
@theme static {
|
||||
--color-ink: #111;
|
||||
--color-ink-soft: #333;
|
||||
--color-ink-muted: #555;
|
||||
--color-ink-faint: #8a8a8a;
|
||||
--color-ink-link: #0066cc;
|
||||
--color-ink-danger: #c00;
|
||||
--color-paper: #fff;
|
||||
--color-paper-tint: #f5f5f5;
|
||||
--color-paper-shade: #eee;
|
||||
--color-line: #ccc;
|
||||
--color-line-soft: #e0e0e0;
|
||||
|
||||
/* Status: identity, so always shown with its label, never colour alone. */
|
||||
--color-solved: #0a7d0a;
|
||||
--color-solving: #9a6700;
|
||||
--color-skipped: #777;
|
||||
|
||||
/* Sequential blue (dataviz reference ramp): the solve heatmap. */
|
||||
--color-seq-0: #ebebe8;
|
||||
--color-seq-1: #9ec5f4;
|
||||
--color-seq-2: #5598e7;
|
||||
--color-seq-3: #256abf;
|
||||
--color-seq-4: #0d366b;
|
||||
|
||||
--font-heading: "big_noodle_titling", sans-serif;
|
||||
--font-body: "CreatoDisplay", sans-serif;
|
||||
--font-mono: ui-monospace, "JetBrains Mono", "SF Mono", Menlo, Consolas, monospace;
|
||||
--default-font-family: var(--font-body);
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
overflow-x: hidden;
|
||||
background: var(--color-paper-tint);
|
||||
color: var(--color-ink);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
h1,
|
||||
h2,
|
||||
h3 {
|
||||
font-family: var(--font-heading);
|
||||
font-weight: normal;
|
||||
letter-spacing: 0.02em;
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
a {
|
||||
color: var(--color-ink-link);
|
||||
}
|
||||
|
||||
.card {
|
||||
background: var(--color-paper);
|
||||
border: 1px solid var(--color-line-soft);
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.badge {
|
||||
display: inline-block;
|
||||
padding: 1px 8px;
|
||||
border-radius: 999px;
|
||||
font-size: 0.75rem;
|
||||
border: 1px solid var(--color-line);
|
||||
color: var(--color-ink-muted);
|
||||
background: var(--color-paper);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.badge.solved {
|
||||
color: var(--color-solved);
|
||||
border-color: currentColor;
|
||||
}
|
||||
.badge.solving {
|
||||
color: var(--color-solving);
|
||||
border-color: currentColor;
|
||||
}
|
||||
.badge.skipped {
|
||||
color: var(--color-skipped);
|
||||
border-style: dashed;
|
||||
}
|
||||
|
||||
.btn {
|
||||
padding: 6px 14px;
|
||||
border: 1px solid var(--color-line);
|
||||
border-radius: 4px;
|
||||
background: var(--color-paper);
|
||||
color: var(--color-ink);
|
||||
cursor: pointer;
|
||||
}
|
||||
.btn:hover:not(:disabled) {
|
||||
border-color: var(--color-ink-muted);
|
||||
}
|
||||
.btn:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: default;
|
||||
}
|
||||
.btn.primary {
|
||||
background: var(--color-ink);
|
||||
border-color: var(--color-ink);
|
||||
color: var(--color-paper);
|
||||
}
|
||||
|
||||
.error {
|
||||
color: var(--color-ink-danger);
|
||||
}
|
||||
.muted {
|
||||
color: var(--color-ink-muted);
|
||||
}
|
||||
|
||||
/* highlight.js tokens, in the paper palette. */
|
||||
.hljs {
|
||||
color: var(--color-ink-soft);
|
||||
}
|
||||
.hljs-comment,
|
||||
.hljs-quote {
|
||||
color: #6a737d;
|
||||
font-style: italic;
|
||||
}
|
||||
.hljs-keyword,
|
||||
.hljs-selector-tag,
|
||||
.hljs-built_in,
|
||||
.hljs-meta .hljs-keyword {
|
||||
color: #a3268d;
|
||||
}
|
||||
.hljs-type,
|
||||
.hljs-title.class_ {
|
||||
color: #0b6e99;
|
||||
}
|
||||
.hljs-string,
|
||||
.hljs-meta .hljs-string {
|
||||
color: #1a7f37;
|
||||
}
|
||||
.hljs-number,
|
||||
.hljs-literal {
|
||||
color: #b35900;
|
||||
}
|
||||
.hljs-title.function_,
|
||||
.hljs-title {
|
||||
color: #5a3fc0;
|
||||
}
|
||||
.hljs-meta {
|
||||
color: #8250df;
|
||||
}
|
||||
.hljs-variable,
|
||||
.hljs-params {
|
||||
color: var(--color-ink-soft);
|
||||
}
|
||||
|
||||
/* Rendered notes (markdown-it). */
|
||||
.prose {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.prose > * + * {
|
||||
margin-top: 0.75em;
|
||||
}
|
||||
.prose h1,
|
||||
.prose h2,
|
||||
.prose h3 {
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
.prose ul {
|
||||
list-style: disc;
|
||||
padding-left: 1.5em;
|
||||
}
|
||||
.prose ol {
|
||||
list-style: decimal;
|
||||
padding-left: 1.5em;
|
||||
}
|
||||
.prose code {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.875em;
|
||||
background: var(--color-paper-shade);
|
||||
padding: 1px 4px;
|
||||
border-radius: 3px;
|
||||
}
|
||||
.prose pre {
|
||||
background: var(--color-paper-tint);
|
||||
padding: 12px;
|
||||
border-radius: 4px;
|
||||
overflow-x: auto;
|
||||
}
|
||||
.prose pre code {
|
||||
background: none;
|
||||
padding: 0;
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
<script setup>
|
||||
/**
|
||||
* A file with line numbers, highlighting and a copy button. Only the
|
||||
* languages the workspace uses are registered, which keeps highlight.js to a
|
||||
* few kilobytes instead of the full bundle.
|
||||
*/
|
||||
import { computed, ref } from "vue";
|
||||
import hljs from "highlight.js/lib/core";
|
||||
import cpp from "highlight.js/lib/languages/cpp";
|
||||
import python from "highlight.js/lib/languages/python";
|
||||
|
||||
hljs.registerLanguage("cpp", cpp);
|
||||
hljs.registerLanguage("c", cpp);
|
||||
hljs.registerLanguage("python", python);
|
||||
|
||||
const props = defineProps({
|
||||
content: { type: String, required: true },
|
||||
lang: { type: String, default: "" },
|
||||
truncated: { type: Boolean, default: false },
|
||||
});
|
||||
|
||||
// highlight.js escapes the source itself, so v-html on its output is safe.
|
||||
const html = computed(() => {
|
||||
const text = props.content.replace(/\n$/, "");
|
||||
if (props.lang && hljs.getLanguage(props.lang)) {
|
||||
return hljs.highlight(text, { language: props.lang }).value;
|
||||
}
|
||||
return text.replace(/[&<>]/g, (c) => ({ "&": "&", "<": "<", ">": ">" })[c]);
|
||||
});
|
||||
const lines = computed(() => props.content.replace(/\n$/, "").split("\n").length);
|
||||
|
||||
const copied = ref(false);
|
||||
async function copy() {
|
||||
try {
|
||||
await navigator.clipboard.writeText(props.content);
|
||||
copied.value = true;
|
||||
setTimeout(() => (copied.value = false), 1500);
|
||||
} catch {
|
||||
// Clipboard access refused (insecure context or permissions): nothing to do.
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="code">
|
||||
<button class="copy" type="button" @click="copy">{{ copied ? "Copied" : "Copy" }}</button>
|
||||
<div class="scroll">
|
||||
<pre class="gutter" aria-hidden="true">{{ Array.from({ length: lines }, (_, i) => i + 1).join("\n") }}</pre>
|
||||
<pre class="hljs src"><code v-html="html"></code></pre>
|
||||
</div>
|
||||
<p v-if="truncated" class="cut muted">Cut short: the file is larger than the site shows.</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.code {
|
||||
position: relative;
|
||||
background: var(--color-paper);
|
||||
border: 1px solid var(--color-line-soft);
|
||||
border-radius: 6px;
|
||||
}
|
||||
.scroll {
|
||||
display: flex;
|
||||
overflow-x: auto;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.8125rem;
|
||||
line-height: 1.55;
|
||||
}
|
||||
pre {
|
||||
margin: 0;
|
||||
padding: 12px 0;
|
||||
font-family: inherit;
|
||||
}
|
||||
.gutter {
|
||||
padding: 12px 10px 12px 12px;
|
||||
text-align: right;
|
||||
color: var(--color-ink-faint);
|
||||
user-select: none;
|
||||
border-right: 1px solid var(--color-line-soft);
|
||||
position: sticky;
|
||||
left: 0;
|
||||
background: var(--color-paper);
|
||||
}
|
||||
.src {
|
||||
padding-left: 12px;
|
||||
padding-right: 64px;
|
||||
}
|
||||
.copy {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
right: 8px;
|
||||
z-index: 1;
|
||||
padding: 2px 10px;
|
||||
font-size: 0.75rem;
|
||||
border: 1px solid var(--color-line);
|
||||
border-radius: 4px;
|
||||
background: var(--color-paper);
|
||||
color: var(--color-ink-muted);
|
||||
cursor: pointer;
|
||||
}
|
||||
.copy:hover {
|
||||
color: var(--color-ink);
|
||||
}
|
||||
.cut {
|
||||
padding: 6px 12px;
|
||||
font-size: 0.8rem;
|
||||
border-top: 1px solid var(--color-line-soft);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Small display helpers shared by the views.
|
||||
*/
|
||||
|
||||
export const STATUS_LABELS = { solving: "Solving", solved: "Solved", skipped: "Skipped" };
|
||||
|
||||
export const LANG_LABELS = { cpp: "C++", c: "C", python: "Python", java: "Java", rust: "Rust", go: "Go" };
|
||||
|
||||
// "diamond-collector" -> "Diamond Collector"
|
||||
export function title(name) {
|
||||
return name.replace(/[-_]+/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
|
||||
}
|
||||
|
||||
export function formatDate(iso, opts = { day: "numeric", month: "short", year: "numeric" }) {
|
||||
if (!iso) return "";
|
||||
return new Date(iso).toLocaleDateString(undefined, opts);
|
||||
}
|
||||
|
||||
// Local calendar day, "YYYY-MM-DD": the heatmap and streak count days where
|
||||
// the viewer is, not in UTC.
|
||||
export function dayKey(date) {
|
||||
const d = new Date(date);
|
||||
const p = (n) => String(n).padStart(2, "0");
|
||||
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* App entry point. Mounts <App> on #app with the router.
|
||||
*/
|
||||
|
||||
import { createApp } from "vue";
|
||||
import App from "./App.vue";
|
||||
import router from "./router";
|
||||
import "./assets/styles.css";
|
||||
|
||||
createApp(App).use(router).mount("#app");
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* Routes, under the app's base path (/usaco/, from vite.config.js).
|
||||
*
|
||||
* Everything is public; what the admin sees beyond solved problems is decided
|
||||
* by the server per request (the same URLs, more data), so there are no guards.
|
||||
*/
|
||||
|
||||
import { createRouter, createWebHistory } from "vue-router";
|
||||
|
||||
export default createRouter({
|
||||
history: createWebHistory(import.meta.env.BASE_URL),
|
||||
routes: [
|
||||
{ path: "/", name: "list", component: () => import("@/views/ProblemList.vue") },
|
||||
{ path: "/p/:name", name: "problem", component: () => import("@/views/ProblemPage.vue"), props: true },
|
||||
{ path: "/stats", name: "stats", component: () => import("@/views/StatsPage.vue") },
|
||||
{ path: "/:pathMatch(.*)*", redirect: "/" },
|
||||
],
|
||||
scrollBehavior: (to, from, saved) => saved || { top: 0 },
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* What to do when an admin action is refused.
|
||||
*
|
||||
* The site has no login of its own: it borrows the main site's session
|
||||
* (internal/auth on the server), as the job tracker does. By the time a
|
||||
* request is refused the server has already tried the site's refresh token,
|
||||
* so the only way back is the site's login page, which returns here after.
|
||||
*/
|
||||
|
||||
export function goToLogin() {
|
||||
const here = window.location.pathname + window.location.search;
|
||||
window.location.assign(`/admin/login?redirect=${encodeURIComponent(here)}`);
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
<script setup>
|
||||
/**
|
||||
* The problem list. Visitors see solved problems; the admin also sees what
|
||||
* is in progress or skipped (the server decides, this only shows the tabs
|
||||
* when there is something behind them). Filter and sort live in the query
|
||||
* string so a filtered view can be linked and survives the back button.
|
||||
*/
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { RouterLink, useRoute, useRouter } from "vue-router";
|
||||
import { listProblems } from "@/api";
|
||||
import { LANG_LABELS, STATUS_LABELS, formatDate, title } from "@/format";
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
|
||||
const problems = ref([]);
|
||||
const admin = ref(false);
|
||||
const loading = ref(true);
|
||||
const error = ref("");
|
||||
|
||||
const status = computed({
|
||||
get: () => route.query.status || "all",
|
||||
set: (v) => router.replace({ query: { ...route.query, status: v === "all" ? undefined : v } }),
|
||||
});
|
||||
const sort = computed({
|
||||
get: () => route.query.sort || "recent",
|
||||
set: (v) => router.replace({ query: { ...route.query, sort: v === "recent" ? undefined : v } }),
|
||||
});
|
||||
const search = computed({
|
||||
get: () => route.query.q || "",
|
||||
set: (v) => router.replace({ query: { ...route.query, q: v || undefined } }),
|
||||
});
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const data = await listProblems();
|
||||
problems.value = data.problems;
|
||||
admin.value = data.admin;
|
||||
} catch (e) {
|
||||
error.value = e.message;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
});
|
||||
|
||||
const counts = computed(() => {
|
||||
const c = { all: problems.value.length, solved: 0, solving: 0, skipped: 0 };
|
||||
for (const p of problems.value) c[p.status]++;
|
||||
return c;
|
||||
});
|
||||
|
||||
const tabs = computed(() =>
|
||||
admin.value ? ["all", "solving", "solved", "skipped"] : [],
|
||||
);
|
||||
|
||||
// When a problem was last worked on, for sorting: the solve date if it has
|
||||
// one, else its last commit.
|
||||
const when = (p) => p.solvedAt || p.lastTouched || "";
|
||||
|
||||
const shown = computed(() => {
|
||||
const q = search.value.trim().toLowerCase();
|
||||
const list = problems.value.filter(
|
||||
(p) =>
|
||||
(status.value === "all" || p.status === status.value) &&
|
||||
(!q || p.name.includes(q.replace(/\s+/g, "-")) || (p.source || "").toLowerCase().includes(q)),
|
||||
);
|
||||
if (sort.value === "name") return list.sort((a, b) => a.name.localeCompare(b.name));
|
||||
return list.sort((a, b) => when(b).localeCompare(when(a)) || a.name.localeCompare(b.name));
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section>
|
||||
<p v-if="!loading && !error" class="intro muted">
|
||||
{{ counts.solved }} solved problems from USACO and other judges, each with its solution and test cases.
|
||||
</p>
|
||||
|
||||
<div class="controls">
|
||||
<div v-if="tabs.length" class="tabs" role="tablist">
|
||||
<button
|
||||
v-for="t in tabs"
|
||||
:key="t"
|
||||
role="tab"
|
||||
:aria-selected="status === t"
|
||||
:class="{ on: status === t }"
|
||||
@click="status = t"
|
||||
>
|
||||
{{ t === "all" ? "All" : STATUS_LABELS[t] }} <span class="n">{{ counts[t] }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<input v-model="search" type="search" placeholder="Search problems" aria-label="Search problems" />
|
||||
<select v-model="sort" aria-label="Sort by">
|
||||
<option value="recent">Most recent</option>
|
||||
<option value="name">Name</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<p v-if="loading" class="muted">Loading…</p>
|
||||
<p v-else-if="error" class="error">{{ error }}</p>
|
||||
<p v-else-if="!shown.length" class="muted">Nothing matches.</p>
|
||||
|
||||
<ul v-else class="list">
|
||||
<li v-for="p in shown" :key="p.name">
|
||||
<RouterLink :to="{ name: 'problem', params: { name: p.name } }" class="row card">
|
||||
<div class="main">
|
||||
<span class="name">{{ title(p.name) }}</span>
|
||||
<span class="meta muted">
|
||||
<template v-if="p.langs.length">{{ p.langs.map((l) => LANG_LABELS[l] || l).join(", ") }}</template>
|
||||
<template v-if="p.tests"> · {{ p.tests }} test{{ p.tests === 1 ? "" : "s" }}</template>
|
||||
<template v-if="p.hasNotes"> · notes</template>
|
||||
</span>
|
||||
</div>
|
||||
<div class="side">
|
||||
<span v-if="p.source" class="badge">{{ p.source }}</span>
|
||||
<span v-if="admin || p.status !== 'solved'" class="badge" :class="p.status">{{ STATUS_LABELS[p.status] }}</span>
|
||||
<time v-if="when(p)" class="muted" :datetime="when(p)">{{ formatDate(when(p)) }}</time>
|
||||
</div>
|
||||
</RouterLink>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.intro {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.controls {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px 12px;
|
||||
align-items: center;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.tabs {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
margin-right: auto;
|
||||
}
|
||||
.tabs button {
|
||||
padding: 4px 12px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid transparent;
|
||||
color: var(--color-ink-muted);
|
||||
cursor: pointer;
|
||||
}
|
||||
.tabs button.on {
|
||||
border-color: var(--color-ink);
|
||||
color: var(--color-ink);
|
||||
background: var(--color-paper);
|
||||
}
|
||||
.tabs .n {
|
||||
color: var(--color-ink-faint);
|
||||
margin-left: 2px;
|
||||
}
|
||||
input,
|
||||
select {
|
||||
padding: 6px 10px;
|
||||
border: 1px solid var(--color-line);
|
||||
border-radius: 4px;
|
||||
background: var(--color-paper);
|
||||
min-width: 0;
|
||||
}
|
||||
input {
|
||||
flex: 1 1 200px;
|
||||
max-width: 320px;
|
||||
}
|
||||
.list {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
}
|
||||
.row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 8px 16px;
|
||||
padding: 12px 16px;
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
.row:hover {
|
||||
border-color: var(--color-ink-faint);
|
||||
}
|
||||
.main {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
}
|
||||
.name {
|
||||
font-size: 1.05rem;
|
||||
}
|
||||
.meta {
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
.side {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
time {
|
||||
min-width: 7.5em;
|
||||
text-align: right;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,323 @@
|
||||
<script setup>
|
||||
/**
|
||||
* One problem: its solution files, sample input, saved tests, notes and git
|
||||
* history. The admin also gets the status buttons and the link/notes editor;
|
||||
* each edit is a commit the server pushes, and the response is the problem
|
||||
* as it is afterwards, so the page just takes it.
|
||||
*/
|
||||
import { computed, ref, watch } from "vue";
|
||||
import { RouterLink } from "vue-router";
|
||||
import MarkdownIt from "markdown-it";
|
||||
import CodeBlock from "@/components/CodeBlock.vue";
|
||||
import { getMe, getProblem, setStatus, updateMeta } from "@/api";
|
||||
import { LANG_LABELS, STATUS_LABELS, formatDate, title } from "@/format";
|
||||
|
||||
const props = defineProps({ name: { type: String, required: true } });
|
||||
|
||||
// html: false — notes are rendered as markdown only, never as raw HTML.
|
||||
const md = new MarkdownIt({ html: false, linkify: true });
|
||||
|
||||
const problem = ref(null);
|
||||
const admin = ref(false);
|
||||
const loading = ref(true);
|
||||
const error = ref("");
|
||||
const activeFile = ref(0);
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
error.value = "";
|
||||
activeFile.value = 0;
|
||||
try {
|
||||
const [p, me] = await Promise.all([getProblem(props.name), getMe().catch(() => ({ admin: false }))]);
|
||||
problem.value = p;
|
||||
admin.value = me.admin;
|
||||
} catch (e) {
|
||||
problem.value = null;
|
||||
error.value = e.status === 404 ? "No such problem." : e.message;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
watch(() => props.name, load, { immediate: true });
|
||||
|
||||
const notesHtml = computed(() => (problem.value?.notes ? md.render(problem.value.notes) : ""));
|
||||
const file = computed(() => problem.value?.files[activeFile.value]);
|
||||
|
||||
// ---- admin edits ----
|
||||
const saving = ref(false);
|
||||
const editError = ref("");
|
||||
const editing = ref(false);
|
||||
const draftUrl = ref("");
|
||||
const draftNotes = ref("");
|
||||
|
||||
function startEdit() {
|
||||
draftUrl.value = problem.value.url || "";
|
||||
draftNotes.value = problem.value.notes || "";
|
||||
editError.value = "";
|
||||
editing.value = true;
|
||||
}
|
||||
|
||||
async function run(action) {
|
||||
saving.value = true;
|
||||
editError.value = "";
|
||||
try {
|
||||
problem.value = await action();
|
||||
return true;
|
||||
} catch (e) {
|
||||
editError.value = e.message;
|
||||
return false;
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function saveMeta() {
|
||||
if (await run(() => updateMeta(props.name, { url: draftUrl.value, notes: draftNotes.value }))) {
|
||||
editing.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const moves = computed(() => {
|
||||
const s = problem.value?.status;
|
||||
return [
|
||||
{ to: "solved", label: "Mark solved" },
|
||||
{ to: "skipped", label: "Skip" },
|
||||
{ to: "solving", label: "Reopen" },
|
||||
].filter((m) => m.to !== s);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<p v-if="loading" class="muted">Loading…</p>
|
||||
<div v-else-if="error">
|
||||
<p class="error">{{ error }}</p>
|
||||
<RouterLink to="/">Back to the list</RouterLink>
|
||||
</div>
|
||||
|
||||
<article v-else-if="problem" class="page">
|
||||
<header class="head">
|
||||
<RouterLink to="/" class="back">← All problems</RouterLink>
|
||||
<h1>{{ title(problem.name) }}</h1>
|
||||
<div class="facts">
|
||||
<span class="badge" :class="problem.status">{{ STATUS_LABELS[problem.status] }}</span>
|
||||
<a v-if="problem.url" :href="problem.url" target="_blank" rel="noopener noreferrer">
|
||||
{{ problem.source || "Problem statement" }} ↗
|
||||
</a>
|
||||
<span v-if="problem.solvedAt" class="muted">Solved {{ formatDate(problem.solvedAt) }}</span>
|
||||
<span v-else-if="problem.firstSeen" class="muted">Started {{ formatDate(problem.firstSeen) }}</span>
|
||||
<span v-if="problem.io" class="muted">File I/O: <code>{{ problem.io }}.in</code></span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section v-if="admin" class="admin card">
|
||||
<div class="admin-row">
|
||||
<span class="muted">Admin</span>
|
||||
<button v-for="m in moves" :key="m.to" class="btn" :disabled="saving" @click="run(() => setStatus(problem.name, m.to))">
|
||||
{{ m.label }}
|
||||
</button>
|
||||
<button v-if="!editing" class="btn" :disabled="saving" @click="startEdit">Edit link and notes</button>
|
||||
<span v-if="saving" class="muted">Saving to git…</span>
|
||||
</div>
|
||||
<form v-if="editing" class="editor" @submit.prevent="saveMeta">
|
||||
<label>
|
||||
Problem link
|
||||
<input v-model="draftUrl" type="url" placeholder="https://usaco.org/index.php?page=viewproblem2&cpid=…" />
|
||||
</label>
|
||||
<label>
|
||||
Notes (markdown)
|
||||
<textarea v-model="draftNotes" rows="8" placeholder="Approach, complexity, what tripped you up…"></textarea>
|
||||
</label>
|
||||
<div class="admin-row">
|
||||
<button class="btn primary" type="submit" :disabled="saving">Save</button>
|
||||
<button class="btn" type="button" :disabled="saving" @click="editing = false">Cancel</button>
|
||||
</div>
|
||||
</form>
|
||||
<p v-if="editError" class="error">{{ editError }}</p>
|
||||
</section>
|
||||
|
||||
<section v-if="notesHtml" class="notes card prose" v-html="notesHtml"></section>
|
||||
|
||||
<section>
|
||||
<h2>Solution</h2>
|
||||
<p v-if="!problem.files.length" class="muted">No solution file yet.</p>
|
||||
<template v-else>
|
||||
<div v-if="problem.files.length > 1" class="file-tabs" role="tablist">
|
||||
<button
|
||||
v-for="(f, i) in problem.files"
|
||||
:key="f.name"
|
||||
role="tab"
|
||||
:aria-selected="i === activeFile"
|
||||
:class="{ on: i === activeFile }"
|
||||
@click="activeFile = i"
|
||||
>
|
||||
{{ f.name }} <span class="muted">{{ LANG_LABELS[f.lang] || f.lang }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<p v-else class="filename muted">{{ file.name }}</p>
|
||||
<CodeBlock :key="file.name" :content="file.content" :lang="file.lang" :truncated="file.truncated" />
|
||||
</template>
|
||||
</section>
|
||||
|
||||
<section v-if="problem.sample">
|
||||
<h2>Sample input</h2>
|
||||
<p class="filename muted">{{ problem.sample.name }}</p>
|
||||
<CodeBlock :content="problem.sample.content" :truncated="problem.sample.truncated" />
|
||||
</section>
|
||||
|
||||
<section v-if="problem.testCases.length">
|
||||
<h2>Tests</h2>
|
||||
<details v-for="t in problem.testCases" :key="t.name" class="test card">
|
||||
<summary>Test {{ t.name }}</summary>
|
||||
<div class="io">
|
||||
<div>
|
||||
<p class="filename muted">Input</p>
|
||||
<CodeBlock :content="t.input.content" :truncated="t.input.truncated" />
|
||||
</div>
|
||||
<div>
|
||||
<p class="filename muted">Expected output</p>
|
||||
<CodeBlock v-if="t.output" :content="t.output.content" :truncated="t.output.truncated" />
|
||||
<p v-else class="muted">Not saved.</p>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
</section>
|
||||
|
||||
<section v-if="problem.history.length">
|
||||
<h2>History</h2>
|
||||
<ol class="history">
|
||||
<li v-for="c in problem.history" :key="c.hash">
|
||||
<time :datetime="c.date" class="muted">{{ formatDate(c.date) }}</time>
|
||||
<span>{{ c.subject }}</span>
|
||||
<code class="muted">{{ c.hash.slice(0, 7) }}</code>
|
||||
</li>
|
||||
</ol>
|
||||
</section>
|
||||
</article>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.page {
|
||||
display: grid;
|
||||
gap: 28px;
|
||||
min-width: 0;
|
||||
}
|
||||
.page > section {
|
||||
min-width: 0;
|
||||
}
|
||||
.back {
|
||||
font-size: 0.875rem;
|
||||
color: var(--color-ink-muted);
|
||||
text-decoration: none;
|
||||
}
|
||||
.back:hover {
|
||||
color: var(--color-ink);
|
||||
}
|
||||
h1 {
|
||||
font-size: 2.75rem;
|
||||
margin: 6px 0 10px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
h2 {
|
||||
font-size: 1.6rem;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.facts {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px 16px;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
.facts code,
|
||||
.history code {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.85em;
|
||||
}
|
||||
.admin {
|
||||
padding: 12px 16px;
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
}
|
||||
.admin-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.editor {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
}
|
||||
.editor label {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
font-size: 0.875rem;
|
||||
color: var(--color-ink-muted);
|
||||
}
|
||||
.editor input,
|
||||
.editor textarea {
|
||||
padding: 8px 10px;
|
||||
border: 1px solid var(--color-line);
|
||||
border-radius: 4px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.85rem;
|
||||
color: var(--color-ink);
|
||||
background: var(--color-paper);
|
||||
}
|
||||
.notes {
|
||||
padding: 16px 20px;
|
||||
}
|
||||
.file-tabs {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.file-tabs button {
|
||||
padding: 4px 12px;
|
||||
border: 1px solid var(--color-line-soft);
|
||||
border-radius: 4px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.8rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.file-tabs button.on {
|
||||
border-color: var(--color-ink);
|
||||
background: var(--color-paper);
|
||||
}
|
||||
.filename {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.8rem;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.test {
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.test summary {
|
||||
padding: 8px 14px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.io {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
|
||||
gap: 12px;
|
||||
padding: 0 14px 14px;
|
||||
min-width: 0;
|
||||
}
|
||||
.io > div {
|
||||
min-width: 0;
|
||||
}
|
||||
.history {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
.history li {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px 12px;
|
||||
}
|
||||
.history time {
|
||||
min-width: 7.5em;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,345 @@
|
||||
<script setup>
|
||||
/**
|
||||
* Solve statistics, computed in the browser from the problem list: the
|
||||
* headline counts, a year of solves as a calendar heatmap, and the same data
|
||||
* by month as a table (the heatmap's accessible equivalent).
|
||||
*
|
||||
* Days are the viewer's local days (format.dayKey). The solve date is the
|
||||
* commit that moved a problem into solved/, so a batch of problems committed
|
||||
* together lands on one day.
|
||||
*/
|
||||
import { computed, nextTick, onMounted, ref } from "vue";
|
||||
import { RouterLink } from "vue-router";
|
||||
import { listProblems } from "@/api";
|
||||
import { dayKey, formatDate, title } from "@/format";
|
||||
|
||||
const problems = ref([]);
|
||||
const loading = ref(true);
|
||||
const error = ref("");
|
||||
const scroller = ref(null);
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
problems.value = (await listProblems()).problems;
|
||||
} catch (e) {
|
||||
error.value = e.message;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
// Start the heatmap at today's end on narrow screens.
|
||||
await nextTick();
|
||||
if (scroller.value) scroller.value.scrollLeft = scroller.value.scrollWidth;
|
||||
});
|
||||
|
||||
const solved = computed(() => problems.value.filter((p) => p.status === "solved" && p.solvedAt));
|
||||
|
||||
// day key -> names solved that day
|
||||
const byDay = computed(() => {
|
||||
const m = new Map();
|
||||
for (const p of solved.value) {
|
||||
const k = dayKey(p.solvedAt);
|
||||
if (!m.has(k)) m.set(k, []);
|
||||
m.get(k).push(p.name);
|
||||
}
|
||||
return m;
|
||||
});
|
||||
|
||||
const DAY = 86400000;
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
|
||||
function addDays(d, n) {
|
||||
const x = new Date(d);
|
||||
x.setDate(x.getDate() + n);
|
||||
return x;
|
||||
}
|
||||
|
||||
const streaks = computed(() => {
|
||||
const days = [...byDay.value.keys()].sort();
|
||||
let longest = 0;
|
||||
let run = 0;
|
||||
let prev = null;
|
||||
for (const k of days) {
|
||||
const d = new Date(k + "T00:00:00");
|
||||
run = prev && Math.round((d - prev) / DAY) === 1 ? run + 1 : 1;
|
||||
longest = Math.max(longest, run);
|
||||
prev = d;
|
||||
}
|
||||
// The current streak may end yesterday: today is not over yet.
|
||||
let current = 0;
|
||||
let d = byDay.value.has(dayKey(today)) ? today : addDays(today, -1);
|
||||
while (byDay.value.has(dayKey(d))) {
|
||||
current++;
|
||||
d = addDays(d, -1);
|
||||
}
|
||||
return { current, longest };
|
||||
});
|
||||
|
||||
const recent = (days) => solved.value.filter((p) => new Date(p.solvedAt) >= addDays(today, -days + 1)).length;
|
||||
|
||||
const tiles = computed(() => [
|
||||
{ label: "Solved", value: solved.value.length },
|
||||
{ label: "Last 30 days", value: recent(30) },
|
||||
{ label: "Current streak", value: streaks.value.current, unit: streaks.value.current === 1 ? "day" : "days" },
|
||||
{ label: "Longest streak", value: streaks.value.longest, unit: streaks.value.longest === 1 ? "day" : "days" },
|
||||
]);
|
||||
|
||||
// ---- heatmap: 53 weeks ending this week, Monday-first rows ----
|
||||
const CELL = 12;
|
||||
const GAP = 2; // surface gap between cells
|
||||
const LEFT = 28; // weekday labels
|
||||
const TOP = 18; // month labels
|
||||
const WEEKS = 53;
|
||||
|
||||
const start = computed(() => {
|
||||
const dow = (today.getDay() + 6) % 7; // 0 = Monday
|
||||
return addDays(today, -dow - (WEEKS - 1) * 7);
|
||||
});
|
||||
|
||||
const cells = computed(() => {
|
||||
const out = [];
|
||||
for (let w = 0; w < WEEKS; w++) {
|
||||
for (let d = 0; d < 7; d++) {
|
||||
const date = addDays(start.value, w * 7 + d);
|
||||
if (date > today) continue;
|
||||
const names = byDay.value.get(dayKey(date)) || [];
|
||||
out.push({ key: dayKey(date), date, names, x: LEFT + w * (CELL + GAP), y: TOP + d * (CELL + GAP) });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
});
|
||||
|
||||
const months = computed(() => {
|
||||
const out = [];
|
||||
let last = -1;
|
||||
for (let w = 0; w < WEEKS; w++) {
|
||||
const d = addDays(start.value, w * 7);
|
||||
if (d.getMonth() !== last) {
|
||||
last = d.getMonth();
|
||||
// Skip a label squeezed into the first partial column.
|
||||
if (w > 0 || d.getDate() <= 7) {
|
||||
out.push({ x: LEFT + w * (CELL + GAP), label: d.toLocaleDateString(undefined, { month: "short" }) });
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
});
|
||||
|
||||
const width = LEFT + WEEKS * (CELL + GAP);
|
||||
const height = TOP + 7 * (CELL + GAP);
|
||||
|
||||
// Sequential steps: 0 is the empty-day neutral, 4 is "4 or more".
|
||||
const level = (n) => Math.min(n, 4);
|
||||
|
||||
const hover = ref(null);
|
||||
function show(c, ev) {
|
||||
const box = ev.currentTarget.closest(".heat").getBoundingClientRect();
|
||||
const r = ev.currentTarget.getBoundingClientRect();
|
||||
hover.value = { ...c, left: r.left - box.left + r.width / 2, top: r.top - box.top };
|
||||
}
|
||||
|
||||
// ---- monthly table ----
|
||||
const monthly = computed(() => {
|
||||
const m = new Map();
|
||||
for (const p of solved.value) {
|
||||
const d = new Date(p.solvedAt);
|
||||
const k = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
|
||||
if (!m.has(k)) m.set(k, { key: k, date: new Date(d.getFullYear(), d.getMonth(), 1), names: [] });
|
||||
m.get(k).names.push(p.name);
|
||||
}
|
||||
return [...m.values()].sort((a, b) => b.key.localeCompare(a.key));
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<p v-if="loading" class="muted">Loading…</p>
|
||||
<p v-else-if="error" class="error">{{ error }}</p>
|
||||
|
||||
<div v-else class="stats">
|
||||
<div class="tiles">
|
||||
<div v-for="t in tiles" :key="t.label" class="tile card">
|
||||
<span class="label muted">{{ t.label }}</span>
|
||||
<span class="value">{{ t.value }}<small v-if="t.unit" class="muted"> {{ t.unit }}</small></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section>
|
||||
<h2>Solves in the last year</h2>
|
||||
<div class="heat card" @mouseleave="hover = null">
|
||||
<div ref="scroller" class="heat-scroll">
|
||||
<svg :width="width" :height="height" role="img" :aria-label="`Calendar of solves over the last year; ${solved.length} in total. The table below lists them by month.`">
|
||||
<text v-for="m in months" :key="m.x" :x="m.x" y="11" class="axis">{{ m.label }}</text>
|
||||
<text v-for="(d, i) in ['Mon', '', 'Wed', '', 'Fri', '', '']" :key="i" x="0" :y="TOP + i * (CELL + GAP) + CELL - 2" class="axis">{{ d }}</text>
|
||||
<rect
|
||||
v-for="c in cells"
|
||||
:key="c.key"
|
||||
:x="c.x"
|
||||
:y="c.y"
|
||||
:width="CELL"
|
||||
:height="CELL"
|
||||
rx="2"
|
||||
:class="['cell', `l${level(c.names.length)}`, { hot: hover && hover.key === c.key }]"
|
||||
@mouseenter="show(c, $event)"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<div class="legend muted" aria-hidden="true">
|
||||
Less
|
||||
<svg v-for="l in [0, 1, 2, 3, 4]" :key="l" width="12" height="12"><rect width="12" height="12" rx="2" :class="['cell', `l${l}`]" /></svg>
|
||||
More
|
||||
</div>
|
||||
<div v-if="hover" class="tip" :style="{ left: hover.left + 'px', top: hover.top + 'px' }">
|
||||
<strong>{{ hover.names.length || "No" }} solve{{ hover.names.length === 1 ? "" : "s" }}</strong>
|
||||
<span class="muted">{{ formatDate(hover.date, { weekday: "short", day: "numeric", month: "short", year: "numeric" }) }}</span>
|
||||
<span v-for="n in hover.names.slice(0, 6)" :key="n">{{ title(n) }}</span>
|
||||
<span v-if="hover.names.length > 6" class="muted">and {{ hover.names.length - 6 }} more</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>By month</h2>
|
||||
<table v-if="monthly.length" class="card">
|
||||
<thead>
|
||||
<tr><th scope="col">Month</th><th scope="col" class="num">Solved</th><th scope="col">Problems</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="m in monthly" :key="m.key">
|
||||
<td>{{ formatDate(m.date, { month: "long", year: "numeric" }) }}</td>
|
||||
<td class="num">{{ m.names.length }}</td>
|
||||
<td class="names">
|
||||
<template v-for="(n, i) in m.names" :key="n">
|
||||
<RouterLink :to="{ name: 'problem', params: { name: n } }">{{ title(n) }}</RouterLink><span v-if="i < m.names.length - 1">, </span>
|
||||
</template>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p v-else class="muted">Nothing solved yet.</p>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.stats {
|
||||
display: grid;
|
||||
gap: 28px;
|
||||
min-width: 0;
|
||||
}
|
||||
.stats > section {
|
||||
min-width: 0;
|
||||
}
|
||||
h2 {
|
||||
font-size: 1.6rem;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.tiles {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
.tile {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 14px 16px;
|
||||
}
|
||||
.label {
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
.value {
|
||||
font-family: var(--font-heading);
|
||||
font-size: 2.75rem;
|
||||
line-height: 1.1;
|
||||
}
|
||||
.value small {
|
||||
margin-left: 0.3em;
|
||||
font-family: var(--font-body);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
.heat {
|
||||
position: relative;
|
||||
padding: 14px 16px 10px;
|
||||
}
|
||||
.heat-scroll {
|
||||
overflow-x: auto;
|
||||
}
|
||||
svg {
|
||||
display: block;
|
||||
}
|
||||
.axis {
|
||||
font-size: 10px;
|
||||
fill: var(--color-ink-faint);
|
||||
}
|
||||
.cell {
|
||||
fill: var(--color-seq-0);
|
||||
}
|
||||
.cell.l1 {
|
||||
fill: var(--color-seq-1);
|
||||
}
|
||||
.cell.l2 {
|
||||
fill: var(--color-seq-2);
|
||||
}
|
||||
.cell.l3 {
|
||||
fill: var(--color-seq-3);
|
||||
}
|
||||
.cell.l4 {
|
||||
fill: var(--color-seq-4);
|
||||
}
|
||||
.cell.hot {
|
||||
stroke: var(--color-ink);
|
||||
stroke-width: 1.5;
|
||||
}
|
||||
.legend {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 3px;
|
||||
margin-top: 8px;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
.tip {
|
||||
position: absolute;
|
||||
transform: translate(-50%, calc(-100% - 8px));
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
padding: 8px 10px;
|
||||
background: var(--color-paper);
|
||||
border: 1px solid var(--color-line);
|
||||
border-radius: 4px;
|
||||
box-shadow: 0 2px 8px rgb(0 0 0 / 0.12);
|
||||
font-size: 0.8rem;
|
||||
white-space: nowrap;
|
||||
pointer-events: none;
|
||||
z-index: 2;
|
||||
}
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
th,
|
||||
td {
|
||||
text-align: left;
|
||||
padding: 8px 12px;
|
||||
border-bottom: 1px solid var(--color-line-soft);
|
||||
vertical-align: top;
|
||||
}
|
||||
th {
|
||||
font-weight: normal;
|
||||
color: var(--color-ink-muted);
|
||||
}
|
||||
tr:last-child td {
|
||||
border-bottom: none;
|
||||
}
|
||||
.num {
|
||||
text-align: right;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.names {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
td:first-child {
|
||||
white-space: nowrap;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,26 @@
|
||||
import { fileURLToPath, URL } from "node:url";
|
||||
|
||||
import { defineConfig } from "vite";
|
||||
import tailwindcss from "@tailwindcss/vite";
|
||||
import vue from "@vitejs/plugin-vue";
|
||||
|
||||
// The app is served under /usaco/ (BASE_PATH on the server), so every asset
|
||||
// URL and the router's history base carry it. Changing one means changing both.
|
||||
//
|
||||
// `npm run dev` proxies the API to the Go server: VITE_PROXY_USACO (default
|
||||
// localhost:8080, the standalone docker-compose).
|
||||
export default defineConfig({
|
||||
base: "/usaco/",
|
||||
plugins: [vue(), tailwindcss()],
|
||||
resolve: {
|
||||
alias: {
|
||||
"@": fileURLToPath(new URL("./src", import.meta.url)),
|
||||
},
|
||||
},
|
||||
server: {
|
||||
host: "0.0.0.0",
|
||||
proxy: {
|
||||
"/usaco/api": process.env.VITE_PROXY_USACO || "http://localhost:8080",
|
||||
},
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user