Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0b6b40eed8 |
No files matched your search
@@ -0,0 +1,49 @@
|
||||
# .forker.yaml — per-fork configuration for Repo Forker.
|
||||
#
|
||||
# The upstream URL and its token are NOT set here. They are set in the Gitea UI:
|
||||
# Settings -> Actions -> Variables & Secrets
|
||||
# UPSTREAM_URL = https://github.com/owner/repo.git (any provider)
|
||||
# UPSTREAM_TOKEN = <token that can read the upstream>
|
||||
# This keeps secrets out of the repo. Everything below is non-secret.
|
||||
#
|
||||
# All values are optional; sensible defaults apply when a key is absent.
|
||||
|
||||
# (unused — Bearer auth needs no username; retained for compatibility)
|
||||
token_user: oauth2
|
||||
|
||||
# Mirror all tags (true/false). Default: true
|
||||
mirror_tags: true
|
||||
|
||||
# Prune branches that were deleted upstream (true/false). Default: true
|
||||
mirror_prune: true
|
||||
|
||||
# Which upstream branches to mirror. "*" = all (default).
|
||||
# Comma-separated list to restrict, e.g. "main,develop" (stray spaces
|
||||
# tolerated). NOTE: pruning is always checked against the FULL upstream
|
||||
# branch set, so a branch outside this filter but still upstream is never
|
||||
# deleted.
|
||||
mirror_branches: "*"
|
||||
|
||||
# When a new upstream tag is mirrored, automatically build + publish a release
|
||||
# on this Gitea (true/false). Default: true
|
||||
on_new_tag: true
|
||||
|
||||
# Also mirror the upstream's existing releases (metadata + assets) via the
|
||||
# provider API (true/false). Default: false
|
||||
mirror_upstream_releases: false
|
||||
|
||||
# Build commands run inside the tag's working tree to produce release assets.
|
||||
# Multiple commands are ';'-separated. Leave empty to skip the local build and
|
||||
# only mirror upstream release assets.
|
||||
# build_cmd: "make && go build -o dist/app ."
|
||||
build_cmd: ""
|
||||
|
||||
# Optional: point to a custom build script (path relative to the forker branch)
|
||||
# instead of build_cmd. If set, build_cmd is ignored.
|
||||
# build_script: "forker/build-custom.sh"
|
||||
build_script: ""
|
||||
|
||||
# Artifacts to attach to the locally-built release. Space-separated globs,
|
||||
# relative to the tag's working tree.
|
||||
# artifacts: "dist/*"
|
||||
artifacts: ""
|
||||
@@ -0,0 +1,38 @@
|
||||
name: Repo Forker — Release (build + publish)
|
||||
|
||||
# Produces a release on this Gitea fork. Two modes (see .forker.yaml):
|
||||
# BUILD — checkout the tag's working tree, run the configured build command,
|
||||
# publish the release (tag + assets) on this Gitea.
|
||||
# MIRROR — mirror the upstream's existing release (metadata + assets).
|
||||
#
|
||||
# NOTE: this workflow is triggered MANUALLY from the UI (workflow_dispatch).
|
||||
# Automatic releases on new tags are handled INLINE by sync.sh, because a
|
||||
# mirrored tag points at an upstream commit whose tree has no .gitea/workflows,
|
||||
# so a "push: tags" trigger would never find this file. See sync.sh.
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'Tag to release'
|
||||
required: true
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Run release
|
||||
run: |
|
||||
export GITEA_REPO="${GITEA_OWNER_REPO##*/}"
|
||||
bash forker/release.sh "$TAG"
|
||||
env:
|
||||
GITEA_SERVER_URL: ${{ gitea.server_url }}
|
||||
GITEA_OWNER: ${{ gitea.repository_owner }}
|
||||
GITEA_OWNER_REPO: ${{ gitea.repository }}
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
UPSTREAM_URL: ${{ vars.UPSTREAM_URL }}
|
||||
UPSTREAM_TOKEN: ${{ secrets.UPSTREAM_TOKEN }}
|
||||
TAG: ${{ inputs.tag }}
|
||||
@@ -0,0 +1,35 @@
|
||||
name: Repo Forker — Runner check
|
||||
|
||||
# Verifies a runner is available for this repo before relying on the cron sync
|
||||
# and local builds. Run it once after forking (or when a sync run is "pending"
|
||||
# for a long time — that usually means no runner is registered for this repo).
|
||||
#
|
||||
# In this Gitea build, runners are repo-scoped: a runner registered on one repo
|
||||
# does NOT serve another. Register a runner for this repo (see README, "Runner").
|
||||
|
||||
on:
|
||||
workflow_dispatch: {}
|
||||
|
||||
jobs:
|
||||
check:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Confirm a runner picked this job up
|
||||
run: |
|
||||
echo "A runner is online and serving this job."
|
||||
echo "OS=$RUNNER_OS Arch=$RUNNER_ARCH"
|
||||
|
||||
- name: Which runner(s) serve this repo
|
||||
env:
|
||||
GITEA_SERVER_URL: ${{ gitea.server_url }}
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
run: |
|
||||
# The repo-level API does NOT list shared runners, so check the
|
||||
# shared (instance) list too and report which serves the repo.
|
||||
# (The Gitea Actions token has admin scope in this setup; with a
|
||||
# plain repo token the admin call 403s and we say so, not hide it.)
|
||||
curl -sS --max-time 20 -H "Authorization: Bearer $GITEA_TOKEN" \
|
||||
"$GITEA_SERVER_URL/api/v1/repos/${GITEA_OWNER}/${GITEA_REPO}/actions/runners" > /tmp/repo_runners.json
|
||||
curl -sS --max-time 20 -H "Authorization: Bearer $GITEA_TOKEN" \
|
||||
"$GITEA_SERVER_URL/api/v1/admin/actions/runners?limit=50" > /tmp/shared_runners.json
|
||||
python3 -c 'import json; R=json.load(open("/tmp/repo_runners.json")).get("runners",[]); S=[r for r in json.load(open("/tmp/shared_runners.json")).get("runners",[]) if r.get("shared")]; print("Repo-scoped runners: "+(", ".join("%s (%s)"%(r["name"],r["status"]) for r in R) or "(none)")); print("Shared runners: "+(", ".join("%s (%s)"%(r["name"],r["status"]) for r in S) or "(none)")); print("OK: a runner serves this repo." if (R or S) else "WARNING: no runner (repo-scoped or shared) registered - cron runs will stay queued.")'
|
||||
@@ -0,0 +1,82 @@
|
||||
name: Repo Forker — Sync (mirror upstream)
|
||||
|
||||
# Periodically mirrors the upstream repo (all branches, tags, full history) into
|
||||
# this Gitea fork. This is the "worker" job.
|
||||
#
|
||||
# One-time setup (Gitea UI):
|
||||
# Settings -> Actions -> Variables & Secrets
|
||||
# UPSTREAM_URL = https://github.com/owner/repo.git (any provider)
|
||||
# UPSTREAM_TOKEN = <secret: token that can read the upstream>
|
||||
# GITEA_* values below are injected automatically by Gitea Actions.
|
||||
|
||||
on:
|
||||
schedule:
|
||||
# "very periodically" — every 10 minutes. Tune to taste (5-field cron).
|
||||
- cron: '*/10 * * * *'
|
||||
workflow_dispatch: {} # manual trigger from the UI
|
||||
push:
|
||||
branches: [forker] # re-sync when the forker config changes
|
||||
|
||||
jobs:
|
||||
sync:
|
||||
runs-on: ubuntu-latest
|
||||
# A cold full-history fetch can exceed the 10-min cron interval (or a
|
||||
# push/dispatch can land mid-run); without this, two overlapping runs
|
||||
# both see the same tag as "missing release" and both build/publish —
|
||||
# duplicate releases + double builds. Serialize per repo (do NOT
|
||||
# cancel-in-progress: an in-flight sync must finish).
|
||||
concurrency:
|
||||
group: sync-${{ gitea.repository }}
|
||||
steps:
|
||||
# A repo without UPSTREAM_URL (e.g. the template itself) is not a mirror:
|
||||
# skip the whole job with a notice instead of failing.
|
||||
- name: Upstream configured?
|
||||
id: check
|
||||
env:
|
||||
UPSTREAM_URL: ${{ vars.UPSTREAM_URL }}
|
||||
run: |
|
||||
if [ -z "$UPSTREAM_URL" ]; then
|
||||
echo "::notice::UPSTREAM_URL is not set — this repo is not configured as a mirror (e.g. the template). No-op."
|
||||
echo "configured=false" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "configured=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Checkout
|
||||
if: steps.check.outputs.configured == 'true'
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Restore mirror cache
|
||||
if: steps.check.outputs.configured == 'true'
|
||||
uses: actions/cache@v4
|
||||
continue-on-error: true # no cache service configured? continue cold — still correct
|
||||
with:
|
||||
path: .mirror
|
||||
# Unique per run so saves never conflict; restore-keys pulls the most
|
||||
# recent saved mirror (incremental fetch). No cache → full fetch, still
|
||||
# correct.
|
||||
key: forker-mirror-${{ github.run_id }}
|
||||
restore-keys: |
|
||||
forker-mirror-
|
||||
|
||||
- name: Show config
|
||||
if: steps.check.outputs.configured == 'true'
|
||||
run: |
|
||||
echo "UPSTREAM_URL=${UPSTREAM_URL:?set in Gitea UI (Variables & Secrets)}"
|
||||
echo "Gitea repo: ${{ gitea.repository }}"
|
||||
env:
|
||||
UPSTREAM_URL: ${{ vars.UPSTREAM_URL }}
|
||||
|
||||
- name: Run sync
|
||||
if: steps.check.outputs.configured == 'true'
|
||||
run: |
|
||||
# gitea.repository is "owner/repo"; extract just the repo name.
|
||||
export GITEA_REPO="${GITEA_OWNER_REPO##*/}"
|
||||
bash forker/sync.sh
|
||||
env:
|
||||
GITEA_SERVER_URL: ${{ gitea.server_url }}
|
||||
GITEA_OWNER: ${{ gitea.repository_owner }}
|
||||
GITEA_OWNER_REPO: ${{ gitea.repository }}
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
UPSTREAM_URL: ${{ vars.UPSTREAM_URL }}
|
||||
UPSTREAM_TOKEN: ${{ secrets.UPSTREAM_TOKEN }}
|
||||
@@ -0,0 +1,23 @@
|
||||
# The bare mirror holds upstream objects; never commit it.
|
||||
.mirror/
|
||||
|
||||
# Local runner config (contains tokens) — but KEEP runner/docker-compose.yml
|
||||
# tracked, otherwise a fresh fork has no documented runner setup at all.
|
||||
# (The runner/_svc_*.go files are untracked Gitea-source scratch snippets.)
|
||||
runner/config/
|
||||
runner/_svc_*.go
|
||||
*.runner.conf
|
||||
|
||||
# OS / editor noise
|
||||
.DS_Store
|
||||
*.swp
|
||||
.idea/
|
||||
.vscode/
|
||||
|
||||
# stray binaries that are never part of this template
|
||||
*.AppImage
|
||||
*.appimage
|
||||
.superdesign/
|
||||
ui/node_modules/
|
||||
ui/dist/
|
||||
ui/*.log
|
||||
@@ -0,0 +1,151 @@
|
||||
# AGENTS.md — how to operate Repo Forker
|
||||
|
||||
Instructions for AI agents (and humans) working on or with this repository.
|
||||
|
||||
## What this is
|
||||
|
||||
A **template**. Each fork/generation of it is a *live mirror* of one upstream
|
||||
git repo on this Gitea: all branches, all tags, full history, plus releases
|
||||
produced on the runner. The working tree (the `forker` branch) holds only the
|
||||
machinery — the upstream's content never enters it.
|
||||
|
||||
```
|
||||
This repo (template) → fork/generate per upstream (Lago/<upstream>)
|
||||
├── forker branch ← scripts, config, workflows
|
||||
├── .mirror/ ← bare mirror (gitignored)
|
||||
└── refs ← upstream branches + tags
|
||||
```
|
||||
|
||||
## Golden rules (non-negotiable)
|
||||
|
||||
1. **Never authenticate to upstreams with the operator's personal accounts or
|
||||
stored credentials.** Public upstreams are fetched **anonymously**:
|
||||
`sync.sh`/`release.sh` cut `GIT_CONFIG_GLOBAL`/`GIT_CONFIG_SYSTEM` and the
|
||||
credential helper before any upstream git call, and add a Bearer header
|
||||
**only** when `UPSTREAM_TOKEN` is explicitly set. Do not "simplify" this
|
||||
away — a `credential.helper=store` entry must never be offered to
|
||||
`git fetch`. Do not pass tokens from `~/.git-credentials` into the tool.
|
||||
2. **An empty token must mean "no auth header", not "Bearer <empty>".**
|
||||
GitHub rejects empty Bearer headers (401). All code paths (git
|
||||
`extraHeader`, `provider.sh` curl calls) must branch on token presence.
|
||||
3. **Secrets live in Gitea Actions Variables/Secrets, never in the repo.**
|
||||
`UPSTREAM_URL` (variable) and `UPSTREAM_TOKEN` (secret, optional). The
|
||||
`GITEA_*` values are injected by Gitea Actions automatically.
|
||||
4. **Keep `.forker.yaml` flat** (`key: value`, no nesting) — `config.sh` is a
|
||||
simple grep parser.
|
||||
|
||||
## How it runs
|
||||
|
||||
- **Cron** (`sync.yml`, every 10 min) → `forker/sync.sh`:
|
||||
1. fetch all branches + tags + history into the bare `.mirror/` (incremental
|
||||
when `actions/cache` restores it),
|
||||
2. push refs onto this repo + prune what upstream deleted (fork state is
|
||||
read via the Gitea **API**, not git state — works on cold mirrors),
|
||||
3. for each **tag that has no release yet**, run `forker/release.sh <tag>`
|
||||
inline (a tag-push can't trigger a workflow: the tag points at an upstream
|
||||
commit whose tree has no `.gitea/workflows`). The "missing release" check
|
||||
(not "new tag") makes a failed release retry on the next cron tick.
|
||||
`release.sh` publishes only when there is actual content (build assets or
|
||||
an existing upstream release) and fails loudly on a bad asset
|
||||
download/upload — a partial release never masquerades as success.
|
||||
4. `forker/check-unit.sh` — verifies the **Releases unit** is enabled
|
||||
(self-heals via the units API when the build exposes it; otherwise
|
||||
detects the 404 and prints the one-time UI fix).
|
||||
- `release.sh` = local build (if `build_cmd`/`build_script` set) + optional
|
||||
upstream-release mirror (metadata + assets via `forker/lib/provider.sh`).
|
||||
Idempotent: an existing release is skipped, not duplicated.
|
||||
- `runner-check.yml` — run once per repo to confirm a runner serves it.
|
||||
**Runners are repo-scoped on this Gitea build**: a runner registered on one
|
||||
repo does not serve another. Use a **shared** runner (or PATCH the runner
|
||||
to `"shared":true` — the units/runners APIs are missing here, so UI/DB).
|
||||
|
||||
## Known Gitea-build quirks (verified on git.lago.dev, Gitea 28.1.0)
|
||||
|
||||
- **Forks are created without the Releases unit**
|
||||
(`DefaultForkRepoUnits = [Code, PullRequests]`) → release assets 404 on the
|
||||
web download route (`context.RequireUnitReader`), the source tarball 404s
|
||||
too, while the API by-id works. Fix: enable the Releases unit
|
||||
(Settings → Repository, or DB `INSERT INTO repo_unit (repo_id, type) ... 4` —
|
||||
there is no units API on this build). `check-unit.sh` detects/fixes.
|
||||
**Prefer generating from this template over forking**: generated repos are
|
||||
not forks and get the full unit set (and Gitea only allows 1 fork of a
|
||||
repo per user).
|
||||
- **GitHub asset gotcha**: for a release addressed by *tag*, the asset
|
||||
`download_url` is **null** — the API `url` returns JSON metadata unless
|
||||
`Accept: application/octet-stream` is sent. `provider.sh` instead resolves
|
||||
to the **web download URL** (`github.com/.../releases/download/<tag>/<file>`),
|
||||
which is also unthrottled (the REST asset endpoint is 60 req/h
|
||||
unauthenticated — not enough to mirror ~200 assets).
|
||||
- Runner registration: the `gitea/act_runner` CLI (old and new) fails on this
|
||||
build ("instance address is empty"); runner creation via API is 405.
|
||||
Existing runners can be made shared via `PATCH /api/v1/admin/actions/runners/<id>`.
|
||||
- `actions/cache` timeouts on this build are handled with
|
||||
`continue-on-error: true` (cold fetch is still correct). The artifact cache
|
||||
service itself is NOT configured on this Gitea — every sync is a cold fetch
|
||||
(correct, slower; the cache steps are kept in case a backend is added).
|
||||
- **Per-job DNS flapping:** the ephemeral per-job container intermittently
|
||||
fails to resolve `git.lago.dev` on the fork push (the runner daemon's own
|
||||
network resolves fine). `sync.sh` therefore wraps every fork push in
|
||||
`push_once` — retry with backoff on transient network errors (resolve /
|
||||
connect / timeout), abort immediately on non-network failures.
|
||||
|
||||
## Editing the template vs. a mirror repo
|
||||
|
||||
- **Template** (this repo): edit on `forker` and `git push`. Mirror repos do
|
||||
**not** auto-track the template — sync them manually after a template
|
||||
change:
|
||||
- **Forked repos** (e.g. `Lago/photocraft`): the `forker` branch *is* a
|
||||
descendant of the template's, so a normal merge works:
|
||||
```
|
||||
git remote add template <template-url>
|
||||
git fetch template forker
|
||||
git checkout forker && git merge template/forker
|
||||
git push origin forker
|
||||
```
|
||||
- **Generated repos** (e.g. `Lago/pdfcraft`): the `forker` branch is an
|
||||
**unrelated snapshot** (no common ancestor — `git merge` fails with
|
||||
add/add conflicts). Reset it to the template and re-apply the single
|
||||
per-repo setting, then force-push:
|
||||
```
|
||||
git checkout forker
|
||||
git fetch template forker
|
||||
git reset --hard template/forker
|
||||
# re-apply this repo's .forker.yaml setting(s), e.g.:
|
||||
sed -i 's/^mirror_upstream_releases: false/mirror_upstream_releases: true/' .forker.yaml
|
||||
git commit -am "Adopt template; enable mirror_upstream_releases"
|
||||
git push --force origin forker
|
||||
```
|
||||
This is safe: `forker` holds only the machinery + config (the upstream
|
||||
content lives on the mirrored branches), so the snapshot's extra content
|
||||
is discarded by design.
|
||||
- **Per-repo config**: edit `.forker.yaml` in the UI on the `forker` branch.
|
||||
Pushing to `forker` triggers a re-sync.
|
||||
|
||||
## Local testing (without the runner)
|
||||
|
||||
```
|
||||
export UPSTREAM_URL=... UPSTREAM_TOKEN= # empty for public upstreams
|
||||
export GITEA_TOKEN=... GITEA_SERVER_URL=... GITEA_OWNER=... GITEA_REPO=...
|
||||
bash forker/sync.sh # full mirror (use a scratch repo!)
|
||||
bash forker/release.sh <tag>
|
||||
make check-unit
|
||||
```
|
||||
Test against a **scratch repo** you delete afterwards; never point the scripts
|
||||
at a real mirror while experimenting. `GITEA_TOKEN` from Actions is an API
|
||||
token (Bearer works for API + git); a *password* only works for basic auth —
|
||||
expect the Bearer API calls to fail when testing with a password.
|
||||
|
||||
## File map
|
||||
|
||||
- `forker/sync.sh` — mirror worker (fetch/push/prune + inline releases + unit check)
|
||||
- `forker/release.sh` — local build + upstream-release mirror, idempotent
|
||||
- `forker/check-unit.sh` — Releases unit detection/self-heal (exit 10 = missing)
|
||||
- `forker/lib/config.sh` — flat `.forker.yaml` parser
|
||||
- `forker/lib/provider.sh` — provider-agnostic releases API (github/gitea/codeberg)
|
||||
- `forker/runner-register.sh` — runner registration (see quirks above)
|
||||
- `.gitea/workflows/` — sync.yml (cron), release.yml (manual), runner-check.yml
|
||||
- `runner/docker-compose.yml` — gitea-act-runner in Docker (tracked; the local
|
||||
`runner/config/` token dir is gitignored)
|
||||
- `Makefile` — local targets (sync / release / mirror-releases / runner-check /
|
||||
runner-register / check-unit); `runner-check` queries the Gitea runner APIs
|
||||
- `docs/index.html` — architecture webpage (static)
|
||||
@@ -0,0 +1,43 @@
|
||||
# Repo Forker — convenience targets.
|
||||
# Most work happens in the Gitea Actions workflows; these targets are for local
|
||||
# use (dry-runs, runner setup) and for debugging on the runner.
|
||||
|
||||
CONFIG_FILE ?= .forker.yaml
|
||||
|
||||
.PHONY: help sync release mirror-releases runner-check runner-register check-unit
|
||||
|
||||
help:
|
||||
@echo "Repo Forker targets:"
|
||||
@echo " sync Run a manual sync (needs UPSTREAM_* + GITEA_* env)"
|
||||
@echo " release TAG=x Run a release for tag x"
|
||||
@echo " mirror-releases Mirror upstream releases for a tag (release.sh MIRROR)"
|
||||
@echo " runner-check Run the runner-check workflow logic locally"
|
||||
@echo " runner-register Register a shared gitea-act-runner (see README)"
|
||||
@echo " check-unit Verify the Releases unit is enabled (fork quirk)"
|
||||
|
||||
sync:
|
||||
bash forker/sync.sh
|
||||
|
||||
release:
|
||||
@test -n "$(TAG)" || (echo "make release TAG=<tag>"; exit 1)
|
||||
bash forker/release.sh "$(TAG)"
|
||||
|
||||
mirror-releases:
|
||||
@test -n "$(TAG)" || (echo "make mirror-releases TAG=<tag>"; exit 1)
|
||||
bash forker/release.sh "$(TAG)"
|
||||
|
||||
runner-check:
|
||||
@test -n "$(GITEA_SERVER_URL)" -a -n "$(GITEA_TOKEN)" -a -n "$(GITEA_OWNER)" -a -n "$(GITEA_REPO)" \
|
||||
|| { echo "needs GITEA_SERVER_URL/GITEA_TOKEN/GITEA_OWNER/GITEA_REPO (or run the workflow instead)"; exit 1; }
|
||||
@curl -sS --max-time 20 -H "Authorization: Bearer $(GITEA_TOKEN)" \
|
||||
"$(GITEA_SERVER_URL)/api/v1/repos/$(GITEA_OWNER)/$(GITEA_REPO)/actions/runners" > /tmp/rc_repo.json
|
||||
@curl -sS --max-time 20 -H "Authorization: Bearer $(GITEA_TOKEN)" \
|
||||
"$(GITEA_SERVER_URL)/api/v1/admin/actions/runners?limit=50" > /tmp/rc_shared.json || true
|
||||
@python3 -c 'import json; R=json.load(open("/tmp/rc_repo.json")).get("runners",[]); S=[r for r in json.load(open("/tmp/rc_shared.json")).get("runners",[]) if r.get("shared")]; print("Repo-scoped runners: "+(", ".join("%s (%s)"%(r["name"],r["status"]) for r in R) or "(none)")); print("Shared runners: "+(", ".join("%s (%s)"%(r["name"],r["status"]) for r in S) or "(none)")); print("OK: a runner serves this repo." if (R or S) else "WARNING: no runner (repo-scoped or shared) registered - cron runs will stay queued.")'
|
||||
@rm -f /tmp/rc_repo.json /tmp/rc_shared.json
|
||||
|
||||
runner-register:
|
||||
bash forker/runner-register.sh
|
||||
|
||||
check-unit:
|
||||
bash forker/check-unit.sh
|
||||
@@ -0,0 +1,221 @@
|
||||
# Repo Forker
|
||||
|
||||
> 📖 **Documentación y arquitectura interactiva:** [docs/index.html](docs/index.html) — qué es, cómo funciona, cómo crear un fork paso a paso, runner, config y limitaciones.
|
||||
|
||||
> 🖥️ **UI de gestión local (mirrors):** [ui/README.md](ui/README.md) — `cd ui && npm install && npm run build && node bin/repo-forker-ui.js` → http://127.0.0.1:8731. Crea/elimina/monitorea mirrors, paridad vs upstream, logs en vivo, cola del runner.
|
||||
|
||||
Turn **any** git repo (GitHub, Gitea, Codeberg, …) into a **live mirror on your
|
||||
Gitea** — all branches, all tags, full commit history — synced very
|
||||
periodically by a Gitea Actions runner (your "gitea worker"), with releases
|
||||
produced **locally on the runner** (and optionally mirrored from the upstream).
|
||||
|
||||
This repo is a **template**. You **fork** it once per upstream; the fork *is*
|
||||
the mirror. The upstream's content never touches the working tree: upstream
|
||||
objects live in a bare mirror (`.mirror/`, gitignored) and are pushed as refs
|
||||
so they show up in the Gitea UI.
|
||||
|
||||
```
|
||||
Fork of this template (Lago/<upstream>)
|
||||
├── working tree (forker branch) ← the machinery: scripts, config, workflows
|
||||
├── .mirror/ ← bare mirror of the upstream (gitignored)
|
||||
└── refs: <upstream branches> + <tags> ← visible in the Gitea UI
|
||||
```
|
||||
|
||||
## How it works
|
||||
|
||||
1. **Sync (the worker).** A cron workflow runs every N minutes. `sync.sh` fetches
|
||||
all branches + tags + full history from the upstream into a true bare mirror
|
||||
(`.mirror/`), then pushes them onto this fork and **prunes** what the upstream
|
||||
deleted. The fork's current state is read via the Gitea API (not git state),
|
||||
so prune + change-detection work even when the workspace is wiped between
|
||||
runs. `actions/cache` restores `.mirror/` when possible → incremental fetches.
|
||||
2. **Release (local build).** When sync detects a **new tag**, it invokes
|
||||
`release.sh` inline: checkout the tag's tree, run your build command **on the
|
||||
runner**, publish the release (tag + assets) on this Gitea. (A tag-push can't
|
||||
trigger a workflow on its own — the tag points at an upstream commit whose
|
||||
tree has no `.gitea/workflows` — so sync does it.) Re-running is idempotent:
|
||||
an existing release is skipped, not duplicated.
|
||||
3. **Release (mirror, optional).** If enabled, the upstream's existing release
|
||||
(metadata + assets) is copied over via the provider API
|
||||
(GitHub / Gitea / Codeberg — auto-detected in `forker/lib/provider.sh`).
|
||||
|
||||
## Quick start (3 steps)
|
||||
|
||||
### 1. Fork this template
|
||||
In the Gitea UI: **this repo → Fork** → name it after the upstream
|
||||
(e.g. `Lago/some-upstream`).
|
||||
|
||||
### 2. Point it at the upstream (the "remote")
|
||||
In the fork: **Settings → Actions → Variables & Secrets**
|
||||
- **Variable** `UPSTREAM_URL` = `https://github.com/owner/repo.git` (any provider)
|
||||
- **Secret** `UPSTREAM_TOKEN` = *(optional — only for private upstreams.)*
|
||||
Public upstreams are mirrored **anonymously** and the tool never
|
||||
authenticates against them: the global/system git config and the
|
||||
credential helper are cut for all upstream git calls, so a stored
|
||||
`~/.git-credentials` entry is never used. Only set a token when the
|
||||
upstream is private (or you need a higher API rate for mirrored
|
||||
releases).
|
||||
|
||||
Everything non-secret (which branches, how often, build command, artifacts) lives
|
||||
in **`.forker.yaml`** — edit it in the UI on the `forker` branch.
|
||||
|
||||
> The `GITEA_*` values (server URL, owner, repo, token) are injected
|
||||
> automatically by Gitea Actions — you don't set them. (`GITEA_TOKEN` in the
|
||||
> workflow env block is Gitea's **built-in** Actions secret, not a
|
||||
> user-created secret — don't create one.)
|
||||
|
||||
### 3. Make sure a runner serves this repo
|
||||
In this Gitea build, **runners are repo-scoped**: a runner registered on one
|
||||
repo does **not** serve another. So either:
|
||||
|
||||
- **Shared runner (recommended, one-time):** register a single runner that serves
|
||||
**all** repos. See [Runner](#runner).
|
||||
- **Per-repo runner:** register a runner for this specific repo.
|
||||
|
||||
Then trigger **Settings → Actions → "Repo Forker — Runner check"** and confirm it
|
||||
completes. If sync runs stay *pending* for a long time, no runner is serving
|
||||
this repo.
|
||||
|
||||
That's it. The cron sync starts pulling the upstream in, and releases are
|
||||
produced locally when tags appear. Note: with the template defaults
|
||||
(`build_cmd` empty, `mirror_upstream_releases: false`) there is nothing to
|
||||
build, so new tags are mirrored as **refs only** — set a `build_cmd` /
|
||||
`build_script` (or `mirror_upstream_releases: true`) for releases to appear.
|
||||
|
||||
## Configuration (`.forker.yaml`)
|
||||
|
||||
| Key | Default | Meaning |
|
||||
|---|---|---|
|
||||
| `token_user` | `oauth2` | *(unused — Bearer auth needs no username; retained for compatibility)* |
|
||||
| `mirror_tags` | `true` | Mirror all tags |
|
||||
| `mirror_prune` | `true` | Prune branches deleted upstream |
|
||||
| `mirror_branches` | `*` | `*` = all, or a comma list (`main,develop`) |
|
||||
| `on_new_tag` | `true` | Build+publish a release when a new tag is mirrored |
|
||||
| `mirror_upstream_releases` | `false` | Also copy the upstream's release (metadata + assets) |
|
||||
| `build_cmd` | — | Build command(s), `;`-separated, run in the tag's tree |
|
||||
| `build_script` | — | Path to a custom build script (overrides `build_cmd`) |
|
||||
| `artifacts` | — | Space-separated globs of files to attach to the release |
|
||||
|
||||
## Manual triggers
|
||||
|
||||
- **Sync now:** Settings → Actions → *Repo Forker — Sync* → Run workflow.
|
||||
- **Release a tag:** Settings → Actions → *Repo Forker — Release* → Run workflow
|
||||
→ enter the tag.
|
||||
- **Check the runner:** Settings → Actions → *Repo Forker — Runner check*.
|
||||
|
||||
Or from a machine that has the repo + env vars: `make sync`,
|
||||
`make release TAG=v1.2.3`.
|
||||
|
||||
## Runner
|
||||
|
||||
The sync (cron) and the local release build both need a **Gitea Actions runner**
|
||||
serving the repo. In this build, runners are **repo-scoped**, so the clean path
|
||||
is a **shared runner** registered once:
|
||||
|
||||
```bash
|
||||
# install gitea-act-runner (see the Gitea runner docs), then:
|
||||
GITEA_SERVER_URL=https://git.lago.dev \
|
||||
GITEA_TOKEN=<admin-token> \
|
||||
GITEA_OWNER=Lago GITEA_REPO=any \
|
||||
bash forker/runner-register.sh shared
|
||||
|
||||
# then start it (e.g. via docker, see runner/docker-compose.yml)
|
||||
gitea-act-runner run
|
||||
```
|
||||
|
||||
`forker/runner-register.sh` auto-generates a registration token via
|
||||
`POST /api/v1/admin/actions/runners/registration-token` (verified working on this
|
||||
instance) and registers either a **shared** runner or a **per-repo** one.
|
||||
|
||||
> The existing online runner on this instance (id 3, `496cfb9f4583`,
|
||||
> `ubuntu-latest/24.04/22.04`) is registered to `Lago/Tide` only — it will not
|
||||
> serve your forks. Register a shared runner (or one per repo) as above.
|
||||
|
||||
> **This Gitea build quirk (verified):** the `act_runner` CLI fails to
|
||||
> register ("instance address is empty") on both `gitea/act_runner:0.6.1`
|
||||
> and `0.2.13`, and the runner-creation API returns 405. The path that
|
||||
> **does** work: take an existing registered runner and PATCH it to shared:
|
||||
> ```bash
|
||||
> curl -X PATCH "$GITEA_SERVER_URL/api/v1/admin/actions/runners/<id>" \
|
||||
> -H "Authorization: Bearer $GITEA_TOKEN" \
|
||||
> -d '{"name":"gitea-runner-forker","labels":["ubuntu-latest"],"shared":true,"disabled":false}'
|
||||
> ```
|
||||
> then point a `gitea/act_runner:0.6.1` container at its config
|
||||
> (`runner/docker-compose.yml`).
|
||||
|
||||
## Repository layout
|
||||
|
||||
```
|
||||
repo-forker/
|
||||
├── .gitea/workflows/
|
||||
│ ├── sync.yml # cron: mirror upstream (the "worker"); restores .mirror cache
|
||||
│ ├── release.yml # MANUAL only (a tag push can't trigger it); see sync.sh
|
||||
│ └── runner-check.yml # verify a runner serves this repo
|
||||
├── forker/
|
||||
│ ├── sync.sh # true-mirror fetch + push + prune + inline new-tag release + unit check
|
||||
│ ├── release.sh # local build + publish release (± mirror upstream), idempotent
|
||||
│ ├── runner-register.sh # register a shared / per-repo runner
|
||||
│ ├── check-unit.sh # verify/fix the Releases unit (Gitea fork quirk)
|
||||
│ └── lib/
|
||||
│ ├── config.sh # load .forker.yaml
|
||||
│ └── provider.sh # detect provider + releases API (Gitea/GitHub/Codeberg)
|
||||
├── .mirror/ # bare mirror (gitignored, cached by the workflow)
|
||||
├── .forker.yaml # per-fork config (non-secret)
|
||||
├── Makefile
|
||||
├── runner/docker-compose.yml
|
||||
└── README.md
|
||||
```
|
||||
|
||||
## Notes & limitations
|
||||
|
||||
- **Releases are not git objects.** Git only carries the *tag*; release *assets*
|
||||
live on the Gitea. "Local release" = build on the runner + upload via the
|
||||
Gitea API. Mirroring upstream assets works anonymously for public upstreams
|
||||
(a token is only needed for private ones).
|
||||
- **Ephemeral workspace.** The Gitea runner wipes the workspace between runs.
|
||||
`sync.sh` is written to not depend on leftover git state: it re-reads the fork's
|
||||
current refs via the API every run. `actions/cache` on `.mirror/` makes the
|
||||
fetch incremental when it hits; a cold cache just means a full-history fetch
|
||||
(correct, slower).
|
||||
- **Tags point at upstream commits.** That's intentional — it keeps commit
|
||||
hashes identical to the upstream. It also means the workflow can't be
|
||||
triggered *by the tag* (the tag's tree has no workflows), so sync triggers
|
||||
releases inline.
|
||||
- **Provider differences** (releases API, token username) are isolated in
|
||||
`forker/lib/provider.sh`; the rest is provider-agnostic.
|
||||
- **Secrets stay out of the repo.** Upstream URL/token are Gitea Actions
|
||||
Variables/Secrets; the Gitea token is the built-in `GITEA_TOKEN`.
|
||||
- **Runner is the hard dependency.** Without a runner serving the repo, the cron
|
||||
sync and local builds won't run — run the *Runner check* first.
|
||||
- **Gitea forks ship without the Releases unit → asset downloads 404.**
|
||||
Root cause found on this instance (verified in the Gitea source + DB): a fork
|
||||
is created with `DefaultForkRepoUnits = [Code, PullRequests]` — **no
|
||||
Releases unit** — while normal repos get it. So release *assets* uploaded to
|
||||
a fork repo are listed in the API (by-id works) but the web
|
||||
`browser_download_url` returns 404 at the unit-permission check, and the
|
||||
release *source tarball* 404s too.
|
||||
**Detected + fixed:** `sync.sh` runs `check-unit.sh` at the end of every
|
||||
sync — it self-heals via the units API on builds that expose it, and on
|
||||
this build (no units API) it detects the 404 (confirming the API by-id
|
||||
path still works) and prints the exact one-time fix: UI → Settings →
|
||||
Repository → enable the **Releases** unit. `make check-unit` runs it
|
||||
standalone.
|
||||
|
||||
## Security notes
|
||||
|
||||
- **Upstreams are fetched anonymously by default.** `sync.sh` / `release.sh`
|
||||
cut `GIT_CONFIG_GLOBAL`/`GIT_CONFIG_SYSTEM` and the credential helper before
|
||||
any upstream git call, and add a Bearer header **only** when `UPSTREAM_TOKEN`
|
||||
is set. A stored `~/.git-credentials` entry is therefore *never* offered to
|
||||
`git fetch` — a public upstream is a pure anonymous fetch.
|
||||
- **`build_cmd` / `build_script` run with the tokens in the environment.**
|
||||
`release.sh` keeps `GITEA_TOKEN` and `UPSTREAM_TOKEN` set so it can fetch the
|
||||
tag's tree and publish assets. Any repo member can edit `.forker.yaml`, so a
|
||||
malicious `build_cmd` could exfiltrate both tokens. Treat `build_cmd` /
|
||||
`build_script` as **trusted code with credential access** — only put commands
|
||||
you (or the repo owners) trust there.
|
||||
- **Tokens briefly persist in the cached `.mirror/` git config.** The per-URL
|
||||
`http.<url>.extraHeader` Bearer header is written into `.mirror/config`, and
|
||||
`.mirror/` is the `actions/cache` path. The cache is repo-scoped (not
|
||||
committed), but a cache-service reader can read it until the next save
|
||||
overwrites it. The tokens are never written into the repo itself.
|
||||
@@ -0,0 +1,102 @@
|
||||
# TODO — a futuro
|
||||
|
||||
## [UI] Gestión local de mirrors (npx)
|
||||
|
||||
Una web local (arrancable con `npx`) para gestionar todo el ecosistema de
|
||||
Repo Forker desde un solo lugar, sin tocar API/curl/DB.
|
||||
|
||||
### Idea
|
||||
```
|
||||
npx repo-forker-ui # -> http://localhost:8731 (o el puerto libre)
|
||||
```
|
||||
El UI habla con la API de Gitea (con un token que el usuario pega una vez,
|
||||
guardado localmente — nunca en el repo) y ejecuta las mismas operaciones que
|
||||
los scripts, pero de forma guiada.
|
||||
|
||||
### Features (por prioridad)
|
||||
|
||||
**P0 — Gestión de mirrors (el corazón):**
|
||||
- **Crear un mirror**: pega la URL del upstream (GitHub/Gitea/Codeberg/otro)
|
||||
+ nombre → el UI hace lo que se hace hoy por API/curl:
|
||||
1. `POST /repos/{owner}/repo-forker/generate` con `git_content: true`
|
||||
2. crea la variable `UPSTREAM_URL` (`POST .../actions/variables/UPSTREAM_URL`)
|
||||
3. `PATCH` default branch → la del upstream (o `main`)
|
||||
4. activa `mirror_upstream_releases` en la rama `forker` (reset + re-apply,
|
||||
el procedimiento de AGENTS.md para repos generados)
|
||||
5. dispara el primer `sync.yml` (dispatch) y muestra el progreso
|
||||
- **Lista de mirrors**: todos los repos generados desde `repo-forker`
|
||||
(detectables por la rama `forker` + la variable `UPSTREAM_URL`), con:
|
||||
- estado del último `sync.yml` (green/red, timestamp, duración)
|
||||
- branches / tags / releases / assets (vs upstream — paridad)
|
||||
- unidades activas (Code/Issues/PR/Releases/...)
|
||||
- **Stats y gráficas** (por mirror y agregado):
|
||||
- timeline de runs (success/failure/queued) — sparkline de los últimos 7 días
|
||||
- tiempo de sync por run (cold vs incremental — la caché, cuando exista)
|
||||
- assets por release (barras), crecimiento de branches/tags
|
||||
- latencia de mirror: commits upstream sin replicar todavía
|
||||
- **Eliminar un mirror**: delete del repo (con confirmación + advertencia de
|
||||
lo que se pierde; el template queda intacto)
|
||||
- **Re-sincronizar / forzar**: dispatch manual de `sync.yml` / `release.yml` /
|
||||
`runner-check.yml` desde la UI
|
||||
- **Config per-repo**: editar `.forker.yaml` (los campos conocidos:
|
||||
`mirror_branches`, `mirror_tags`, `mirror_prune`, `mirror_upstream_releases`,
|
||||
`build_cmd`, `build_script`, `artifacts`, `on_new_tag`) con validación de
|
||||
esquema plano (el parser es grep — el UI debe mantenerlo plano)
|
||||
- **Variables & secrets**: listar/crear/borrar las Variables de Actions
|
||||
(`UPSTREAM_URL`, `UPSTREAM_TOKEN` opcional) — los secrets solo se crean,
|
||||
no se leen (la API no los devuelve)
|
||||
|
||||
**P1 — Observabilidad:**
|
||||
- **Cola del runner**: runs `queued`/`in_progress` en vivo (polling), con
|
||||
tiempo de espera — el runner es serial (maxParallel=1), así que una vista
|
||||
de "fila" es muy útil
|
||||
- **Logs en vivo** de un run (stream del log del job, con el
|
||||
`::group::`/`::notice::` de Gitea Actions renderizado)
|
||||
- **Diagnóstico de un run fallido**: extraer la línea de error del log y
|
||||
sugerir la causa (DNS flap, cache timeout, token, unidad Releases)
|
||||
- **Unidades**: ver/quitar/habilitar la unidad Releases (con fallback a DB
|
||||
cuando la API no existe — este build)
|
||||
- **Alerta** de mirror "desactualizado" (última sync > N min con runner idle)
|
||||
|
||||
**P2 — Extras:**
|
||||
- **Generar desde otros templates**: que el UI permita usar cualquier repo
|
||||
marcado `template: true` (no solo repo-forker)
|
||||
- **Import de config**: pegar un `.forker.yaml` y aplicarlo
|
||||
- **Export del estado**: snapshot JSON de todos los mirrors (para backups /
|
||||
re-crear después de una catástrofe)
|
||||
- **Comparador de paridad**: side-by-side upstream vs fork (branches/tags/
|
||||
releases) con diff visual (lo que falta se marca)
|
||||
|
||||
### Notas de diseño
|
||||
|
||||
- **Stack sugerido**: Vite + React (o SvelteKit) + Tailwind; el backend
|
||||
"npx" puede ser un thin server Node que solo hace proxy + auth al Gitea
|
||||
(el UI puede ser 100% client-side si el token se guarda en `localStorage`;
|
||||
el proxy solo evita CORS y esconde el token de los logs del navegador).
|
||||
- **Auth**: el usuario pega su token Gitea (o basic) una vez; se guarda en
|
||||
`~/.repo-forker/credentials` (chmod 600) o `localStorage` según el modo.
|
||||
NUNCA se sube al repo.
|
||||
- **Idempotencia**: todas las acciones de creación deben ser idempotentes
|
||||
(re-crear el mirror con el mismo nombre → "ya existe" + enlazar).
|
||||
- **No duplicar lógica**: las operaciones (generate, variable, default branch,
|
||||
forker reset+re-apply, dispatch) ya están probadas en esta sesión — el UI
|
||||
las reproduce tal cual, no inventa variantes.
|
||||
- **Modo offline**: la UI debe funcionar aunque el Gitea esté caído (los
|
||||
últimos datos cacheados + estado "offline").
|
||||
|
||||
### Criterio de "hecho" (P0)
|
||||
|
||||
1. `npx repo-forker-ui` arranca y se conecta a un Gitea (URL + token).
|
||||
2. Desde la UI: crear un mirror de un repo GitHub público → aparece en la
|
||||
lista con su primer sync en verde y paridad correcta.
|
||||
3. Eliminar un mirror desde la UI (con confirmación).
|
||||
4. Ver en la UI: últimos 20 runs de cada mirror, paridad de
|
||||
branches/tags/releases, y el log del último run.
|
||||
5. Re-sincronizar (dispatch) desde la UI.
|
||||
|
||||
### Estado: **A FUTURO — no empezar sin revisar esta spec**
|
||||
|
||||
La infraestructura ya soporta todo lo que el UI necesita (APIs de generate,
|
||||
variables, dispatch, runners, releases; scripts de sync con retry; `check-unit`;
|
||||
cron de limpieza en tizona). Faltan decisiones: stack, nombre del paquete,
|
||||
y si el modo "solo client-side con token en localStorage" es suficiente.
|
||||
|
Before Width: | Height: | Size: 471 KiB |
|
Before Width: | Height: | Size: 222 KiB |
|
Before Width: | Height: | Size: 858 KiB |
|
Before Width: | Height: | Size: 247 KiB |
@@ -0,0 +1,444 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="es">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Repo Forker — Documentación y Arquitectura</title>
|
||||
<style>
|
||||
:root{
|
||||
--bg:#0d1117; --panel:#161b22; --panel2:#1c2333; --border:#30363d;
|
||||
--text:#e6edf3; --muted:#8b949e; --accent:#58a6ff; --accent2:#7ee787;
|
||||
--warn:#f2cc60; --danger:#f85149; --code-bg:#0d1117; --chip:#21262d;
|
||||
}
|
||||
*{box-sizing:border-box;}
|
||||
html{scroll-behavior:smooth;}
|
||||
body{
|
||||
margin:0; background:var(--bg); color:var(--text);
|
||||
font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
|
||||
line-height:1.6; font-size:16px;
|
||||
}
|
||||
code,pre,.mono{font-family:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Consolas,monospace;}
|
||||
a{color:var(--accent); text-decoration:none;}
|
||||
a:hover{text-decoration:underline;}
|
||||
|
||||
/* Layout */
|
||||
.wrap{max-width:1000px; margin:0 auto; padding:0 20px 120px;}
|
||||
header.hero{
|
||||
padding:64px 20px 40px; text-align:center;
|
||||
background:radial-gradient(1200px 400px at 50% -10%, #1f2a44 0%, transparent 70%);
|
||||
border-bottom:1px solid var(--border);
|
||||
}
|
||||
.hero h1{font-size:2.6rem; margin:0 0 8px; letter-spacing:-.5px;}
|
||||
.hero .tag{color:var(--muted); font-size:1.15rem; max-width:640px; margin:0 auto;}
|
||||
.pill{display:inline-block; background:var(--chip); border:1px solid var(--border);
|
||||
border-radius:999px; padding:3px 12px; font-size:.8rem; color:var(--accent2); margin:14px 4px 0;}
|
||||
|
||||
/* Nav */
|
||||
nav.toc{
|
||||
position:sticky; top:0; z-index:10; background:rgba(13,17,23,.9);
|
||||
backdrop-filter:blur(8px); border-bottom:1px solid var(--border);
|
||||
}
|
||||
nav.toc .inner{max-width:1000px; margin:0 auto; padding:10px 20px; display:flex;
|
||||
gap:18px; flex-wrap:wrap; font-size:.9rem;}
|
||||
nav.toc a{color:var(--muted);} nav.toc a:hover{color:var(--text);}
|
||||
|
||||
section{margin-top:56px;}
|
||||
h2{font-size:1.7rem; border-bottom:1px solid var(--border); padding-bottom:10px; margin:0 0 6px;}
|
||||
h2 .n{color:var(--accent); font-size:1rem; margin-right:10px; font-weight:600;}
|
||||
h3{font-size:1.15rem; margin-top:30px;}
|
||||
p{color:var(--text);}
|
||||
.lead{color:var(--muted); font-size:1.05rem; margin-top:0;}
|
||||
.muted{color:var(--muted);}
|
||||
small{color:var(--muted);}
|
||||
|
||||
/* Cards */
|
||||
.grid{display:grid; gap:16px; grid-template-columns:repeat(auto-fit,minmax(240px,1fr));}
|
||||
.card{background:var(--panel); border:1px solid var(--border); border-radius:10px; padding:18px;}
|
||||
.card h4{margin:0 0 6px; font-size:1rem;}
|
||||
.card .ico{font-size:1.6rem;}
|
||||
|
||||
/* Code */
|
||||
pre{background:var(--code-bg); border:1px solid var(--border); border-radius:8px;
|
||||
padding:14px 16px; overflow-x:auto; font-size:.85rem; line-height:1.5;}
|
||||
code.inline{background:var(--chip); border:1px solid var(--border); border-radius:5px;
|
||||
padding:1px 6px; font-size:.85em;}
|
||||
|
||||
/* Steps */
|
||||
.steps{counter-reset:step; list-style:none; padding:0; margin:10px 0;}
|
||||
.steps li{position:relative; padding:0 0 22px 48px;}
|
||||
.steps li::before{
|
||||
counter-increment:step; content:counter(step);
|
||||
position:absolute; left:0; top:0; width:32px; height:32px; border-radius:50%;
|
||||
background:var(--panel2); border:1px solid var(--accent); color:var(--accent);
|
||||
display:flex; align-items:center; justify-content:center; font-weight:700;
|
||||
}
|
||||
.steps li h4{margin:4px 0 4px;}
|
||||
|
||||
/* Diagram */
|
||||
.diagram{background:var(--panel); border:1px solid var(--border); border-radius:12px;
|
||||
padding:26px; overflow-x:auto;}
|
||||
.flow{display:flex; align-items:stretch; gap:0; flex-wrap:nowrap; min-width:640px;}
|
||||
.node{flex:1; background:var(--panel2); border:1px solid var(--border); border-radius:10px;
|
||||
padding:14px; text-align:center; display:flex; flex-direction:column; justify-content:center;}
|
||||
.node .t{font-weight:700; font-size:.95rem;}
|
||||
.node .s{color:var(--muted); font-size:.78rem; margin-top:4px;}
|
||||
.node.up{border-color:var(--warn);} .node.fk{border-color:var(--accent2);}
|
||||
.node.wk{border-color:var(--accent);}
|
||||
.arrow{align-self:center; color:var(--muted); font-size:1.5rem; padding:0 6px;}
|
||||
.arrow .lbl{display:block; font-size:.68rem; text-align:center; color:var(--muted); max-width:90px; line-height:1.2;}
|
||||
|
||||
/* Table */
|
||||
table{width:100%; border-collapse:collapse; font-size:.9rem; margin:10px 0;}
|
||||
th,td{text-align:left; padding:9px 12px; border-bottom:1px solid var(--border); vertical-align:top;}
|
||||
th{color:var(--muted); font-weight:600; font-size:.78rem; text-transform:uppercase; letter-spacing:.4px;}
|
||||
td code{background:var(--chip); padding:1px 6px; border-radius:4px; font-size:.85em;}
|
||||
|
||||
/* Callouts */
|
||||
.callout{border-left:3px solid var(--accent); background:var(--panel); border-radius:0 8px 8px 0;
|
||||
padding:12px 16px; margin:16px 0;}
|
||||
.callout.warn{border-color:var(--warn);}
|
||||
.callout.danger{border-color:var(--danger);}
|
||||
.callout.ok{border-color:var(--accent2);}
|
||||
.callout .h{font-weight:700; margin-bottom:4px;}
|
||||
.callout.warn .h{color:var(--warn);} .callout.danger .h{color:var(--danger);}
|
||||
.callout.ok .h{color:var(--accent2);}
|
||||
|
||||
.badge{display:inline-block; font-size:.72rem; padding:2px 8px; border-radius:999px;
|
||||
border:1px solid var(--border); background:var(--chip); color:var(--muted); vertical-align:middle;}
|
||||
.badge.on{color:var(--accent2); border-color:var(--accent2);}
|
||||
ul.clean{padding-left:20px;} ul.clean li{margin:4px 0;}
|
||||
.cols{display:grid; grid-template-columns:repeat(auto-fit,minmax(260px,1fr)); gap:20px;}
|
||||
footer{margin-top:60px; padding-top:24px; border-top:1px solid var(--border); color:var(--muted); font-size:.85rem;}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<header class="hero">
|
||||
<h1>Repo Forker</h1>
|
||||
<p class="tag">Convierte <strong>cualquier repo git</strong> (GitHub, Gitea, Codeberg…) en un
|
||||
<strong>espejo vivo en tu Gitea</strong> — todas las branches, tags e historial completo —
|
||||
sincronizado muy periódicamente por un <strong>runner compartido</strong>, con las
|
||||
<strong>releases compiladas localmente</strong>.</p>
|
||||
<span class="pill">template repo</span>
|
||||
<span class="pill">fork = espejo</span>
|
||||
<span class="pill">shell + Gitea Actions</span>
|
||||
<span class="pill">Gitea 28.1.0 · runner v0.6.1</span>
|
||||
</header>
|
||||
|
||||
<nav class="toc"><div class="inner">
|
||||
<a href="#que">¿Qué es?</a>
|
||||
<a href="#arq">Arquitectura</a>
|
||||
<a href="#flujo">Flujo de un sync</a>
|
||||
<a href="#releases">Releases</a>
|
||||
<a href="#setup">Crear un fork</a>
|
||||
<a href="#runner">Runner</a>
|
||||
<a href="#config">Configuración</a>
|
||||
<a href="#layout">Estructura</a>
|
||||
<a href="#faq">FAQ / Limitaciones</a>
|
||||
</div></nav>
|
||||
|
||||
<div class="wrap">
|
||||
|
||||
<!-- ==================== QUÉ ES ==================== -->
|
||||
<section id="que">
|
||||
<h2><span class="n">01</span>¿Qué es Repo Forker?</h2>
|
||||
<p class="lead">Es un <strong>template</strong>. No lo "usas" directamente: lo <strong>forkeas</strong> una
|
||||
vez por cada repo que quieras espejar, y <strong>ese fork ES el espejo</strong>.</p>
|
||||
<div class="grid" style="margin-top:22px">
|
||||
<div class="card"><div class="ico">🪞</div><h4>Espejo completo</h4>
|
||||
<p class="muted">Trae <em>all</em> branches, <em>all</em> tags y el historial completo de commits del upstream.
|
||||
Los commits conservan su hash original.</p></div>
|
||||
<div class="card"><div class="ico">⏱️</div><h4>Muy periódico</h4>
|
||||
<p class="muted">Un cron en Gitea Actions lo actualiza cada N minutos (por defecto cada 10).
|
||||
Incremental gracias a un cache del mirror.</p></div>
|
||||
<div class="card"><div class="ico">📦</div><h4>Releases locales</h4>
|
||||
<p class="muted">Al aparecer un tag nuevo, el runner <em>compila</em> el código y publica la release
|
||||
(tag + assets) en tu Gitea. Opcionalmente espeja las del upstream.</p></div>
|
||||
<div class="card"><div class="ico">🔀</div><h4>Multiprovider</h4>
|
||||
<p class="muted">El upstream puede estar en GitHub, Gitea, Codeberg… La detección de provider y su
|
||||
API de releases va aislada en un solo fichero.</p></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ==================== ARQUITECTURA ==================== -->
|
||||
<section id="arq">
|
||||
<h2><span class="n">02</span>Arquitectura</h2>
|
||||
<p class="lead">Cada fork se divide en tres zonas que <strong>no se pisan entre sí</strong>:</p>
|
||||
|
||||
<div class="diagram" style="margin-top:20px">
|
||||
<div class="flow">
|
||||
<div class="node up"><div class="t">Upstream</div><div class="s">GitHub / Gitea / Codeberg<br>(fuente de verdad)</div></div>
|
||||
<div class="arrow">→<span class="lbl">fetch --force<br>branches+tags</span></div>
|
||||
<div class="node fk"><div class="t">Fork = Espejo</div><div class="s">Lago/<upstream><br>(tu repo en Gitea)</div></div>
|
||||
<div class="arrow">→<span class="lbl">push refs</span></div>
|
||||
<div class="node wk"><div class="t">Runner shared</div><div class="s">gitea-act_runner<br>(el "worker")</div></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h3>Dentro del fork: las 3 zonas</h3>
|
||||
<table>
|
||||
<tr><th>Zona</th><th>Qué contiene</th><th>Vive en</th><th>¿Se sube a git?</th></tr>
|
||||
<tr><td><strong>Working tree</strong> <span class="badge">rama forker</span></td>
|
||||
<td>La <em>maquinaria</em>: scripts, workflows, config. El contenido del upstream <strong>jamás</strong> toca aquí.</td>
|
||||
<td>rama <code>forker</code></td><td>Sí</td></tr>
|
||||
<tr><td><strong>Bare mirror</strong></td>
|
||||
<td>Los objetos del upstream (branches en <code>refs/heads/*</code>, tags en <code>refs/tags/*</code>).</td>
|
||||
<td><code>.mirror/</code></td><td>No (gitignored + cache)</td></tr>
|
||||
<tr><td><strong>Refs visibles</strong></td>
|
||||
<td>Las branches y tags del upstream, pushadas como refs de primer nivel → aparecen en la UI de Gitea.</td>
|
||||
<td>el propio repo</td><td>Sí (son refs)</td></tr>
|
||||
</table>
|
||||
|
||||
<div class="callout">
|
||||
<div class="h">¿Por qué el working tree y el mirror están separados?</div>
|
||||
Porque el contenido del upstream no tiene <code>.gitea/workflows/</code> ni los scripts de la maquinaria.
|
||||
Si el mirror "aplastara" el working tree, al check outar una branch espejada se perdería la capacidad de
|
||||
auto-sincronizarse. Separarlo mantiene la maquinaria intacta y el espejo puro.
|
||||
</div>
|
||||
|
||||
<h3>Los datos de configuración</h3>
|
||||
<p>El <strong>remote</strong> (dónde está el upstream) y sus credenciales se configuran <strong>vía la UI de Gitea</strong>
|
||||
(Variables & Secrets), no en el repo: así los secrets nunca se versionan. El resto (qué branches, cada cuánto,
|
||||
cómo compilar) va en <code>.forker.yaml</code>.</p>
|
||||
</section>
|
||||
|
||||
<!-- ==================== FLUJO ==================== -->
|
||||
<section id="flujo">
|
||||
<h2><span class="n">03</span>Flujo de un sync (el "worker")</h2>
|
||||
<p class="lead">Cada run del cron (<code>sync.yml</code>) ejecuta <code>forker/sync.sh</code>. Es
|
||||
<strong>idempotente</strong> y <strong>no depende</strong> de que el workspace sobreviva entre runs
|
||||
(Gitea lo borra): el estado previo se lee <strong>por API</strong>.</p>
|
||||
|
||||
<div class="diagram" style="margin-top:20px">
|
||||
<div class="flow" style="min-width:560px">
|
||||
<div class="node"><div class="t">1 · Restore</div><div class="s">cache de <code>.mirror</code><br>(si toca: fetch incremental)</div></div>
|
||||
<div class="arrow">→</div>
|
||||
<div class="node up"><div class="t">2 · Fetch</div><div class="s">upstream → <code>.mirror</code><br>(Bearer token)</div></div>
|
||||
<div class="arrow">→</div>
|
||||
<div class="node"><div class="t">3 · Estado fork</div><div class="s">GET /branches /tags<br>vía API (paginado)</div></div>
|
||||
</div>
|
||||
<div class="flow" style="min-width:560px; margin-top:14px">
|
||||
<div class="node fk"><div class="t">4 · Push</div><div class="s">branches + tags al fork<br>(Bearer, preserva <code>forker</code>)</div></div>
|
||||
<div class="arrow">→</div>
|
||||
<div class="node"><div class="t">5 · Prune</div><div class="s">borra lo que el upstream<br>ya no tiene</div></div>
|
||||
<div class="arrow">→</div>
|
||||
<div class="node wk"><div class="t">6 · New tags?</div><div class="s">si hay tags nuevos →<br>release inline</div></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ul class="clean">
|
||||
<li><strong>Auth por Bearer per-URL:</strong> git usa <code>http.<url>.extraHeader</code> con
|
||||
<code>Authorization: Bearer</code> — un token para el upstream, otro para el fork. No se necesita
|
||||
username, así que no peca de la regla de Gitea "el username debe coincidir con el dueño del token".</li>
|
||||
<li><strong>Prune y "nuevo tag" sin estado local:</strong> como <code>.mirror</code> no persiste, el estado
|
||||
anterior se reconstruye preguntando al fork por su API. Por eso <code>forker</code> (la rama de la
|
||||
maquinaria) nunca se toca: está explícitamente exenta del prune.</li>
|
||||
<li><strong>Cache opcional:</strong> <code>actions/cache</code> restaura <code>.mirror</code> para hacer el
|
||||
fetch incremental. Si no hay cache (o no hay servicio de cache), hace fetch completo — <em>correcto, más lento</em>.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<!-- ==================== RELEASES ==================== -->
|
||||
<section id="releases">
|
||||
<h2><span class="n">04</span>Releases</h2>
|
||||
<p class="lead">En git solo existe el <em>tag</em>. La <em>release</em> (con sus assets/binarios) es un objeto de
|
||||
Gitea. Repo Forker produce releases de dos formas, ambas <strong>en el runner</strong>:</p>
|
||||
|
||||
<div class="cols" style="margin-top:16px">
|
||||
<div class="card">
|
||||
<h4>🔨 Build local <span class="badge on">siempre que configures build_cmd</span></h4>
|
||||
<p class="muted">Cuando un <strong>tag nuevo</strong> aparece, <code>release.sh</code> hace checkout de ese
|
||||
tag, ejecuta tu comando de build (o un script) <em>dentro del runner</em>, recoge los artifacts y publica
|
||||
la release con esos assets. Es idempotente: si la release ya existe, la salta.</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h4>🪞 Espejo del upstream <span class="badge">opcional</span></h4>
|
||||
<p class="muted">Si activas <code>mirror_upstream_releases</code>, además copia el <em>metadata</em> y los
|
||||
<em>assets</em> de la release que el upstream ya tenga para ese tag, usando su API (Gitea/GitHub/Codeberg,
|
||||
auto-detectada). Útil si el upstream publica binarios y quieres tenerlos sin recompilar.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="callout warn">
|
||||
<div class="h">¿Por qué no se dispara una release "al hacer push del tag"?</div>
|
||||
Un tag espejado apunta a un <strong>commit del upstream</strong>, cuyo árbol <em>no</em> contiene
|
||||
<code>.gitea/workflows/</code>. Gitea no encuentra el workflow y no lo ejecuta. Por eso el sync detecta el
|
||||
tag nuevo y lanza la release <strong>inline</strong> (desde la rama <code>forker</code>, que sí tiene los
|
||||
workflows). <code>release.yml</code> queda para dispararlo <em>manualmente</em>.
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ==================== SETUP ==================== -->
|
||||
<section id="setup">
|
||||
<h2><span class="n">05</span>Cómo crear un repo basado en esto</h2>
|
||||
<p class="lead">Tres pasos. En total, unos minutos la primera vez.</p>
|
||||
|
||||
<ol class="steps">
|
||||
<li>
|
||||
<h4>Fork el template</h4>
|
||||
<p class="muted">En Gitea: <strong>este repo → Fork</strong>. Nómbralo como el upstream
|
||||
(p. ej. <code>Lago/some-upstream</code>). El fork hereda la rama <code>forker</code> y toda la maquinaria.</p>
|
||||
<div class="callout danger">
|
||||
<div class="h">Importante: activa Actions</div>
|
||||
En el fork: <strong>Settings → Actions → Enable Actions</strong>. Sin esto los workflows no corren.
|
||||
<span class="muted">(No se puede activar vía API en este build — hay que hacerlo en la UI.)</span>
|
||||
</div>
|
||||
</li>
|
||||
<li>
|
||||
<h4>Apunta al upstream (el "remote")</h4>
|
||||
<p class="muted">En el fork: <strong>Settings → Actions → Variables & Secrets</strong>. Crea:</p>
|
||||
<table>
|
||||
<tr><th>Tipo</th><th>Nombre</th><th>Valor</th></tr>
|
||||
<tr><td>Variable</td><td><code>UPSTREAM_URL</code></td>
|
||||
<td><code>https://github.com/owner/repo.git</code> (cualquier provider)</td></tr>
|
||||
<tr><td>Secret</td><td><code>UPSTREAM_TOKEN</code></td>
|
||||
<td>un token que pueda <em>leer</em> ese upstream</td></tr>
|
||||
</table>
|
||||
<p class="muted">Los valores <code>GITEA_*</code> (server, owner, repo, token) se inyectan solos con el
|
||||
contexto de Gitea Actions — no los configuras.</p>
|
||||
</li>
|
||||
<li>
|
||||
<h4>(Opcional) Ajusta la config y compila releases</h4>
|
||||
<p class="muted">Edita <code>.forker.yaml</code> en la rama <code>forker</code> para elegir branches,
|
||||
intervalo, y — si quieres releases por build — el <code>build_cmd</code> y los <code>artifacts</code>.</p>
|
||||
</li>
|
||||
<li>
|
||||
<h4>Verifica que un runner lo sirve y lanza</h4>
|
||||
<p class="muted">Si aún no hay runner compartido, ver la sección <a href="#runner">Runner</a>. Después:
|
||||
<strong>Settings → Actions → "Runner check" → Run</strong> para confirmar, y "Sync" para un sync manual.
|
||||
El cron se encargará del resto.</p>
|
||||
</li>
|
||||
</ol>
|
||||
</section>
|
||||
|
||||
<!-- ==================== RUNNER ==================== -->
|
||||
<section id="runner">
|
||||
<h2><span class="n">06</span>Runner (el "gitea worker")</h2>
|
||||
<p class="lead">El cron y el build local necesitan un <strong>runner de Gitea Actions</strong>. En este
|
||||
build los runners son <em>repo-scoped</em>: uno registrado en un repo no sirve a otro. La solución limpia es
|
||||
<strong>un runner shared</strong> registrado una vez, que sirve a <em>todos</em> los forks.</p>
|
||||
|
||||
<div class="callout ok">
|
||||
<div class="h">Ya está montado en tu instancia</div>
|
||||
<code>gitea-runner-forker</code> <span class="badge on">online</span> — registro a nivel de instancia
|
||||
(global) con la imagen <code>gitea/act_runner:0.6.1</code>. Sirve a todos los repos, incluida la rama de
|
||||
forks. No tienes que hacer nada más.
|
||||
</div>
|
||||
|
||||
<h3>Si necesitas registrar uno nuevo (Docker)</h3>
|
||||
<p>Un runner registrado con un <strong>token de instancia</strong> es, por definición, compartido:</p>
|
||||
<pre><code>docker run -d \
|
||||
--name gitea-shared-runner \
|
||||
--restart unless-stopped \
|
||||
-v /var/run/docker.sock:/var/run/docker.sock \
|
||||
-v gitea-shared-runner-data:/data \
|
||||
-e GITEA_INSTANCE_URL=https://git.lago.dev/ \
|
||||
-e GITEA_RUNNER_NAME=gitea-shared-runner \
|
||||
-e GITEA_RUNNER_REGISTRATION_TOKEN=<token-de-instancia> \
|
||||
gitea/act_runner:0.6.1</code></pre>
|
||||
<ul class="clean">
|
||||
<li>El token de instancia se genera en <strong>Admin → Actions → Runners</strong> (o vía API
|
||||
<code>POST /api/v1/admin/actions/runners/registration-token</code>).</li>
|
||||
<li>Si el contenedor arranca y el log dice <code>declare successfully</code> con un nombre antiguo, es que
|
||||
<code>/data</code> ya tenía un fichero <code>.runner</code>: <strong>bórralo</strong> para que registre de
|
||||
cero con el token nuevo.</li>
|
||||
<li>Para renombrar: cambia <code>GITEA_RUNNER_NAME</code> y borra <code>.runner</code> (el nombre se fija en
|
||||
el registro; no se puede cambiar solo por UI).</li>
|
||||
<li>Si un job necesita docker <em>dentro</em>, usa la variante <code>-dind</code>. Para git + compilar, la normal basta.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<!-- ==================== CONFIG ==================== -->
|
||||
<section id="config">
|
||||
<h2><span class="n">07</span>Configuración (<code>.forker.yaml</code>)</h2>
|
||||
<p class="lead">Todo es opcional; hay defaults razonables. Vive en la rama <code>forker</code>.
|
||||
<strong>Nada que sea un secret va aquí</strong> (eso va en Variables & Secrets).</p>
|
||||
<table>
|
||||
<tr><th>Clave</th><th>Default</th><th>Qué hace</th></tr>
|
||||
<tr><td><code>token_user</code></td><td><code>oauth2</code></td>
|
||||
<td>Username para el token del upstream. <em>Nota:</em> con auth Bearer (actual) este valor ya no se usa
|
||||
para git; se conserva para compatibilidad.</td></tr>
|
||||
<tr><td><code>mirror_tags</code></td><td><code>true</code></td><td>Espejar todos los tags.</td></tr>
|
||||
<tr><td><code>mirror_prune</code></td><td><code>true</code></td><td>Borrar branches/tags que el upstream eliminó.</td></tr>
|
||||
<tr><td><code>mirror_branches</code></td><td><code>*</code></td><td><code>*</code>=todas, o lista <code>main,develop</code>.</td></tr>
|
||||
<tr><td><code>on_new_tag</code></td><td><code>true</code></td><td>Compilar + publicar release al detectar un tag nuevo.</td></tr>
|
||||
<tr><td><code>mirror_upstream_releases</code></td><td><code>false</code></td><td>Además, copiar la release (metadata+assets) del upstream.</td></tr>
|
||||
<tr><td><code>build_cmd</code></td><td>—</td><td>Comando(s) de build (separados por <code>;</code>) en el árbol del tag.</td></tr>
|
||||
<tr><td><code>build_script</code></td><td>—</td><td>Ruta a un script de build (dentro de la rama <code>forker</code>). Sustituye a <code>build_cmd</code>.</td></tr>
|
||||
<tr><td><code>artifacts</code></td><td>—</td><td>Globs (relativos al tag) de los ficheros a adjuntar como assets.</td></tr>
|
||||
</table>
|
||||
|
||||
<h3>Ejemplo</h3>
|
||||
<pre><code># Espejar todo, compilar un binario cuando aparezca un tag
|
||||
token_user: oauth2
|
||||
mirror_branches: "*"
|
||||
on_new_tag: true
|
||||
build_cmd: "mkdir -p dist && make build && cp out/myapp dist/"
|
||||
artifacts: "dist/*"</code></pre>
|
||||
</section>
|
||||
|
||||
<!-- ==================== LAYOUT ==================== -->
|
||||
<section id="layout">
|
||||
<h2><span class="n">08</span>Estructura del repo</h2>
|
||||
<pre><code>repo-forker/
|
||||
├── .gitea/workflows/
|
||||
│ ├── sync.yml # cron: espeja el upstream (el "worker")
|
||||
│ ├── release.yml # MANUAL: build + publica una release
|
||||
│ └── runner-check.yml # verifica que un runner sirve este repo
|
||||
├── forker/
|
||||
│ ├── sync.sh # fetch mirror + push refs + prune + release inline
|
||||
│ ├── release.sh # build local / espejo upstream + publica (idempotente)
|
||||
│ ├── runner-register.sh # registra un runner (shared / por-repo)
|
||||
│ └── lib/
|
||||
│ ├── config.sh # lee .forker.yaml
|
||||
│ └── provider.sh # detecta provider + API de releases (Gitea/GitHub/Codeberg)
|
||||
├── docs/index.html # ← esta página
|
||||
├── .mirror/ # bare mirror (gitignored, en cache)
|
||||
├── .forker.yaml # config por fork (no-secreta)
|
||||
├── runner/docker-compose.yml
|
||||
├── Makefile
|
||||
└── README.md</code></pre>
|
||||
</section>
|
||||
|
||||
<!-- ==================== FAQ ==================== -->
|
||||
<section id="faq">
|
||||
<h2><span class="n">09</span>FAQ / Limitaciones</h2>
|
||||
<div class="cols">
|
||||
<div>
|
||||
<h3>¿Cuánto pesa el mirror?</h3>
|
||||
<p class="muted">Igual que el upstream (trae el historial completo). En el runner vive en <code>.mirror/</code>
|
||||
(efímero + cache). En tu disco, solo si lo ejecutas en local.</p>
|
||||
|
||||
<h3>¿Las branches espejadas son read-only?</h3>
|
||||
<p class="muted">Se sobre escriben en cada sync (<code>--force</code>). No hagas commits en ellas; la rama
|
||||
<strong>de trabajo</strong> es <code>forker</code>.</p>
|
||||
|
||||
<h3>¿Funciona con upstream privado?</h3>
|
||||
<p class="muted">Sí, si <code>UPSTREAM_TOKEN</code> puede leerlo. La auth es Bearer per-URL, así que funciona
|
||||
incluso si el upstream privado está en la <em>misma</em> instancia que el fork.</p>
|
||||
</div>
|
||||
<div>
|
||||
<h3>¿Qué pasa si no hay runner?</h3>
|
||||
<p class="muted">Los runs quedan en cola y no se ejecutan. Lanza el <em>Runner check</em> para diagnosticar.</p>
|
||||
|
||||
<h3>Limitación conocida de este build de Gitea</h3>
|
||||
<p class="muted">En esta instancia, las <strong>assets de release en repos-fork</strong> se listan bien pero su
|
||||
descarga por <code>browser_download_url</code> devuelve 404 (en repos no-fork funciona). Es un bug del fork en
|
||||
Gitea, no de Repo Forker. El tarball de release (código) sí funciona. Si necesitas binarios descargables en el
|
||||
fork, hay que corregirlo a nivel de Gitea.</p>
|
||||
|
||||
<h3>¿Puedo versionar la maquinaria?</h3>
|
||||
<p class="muted">Sí: toda la maquinaria vive en la rama <code>forker</code> y es tu código normal. Si mejoras
|
||||
un script, hazle commit ahí y el siguiente sync usa la versión nueva.</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<footer>
|
||||
Repo Forker · template para espejos git en Gitea · verificado end-to-end contra git.lago.dev (Gitea 28.1.0,
|
||||
runner gitea-act_runner v0.6.1) · <a href="../">← volver al README</a>
|
||||
</footer>
|
||||
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
Before Width: | Height: | Size: 469 KiB |
@@ -0,0 +1,198 @@
|
||||
#!/usr/bin/env bash
|
||||
# check-unit.sh — verify the Releases unit is enabled on this repo (the fork).
|
||||
#
|
||||
# WHY: Gitea creates FORKS with DefaultForkRepoUnits = [Code, PullRequests] —
|
||||
# NO Releases unit. Without it, release ASSETS on the fork 404 on the web
|
||||
# download route (browser_download_url) even though the API lists them
|
||||
# correctly (by-id works). The release source tarball 404s too. So a fork
|
||||
# silently produces un-downloadable releases.
|
||||
#
|
||||
# This script:
|
||||
# 1. If the units API exists (newer Gitea builds): checks the Releases unit
|
||||
# and, if it is disabled, ENABLES IT via the API (self-healing).
|
||||
# 2. If the units API is absent (this build): probes the web download URL of
|
||||
# the latest release's asset — 200 = OK, 404 = unit missing.
|
||||
# 3. Prints a loud one-time-style warning with the exact UI fix when the
|
||||
# unit is missing (there is no API to fix it on this build).
|
||||
#
|
||||
# Exit codes: 0 = ok / not-verifiable, 10 = Releases unit missing (or
|
||||
# auto-fix failed), 1 = environment error.
|
||||
#
|
||||
# Inputs: GITEA_SERVER_URL, GITEA_OWNER, GITEA_REPO, GITEA_TOKEN (optional).
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
GITEA_SERVER_URL="${GITEA_SERVER_URL:?GITEA_SERVER_URL is required}"
|
||||
GITEA_OWNER="${GITEA_OWNER:?GITEA_OWNER is required}"
|
||||
GITEA_REPO="${GITEA_REPO:?GITEA_REPO is required}"
|
||||
GITEA_TOKEN="${GITEA_TOKEN:-}"
|
||||
|
||||
auth=()
|
||||
if [ -n "$GITEA_TOKEN" ]; then
|
||||
# API token (Bearer) or password (Basic) — use whichever Gitea accepts.
|
||||
# GITEA_TOKEN from Actions is an API token -> Bearer.
|
||||
auth=(-H "Authorization: Bearer $GITEA_TOKEN")
|
||||
fi
|
||||
|
||||
api() { # api <path> — GET with auth, prints body (or empty)
|
||||
curl -sS --max-time 30 ${auth[@]+"${auth[@]}"} \
|
||||
"$GITEA_SERVER_URL/api/v1$1" 2>/dev/null || true
|
||||
}
|
||||
|
||||
http_code() { # http_code <path> — GET status code
|
||||
curl -sS --max-time 30 -o /dev/null -w "%{http_code}" \
|
||||
${auth[@]+"${auth[@]}"} "$GITEA_SERVER_URL/api/v1$1" 2>/dev/null || echo 000
|
||||
}
|
||||
|
||||
WARN() {
|
||||
echo "!! ==============================================================="
|
||||
echo "!! Releases unit is DISABLED on $GITEA_OWNER/$GITEA_REPO."
|
||||
echo "!! This is a known Gitea fork quirk: forks are created WITHOUT the"
|
||||
echo "!! Releases unit, so release assets 404 on the web download route"
|
||||
echo "!! (the API lists them fine, but you can't download them)."
|
||||
echo "!!"
|
||||
echo "!! Fix (one-time): UI -> Settings -> Repository -> enable the"
|
||||
echo "!! 'Releases' unit. (The units API is unavailable on this Gitea"
|
||||
echo "!! build, so it can't be fixed automatically.)"
|
||||
echo "!! Until then: releases exist but their assets are not downloadable."
|
||||
echo "!! ==============================================================="
|
||||
}
|
||||
|
||||
# --- 1) units API path (self-healing on builds that have it) -------------
|
||||
# NOTE on the API shape (Gitea Unit JSON): `enabled` is a TOP-LEVEL field,
|
||||
# and the PATCH body (UnitOption) expects `enabled` top-level too — NOT
|
||||
# nested under "config". (Gitea's Go struct: Unit{..., Enabled bool,
|
||||
# Config UnitConfig}; the config object only holds per-unit options like
|
||||
# auto_merge.) Reading/PATCHing the wrong field made the old code
|
||||
# "fix" a unit that was already enabled and report a false success.
|
||||
CODE_UNITS="$(http_code "/repos/$GITEA_OWNER/$GITEA_REPO/units")"
|
||||
if [ "$CODE_UNITS" = "200" ]; then
|
||||
# Prints: <enabled:True/False> or <missing> if there is no Releases unit row.
|
||||
state="$(api "/repos/$GITEA_OWNER/$GITEA_REPO/units" | python3 -c '
|
||||
import sys, json
|
||||
try:
|
||||
d = json.load(sys.stdin)
|
||||
except Exception:
|
||||
sys.exit(1)
|
||||
units = d if isinstance(d, list) else d.get("units", [])
|
||||
for u in units:
|
||||
if u.get("unit_type") == 4 or "releases" in str(u.get("name","")).lower():
|
||||
print(u.get("enabled", False))
|
||||
break
|
||||
else:
|
||||
print("missing")
|
||||
' 2>/dev/null || echo unknown)"
|
||||
if [ "$state" = "missing" ]; then
|
||||
# no unit row at all -> add it via POST (some builds support this)
|
||||
resp="$(curl -sS --max-time 30 -o /dev/null -w "%{http_code}" \
|
||||
${auth[@]+"${auth[@]}"} -X POST \
|
||||
"$GITEA_SERVER_URL/api/v1/repos/$GITEA_OWNER/$GITEA_REPO/units" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"unit_type":4,"config":{"enabled":true}}' 2>/dev/null || echo 000)"
|
||||
if [ "$resp" != "201" ] && [ "$resp" != "200" ]; then
|
||||
echo ">> Units API: Releases unit row missing and POST failed (HTTP $resp) — manual fix needed."
|
||||
WARN
|
||||
exit 10
|
||||
fi
|
||||
elif [ "$state" = "False" ] || [ "$state" = "false" ] || [ -z "$state" ] || [ "$state" = "unknown" ]; then
|
||||
# disabled (or unknown) -> try to enable via PATCH (top-level `enabled`)
|
||||
resp="$(curl -sS --max-time 30 -o /dev/null -w "%{http_code}" \
|
||||
${auth[@]+"${auth[@]}"} -X PATCH \
|
||||
"$GITEA_SERVER_URL/api/v1/repos/$GITEA_OWNER/$GITEA_REPO/units/4" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"enabled":true}' 2>/dev/null || echo 000)"
|
||||
if [ "$resp" != "200" ]; then
|
||||
echo ">> Units API present but PATCH failed (HTTP $resp) — manual fix needed."
|
||||
WARN
|
||||
exit 10
|
||||
fi
|
||||
fi
|
||||
# RE-VERIFY after any mutation (a 200 alone is not proof of change).
|
||||
after="$(api "/repos/$GITEA_OWNER/$GITEA_REPO/units" | python3 -c '
|
||||
import sys, json
|
||||
try:
|
||||
d = json.load(sys.stdin)
|
||||
except Exception:
|
||||
sys.exit(1)
|
||||
units = d if isinstance(d, list) else d.get("units", [])
|
||||
for u in units:
|
||||
if u.get("unit_type") == 4 or "releases" in str(u.get("name","")).lower():
|
||||
print("True" if u.get("enabled") else "False")
|
||||
break
|
||||
else:
|
||||
print("missing")
|
||||
' 2>/dev/null || echo unknown)"
|
||||
if [ "$after" = "True" ]; then
|
||||
if [ "$state" = "$after" ]; then
|
||||
echo ">> Releases unit enabled (verified via units API)."
|
||||
else
|
||||
echo ">> Fixed: enabled the Releases unit via the units API (verified)."
|
||||
fi
|
||||
exit 0
|
||||
fi
|
||||
echo ">> Units API: still not enabled after the attempt (state: $after) — manual fix needed."
|
||||
WARN
|
||||
exit 10
|
||||
fi
|
||||
|
||||
# --- 2) fallback: web download probe (units API absent) --------------------
|
||||
# Find the latest release that has at least one asset.
|
||||
probe_url="$(api "/repos/$GITEA_OWNER/$GITEA_REPO/releases?limit=10" | python3 -c '
|
||||
import sys, json
|
||||
try:
|
||||
d = json.load(sys.stdin)
|
||||
except Exception:
|
||||
sys.exit(0)
|
||||
for r in (d if isinstance(d, list) else []):
|
||||
assets = r.get("assets") or []
|
||||
if assets:
|
||||
print(assets[0].get("browser_download_url",""))
|
||||
break
|
||||
' 2>/dev/null || true)"
|
||||
|
||||
if [ -z "$probe_url" ]; then
|
||||
echo ">> Cannot verify the Releases unit (no release with assets yet)."
|
||||
echo ">> NOTE: if this is a fork, remember to enable the 'Releases' unit"
|
||||
echo ">> (Settings -> Repository) once releases appear, or asset downloads 404."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
code="$(curl -sS --max-time 60 -o /dev/null -w "%{http_code}" \
|
||||
${auth[@]+"${auth[@]}"} "$probe_url" 2>/dev/null || echo 000)"
|
||||
case "$code" in
|
||||
200|301|302|303)
|
||||
echo ">> Releases unit OK (web asset download works: HTTP $code)."
|
||||
exit 0
|
||||
;;
|
||||
404)
|
||||
# Confirm it is the unit (not a deleted asset): the API by-id path
|
||||
# bypasses the unit-permission check. If it 200s while the web route
|
||||
# 404s, the Releases unit is the culprit.
|
||||
api_by_id="$(api "/repos/$GITEA_OWNER/$GITEA_REPO/releases?limit=10" | python3 -c '
|
||||
import sys, json
|
||||
try:
|
||||
d = json.load(sys.stdin)
|
||||
except Exception:
|
||||
sys.exit(0)
|
||||
for r in (d if isinstance(d, list) else []):
|
||||
a = r.get("assets") or []
|
||||
if a:
|
||||
print(r.get("id", 0), a[0].get("id", 0))
|
||||
break
|
||||
' 2>/dev/null || true)"
|
||||
if [ -n "$api_by_id" ]; then
|
||||
set -- $api_by_id
|
||||
rid="$1" aid="$2"
|
||||
api_code="$(curl -sS --max-time 30 -o /dev/null -w "%{http_code}" \
|
||||
${auth[@]+"${auth[@]}"} \
|
||||
"$GITEA_SERVER_URL/api/v1/repos/$GITEA_OWNER/$GITEA_REPO/releases/$rid/assets/$aid" 2>/dev/null || echo 000)"
|
||||
[ "$api_code" = "200" ] && echo ">> Confirmed: API by-id works (HTTP 200) but web route 404s -> Releases unit missing."
|
||||
fi
|
||||
WARN
|
||||
exit 10
|
||||
;;
|
||||
*)
|
||||
echo ">> Releases unit check inconclusive (HTTP $code on asset probe)."
|
||||
exit 0
|
||||
;;
|
||||
esac
|
||||
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env bash
|
||||
# config.sh — load .forker.yaml (flat key: value) into shell variables.
|
||||
# Sourced by other scripts. Keeps the YAML trivial (no nesting) so a simple
|
||||
# parser is robust and the file stays human-editable in the Gitea UI.
|
||||
|
||||
# cfg_get <key> <default>
|
||||
cfg_get() {
|
||||
local key="$1" default="$2"
|
||||
local file="${CONFIG_FILE:-.forker.yaml}"
|
||||
[ -f "$file" ] || { echo "$default"; return; }
|
||||
local val
|
||||
val="$(grep -E "^[[:space:]]*${key}[[:space:]]*:" "$file" | head -n1 \
|
||||
| sed -E "s/^[[:space:]]*${key}[[:space:]]*:[[:space:]]*//" \
|
||||
| sed -E 's/[[:space:]]+#.*$//' \
|
||||
| sed -E 's/^"(.*)"$/\1/; s/^'"'"'(.*)'"'"'$/\1/' \
|
||||
| sed -E 's/[[:space:]]+$//')"
|
||||
[ -z "$val" ] && val="$default"
|
||||
echo "$val"
|
||||
}
|
||||
|
||||
# load_config sets: TOKEN_USER, MIRROR_TAGS, MIRROR_PRUNE, MIRROR_BRANCHES,
|
||||
# ON_NEW_TAG, MIRROR_UPSTREAM_RELEASES, BUILD_CMD, BUILD_SCRIPT, ARTIFACTS
|
||||
load_config() {
|
||||
TOKEN_USER="$(cfg_get token_user "oauth2")"
|
||||
MIRROR_TAGS="$(cfg_get mirror_tags "true")"
|
||||
MIRROR_PRUNE="$(cfg_get mirror_prune "true")"
|
||||
MIRROR_BRANCHES="$(cfg_get mirror_branches "*")"
|
||||
ON_NEW_TAG="$(cfg_get on_new_tag "true")"
|
||||
MIRROR_UPSTREAM_RELEASES="$(cfg_get mirror_upstream_releases "false")"
|
||||
BUILD_CMD="$(cfg_get build_cmd "")"
|
||||
BUILD_SCRIPT="$(cfg_get build_script "")"
|
||||
ARTIFACTS="$(cfg_get artifacts "")"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
#!/usr/bin/env bash
|
||||
# provider.sh — detect the upstream provider and expose a uniform releases API.
|
||||
#
|
||||
# Sourced by other scripts. Provides:
|
||||
# detect_provider <url> -> prints gitea|github|codeberg|unknown
|
||||
# releases_api_base <url> -> prints the REST base for the repo
|
||||
# releases_auth_header <url> -> prints "Authorization: ..." line
|
||||
# list_releases <url> <token> -> prints JSON array of releases (normalized)
|
||||
# get_release <url> <token> <tag> -> prints one release JSON
|
||||
# download_asset <url> <token> <asset_url> <dest>
|
||||
#
|
||||
# The token is passed in (from the Gitea Actions secret), never read from the
|
||||
# repo. Provider differences are isolated here so the rest of the code is
|
||||
# provider-agnostic.
|
||||
|
||||
set -o pipefail
|
||||
|
||||
# --- detection ---------------------------------------------------------------
|
||||
# Bare hostname from a URL: "https://host", "https://host/", or "https://host/path".
|
||||
host_of() { local u="${1#*://}"; echo "${u%%/*}"; }
|
||||
|
||||
# Base URL with scheme, no path: "https://host" (for building absolute API URLs).
|
||||
base_url_of() {
|
||||
local u="$1" scheme rest host
|
||||
scheme="${u%%://*}"; rest="${u#*://}" # split off scheme
|
||||
host="${rest%%/*}" # host (stop at first /)
|
||||
echo "${scheme}://${host}"
|
||||
}
|
||||
|
||||
detect_provider() {
|
||||
local url="${1:-}"
|
||||
local host
|
||||
host="$(host_of "$url")"
|
||||
case "$host" in
|
||||
github.com|api.github.com|githubusercontent.com) echo "github" ;;
|
||||
codeberg.org|*.codeberg.org) echo "codeberg" ;;
|
||||
gitea.com|*.gitea.com) echo "gitea" ;;
|
||||
*)
|
||||
# Fallback: unknown hosts are treated as Gitea-compatible (the most common
|
||||
# self-hosted shape). The releases API is Gitea's; if a host speaks a
|
||||
# different dialect the mirror step will simply find no matching release.
|
||||
echo "gitea"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# owner/repo from a clone URL (https://host/owner/repo.git or .../owner/repo)
|
||||
owner_repo() {
|
||||
local url="${1:-}"
|
||||
# strip protocol, host, .git, trailing slash
|
||||
local path
|
||||
path="${url#*://}"
|
||||
path="${path#*/}" # drop host
|
||||
path="${path%.git}"
|
||||
path="${path%/}"
|
||||
echo "$path" # owner/repo
|
||||
}
|
||||
|
||||
# --- releases API -----------------------------------------------------------
|
||||
# Each provider returns a slightly different shape. We normalize to:
|
||||
# [{"tag": "...", "name": "...", "body": "...", "assets": [{"name": "...", "url": "...", "size": N}]}]
|
||||
|
||||
# auth_args <token> — sets the global AUTH_ARGS array to -H "Authorization:
|
||||
# Bearer <token>", or empty. An empty Bearer header makes GitHub reject the
|
||||
# request (401 "Bad credentials"); public repos need no auth at all.
|
||||
auth_args() {
|
||||
local token="${1:-}"
|
||||
AUTH_ARGS=()
|
||||
if [ -n "$token" ]; then
|
||||
AUTH_ARGS=(-H "Authorization: Bearer $token")
|
||||
fi
|
||||
}
|
||||
|
||||
list_releases() {
|
||||
local url="${1:-}"
|
||||
local token="${2:-}"
|
||||
local provider
|
||||
provider="$(detect_provider "$url")"
|
||||
local base owner_repo_ api
|
||||
base="$(base_url_of "$url")"
|
||||
owner_repo_="$(owner_repo "$url")"
|
||||
# GitHub's REST API lives on api.github.com (no /api/v1 prefix), while
|
||||
# Gitea/Codeberg use <host>/api/v1.
|
||||
if [ "$provider" = "github" ]; then
|
||||
api="https://api.github.com/repos/$owner_repo_/releases"
|
||||
else
|
||||
api="$base/api/v1/repos/$owner_repo_/releases"
|
||||
fi
|
||||
auth_args "$token"
|
||||
local clone_base
|
||||
clone_base="$(github_clone_base "$url")"
|
||||
|
||||
case "$provider" in
|
||||
github)
|
||||
# GitHub: token via header (only when set), per_page for pagination
|
||||
# shellcheck disable=SC2068 # AUTH_ARGS is a safe -H pair
|
||||
curl -sS --max-time 60 \
|
||||
${AUTH_ARGS[@]+"${AUTH_ARGS[@]}"} \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
"$api?per_page=100" | _norm_releases github "$clone_base"
|
||||
;;
|
||||
gitea|codeberg)
|
||||
# Gitea and Codeberg both use the Gitea API shape; Bearer works for both.
|
||||
# shellcheck disable=SC2068 # AUTH_ARGS is a safe -H pair
|
||||
curl -sS --max-time 60 \
|
||||
${AUTH_ARGS[@]+"${AUTH_ARGS[@]}"} \
|
||||
"$api?limit=100" | _norm_releases gitea "$clone_base"
|
||||
;;
|
||||
*)
|
||||
echo "[]"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
get_release() {
|
||||
local url="${1:-}" token="${2:-}" tag="${3:-}"
|
||||
local provider base owner_repo_ api
|
||||
provider="$(detect_provider "$url")"
|
||||
base="$(base_url_of "$url")"
|
||||
owner_repo_="$(owner_repo "$url")"
|
||||
# GitHub's REST API lives on api.github.com (no /api/v1 prefix), while
|
||||
# Gitea/Codeberg use <host>/api/v1.
|
||||
if [ "$provider" = "github" ]; then
|
||||
api="https://api.github.com/repos/$owner_repo_/releases/tags/$tag"
|
||||
else
|
||||
api="$base/api/v1/repos/$owner_repo_/releases/tags/$tag"
|
||||
fi
|
||||
# Bearer only when a token is set (public repos: no auth header at all).
|
||||
# The clone URL + tag are passed so GitHub assets resolve to the web
|
||||
# download URL (unthrottled) instead of the REST asset endpoint.
|
||||
local clone_base code body rc
|
||||
clone_base="$(github_clone_base "$url")"
|
||||
# Capture the HTTP code: a 404 (no release for this tag upstream) must be
|
||||
# distinguishable from a valid-but-empty release, so it is NOT normalized
|
||||
# into a pseudo-release with zero assets.
|
||||
body="$(mktemp)"
|
||||
if [ -n "$token" ]; then
|
||||
code="$(curl -sS --max-time 60 -o "$body" -w '%{http_code}' \
|
||||
-H "Authorization: Bearer $token" "$api" 2>/dev/null || echo 000)"
|
||||
else
|
||||
code="$(curl -sS --max-time 60 -o "$body" -w '%{http_code}' \
|
||||
"$api" 2>/dev/null || echo 000)"
|
||||
fi
|
||||
case "$code" in
|
||||
200) _norm_release "$provider" "$clone_base" "$tag" < "$body"; rc=0 ;;
|
||||
404) echo '{}'; rc=0 ;;
|
||||
*) echo "ERROR: get_release $tag returned HTTP $code" >&2; rc=1 ;;
|
||||
esac
|
||||
rm -f "$body"
|
||||
return "$rc"
|
||||
}
|
||||
|
||||
# github_clone_base <url> -> "https://github.com/owner/repo" (or "" for
|
||||
# non-GitHub). Used to build the unthrottled web asset download URL.
|
||||
github_clone_base() {
|
||||
local url="${1:-}" host path
|
||||
host="$(host_of "$url")"
|
||||
case "$host" in
|
||||
github.com)
|
||||
path="${url#*://}"; path="${path#*/}" # owner/repo[.git]
|
||||
path="${path%.git}"
|
||||
echo "https://github.com/$path"
|
||||
;;
|
||||
*) echo "" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Normalize a single release object.
|
||||
# _norm_release <provider> <clone_base> <tag>
|
||||
# For GitHub, when the asset's download_url is null (true for releases
|
||||
# addressed by tag), resolve the asset to the WEB download URL
|
||||
# (<clone_base>/releases/download/<tag>/<name>) — this is unthrottled,
|
||||
# unlike the REST asset endpoint (60 req/h unauthenticated). Falls back to
|
||||
# the API url (which download_asset handles via Accept: octet-stream).
|
||||
_norm_release() {
|
||||
local provider="$1" clone_base="${2:-}" tag="${3:-}"
|
||||
# NOTE: use `python3 -c` (script as a string) so STDIN remains the curl pipe.
|
||||
# A heredoc (`python3 - <<'PY'`) would consume stdin and the JSON would be lost.
|
||||
CB="$clone_base" TAG="$tag" PROVIDER="$provider" python3 -c '
|
||||
import sys, json, os
|
||||
cb = os.environ.get("CB","")
|
||||
tag = os.environ.get("TAG","")
|
||||
prov = os.environ.get("PROVIDER","")
|
||||
try:
|
||||
d = json.load(sys.stdin)
|
||||
except Exception:
|
||||
print("{}"); sys.exit(0)
|
||||
if not isinstance(d, dict):
|
||||
print("{}"); sys.exit(0)
|
||||
assets = []
|
||||
for a in (d.get("assets") or []):
|
||||
name = a.get("name")
|
||||
u = a.get("download_url") or a.get("url") or a.get("browser_download_url")
|
||||
if prov == "github" and not a.get("download_url") and cb and tag and name:
|
||||
# REST asset url -> unthrottled web url
|
||||
u = cb + "/releases/download/" + tag + "/" + name
|
||||
assets.append({"name": name, "url": u, "size": a.get("size")})
|
||||
print(json.dumps({
|
||||
"tag": d.get("tag_name"),
|
||||
"name": d.get("name"),
|
||||
"body": d.get("body") or d.get("description") or "",
|
||||
"assets": assets,
|
||||
}))'
|
||||
}
|
||||
|
||||
# Normalize a list of release objects.
|
||||
# _norm_releases <provider> <clone_base>
|
||||
# GitHub assets resolve to the unthrottled web download URL when possible
|
||||
# (see _norm_release); non-GitHub providers ignore clone_base.
|
||||
_norm_releases() {
|
||||
local provider="$1" clone_base="${2:-}"
|
||||
# stdin must stay the curl pipe -> use `python3 -c`, not a heredoc.
|
||||
CB="$clone_base" PROVIDER="$provider" python3 -c '
|
||||
import sys, json, os
|
||||
cb = os.environ.get("CB","")
|
||||
prov = os.environ.get("PROVIDER","")
|
||||
try:
|
||||
d = json.load(sys.stdin)
|
||||
except Exception:
|
||||
print("[]"); sys.exit(0)
|
||||
if not isinstance(d, list):
|
||||
print("[]"); sys.exit(0)
|
||||
out = []
|
||||
for r in d:
|
||||
tag = r.get("tag_name") or ""
|
||||
assets = []
|
||||
for a in (r.get("assets") or []):
|
||||
name = a.get("name")
|
||||
u = a.get("download_url") or a.get("url") or a.get("browser_download_url")
|
||||
if prov == "github" and not a.get("download_url") and cb and tag and name:
|
||||
u = cb + "/releases/download/" + tag + "/" + name
|
||||
assets.append({"name": name, "url": u, "size": a.get("size")})
|
||||
out.append({
|
||||
"tag": tag,
|
||||
"name": r.get("name"),
|
||||
"body": r.get("body") or r.get("description") or "",
|
||||
"assets": assets,
|
||||
})
|
||||
print(json.dumps(out))'
|
||||
}
|
||||
|
||||
download_asset() {
|
||||
local url="${1:-}" token="${2:-}" asset_url="${3:-}" dest="${4:-}"
|
||||
# Accept: application/octet-stream is REQUIRED for GitHub: for a release
|
||||
# addressed by tag, the asset's `download_url` is null, so the API `url`
|
||||
# is used — without this header it returns the asset's JSON metadata
|
||||
# (HTTP 200, ~1.8 KB) instead of the binary file. Harmless for direct
|
||||
# file URLs (Gitea/Codeberg browser_download_url).
|
||||
#
|
||||
# Fail LOUDLY: a 404 / rate-limit body must not be written to $dest and
|
||||
# then attached as a (corrupt/JSON) asset. --fail makes curl exit non-zero
|
||||
# on HTTP >= 400; we also delete a partial file on failure so the caller's
|
||||
# set -e aborts the release instead of shipping a bad asset.
|
||||
local rc=0
|
||||
if [ -n "$token" ]; then
|
||||
curl -sSL --fail --max-time 300 -H "Authorization: Bearer $token" \
|
||||
-H "Accept: application/octet-stream" -o "$dest" "$asset_url" || rc=$?
|
||||
else
|
||||
curl -sSL --fail --max-time 300 -H "Accept: application/octet-stream" \
|
||||
-o "$dest" "$asset_url" || rc=$?
|
||||
fi
|
||||
if [ "$rc" -ne 0 ]; then
|
||||
rm -f "$dest"
|
||||
echo "ERROR: asset download failed (curl exit $rc): $asset_url" >&2
|
||||
return 1
|
||||
fi
|
||||
[ -s "$dest" ] || { rm -f "$dest"; echo "ERROR: asset download empty: $asset_url" >&2; return 1; }
|
||||
}
|
||||
|
||||
# Does a release for this tag already exist on THIS gitea? Prints yes/no.
|
||||
# release_exists <gitea_url> <owner/repo> <token> <tag>
|
||||
release_exists() {
|
||||
local gitea_url="${1:-}" owner_repo_="${2:-}" token="${3:-}" tag="${4:-}"
|
||||
local code
|
||||
code="$(curl -sS --max-time 30 -o /dev/null -w "%{http_code}" \
|
||||
-H "Authorization: Bearer $token" \
|
||||
"$gitea_url/api/v1/repos/$owner_repo_/releases/tags/$tag")"
|
||||
[ "$code" = "200" ] && echo "yes" || echo "no"
|
||||
}
|
||||
|
||||
# Publish a release on THIS gitea (the fork). Token is the Gitea token.
|
||||
# publish_local_release <gitea_url> <owner/repo> <token> <tag> <name> <body> [asset_file ...]
|
||||
publish_local_release() {
|
||||
local gitea_url="${1:-}" owner_repo_="${2:-}" token="${3:-}" tag="${4:-}"
|
||||
local name="${5:-}" body="${6:-}"
|
||||
shift 6
|
||||
local assets=(${@+"$@"})
|
||||
|
||||
# Create the release (tag must already exist in the repo).
|
||||
local resp
|
||||
resp="$(curl -sS --max-time 60 -X POST \
|
||||
-H "Authorization: Bearer $token" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "$(python3 -c 'import sys,json;print(json.dumps({"tag_name":sys.argv[1],"name":sys.argv[2],"body":sys.argv[3]}))' "$tag" "$name" "$body")" \
|
||||
"$gitea_url/api/v1/repos/$owner_repo_/releases")"
|
||||
local release_id
|
||||
release_id="$(echo "$resp" | python3 -c 'import sys,json;print(json.load(sys.stdin).get("id",""))' 2>/dev/null)"
|
||||
[ -z "$release_id" ] && { echo "ERROR: could not create release: $resp" >&2; return 1; }
|
||||
|
||||
# Attach assets (if any). Gitea's upload field is "attachment".
|
||||
# Fail LOUDLY: a failed upload (413 too large, 404, transient) must abort
|
||||
# the release, not be swallowed — release.sh's idempotency guard would
|
||||
# otherwise skip this tag forever and the release would be permanently
|
||||
# partial while every subsequent run reports green.
|
||||
local f rc
|
||||
for f in "${assets[@]}"; do
|
||||
[ -f "$f" ] || continue
|
||||
rc=0
|
||||
curl -sS --fail --max-time 300 -X POST \
|
||||
-H "Authorization: Bearer $token" \
|
||||
-F "attachment=@$f" \
|
||||
"$gitea_url/api/v1/repos/$owner_repo_/releases/$release_id/assets" \
|
||||
>/dev/null || rc=$?
|
||||
if [ "$rc" -ne 0 ]; then
|
||||
echo "ERROR: asset upload failed (curl exit $rc): $f -> release $release_id" >&2
|
||||
return 1
|
||||
fi
|
||||
done
|
||||
echo "$release_id"
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
#!/usr/bin/env bash
|
||||
# release.sh — produce a release on this Gitea fork.
|
||||
#
|
||||
# Two modes (both on by default; controlled by .forker.yaml):
|
||||
# 1. BUILD: checkout the tag's working tree, run the configured build
|
||||
# command, and publish a release (tag + assets) on this Gitea.
|
||||
# 2. MIRROR: mirror the upstream's existing releases (metadata + assets) via
|
||||
# the provider API (see lib/provider.sh).
|
||||
#
|
||||
# Inputs (from Gitea Actions Variables/Secrets):
|
||||
# GITEA_TOKEN, GITEA_SERVER_URL, GITEA_OWNER, GITEA_REPO
|
||||
# UPSTREAM_URL, UPSTREAM_TOKEN (only needed for MIRROR mode)
|
||||
#
|
||||
# Args:
|
||||
# $1 = tag to release (required)
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
source forker/lib/config.sh
|
||||
source forker/lib/provider.sh
|
||||
load_config
|
||||
|
||||
TAG="${1:?usage: release.sh <tag>}"
|
||||
GITEA_TOKEN="${GITEA_TOKEN:?GITEA_TOKEN is required}"
|
||||
GITEA_SERVER_URL="${GITEA_SERVER_URL:?GITEA_SERVER_URL is required}"
|
||||
GITEA_OWNER="${GITEA_OWNER:?GITEA_OWNER is required}"
|
||||
GITEA_REPO="${GITEA_REPO:?GITEA_REPO is required}"
|
||||
UPSTREAM_URL="${UPSTREAM_URL:-}"
|
||||
UPSTREAM_TOKEN="${UPSTREAM_TOKEN:-}"
|
||||
|
||||
# --- never touch stored git credentials (same hardening as sync.sh) ---------
|
||||
# All git calls here use explicit Bearer headers (fork build) or are
|
||||
# anonymous (upstream mirror via provider.sh). Cut global/system config and
|
||||
# the credential helper so a stored github.com entry can't be used silently.
|
||||
export GIT_CONFIG_GLOBAL=/dev/null
|
||||
export GIT_CONFIG_NOSYSTEM=1
|
||||
export GIT_CONFIG_SYSTEM=/dev/null
|
||||
|
||||
# REPO_ROOT = the forker-branch checkout (where the machinery lives). The build
|
||||
# runs inside $WORK (the tag's tree), but the build SCRIPT is resolved from here.
|
||||
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
WORK="$(mktemp -d)"
|
||||
trap 'rm -rf "$WORK"' EXIT
|
||||
|
||||
# --- idempotency: skip if this tag already has a release ---------------------
|
||||
if [ "$(release_exists "$GITEA_SERVER_URL" "$GITEA_OWNER/$GITEA_REPO" "$GITEA_TOKEN" "$TAG")" = "yes" ]; then
|
||||
echo ">> Release for $TAG already exists — skipping (idempotent)."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
cd "$WORK"
|
||||
|
||||
# --- 1) local build --------------------------------------------------------
|
||||
ASSETS=()
|
||||
BUILD_ENABLED=false
|
||||
[ -n "$BUILD_CMD" ] && BUILD_ENABLED=true
|
||||
[ -n "$BUILD_SCRIPT" ] && BUILD_ENABLED=true
|
||||
|
||||
if [ "$BUILD_ENABLED" = "true" ]; then
|
||||
echo ">> Building release for tag $TAG (local build)"
|
||||
# checkout the tag into a working tree. Bearer auth scoped to the fork URL
|
||||
# (this repo is fresh; it doesn't inherit sync.sh's http.<url> config).
|
||||
FORK_URL="$GITEA_SERVER_URL/$GITEA_OWNER/$GITEA_REPO.git"
|
||||
git init . >/dev/null
|
||||
git remote add fork "$FORK_URL"
|
||||
git config http."$FORK_URL".extraHeader "Authorization: Bearer $GITEA_TOKEN"
|
||||
git fetch --depth=1 fork "refs/tags/$TAG"
|
||||
git checkout -q FETCH_HEAD
|
||||
|
||||
if [ -n "$BUILD_SCRIPT" ]; then
|
||||
# Build script lives in the forker-branch tree (the machinery), run it with
|
||||
# cwd = the tag's tree so its artifacts land where we expect.
|
||||
[ -f "$REPO_ROOT/$BUILD_SCRIPT" ] || { echo "!! build script not found: $REPO_ROOT/$BUILD_SCRIPT" >&2; exit 1; }
|
||||
bash "$REPO_ROOT/$BUILD_SCRIPT"
|
||||
else
|
||||
eval "$BUILD_CMD"
|
||||
fi
|
||||
|
||||
# collect artifacts (globs are relative to the tag's tree = cwd)
|
||||
if [ -n "$ARTIFACTS" ]; then
|
||||
for g in $ARTIFACTS; do
|
||||
for f in $g; do
|
||||
[ -f "$f" ] && ASSETS+=("$f")
|
||||
done
|
||||
done
|
||||
fi
|
||||
fi
|
||||
|
||||
# --- 2) mirror upstream releases (metadata + assets) ------------------------
|
||||
# $WORK from mktemp -d is already absolute, so the globbed dir below resolves
|
||||
# correctly even though the cwd is now $WORK itself.
|
||||
UPSTREAM_ASSET_DIR="$WORK/upstream_assets"
|
||||
mkdir -p "$UPSTREAM_ASSET_DIR"
|
||||
# UPSTREAM_TOKEN is optional: public upstreams need no auth (get_release /
|
||||
# download_asset skip the header when the token is empty).
|
||||
MIRROR_FOUND=false
|
||||
if [ "$MIRROR_UPSTREAM_RELEASES" = "true" ] && [ -n "$UPSTREAM_URL" ]; then
|
||||
echo ">> Mirroring upstream releases for tag $TAG"
|
||||
# get_release returns '{}' (rc 0) when the upstream has no release for the
|
||||
# tag (HTTP 404); it fails loudly (rc 1) on a hard error, aborting the run.
|
||||
rel="$(get_release "$UPSTREAM_URL" "$UPSTREAM_TOKEN" "$TAG")"
|
||||
# pull the body/name from upstream if present
|
||||
BODY="$(echo "$rel" | python3 -c 'import sys,json;print(json.load(sys.stdin).get("body",""))' 2>/dev/null)"
|
||||
NAME="$(echo "$rel" | python3 -c 'import sys,json;print(json.load(sys.stdin).get("name",""))' 2>/dev/null)"
|
||||
[ -n "$NAME" ] && MIRROR_FOUND=true
|
||||
[ -n "$BODY" ] && MIRROR_FOUND=true
|
||||
# download upstream assets (avoid the subshell-loses-ASSETS trap by writing to
|
||||
# disk). Use the asset's NAME, not basename(url): a GitHub download_url ends
|
||||
# in the numeric asset id (e.g. .../assets/626817787), not the file name.
|
||||
echo "$rel" | python3 -c 'import sys,json
|
||||
for a in json.load(sys.stdin).get("assets",[]):
|
||||
if a.get("url"):
|
||||
print((a.get("name") or "asset") + "\t" + a["url"])
|
||||
' | while IFS=$'\t' read -r fn u; do
|
||||
[ -n "$fn" ] && [ -n "$u" ] || continue
|
||||
echo " asset: $fn"
|
||||
download_asset "$UPSTREAM_URL" "$UPSTREAM_TOKEN" "$u" "$UPSTREAM_ASSET_DIR/$fn"
|
||||
done
|
||||
for f in "$UPSTREAM_ASSET_DIR"/*; do
|
||||
[ -f "$f" ] && ASSETS+=("$f")
|
||||
done
|
||||
[ "${#ASSETS[@]}" -gt 0 ] && MIRROR_FOUND=true
|
||||
fi
|
||||
|
||||
# --- 3) publish on this Gitea ----------------------------------------------
|
||||
# Only publish when there is actual content: the local build produced assets,
|
||||
# or the upstream release exists (name/body/assets). This avoids publishing an
|
||||
# empty "Release $TAG" when the upstream has no release for the tag (and no
|
||||
# build produced assets) — the idempotency guard would otherwise skip the tag
|
||||
# forever, so nothing would ever be retried.
|
||||
HAS_CONTENT=false
|
||||
[ "${#ASSETS[@]}" -gt 0 ] && HAS_CONTENT=true
|
||||
[ "$MIRROR_FOUND" = "true" ] && HAS_CONTENT=true
|
||||
if [ "$HAS_CONTENT" != "true" ]; then
|
||||
echo ">> No content for $TAG (no build assets, no upstream release) — not publishing."
|
||||
exit 0
|
||||
fi
|
||||
NAME="${NAME:-Release $TAG}"
|
||||
BODY="${BODY:-Auto-released by Repo Forker}"
|
||||
echo ">> Publishing release $TAG on $GITEA_SERVER_URL/$GITEA_OWNER/$GITEA_REPO"
|
||||
# shellcheck disable=SC2068 # assets are individual file paths (safe)
|
||||
publish_local_release "$GITEA_SERVER_URL" "$GITEA_OWNER/$GITEA_REPO" "$GITEA_TOKEN" \
|
||||
"$TAG" "$NAME" "$BODY" ${ASSETS[@]+"${ASSETS[@]}"}
|
||||
|
||||
echo ">> Release $TAG published."
|
||||
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/env bash
|
||||
# runner-register.sh — register a gitea-act-runner for this repo (or shared).
|
||||
#
|
||||
# In this Gitea build, runners are repo-scoped. Two options:
|
||||
# 1. Per-repo: register a runner for THIS repo only.
|
||||
# 2. Shared: register ONE runner that serves ALL repos (recommended).
|
||||
#
|
||||
# Requires: gitea-act-runner installed, GITEA_SERVER_URL, GITEA_TOKEN (admin or
|
||||
# repo-scoped token), GITEA_OWNER, GITEA_REPO.
|
||||
#
|
||||
# Usage:
|
||||
# GITEA_SERVER_URL=https://git.lago.dev GITEA_TOKEN=... GITEA_OWNER=Lago \
|
||||
# GITEA_REPO=some-upstream bash forker/runner-register.sh [shared]
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
GITEA_SERVER_URL="${GITEA_SERVER_URL:?GITEA_SERVER_URL is required}"
|
||||
GITEA_TOKEN="${GITEA_TOKEN:?GITEA_TOKEN is required}"
|
||||
GITEA_OWNER="${GITEA_OWNER:?GITEA_OWNER is required}"
|
||||
GITEA_REPO="${GITEA_REPO:?GITEA_REPO is required}"
|
||||
SHARED="${1:-}"
|
||||
|
||||
command -v gitea-act-runner >/dev/null 2>&1 || {
|
||||
echo "gitea-act-runner not found. Install it first (see README 'Runner')." >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Generate a registration token via the Gitea API.
|
||||
REG_TOKEN="$(curl -sS -X POST \
|
||||
-H "Authorization: Bearer $GITEA_TOKEN" \
|
||||
"$GITEA_SERVER_URL/api/v1/admin/actions/runners/registration-token" \
|
||||
| python3 -c 'import sys,json;print(json.load(sys.stdin).get("token",""))' 2>/dev/null)"
|
||||
|
||||
if [ -z "$REG_TOKEN" ]; then
|
||||
echo "WARN: could not auto-generate a registration token." >&2
|
||||
echo " Create one manually in the Gitea UI (Settings -> Actions -> Runners" >&2
|
||||
echo " -> 'Generate runner token') and set RUNNER_REG_TOKEN." >&2
|
||||
REG_TOKEN="${RUNNER_REG_TOKEN:?RUNNER_REG_TOKEN is required}"
|
||||
fi
|
||||
|
||||
if [ "$SHARED" = "shared" ]; then
|
||||
echo ">> Registering a SHARED runner (serves all repos)"
|
||||
gitea-act-runner register \
|
||||
--server "$GITEA_SERVER_URL" \
|
||||
--token "$REG_TOKEN" \
|
||||
--name "shared-runner-$(date +%s)" \
|
||||
--labels "linux,amd64,ubuntu-latest" \
|
||||
--shared
|
||||
else
|
||||
echo ">> Registering a runner for $GITEA_OWNER/$GITEA_REPO"
|
||||
gitea-act-runner register \
|
||||
--server "$GITEA_SERVER_URL" \
|
||||
--token "$REG_TOKEN" \
|
||||
--owner "$GITEA_OWNER" \
|
||||
--repo "$GITEA_REPO" \
|
||||
--name "runner-$GITEA_REPO" \
|
||||
--labels "linux,amd64,ubuntu-latest"
|
||||
fi
|
||||
|
||||
echo ">> Registered. Now start the runner: gitea-act-runner run"
|
||||
@@ -0,0 +1,341 @@
|
||||
#!/usr/bin/env bash
|
||||
# sync.sh — mirror the upstream into this fork (the "worker" job).
|
||||
#
|
||||
# Brings in ALL branches, ALL tags, and full commit history from the upstream,
|
||||
# then pushes them as refs on this Gitea fork. Upstream objects live in a true
|
||||
# bare mirror (.mirror/); the working tree (forker branch) is never touched.
|
||||
#
|
||||
# Design notes:
|
||||
# * .mirror is a TRUE bare mirror: upstream branches live in refs/heads/*,
|
||||
# upstream tags in refs/tags/*. If a previous run's .mirror is restored from
|
||||
# cache (see .gitea/workflows/sync.yml), the fetch is INCREMENTAL; otherwise
|
||||
# it downloads the full history (still correct).
|
||||
# * The fork's current state (which branches/tags it already has) is read via
|
||||
# the Gitea API, not from git state — so prune + "new tag" detection work even
|
||||
# on a cold mirror, and never touch "forker".
|
||||
# * Releases are triggered INLINE (a tag-push cannot trigger a workflow, because
|
||||
# a mirrored tag points at an upstream commit whose tree has no .gitea/workflows).
|
||||
#
|
||||
# Inputs (from Gitea Actions Variables/Secrets):
|
||||
# UPSTREAM_URL, UPSTREAM_TOKEN, GITEA_TOKEN, GITEA_SERVER_URL, GITEA_OWNER,
|
||||
# GITEA_REPO
|
||||
#
|
||||
# Config (from .forker.yaml via load_config):
|
||||
# TOKEN_USER, MIRROR_TAGS, MIRROR_PRUNE, MIRROR_BRANCHES, ON_NEW_TAG,
|
||||
# MIRROR_UPSTREAM_RELEASES, BUILD_CMD, BUILD_SCRIPT
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
source forker/lib/config.sh
|
||||
source forker/lib/provider.sh
|
||||
load_config
|
||||
|
||||
UPSTREAM_URL="${UPSTREAM_URL:?UPSTREAM_URL is required}"
|
||||
UPSTREAM_TOKEN="${UPSTREAM_TOKEN:-}"
|
||||
GITEA_TOKEN="${GITEA_TOKEN:?GITEA_TOKEN is required}"
|
||||
GITEA_SERVER_URL="${GITEA_SERVER_URL:?GITEA_SERVER_URL is required}"
|
||||
GITEA_OWNER="${GITEA_OWNER:?GITEA_OWNER is required}"
|
||||
GITEA_REPO="${GITEA_REPO:?GITEA_REPO is required}"
|
||||
|
||||
MIRROR_DIR=".mirror"
|
||||
mkdir -p "$MIRROR_DIR"
|
||||
|
||||
# --- auth: Bearer per-URL (works on Gitea / GitHub / Codeberg) --------------
|
||||
# We authenticate git over HTTPS with an `Authorization: Bearer <token>`
|
||||
# header, scoped to a URL via git config's http.<url>.extraHeader. This is the
|
||||
# most robust cross-provider option:
|
||||
# * no username needed -> Gitea's "username must match the token owner"
|
||||
# rule can't bite us (it would, e.g. on cron where actor=gitea-actions, or
|
||||
# for a private upstream on the same instance with an OAuth2 token).
|
||||
# * Bearer is accepted by Gitea, Codeberg and GitHub for git-over-HTTPS.
|
||||
# * scoping to the exact repo URL means a same-host upstream and fork each
|
||||
# get their own token (no header collision).
|
||||
# The token never appears in a URL, so it doesn't leak into `git` output/logs.
|
||||
# Fail fast instead of hanging on an interactive credential prompt.
|
||||
export GIT_TERMINAL_PROMPT=0
|
||||
|
||||
# --- upstream is ANONYMOUS by default (never touch stored credentials) ------
|
||||
# Public upstreams must be fetched without authenticating. Without this, a
|
||||
# `credential.helper=store` + a stored github.com entry would SILENTLY
|
||||
# authenticate the fetch with the operator's GitHub account. We cut the
|
||||
# global/system git config and the credential helper for ALL upstream git
|
||||
# calls (env-scoped, does not affect the fork push below, which uses its own
|
||||
# explicit Bearer header). Private upstreams opt in via UPSTREAM_TOKEN.
|
||||
export GIT_CONFIG_GLOBAL=/dev/null
|
||||
export GIT_CONFIG_NOSYSTEM=1
|
||||
export GIT_CONFIG_SYSTEM=/dev/null
|
||||
|
||||
# --- ensure the bare mirror exists -------------------------------------------
|
||||
if [ ! -f "$MIRROR_DIR/HEAD" ]; then
|
||||
echo ">> Initializing bare mirror for $UPSTREAM_URL"
|
||||
git init --bare "$MIRROR_DIR" >/dev/null
|
||||
fi
|
||||
|
||||
# --- fetch everything from upstream (true-mirror layout) --------------------
|
||||
# Bearer auth scoped to the upstream URL (works even when the upstream is a
|
||||
# private repo on the same Gitea instance as the fork).
|
||||
# Only add the Bearer header when a token is actually set (an empty Bearer
|
||||
# header makes GitHub reject the request; public repos need no auth at all).
|
||||
if [ -n "$UPSTREAM_TOKEN" ]; then
|
||||
git --git-dir="$MIRROR_DIR" config http."$UPSTREAM_URL".extraHeader "Authorization: Bearer $UPSTREAM_TOKEN"
|
||||
else
|
||||
git --git-dir="$MIRROR_DIR" config --unset http."$UPSTREAM_URL".extraHeader 2>/dev/null || true
|
||||
fi
|
||||
# With a cached .mirror this is incremental; cold it pulls full history.
|
||||
PRUNE_FLAG=""
|
||||
[ "$MIRROR_PRUNE" = "true" ] && PRUNE_FLAG="--prune"
|
||||
# Retry budget shared by the upstream fetch and the fork push (overridable).
|
||||
# Defined here (before the fetch) so both fetch_once and push_once can use it.
|
||||
PUSH_RETRIES="${PUSH_RETRIES:-3}"
|
||||
# fetch_once — the per-job container intermittently can't resolve the upstream
|
||||
# host (same per-job DNS flap that hits the fork push), so retry transient
|
||||
# network errors with backoff, mirroring push_once. An incremental fetch of an
|
||||
# up-to-date mirror is cheap; a failed fetch must fail the run loudly (a
|
||||
# stale mirror pushed as "success" is the exact thing we never want).
|
||||
fetch_once() {
|
||||
local out rc
|
||||
for (( fa = 1; fa <= PUSH_RETRIES; fa++ )); do
|
||||
rc=0
|
||||
out="$(git --git-dir="$MIRROR_DIR" fetch --force $PRUNE_FLAG \
|
||||
"$UPSTREAM_URL" \
|
||||
'+refs/heads/*:refs/heads/*' \
|
||||
'+refs/tags/*:refs/tags/*' 2>&1)" || rc=$?
|
||||
[ "$rc" -eq 0 ] && return 0
|
||||
case "$out" in
|
||||
*"Could not resolve host"*|*"Failed to connect"*|*"Connection timed out"*|\
|
||||
*"RPC failed"*|*"early EOF"*|*"remote end hung up"*)
|
||||
echo " fetch retry $fa/$PUSH_RETRIES (transient network: ${out##* })"
|
||||
sleep $(( fa * 5 )) ;;
|
||||
*)
|
||||
echo " fetch failed (non-network, not retrying):" >&2
|
||||
printf '%s\n' "$out" | tail -10 >&2
|
||||
return "$rc" ;;
|
||||
esac
|
||||
done
|
||||
echo " giving up after $PUSH_RETRIES fetch attempts; last error:" >&2
|
||||
printf '%s\n' "$out" | tail -10 >&2
|
||||
return 1
|
||||
}
|
||||
echo ">> Fetching all branches + tags from upstream ($UPSTREAM_URL)"
|
||||
fetch_once
|
||||
|
||||
# upstream branches (true-mirror layout: refs/heads/*)
|
||||
all_upstream_branches="$(git --git-dir="$MIRROR_DIR" for-each-ref --format='%(refname:short)' refs/heads/ || true)"
|
||||
# Branches to PUSH, restricted by MIRROR_BRANCHES if configured. Pruning below
|
||||
# must be checked against the FULL upstream list (not the filtered one), so a
|
||||
# fork branch that still exists upstream but is outside the filter is never
|
||||
# deleted.
|
||||
mirror_branches="$all_upstream_branches"
|
||||
if [ "$MIRROR_BRANCHES" != "*" ]; then
|
||||
# split on commas (also tolerate stray spaces)
|
||||
IFS=', ' read -ra want <<< "$MIRROR_BRANCHES"
|
||||
filtered=""
|
||||
for b in "${want[@]}"; do
|
||||
b="$(echo "$b" | sed -E 's/^[[:space:]]+//; s/[[:space:]]+$//')"
|
||||
[ -n "$b" ] || continue
|
||||
printf '%s\n' "$all_upstream_branches" | grep -qxF "$b" && filtered="$filtered $b"
|
||||
done
|
||||
mirror_branches="$filtered"
|
||||
fi
|
||||
|
||||
# --- current state of the fork (via Gitea API) ------------------------------
|
||||
# All pages, so repos with >100 branches/tags are handled correctly.
|
||||
fork_names() {
|
||||
local endpoint="$1" page=1 items
|
||||
while :; do
|
||||
items="$(curl -sS --max-time 60 -H "Authorization: Bearer $GITEA_TOKEN" \
|
||||
"$GITEA_SERVER_URL/api/v1/repos/$GITEA_OWNER/$GITEA_REPO/$endpoint?page=$page&limit=50" 2>/dev/null || true)"
|
||||
[ -z "$items" ] && break
|
||||
printf '%s' "$items" | python3 -c 'import sys,json;print(" ".join(x.get("name","") for x in json.load(sys.stdin)))' 2>/dev/null || true
|
||||
# stop when this page is short (Gitea returns fewer than limit at the end)
|
||||
printf '%s' "$items" | python3 -c 'import sys,json;sys.exit(0 if len(json.load(sys.stdin))<50 else 1)' && break
|
||||
page=$((page+1))
|
||||
[ "$page" -gt 100 ] && break # hard cap
|
||||
done
|
||||
}
|
||||
fork_branches="$(fork_names "branches")"
|
||||
fork_tags="$(fork_names "tags")"
|
||||
|
||||
# register the fork as a push target inside the mirror, with its own Bearer
|
||||
# token scoped to the fork URL (distinct from the upstream header above, so a
|
||||
# same-instance upstream + fork each authenticate with the right token).
|
||||
FORK_URL="$GITEA_SERVER_URL/$GITEA_OWNER/$GITEA_REPO.git"
|
||||
git --git-dir="$MIRROR_DIR" remote remove fork 2>/dev/null || true
|
||||
git --git-dir="$MIRROR_DIR" remote add fork "$FORK_URL"
|
||||
git --git-dir="$MIRROR_DIR" config http."$FORK_URL".extraHeader "Authorization: Bearer $GITEA_TOKEN"
|
||||
|
||||
# --- 1) branches -----------------------------------------------------------
|
||||
# A failed push must fail the run (loudly) — a partial mirror reported as
|
||||
# success is worse than a red run. `&&` would mask the failure under set -e.
|
||||
# Momentary network errors (DNS "Could not resolve host", connect timeouts)
|
||||
# are retried a few times with backoff; a non-network failure aborts at once.
|
||||
push_once() { # push_once <push-args...>
|
||||
# set -e safe: a failing command-substitution assignment would otherwise
|
||||
# abort the script, so catch it with `|| rc=$?` (left of || is exempt).
|
||||
local out rc
|
||||
for (( attempt = 1; attempt <= PUSH_RETRIES; attempt++ )); do
|
||||
rc=0
|
||||
# --force: this is a MIRROR. Upstream is authoritative, so a fork ref that
|
||||
# has drifted (e.g. a leftover from an interrupted partial mirror, or an
|
||||
# upstream rebase/re-tag) must be OVERWRITTEN, not fast-forward-checked —
|
||||
# a single non-FF ref would otherwise reject the whole multi-ref pack. The
|
||||
# machinery "forker" branch is excluded from the push loop above, so it is
|
||||
# never clobbered. (Not --force-with-lease: the fork is not authoritative,
|
||||
# and its refs are expected to be stale.)
|
||||
out="$(git --git-dir="$MIRROR_DIR" push --force fork "$@" 2>&1)" || rc=$?
|
||||
[ "$rc" -eq 0 ] && return 0
|
||||
case "$out" in
|
||||
*"Could not resolve host"*|*"Failed to connect"*|*"Connection timed out"*|\
|
||||
*"RPC failed"*|*"early EOF"*|*"remote end hung up"*)
|
||||
# also widen the backoff: a big multi-ref pack needs time to settle
|
||||
echo " retry $attempt/$PUSH_RETRIES (transient network: ${out##* })"
|
||||
sleep $(( attempt * 5 )) ;;
|
||||
*)
|
||||
echo " push failed (attempt $attempt/$PUSH_RETRIES, non-network — not retrying):" >&2
|
||||
printf '%s\n' "$out" | tail -10 >&2
|
||||
return "$rc" ;;
|
||||
esac
|
||||
done
|
||||
echo " giving up after $PUSH_RETRIES attempts; last error:" >&2
|
||||
printf '%s\n' "$out" | tail -10 >&2
|
||||
return 1
|
||||
}
|
||||
pushed_b=""
|
||||
# Push ALL branches in ONE multi-ref pack (a single connection), not one push
|
||||
# per branch. The per-branch burst opened ~280 separate TLS connections and the
|
||||
# remote dropped the ~20th; one pack is far more robust, and a network failure
|
||||
# retries the whole batch cleanly (a re-push of an already-current ref is
|
||||
# idempotent: "Everything up-to-date").
|
||||
branch_refspecs=""
|
||||
for b in $mirror_branches; do
|
||||
# never let the upstream's content clobber the machinery branch (if the
|
||||
# upstream ever has a branch named "forker")
|
||||
[ "$b" = "forker" ] && continue
|
||||
branch_refspecs="$branch_refspecs refs/heads/$b:refs/heads/$b"
|
||||
done
|
||||
if [ -n "$branch_refspecs" ]; then
|
||||
echo " pushing $(printf '%s' "$branch_refspecs" | wc -w) branches (1 pack)"
|
||||
push_once $branch_refspecs \
|
||||
|| { echo "ERROR: branch push failed after $PUSH_RETRIES attempts — aborting (partial mirror)." >&2; exit 1; }
|
||||
for b in $mirror_branches; do [ "$b" = "forker" ] && continue; pushed_b="$pushed_b $b"; done
|
||||
fi
|
||||
|
||||
# prune fork branches that no longer exist upstream (never touch "forker");
|
||||
# checked against the FULL upstream list (a branch outside the MIRROR_BRANCHES
|
||||
# filter but still present upstream is NOT deleted). One pack for all prunes.
|
||||
if [ "$MIRROR_PRUNE" = "true" ]; then
|
||||
prune_refspecs=""
|
||||
for f in $fork_branches; do
|
||||
[ "$f" = "forker" ] && continue
|
||||
if ! printf '%s\n' "$all_upstream_branches" | grep -qxF "$f"; then
|
||||
echo " prune branch: $f (deleted upstream)"
|
||||
prune_refspecs="$prune_refspecs :refs/heads/$f"
|
||||
fi
|
||||
done
|
||||
if [ -n "$prune_refspecs" ]; then
|
||||
push_once $prune_refspecs \
|
||||
|| echo "WARN: branch prune failed (will retry next run)"
|
||||
fi
|
||||
fi
|
||||
|
||||
# --- 2) tags ----------------------------------------------------------------
|
||||
new_tags=""
|
||||
pushed_t=""
|
||||
upstream_tags="$(git --git-dir="$MIRROR_DIR" for-each-ref --format='%(refname:short)' refs/tags/ || true)"
|
||||
if [ "$MIRROR_TAGS" = "true" ]; then
|
||||
tag_refspecs=""
|
||||
for t in $upstream_tags; do
|
||||
# is this tag NEW relative to the fork? (for inline release triggering)
|
||||
printf '%s\n' $fork_tags | grep -qxF "$t" || new_tags="$new_tags $t"
|
||||
tag_refspecs="$tag_refspecs refs/tags/$t:refs/tags/$t"
|
||||
done
|
||||
if [ -n "$tag_refspecs" ]; then
|
||||
echo " pushing $(printf '%s' "$tag_refspecs" | wc -w) tags (1 pack)"
|
||||
push_once $tag_refspecs \
|
||||
|| { echo "ERROR: tag push failed after $PUSH_RETRIES attempts — aborting (partial mirror)." >&2; exit 1; }
|
||||
for t in $upstream_tags; do pushed_t="$pushed_t $t"; done
|
||||
fi
|
||||
# prune fork tags that no longer exist upstream (one pack for all prunes)
|
||||
if [ "$MIRROR_PRUNE" = "true" ]; then
|
||||
tag_prune_refspecs=""
|
||||
for t in $fork_tags; do
|
||||
if ! printf '%s\n' "$upstream_tags" | grep -qxF "$t"; then
|
||||
echo " prune tag: $t (deleted upstream)"
|
||||
tag_prune_refspecs="$tag_prune_refspecs :refs/tags/$t"
|
||||
fi
|
||||
done
|
||||
if [ -n "$tag_prune_refspecs" ]; then
|
||||
push_once $tag_prune_refspecs \
|
||||
|| echo "WARN: tag prune failed (will retry next run)"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
echo ">> Sync complete. Branches:${pushed_b:- (none)} | Tags:${pushed_t:- (none)} | New tags:${new_tags:- (none)}"
|
||||
|
||||
# --- 1b) fork default branch = upstream default branch --------------------
|
||||
# Generated repos are born with default 'forker' (the only branch that exists
|
||||
# at generate time), and Gitea does NOT switch it once a pre-set branch later
|
||||
# appears (verified: pre-PATCH is a 200 no-op until re-applied). So we
|
||||
# self-correct here on every run: read the upstream's default via ls-remote
|
||||
# --symref (works on GitHub/Gitea/Codeberg; honors the upstream Bearer config,
|
||||
# anonymous otherwise — golden rule kept), and if the fork's default differs,
|
||||
# PATCH it — but only to a branch the fork actually has (a MIRROR_BRANCHES
|
||||
# filter can exclude the upstream default; never point at 'forker').
|
||||
# Self-healing: if the upstream later changes its default, the fork follows.
|
||||
upstream_default="$(git --git-dir="$MIRROR_DIR" ls-remote --symref "$UPSTREAM_URL" HEAD 2>/dev/null \
|
||||
| sed -n 's/^ref: refs\/heads\/\(.*\)[[:space:]]*HEAD$/\1/p' | head -1 \
|
||||
| sed -E 's/[[:space:]]+$//; s/^[[:space:]]+//')"
|
||||
if [ -n "$upstream_default" ] && [ "$upstream_default" != "forker" ]; then
|
||||
# the branch must exist on the fork (just pushed, or already there).
|
||||
# NOTE: grep -qxF would SIGPIPE the (large) printf under `set -o pipefail`
|
||||
# once it matches an early line, giving a false negative — so use grep -xF
|
||||
# (reads ALL input, no early exit) and test the captured output instead.
|
||||
if [ -n "$(printf '%s\n' $mirror_branches $fork_branches | grep -xF "$upstream_default")" ]; then
|
||||
fork_default="$(curl -sS --max-time 20 -H "Authorization: Bearer $GITEA_TOKEN" \
|
||||
"$GITEA_SERVER_URL/api/v1/repos/$GITEA_OWNER/$GITEA_REPO" 2>/dev/null \
|
||||
| python3 -c 'import sys,json;print(json.load(sys.stdin).get("default_branch",""))' 2>/dev/null || true)"
|
||||
if [ -n "$fork_default" ] && [ "$fork_default" != "$upstream_default" ]; then
|
||||
# capture the HTTP status (curl -o exit code is 0 even on 4xx, so we must
|
||||
# check the code, not just the exit status) and log it for diagnosis.
|
||||
db_code="$(curl -sS --max-time 20 -o /tmp/db_resp.$$ -w '%{http_code}' \
|
||||
-X PATCH -H "Authorization: Bearer $GITEA_TOKEN" \
|
||||
"$GITEA_SERVER_URL/api/v1/repos/$GITEA_OWNER/$GITEA_REPO" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"default_branch\":\"$upstream_default\"}" 2>/dev/null)"
|
||||
case "$db_code" in
|
||||
2*) echo " default branch: $fork_default -> $upstream_default (matches upstream)" ;;
|
||||
*) echo "WARN: set default branch -> $upstream_default returned HTTP $db_code (body: $(head -c 200 /tmp/db_resp.$$ 2>/dev/null))" ;;
|
||||
esac
|
||||
rm -f /tmp/db_resp.$$
|
||||
fi
|
||||
else
|
||||
echo " default branch: upstream default '$upstream_default' not mirrored (filtered) — left as-is"
|
||||
fi
|
||||
fi
|
||||
|
||||
# --- 3) build + publish a release for each tag that LACKS one (inline) -----
|
||||
# A tag-push CANNOT trigger release.yml (the tag points at an upstream commit
|
||||
# whose tree has no .gitea/workflows), so we trigger the release here instead.
|
||||
# We check for *missing* releases (not just new tags), so a release that
|
||||
# failed on a previous run is retried by the next cron tick (self-healing);
|
||||
# release.sh's own idempotency guard still prevents duplicates.
|
||||
RELEASE_EXPECTED=false
|
||||
[ -n "$BUILD_CMD" ] && RELEASE_EXPECTED=true
|
||||
[ -n "$BUILD_SCRIPT" ] && RELEASE_EXPECTED=true
|
||||
[ "$MIRROR_UPSTREAM_RELEASES" = "true" ] && RELEASE_EXPECTED=true
|
||||
if [ "$ON_NEW_TAG" = "true" ] && [ "$RELEASE_EXPECTED" = "true" ]; then
|
||||
for t in $upstream_tags; do
|
||||
if [ "$(release_exists "$GITEA_SERVER_URL" "$GITEA_OWNER/$GITEA_REPO" "$GITEA_TOKEN" "$t")" = "no" ]; then
|
||||
echo ">> No release for $t — building + publishing"
|
||||
bash forker/release.sh "$t" || echo "!! release for $t failed (will retry next run)"
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
# --- 4) verify the Releases unit is enabled (fork quirk) -------------------
|
||||
# Gitea creates forks WITHOUT the Releases unit, so release assets 404 on the
|
||||
# web download route. check-unit.sh self-heals when the units API exists and
|
||||
# warns (with the exact UI fix) otherwise. Never fails the sync on its own.
|
||||
bash forker/check-unit.sh || echo "!! check-unit: see the warning above (sync continues)"
|
||||
|
Before Width: | Height: | Size: 247 KiB |
@@ -0,0 +1,18 @@
|
||||
# Run a gitea-act-runner in Docker. After `gitea-act-runner register`, point
|
||||
# this at the generated config (or use the official gitea/act-runner image).
|
||||
#
|
||||
# docker compose -f runner/docker-compose.yml up -d
|
||||
#
|
||||
# The runner must be registered (shared or per-repo) first — see README "Runner".
|
||||
|
||||
services:
|
||||
runner:
|
||||
image: gitea/act_runner:0.6.1
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- ./config:/config
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
environment:
|
||||
# If you registered with `gitea-act-runner register`, the config is in
|
||||
# ./config (copied from the registration output). The container reads it.
|
||||
GITEA_RUNNER_CONFIG: /config/config.yaml
|
||||
|
Before Width: | Height: | Size: 73 KiB |
|
Before Width: | Height: | Size: 63 KiB |
|
Before Width: | Height: | Size: 221 KiB |
|
Before Width: | Height: | Size: 1.8 MiB |
|
Before Width: | Height: | Size: 832 KiB |
@@ -0,0 +1,4 @@
|
||||
node_modules/
|
||||
dist/
|
||||
*.log
|
||||
.superdesign/tmp/
|
||||
@@ -0,0 +1,61 @@
|
||||
# API CONTRACT NOTES — verified live on git.lago.dev (Gitea 28.1.0)
|
||||
|
||||
These override any assumption in DESIGN.md about Gitea response shapes.
|
||||
Every item below was verified with a real request today.
|
||||
|
||||
## Endpoint corrections
|
||||
|
||||
1. **Repo list**: `GET /api/v1/user/repos?limit=50&page=N` (paginate until <50).
|
||||
`GET /api/v1/repos/{owner}` and `GET /api/v1/repos?owner=...` → **404** on this build.
|
||||
|
||||
2. **Workflow-specific runs**: `GET /repos/{o}/{r}/actions/workflows/{file}/actions/runs` → **404**.
|
||||
Use `GET /repos/{o}/{r}/actions/runs?limit=N` and filter client-side on
|
||||
`path` (= `"sync.yml@refs/heads/forker"`). The `?workflow=sync.yml` query
|
||||
param DOES work on this build (verified 200) — acceptable alternative.
|
||||
|
||||
3. **Run object** fields: `id, event, status, conclusion, created_at,
|
||||
completed_at (ISO, both always present), updated_at, path, run_attempt`.
|
||||
duration = (completed_at − created_at) seconds. No `duration_sec` field.
|
||||
|
||||
4. **Jobs/log**: `GET /repos/{o}/{r}/actions/runs/{runId}/jobs` → `{"jobs":[{id,...}]}`;
|
||||
`GET /repos/{o}/{r}/actions/jobs/{jobId}/logs` → **plain text** (one line per
|
||||
run entry; includes `::group::`/`::notice::`/`::warning::` lines).
|
||||
|
||||
5. **Variable**: `GET /repos/{o}/{r}/actions/variables/{name}` →
|
||||
`{"name":"UPSTREAM_URL","data":"<value>","description":""}` — the value field
|
||||
is **`data`**, not `value`.
|
||||
|
||||
6. **Raw file read**: `GET /repos/{o}/{r}/raw/.forker.yaml?ref=forker` → plain
|
||||
text. Write-back: `PUT /repos/{o}/{r}/contents/.forker.yaml` with
|
||||
`{"content": <base64>, "message": ..., "branch": "forker"}`.
|
||||
|
||||
7. **Dispatch**: `POST /repos/{o}/{r}/actions/workflows/sync.yml/dispatches`
|
||||
`{"ref":"forker"}` → **204** (works; the workflow path form is fine here).
|
||||
|
||||
## Object corrections
|
||||
|
||||
8. **Repo object** has NO `units` array. Derive unit names from booleans:
|
||||
`has_code`→Code, `has_issues`→Issues, `has_pull_requests`→Pull Requests,
|
||||
`has_releases`→Releases, `has_packages`→Packages, `has_projects`→Projects,
|
||||
`has_wiki`→Wiki.
|
||||
|
||||
9. **Runner object** (repo + admin lists): `id, name, status
|
||||
("online"|"offline"), busy (bool), disabled, labels:[{name}]`. NO `shared`/
|
||||
`type` fields. Infer type: present in repo-scoped list of ≥2 repos →
|
||||
"shared"; exactly 1 → "repo: {name}"; only in admin list → "shared
|
||||
(unattached)". (The known good runner is `gitea-runner-forker`, id 5,
|
||||
shared.)
|
||||
|
||||
10. **Releases object**: `id, tag_name, name, assets:[{name,size,download_url,...}],
|
||||
published_at, ...`. Asset count = `len(assets)`.
|
||||
|
||||
11. **Mirror detection** (server-side): `GET /user/repos` (paginated) → for each
|
||||
repo: `GET .../branches/forker` (200?) AND `GET .../actions/variables/UPSTREAM_URL`
|
||||
(200 → value in `data`). Exclude the template repo (settings).
|
||||
|
||||
12. **GitHub upstream parity** (anonymous, NO Authorization header — golden
|
||||
rule): `https://api.github.com/repos/{o}/{r}/branches?per_page=100`
|
||||
(paginate), `/tags?per_page=100`, `/releases?per_page=100` (assets inside).
|
||||
Cache 300 s per upstream. Non-GitHub upstreams: `git ls-remote --heads
|
||||
--tags <url>` for counts (spawn, 30 s timeout, no credentials configured);
|
||||
releases via the provider API pattern in `forker/lib/provider.sh`.
|
||||
@@ -0,0 +1,121 @@
|
||||
# DESIGN.md — Repo Forker UI (locked spec)
|
||||
|
||||
**Direction (one sentence):** a dense operator console — near-black GitHub-dark
|
||||
surfaces, hairline borders, ONE blue signal color for "act here", monospace
|
||||
for all data, high-density scannable tables. No gradients on cards, no
|
||||
glassmorphism, no decorative glow. The existing `docs/index.html` palette IS
|
||||
the brand; we match it, we don't invent a parallel system.
|
||||
|
||||
## Token lock (the ONLY colors/sizes/spacing allowed)
|
||||
|
||||
```
|
||||
color:
|
||||
bg #0d1117 page
|
||||
panel #161b22 cards, inputs, table bodies
|
||||
panel2 #1c2333 elevated: hover rows, active nav, dropdowns
|
||||
chip #21262d pills, badges, code blocks
|
||||
border #30363d 1px hairlines ONLY (never 2px, never colored borders except danger blocks)
|
||||
text #e6edf3 primary
|
||||
muted #8b949e secondary, labels, metadata
|
||||
accent #58a6ff THE one signal: primary buttons (dark text #0d1117), links, focus rings, active states
|
||||
ok #7ee787 success
|
||||
warn #f2cc60 warning / stale
|
||||
danger #f85149 failure / destructive
|
||||
ring #58a6ff33 focus ring (accent 20%)
|
||||
|
||||
type (ONLY these sizes — no in-betweens):
|
||||
11 table metadata, timestamps, sublabels
|
||||
12 labels, step text
|
||||
13 table data, chips
|
||||
14 body (base)
|
||||
18 page titles, panel headings (semibold)
|
||||
24 stat numbers (semibold, tabular-nums)
|
||||
families: ui: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif
|
||||
mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace
|
||||
line-height: 1.5 body, 1.2 headings. All repo names/refs/tags/durations/versions/numbers = mono + tabular-nums.
|
||||
|
||||
spacing (ONLY these): 4 · 8 · 12 · 16 · 24 · 32 · 48
|
||||
radius: 8 (panels) · 6 (inputs/buttons) · 999 (pills)
|
||||
elevation: level0 bg · level1 panel · level2 panel2. One soft shadow, only for modals/menus: 0 8px 24px rgba(0,0,0,.5)
|
||||
motion: hover/transition 120ms ease-out · log line fade-in 100ms · check draw 100ms. Nothing else animates.
|
||||
icons: Lucide, 16px, stroke 1.5, currentColor. NEVER emoji.
|
||||
status dots: 8px circle + 1px ring at 25% alpha of same color.
|
||||
```
|
||||
|
||||
## Hierarchy (squint test)
|
||||
1. Page title row (18px + status) → 2. The data table/queue (13px dense) → 3. Panels
|
||||
(headings 12px uppercase muted + 1px top border) → 4. Metadata (11px muted).
|
||||
Left-aligned, dense, not centered. Max content width 1200px, left-aligned in the main column.
|
||||
|
||||
## Pages & inventory (all states required: empty / loading / error / offline)
|
||||
|
||||
Global shell: left sidebar 224px (icon rail + label, active = panel2 bg + 3px accent bar),
|
||||
topbar per page (title + context badge + right actions).
|
||||
|
||||
1. **Dashboard `/`** — stat row (4 StatCards: Mirrors, Healthy x/N, Queued runs, Assets mirrored)
|
||||
+ MirrorTable: columns MIRROR (dot+name) | UPSTREAM | LAST SYNC (word+ago) | DURATION |
|
||||
PARITY (chips br/tags/assets, red when behind) | 7-DAY RUNS (SVG sparkline 56×14) | ACTIONS
|
||||
(re-sync, detail, delete). Empty state: "No mirrors yet" + New mirror button.
|
||||
Stale rule: last success > 30 min AND runner online → warn dot.
|
||||
2. **Detail `/mirrors/:name`** — header (name, dot, upstream link, actions: Re-sync / Run release / Delete).
|
||||
Grid 60/40: LEFT RunTimeline (last 12 runs: dot, #id, event, word, duration, time; failed rows
|
||||
expandable with the failing log line in a danger-tinted code block). RIGHT: ParityPanel
|
||||
(upstream vs fork counts + delta chips), ConfigPanel (flat key: value rows + Edit),
|
||||
VariablesPanel (name + value/mask + copy), UnitsPanel (chips with dots).
|
||||
3. **Wizard `/new`** — 3-step indicator. Step 1: URL input (mono) + name + Continue.
|
||||
Step 2: flat config form (one row per key: label 12px muted 160px + control; toggles for booleans,
|
||||
mono inputs for the rest; validation: no nesting, known keys). Step 3: 5-step progress
|
||||
(generate → variable → default branch → forker config → first sync) with spinner + live
|
||||
first-sync status. Success screen: link to the detail page.
|
||||
4. **Runner `/runner`** — concurrency strip ("serial runner (maxParallel=1)"), QueueTable
|
||||
(position, repo, #run, event, state badge, waited), Runners table (name, status badge,
|
||||
type chip, busy, labels).
|
||||
5. **Settings `/settings`** — Connection card (Gitea URL + token; test & save; stored in
|
||||
`~/.repo-forker/credentials` chmod 600, never in the repo), Template card (template repo
|
||||
name, locked to `Lago/repo-forker` by default), theme note.
|
||||
|
||||
## API contract (local server `/api/*` → Gitea proxy; token never leaves the server)
|
||||
|
||||
```
|
||||
GET /api/health → {ok, gitea: {url, version} | null}
|
||||
POST /api/connect {url, token} → verifies GET /api/v1/user, saves creds, {ok, user, version}
|
||||
GET /api/settings → {configured, url, user, template}
|
||||
GET /api/mirrors → [{name, full, upstream, defaultBranch, lastSync: {id,event,status,conclusion,updatedAt,durationSec} | null,
|
||||
parity: {branches, tags, releases, assets} | null, units: [names], spark: [status×20]}]
|
||||
GET /api/mirrors/:name/runs?limit → [{id, event, status, conclusion, updatedAt, durationSec}]
|
||||
GET /api/mirrors/:name/releases → [{id, tag, name, assets: n}]
|
||||
POST /api/mirrors/:name/dispatch {workflow, ref} → {ok, runId}
|
||||
POST /api/mirrors {upstream, name?, config} → runs the full creation sequence, {ok, repo, steps: [{name, status}]}
|
||||
DELETE /api/mirrors/:name → {ok}
|
||||
GET /api/mirrors/:name/config → {raw, parsed: {key: value}}
|
||||
PUT /api/mirrors/:name/config → {parsed} (validates flat schema, writes .forker.yaml on forker branch)
|
||||
GET /api/mirrors/:name/variables → [{name, value}]
|
||||
POST /api/mirrors/:name/variables {name, value} → {ok}
|
||||
DELETE /api/mirrors/:name/variables/:var → {ok}
|
||||
GET /api/runners → [{id, name, status, busy, shared, labels}]
|
||||
GET /api/queue → [{repo, runId, event, status, waitedSec}] (queued+in_progress across mirrors, ordered)
|
||||
GET /api/mirrors/:name/runs/:id/log?cursor → {lines: [{t, text}], cursor} (Gitea job log, incremental)
|
||||
```
|
||||
|
||||
Mirror detection (server-side): repos of the connected user that have a `forker` branch
|
||||
AND an `UPSTREAM_URL` action variable; the template repo (from /api/settings) is excluded
|
||||
from the list. Parity upstream counts: anonymous GitHub REST for `github.com` upstreams
|
||||
(branches per_page=100 paginated, tags, releases + asset count); for other providers:
|
||||
`git ls-remote` over HTTPS (anonymous) for branch/tag counts, releases via the same
|
||||
provider pattern as `forker/lib/provider.sh` (Gitea/Codeberg: `<base>/api/v1/repos/…/releases`).
|
||||
Parity is computed server-side and cached 5 min (public GitHub: 60 req/h unauth — be gentle:
|
||||
one call per repo per 5 min, no pagination beyond what's needed).
|
||||
|
||||
## States (none may be missing)
|
||||
- **offline** (Gitea unreachable): top banner warn "Gitea unreachable — showing last cached state" + cached data rendered.
|
||||
- **empty** (no mirrors / no runs / no queue): one muted line + one action.
|
||||
- **loading**: skeleton rows (panel2 shimmer, 2 rows) — never a full-page spinner.
|
||||
- **error**: inline danger text with the exact failing line (no generic alerts); retry button for failed actions.
|
||||
- **long content**: ellipsis + title tooltip; log viewer scrolls, table columns fixed.
|
||||
|
||||
## Build & run
|
||||
- Vite + React 18 + TypeScript + Tailwind (config maps ONLY the tokens above).
|
||||
- `ui/bin/repo-forker-ui.js`: `npx` entry → starts `server/server.js` (zero-dependency Node
|
||||
http; built-in fetch) on 8731 (or next free), serves `dist/`, proxies `/api/*`.
|
||||
- Server holds the token in `~/.repo-forker/credentials` (chmod 600); the browser only
|
||||
ever talks to `http://127.0.0.1:8731`.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Repo Forker UI
|
||||
|
||||
Local control-plane for managing the mirrors generated from `repo-forker`.
|
||||
A single `npx` command starts a tiny zero-dependency Node server that serves
|
||||
the React app and proxies the Gitea API — the token never leaves your machine
|
||||
and never touches the repo.
|
||||
|
||||
## Run
|
||||
|
||||
```
|
||||
cd ui
|
||||
npm install && npm run build # first time
|
||||
node bin/repo-forker-ui.js # → http://127.0.0.1:8731
|
||||
# or, once published / linked: npx repo-forker-ui
|
||||
```
|
||||
|
||||
Open the URL, paste your Gitea base URL + a token (any scope; it only talks
|
||||
to the API), and the dashboard appears with every mirror (a repo with a
|
||||
`forker` branch + `UPSTREAM_URL` variable; the template is excluded).
|
||||
|
||||
Credentials are stored in `~/.repo-forker/credentials` (chmod 600).
|
||||
|
||||
## What it does
|
||||
|
||||
- **Mirrors**: create from any git URL (generate → `UPSTREAM_URL` → default
|
||||
branch → `.forker.yaml` config → first sync), delete, re-sync, view parity
|
||||
(branches/tags/releases/assets vs upstream — anonymous for public GitHub),
|
||||
edit the flat `.forker.yaml`, manage action variables, 7-day run sparkline,
|
||||
staleness badge (last success > 30 min with the runner online).
|
||||
- **Detail**: run history (last 12, failed ones expandable with the failing
|
||||
log line), live log viewer, units, variables, config.
|
||||
- **Runner**: serial-queue view (the runner is `maxParallel=1`), runners
|
||||
online/offline, busy state, wait times.
|
||||
- **States**: offline banner + cached data, empty states, skeletons, exact
|
||||
error lines.
|
||||
|
||||
## Design
|
||||
|
||||
See [DESIGN.md](DESIGN.md) — the locked token set and the direction (dense
|
||||
operator console, GitHub-dark, one blue signal color, monospace data).
|
||||
|
||||
## API
|
||||
|
||||
`server/server.js` implements the full contract in DESIGN.md ("API contract"
|
||||
section). All requests go to the Gitea base URL with a Bearer token; upstream
|
||||
parity checks for public GitHub repos are **anonymous** (no auth header — the
|
||||
golden rule), and upstream git operations (non-GitHub providers) run
|
||||
`git ls-remote` without any credential configuration.
|
||||
@@ -0,0 +1,81 @@
|
||||
# VERIFY + POLISH plan (final round)
|
||||
|
||||
## A. Functional verification against the REAL Gitea (git.lago.dev)
|
||||
|
||||
Setup: start the server WITHOUT mock: `node bin/repo-forker-ui.js`, then
|
||||
`POST /api/connect` with `http://127.0.0.1:3000` is WRONG — the real base URL
|
||||
is `https://git.lago.dev` and the token is a temporary one created for this:
|
||||
`POST /api/v1/users/Lago/tokens {"name":"ui-verify","scopes":["all"]}` → capture
|
||||
the `sha1` at creation (the only time it's visible). After verification:
|
||||
`DELETE /api/v1/users/Lago/tokens/{id}`. (The user's stored `~/.git-credentials`
|
||||
line is basic-auth and works too; prefer the temp token so nothing long-lived
|
||||
touches the UI.)
|
||||
|
||||
Checklist (all must pass; report each with a ✓/✗ and the raw JSON snippet):
|
||||
1. `GET /api/health` → ok + gitea version.
|
||||
2. `GET /api/mirrors` → exactly 3 mirrors (photocraft, pdfcraft, AnyPS5), each
|
||||
with: upstream correct, lastSync from the real run, parity matching the
|
||||
known-good numbers (photocraft 273 br / 10 tags / 10 rel / 203 assets;
|
||||
AnyPS5 13 br / 3 tags / 2 rel / 16 assets; pdfcraft its real counts),
|
||||
spark array length ≤20, units include "Releases".
|
||||
3. `GET /api/mirrors/photocraft/runs?limit=12` → real run ids (recent ones:
|
||||
the 1200s range).
|
||||
4. `GET .../runs/{latest}/log` (via jobs) → text contains "Sync complete" or
|
||||
"Releases unit OK".
|
||||
5. `GET /api/runners` → `gitea-runner-forker` present, status online.
|
||||
6. `GET /api/queue` → 200 (possibly empty array — that's fine).
|
||||
7. `GET /api/mirrors/AnyPS5/config` → flat parse with
|
||||
`mirror_upstream_releases: "true"` (string ok) and the other known keys.
|
||||
8. `PUT` config with an INVALID nested value → 400 with a clear message.
|
||||
`PUT` config with a valid no-op value → 200 and no commit spam (or at most
|
||||
one commit).
|
||||
9. **DO NOT** `POST /api/mirrors` (create) or `DELETE` against the real Gitea —
|
||||
creation/deletion are verified in MOCK mode instead (idempotency + delete
|
||||
with the type-the-name confirm are client-side; the server routes just need
|
||||
to 200 against mock).
|
||||
10. `POST /api/mirrors/{name}/dispatch {workflow:"sync.yml"}` → 204/200 on the
|
||||
real Gitea is ACCEPTABLE once (it just re-runs the 10-min cron; harmless).
|
||||
Do it at most once, on AnyPS5.
|
||||
|
||||
## B. Visual verification (offline, MOCK mode)
|
||||
|
||||
1. `MOCK=1 node bin/repo-forker-ui.js` → serve.
|
||||
2. `design_audit` the 5 routes at 1440×900 and 390×844 (mobile).
|
||||
3. Fix EVERY blocker/high the audit names (contrast, target size, spacing off
|
||||
grid, too many font sizes/colors). Deliberate exceptions (e.g. 11px table
|
||||
metadata is below the 14px floor) must be LISTED in the final report, not
|
||||
silently left.
|
||||
4. Screenshots (headless Chrome) of: dashboard (mock 3 mirrors), detail
|
||||
(photocraft, with the failed run expanded), wizard (step 1 + step 3),
|
||||
runner (queue populated), settings (connected). Save under
|
||||
`.design-audit/ui-<timestamp>/`.
|
||||
5. Confirm: no violet/indigo gradient, no emoji, no card gradients, hairline
|
||||
borders, mono for all data, status dots with rings, one accent color doing
|
||||
all "act here" work.
|
||||
|
||||
## C. Code polish pass (before commit)
|
||||
|
||||
- No `console.log` left in src/ or server/ (structured errors only).
|
||||
- No unused imports; TS strict passes; `vite build` clean.
|
||||
- The server is dependency-free (only node built-ins).
|
||||
- `~/.repo-forker/credentials` is written chmod 600; the token never appears
|
||||
in any URL, in logs, or in the client bundle.
|
||||
- Offline banner works: kill nothing — just confirm the UI renders cached data
|
||||
when /api/health fails (test by pointing connect at a dead URL).
|
||||
- Empty states: with the real Gitea, the template repo must NOT appear in
|
||||
/api/mirrors.
|
||||
|
||||
## D. Commit (subagent 5 does it)
|
||||
|
||||
- Branch `forker`, single squashed commit: "Repo Forker UI: local mirror-management
|
||||
control plane (npx repo-forker-ui)" with body: what it does, how to run,
|
||||
design spec pointer, verification summary.
|
||||
- `ui/**` is added to .gitignore? NO — ui/ is tracked (it's the deliverable).
|
||||
Only `ui/node_modules/`, `ui/dist/` are ignored (add to root .gitignore).
|
||||
- Push to origin forker.
|
||||
- DO NOT touch `forker/`, `.gitea/`, `Makefile`, `AGENTS.md`, `docs/` in the
|
||||
commit (only `ui/` + the .gitignore line + a README.md pointer line at most).
|
||||
- Final: report to the user in Spanish, concise: what was built, how to run it
|
||||
(`cd ui && npm install && npm run build && node bin/repo-forker-ui.js`), the
|
||||
verification table, the design-audit findings + fixes, and the open questions
|
||||
(publish as an npm package? P1/P2 scope?).
|
||||
@@ -0,0 +1,26 @@
|
||||
#!/usr/bin/env node
|
||||
/* npx repo-forker-ui — start the local control plane.
|
||||
* Builds on first run if dist/ is missing, then serves on 8731 (or next free).
|
||||
*/
|
||||
'use strict';
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const { spawnSync } = require('child_process');
|
||||
|
||||
const here = __dirname;
|
||||
const uiDir = path.join(here, '..');
|
||||
const dist = path.join(uiDir, 'dist');
|
||||
|
||||
if (!fs.existsSync(path.join(dist, 'index.html'))) {
|
||||
console.log('repo-forker-ui: first run — building (vite build)…');
|
||||
const r = spawnSync('npm', ['run', 'build'], { cwd: uiDir, stdio: 'inherit' });
|
||||
if (r.status !== 0) {
|
||||
console.error('repo-forker-ui: build failed. Run `cd ui && npm install && npm run build` manually.');
|
||||
process.exit(r.status || 1);
|
||||
}
|
||||
}
|
||||
|
||||
// Require the server and start it (its `require.main === module` guard would not
|
||||
// fire when loaded from this bin, so call boot() explicitly).
|
||||
const { boot } = require(path.join(uiDir, 'server', 'server.js'));
|
||||
boot();
|
||||
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Repo Forker</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"name": "repo-forker-ui",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "Local control plane for Repo Forker mirrors",
|
||||
"bin": { "repo-forker-ui": "bin/repo-forker-ui.js" },
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"lucide-react": "^0.454.0",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-router-dom": "^6.28.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.3.12",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"@vitejs/plugin-react": "^4.3.4",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"postcss": "^8.4.49",
|
||||
"tailwindcss": "^3.4.15",
|
||||
"typescript": "^5.6.3",
|
||||
"vite": "^5.4.11"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
module.exports = { plugins: { tailwindcss: {}, autoprefixer: {} } };
|
||||
@@ -0,0 +1,202 @@
|
||||
'use strict';
|
||||
// Canned data for MOCK=1 mode. Shapes match the real /api/* contract exactly.
|
||||
// Timestamps are relative to boot so "time ago" stays plausible.
|
||||
|
||||
const now = Date.now();
|
||||
const iso = (minAgo) => new Date(now - minAgo * 60000).toISOString();
|
||||
|
||||
function run(id, event, status, conclusion, minAgo, durationSec) {
|
||||
return {
|
||||
id, event, status, conclusion,
|
||||
createdAt: iso(minAgo + durationSec / 60), updatedAt: iso(minAgo),
|
||||
durationSec, path: 'sync.yml@refs/heads/forker',
|
||||
};
|
||||
}
|
||||
|
||||
const MIRRORS = [
|
||||
{
|
||||
name: 'photocraft', full: 'Lago/photocraft',
|
||||
upstream: 'https://github.com/storytold/photocraft.git', forkUrl: 'https://git.lago.dev/Lago/photocraft', defaultBranch: 'main',
|
||||
lastSync: run(1203, 'schedule', 'completed', 'success', 3, 372),
|
||||
parity: { branches: 274, tags: 10, releases: 10, assets: 203, upstream: { branches: 273, tags: 10, releases: 10, assets: 203 } },
|
||||
units: ['Code', 'Issues', 'Pull Requests', 'Releases', 'Packages', 'Projects', 'Actions'],
|
||||
spark: ['success','success','success','success','failure','success','success','success','success','success',
|
||||
'success','success','success','success','success','success','success','success','success','success'],
|
||||
},
|
||||
{
|
||||
name: 'pdfcraft', full: 'Lago/pdfcraft',
|
||||
upstream: 'https://github.com/storytold/pdfcraft.git', forkUrl: 'https://git.lago.dev/Lago/pdfcraft', defaultBranch: 'main',
|
||||
lastSync: run(1191, 'push', 'completed', 'success', 8, 160),
|
||||
parity: { branches: 19, tags: 8, releases: 10, assets: 168, upstream: { branches: 18, tags: 8, releases: 10, assets: 168 } },
|
||||
units: ['Code', 'Issues', 'Pull Requests', 'Releases', 'Packages', 'Projects', 'Actions'],
|
||||
spark: Array(20).fill('success'),
|
||||
},
|
||||
{
|
||||
name: 'AnyPS5', full: 'Lago/AnyPS5',
|
||||
upstream: 'https://github.com/boykopovar/AnyPS5.git', forkUrl: 'https://git.lago.dev/Lago/AnyPS5', defaultBranch: 'main',
|
||||
lastSync: run(1199, 'schedule', 'in_progress', null, 1, 45),
|
||||
parity: { branches: 13, tags: 3, releases: 2, assets: 16, upstream: { branches: 13, tags: 3, releases: 2, assets: 16 } },
|
||||
units: ['Code', 'Issues', 'Pull Requests', 'Releases', 'Packages', 'Projects', 'Actions'],
|
||||
spark: ['in_progress', ...Array(19).fill('success')],
|
||||
},
|
||||
];
|
||||
|
||||
const RUNS = {
|
||||
photocraft: [
|
||||
run(1203, 'schedule', 'completed', 'success', 3, 372),
|
||||
run(1199, 'schedule', 'in_progress', null, 1, 45),
|
||||
run(1196, 'schedule', 'completed', 'failure', 13, 96),
|
||||
run(1190, 'push', 'completed', 'success', 28, 402),
|
||||
run(1188, 'schedule', 'completed', 'success', 43, 388),
|
||||
run(1185, 'schedule', 'completed', 'success', 58, 361),
|
||||
run(1181, 'schedule', 'completed', 'failure', 73, 44),
|
||||
run(1178, 'schedule', 'completed', 'success', 88, 395),
|
||||
run(1174, 'schedule', 'completed', 'success', 103, 370),
|
||||
run(1170, 'schedule', 'completed', 'success', 118, 382),
|
||||
run(1166, 'schedule', 'completed', 'success', 133, 377),
|
||||
run(1162, 'schedule', 'completed', 'success', 148, 369),
|
||||
],
|
||||
pdfcraft: [
|
||||
run(1191, 'push', 'completed', 'success', 8, 160),
|
||||
run(1189, 'schedule', 'completed', 'success', 23, 155),
|
||||
run(1186, 'schedule', 'completed', 'success', 38, 149),
|
||||
run(1182, 'schedule', 'completed', 'success', 53, 162),
|
||||
run(1178, 'schedule', 'completed', 'success', 68, 158),
|
||||
run(1174, 'schedule', 'completed', 'success', 83, 151),
|
||||
run(1170, 'schedule', 'completed', 'success', 98, 166),
|
||||
run(1166, 'schedule', 'completed', 'success', 113, 159),
|
||||
],
|
||||
AnyPS5: [
|
||||
run(1199, 'schedule', 'in_progress', null, 1, 45),
|
||||
run(1198, 'push', 'completed', 'success', 16, 38),
|
||||
run(1194, 'schedule', 'completed', 'success', 31, 41),
|
||||
run(1190, 'schedule', 'completed', 'success', 46, 39),
|
||||
run(1186, 'schedule', 'completed', 'success', 61, 44),
|
||||
run(1182, 'schedule', 'completed', 'success', 76, 37),
|
||||
],
|
||||
};
|
||||
|
||||
const LOG_OK = [
|
||||
">> Upstream configured: https://github.com/storytold/photocraft.git",
|
||||
"::group::fetch upstream refs",
|
||||
"remote: Enumerating objects: 18243, done.",
|
||||
"From https://github.com/storytold/photocraft",
|
||||
" 3f21c09..91c47aa main -> upstream/main",
|
||||
"::endgroup::",
|
||||
"::group::push to fork (274 refs)",
|
||||
"To https://git.lago.dev/Lago/photocraft.git",
|
||||
" 91c47aa..b8d2c10 main -> main",
|
||||
"::endgroup::",
|
||||
">> Sync complete. Branches: (274) Tags: (10) New tags: (none)",
|
||||
">> v0.8.2 already released — skipping (idempotent)",
|
||||
">> Releases unit OK (web asset download works: HTTP 200).",
|
||||
].map((text, t) => ({ t, text }));
|
||||
|
||||
const LOG_FAIL = [
|
||||
">> Upstream configured: https://github.com/storytold/photocraft.git",
|
||||
"::group::push to fork (274 refs)",
|
||||
"fatal: unable to access 'https://git.lago.dev/Lago/photocraft.git/': Could not resolve host: git.lago.dev",
|
||||
">> push_once: transient network error, retry 1 in 10s",
|
||||
"fatal: unable to access 'https://git.lago.dev/Lago/photocraft.git/': Could not resolve host: git.lago.dev",
|
||||
">> push_once: transient network error, retry 2 in 20s",
|
||||
"fatal: unable to access 'https://git.lago.dev/Lago/photocraft.git/': Could not resolve host: git.lago.dev",
|
||||
"::error::push failed after 3 attempts — aborting",
|
||||
].map((text, t) => ({ t, text }));
|
||||
|
||||
const RELEASES = {
|
||||
photocraft: ['v0.8.2','v0.7.0','v0.6.0','v0.5.0','v0.3.0','v0.2.0','v0.1.1-rc.5','v0.1.1-rc.4','v0.1.1','v0.1.0']
|
||||
.map((tag, i) => ({ id: 100 - i, tag, name: tag, assets: [40,22,18,12,16,15,14,14,22,30][i] })),
|
||||
pdfcraft: ['v1.4.0','v1.3.2','v1.3.1','v1.3.0','v1.2.0','v1.1.0','v1.0.2','v1.0.1','v1.0.0','v0.9.0']
|
||||
.map((tag, i) => ({ id: 90 - i, tag, name: tag, assets: [22,18,15,12,16,14,10,8,12,6][i] })),
|
||||
AnyPS5: ['v0.1.2','v0.1.1','v0.1.0'].map((tag, i) => ({ id: 80 - i, tag, name: tag, assets: [0,8,8][i] })),
|
||||
};
|
||||
|
||||
const RUNNERS = [
|
||||
{ id: 5, name: 'gitea-runner-forker', status: 'online', busy: true, labels: ['ubuntu-latest','ubuntu-24.04','ubuntu-22.04'], type: 'shared' },
|
||||
{ id: 3, name: '496cfb9f4583', status: 'offline', busy: false, labels: ['ubuntu-latest','ubuntu-24.04'], type: 'repo', repo: 'Lago/Tide' },
|
||||
{ id: 2, name: 'd3847f78c484', status: 'offline', busy: false, labels: ['ubuntu-latest','ubuntu-24.04'], type: 'repo', repo: 'Lago/Tide' },
|
||||
];
|
||||
|
||||
const QUEUE = [
|
||||
{ repo: 'AnyPS5', runId: 1199, event: 'schedule', status: 'in_progress', waitedSec: 45 },
|
||||
{ repo: 'photocraft', runId: 1204, event: 'schedule', status: 'queued', waitedSec: 12 },
|
||||
];
|
||||
|
||||
const CONFIG_RAW = [
|
||||
'# .forker.yaml — per-fork configuration for Repo Forker.',
|
||||
'',
|
||||
'mirror_branches: "*"',
|
||||
'mirror_tags: true',
|
||||
'mirror_prune: true',
|
||||
'mirror_upstream_releases: true',
|
||||
'on_new_tag: true',
|
||||
'build_cmd: ',
|
||||
'build_script: ',
|
||||
'artifacts: ',
|
||||
].join('\n');
|
||||
|
||||
function parseFlatLocal(text) {
|
||||
const KNOWN = ['mirror_branches','mirror_tags','mirror_prune','mirror_upstream_releases','on_new_tag','build_cmd','build_script','artifacts'];
|
||||
const BOOL = ['mirror_tags','mirror_prune','mirror_upstream_releases','on_new_tag'];
|
||||
const parsed = {};
|
||||
for (const line of String(text).split('\n')) {
|
||||
const t = line.trim();
|
||||
if (!t || t.startsWith('#')) continue;
|
||||
const m = line.match(/^([A-Za-z0-9_]+)\s*:\s*(.*)$/);
|
||||
if (!m) continue;
|
||||
let val = m[2].trim();
|
||||
if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) val = val.slice(1, -1);
|
||||
parsed[m[1]] = BOOL.includes(m[1]) ? (val === 'true' || val === '1') : val;
|
||||
}
|
||||
return { raw: text, parsed };
|
||||
}
|
||||
|
||||
const VARIABLES = {
|
||||
photocraft: [{ name: 'UPSTREAM_URL', value: 'https://github.com/storytold/photocraft.git' }],
|
||||
pdfcraft: [{ name: 'UPSTREAM_URL', value: 'https://github.com/storytold/pdfcraft.git' }],
|
||||
AnyPS5: [{ name: 'UPSTREAM_URL', value: 'https://github.com/boykopovar/AnyPS5.git' }],
|
||||
};
|
||||
|
||||
function find(name) {
|
||||
return MIRRORS.find((m) => m.name === name) || MIRRORS[0];
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
health: () => ({ ok: true, gitea: { url: 'http://127.0.0.1:3000', version: '28.1.0' } }),
|
||||
settings: () => ({ configured: true, url: 'http://127.0.0.1:3000', user: 'lago', template: 'Lago/repo-forker' }),
|
||||
mirrors: () => MIRRORS,
|
||||
mirrorRuns: (name, limit) => (RUNS[find(name).name] || []).slice(0, limit || 12),
|
||||
mirrorReleases: (name) => RELEASES[find(name).name] || [],
|
||||
mirrorConfig: (name) => parseFlatLocal(CONFIG_RAW),
|
||||
mirrorVariables: (name) => VARIABLES[find(name).name] || [],
|
||||
log: (name, runId) => {
|
||||
const isFail = String(runId) === '1196' || String(runId) === '1181';
|
||||
const lines = isFail ? LOG_FAIL : LOG_OK;
|
||||
return { lines, cursor: lines.length - 1 };
|
||||
},
|
||||
runners: () => RUNNERS,
|
||||
queue: () => QUEUE,
|
||||
connect: () => ({ ok: true, user: 'lago', version: '28.1.0' }),
|
||||
createMirror: (body) => {
|
||||
// mirror the server: strip a trailing .git from a provided name, else
|
||||
// derive from the upstream URL (last path segment, .git stripped, lower).
|
||||
const b = body || {};
|
||||
const provided = String(b.name || '').trim().replace(/\.git$/i, '');
|
||||
let repoName = provided;
|
||||
if (!repoName) {
|
||||
try { repoName = new URL(b.upstream).pathname.split('/').filter(Boolean).pop().replace(/\.git$/i, '').toLowerCase() || 'new-mirror'; }
|
||||
catch { repoName = 'new-mirror'; }
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
repo: `Lago/${repoName}`,
|
||||
steps: [
|
||||
{ name: 'generate', status: 'ok' },
|
||||
{ name: 'variable', status: 'ok' },
|
||||
{ name: 'default-branch', status: 'ok' },
|
||||
{ name: 'config', status: 'ok' },
|
||||
{ name: 'first-sync', status: 'ok' },
|
||||
],
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,661 @@
|
||||
#!/usr/bin/env node
|
||||
/* Repo Forker UI — zero-dependency local server.
|
||||
* Serves the built app (dist/) and proxies the Gitea API.
|
||||
* The token never leaves this process; it is stored in ~/.repo-forker/credentials (chmod 600).
|
||||
* Usage: node bin/repo-forker-ui.js (or: MOCK=1 node server/server.js for canned data)
|
||||
*/
|
||||
'use strict';
|
||||
const http = require('http');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const { spawn } = require('child_process');
|
||||
|
||||
const MOCK = !!process.env.MOCK;
|
||||
const CRED_DIR = path.join(os.homedir(), '.repo-forker');
|
||||
const CRED_FILE = path.join(CRED_DIR, 'credentials');
|
||||
const TEMPLATE = 'Lago/repo-forker';
|
||||
|
||||
// ---------------------------------------------------------------- credentials
|
||||
function loadCreds() {
|
||||
try {
|
||||
const c = JSON.parse(fs.readFileSync(CRED_FILE, 'utf8'));
|
||||
if (c && c.url && c.token) return c;
|
||||
} catch { /* absent */ }
|
||||
return null;
|
||||
}
|
||||
function saveCreds(c) {
|
||||
fs.mkdirSync(CRED_DIR, { recursive: true });
|
||||
fs.writeFileSync(CRED_FILE, JSON.stringify(c, null, 2));
|
||||
fs.chmodSync(CRED_FILE, 0o600);
|
||||
}
|
||||
let CREDS = MOCK ? { url: 'http://127.0.0.1:3000', token: 'mock', user: 'lago' } : loadCreds();
|
||||
|
||||
// ---------------------------------------------------------------- gitea helper
|
||||
async function gitea(method, apiPath, { body, raw } = {}) {
|
||||
if (MOCK) return mockCall(method, apiPath, body);
|
||||
if (!CREDS) throw new Error('not connected — POST /api/connect first');
|
||||
// Normalize: caller paths may or may not carry the /api/v1 prefix.
|
||||
let ap = apiPath;
|
||||
if (!ap.startsWith('/api/')) ap = '/api/v1' + ap;
|
||||
const url = CREDS.url.replace(/\/+$/, '') + ap;
|
||||
const res = await fetch(url, {
|
||||
method,
|
||||
headers: {
|
||||
Authorization: `Bearer ${CREDS.token}`,
|
||||
...(body ? { 'Content-Type': 'application/json' } : {}),
|
||||
},
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
signal: AbortSignal.timeout(30000),
|
||||
});
|
||||
if (res.status === 204) return { status: 204, data: null };
|
||||
const text = await res.text();
|
||||
let data = raw ? text : null;
|
||||
if (!raw && text) { try { data = JSON.parse(text); } catch { data = text; } }
|
||||
if (!res.ok) {
|
||||
const msg = (data && data.message) || (typeof data === 'string' ? data : text) || `HTTP ${res.status}`;
|
||||
const e = new Error(msg); e.status = res.status;
|
||||
throw e;
|
||||
}
|
||||
return { status: res.status, data };
|
||||
}
|
||||
async function giteaList(apiPath) {
|
||||
const all = [];
|
||||
for (let page = 1; page <= 60; page++) {
|
||||
const { data } = await gitea('GET', `${apiPath}?limit=50&page=${page}`);
|
||||
if (!Array.isArray(data)) break;
|
||||
all.push(...data);
|
||||
if (data.length < 50) break;
|
||||
}
|
||||
return all;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- flat .forker.yaml
|
||||
const KNOWN_KEYS = ['mirror_branches', 'mirror_tags', 'mirror_prune',
|
||||
'mirror_upstream_releases', 'on_new_tag', 'build_cmd', 'build_script', 'artifacts'];
|
||||
const BOOL_KEYS = ['mirror_tags', 'mirror_prune', 'mirror_upstream_releases', 'on_new_tag'];
|
||||
|
||||
function parseVal(key, raw) {
|
||||
let val = String(raw).trim();
|
||||
if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) val = val.slice(1, -1);
|
||||
return BOOL_KEYS.includes(key) ? (val === 'true' || val === '1') : val;
|
||||
}
|
||||
function parseFlat(text) {
|
||||
const parsed = {};
|
||||
for (const line of String(text).split('\n')) {
|
||||
const t = line.trim();
|
||||
if (!t || t.startsWith('#')) continue;
|
||||
const m = line.match(/^([A-Za-z0-9_]+)\s*:\s*(.*)$/);
|
||||
if (!m) throw new Error(`not a flat key: value line — ${t}`);
|
||||
parsed[m[1]] = parseVal(m[1], m[2]);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
// Validate only the client's incoming keys — the file may carry other inert keys
|
||||
// (e.g. `token_user`) that the grep parser ignores. Reject unknown keys + nesting.
|
||||
function validateIncoming(parsed) {
|
||||
for (const k of Object.keys(parsed)) {
|
||||
if (!KNOWN_KEYS.includes(k)) { const e = new Error(`unknown key: ${k} (allowed: ${KNOWN_KEYS.join(', ')})`); e.status = 400; throw e; }
|
||||
if (typeof parsed[k] === 'object') { const e = new Error(`nested value not allowed: ${k} — the parser is flat`); e.status = 400; throw e; }
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function ser(key, v) {
|
||||
if (BOOL_KEYS.includes(key)) return v ? 'true' : 'false';
|
||||
const s = String(v);
|
||||
if (s === '') return '';
|
||||
const needQuote = /[!*|&>%@[\]"\n ]/.test(s) || /^(true|false|null|~)$/i.test(s);
|
||||
return needQuote ? `"${s.replace(/"/g, '\\"')}"` : s;
|
||||
}
|
||||
// Preserving render: a value equal to the original keeps its verbatim line, so
|
||||
// `mirror_branches: "*"` stays quoted and a no-op yields byte-identical text
|
||||
// (→ the caller's `next !== raw` guard skips the PUT). Trailing-newline state
|
||||
// is preserved exactly so a no-op never differs from the source.
|
||||
function renderFlat(parsed, originalText) {
|
||||
const raw = String(originalText);
|
||||
const hadTrailingNL = raw.endsWith('\n');
|
||||
let lines = raw.split('\n');
|
||||
if (hadTrailingNL && lines[lines.length - 1] === '') lines = lines.slice(0, -1);
|
||||
const out = [];
|
||||
const used = new Set();
|
||||
for (const line of lines) {
|
||||
const m = line.match(/^([A-Za-z0-9_]+)\s*:\s*(.*)$/);
|
||||
if (m && m[1] in parsed) {
|
||||
const k = m[1], v = parsed[k];
|
||||
out.push(parseVal(k, m[2]) === v ? line : `${k}: ${ser(k, v)}`);
|
||||
used.add(k);
|
||||
} else out.push(line);
|
||||
}
|
||||
for (const k of KNOWN_KEYS) {
|
||||
if (k in parsed && !used.has(k)) out.push(`${k}: ${ser(k, parsed[k])}`);
|
||||
}
|
||||
let result = out.join('\n');
|
||||
if (hadTrailingNL) result += '\n';
|
||||
return result;
|
||||
}
|
||||
|
||||
// Update an existing repo file on a branch. Gitea's contents API 422s
|
||||
// ("file already exists") if you omit the current blob `sha`, so fetch it first.
|
||||
async function updateRepoFile(full, filePath, content, message, branch) {
|
||||
const { data: meta } = await gitea('GET', `/repos/${full}/contents/${filePath}?ref=${branch}`);
|
||||
const body = {
|
||||
content: Buffer.from(content).toString('base64'),
|
||||
message,
|
||||
branch,
|
||||
};
|
||||
if (meta && meta.sha) body.sha = meta.sha; // present ⇒ update, not create
|
||||
await gitea('PUT', `/repos/${full}/contents/${filePath}`, { body });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- upstream parity (anonymous)
|
||||
const parityCache = new Map();
|
||||
async function upstreamCounts(upstream) {
|
||||
const key = String(upstream).toLowerCase();
|
||||
const hit = parityCache.get(key);
|
||||
if (hit && Date.now() - hit.at < 300000) return hit.data;
|
||||
let data;
|
||||
try {
|
||||
const u = new URL(upstream);
|
||||
data = (u.hostname === 'github.com' || u.hostname === 'gist.github.com')
|
||||
? await githubCounts(u)
|
||||
: await gitLsRemoteCounts(upstream);
|
||||
} catch (e) {
|
||||
data = { branches: null, tags: null, releases: null, assets: null };
|
||||
}
|
||||
parityCache.set(key, { at: Date.now(), data });
|
||||
return data;
|
||||
}
|
||||
async function githubCounts(u) {
|
||||
const parts = u.pathname.split('/').filter(Boolean);
|
||||
const owner = parts[0];
|
||||
const repo = (parts[1] || '').replace(/\.git$/, '');
|
||||
const base = `https://api.github.com/repos/${owner}/${repo}`;
|
||||
const hdr = { 'User-Agent': 'repo-forker-ui (anonymous)' };
|
||||
const listAll = async (p) => {
|
||||
let all = [], page = 1;
|
||||
while (page <= 10) {
|
||||
const r = await fetch(`${base}${p}?per_page=100&page=${page}`, { headers: hdr, signal: AbortSignal.timeout(30000) });
|
||||
if (!r.ok) throw new Error(`github ${p} → ${r.status}`);
|
||||
const arr = await r.json();
|
||||
all.push(...arr);
|
||||
if (arr.length < 100) break;
|
||||
page++;
|
||||
}
|
||||
return all;
|
||||
};
|
||||
const [branches, tags, releases] = await Promise.all([
|
||||
listAll('/branches').catch(() => null),
|
||||
listAll('/tags').catch(() => null),
|
||||
listAll('/releases').catch(() => []),
|
||||
]);
|
||||
return {
|
||||
branches: branches ? branches.length : null,
|
||||
tags: tags ? tags.length : null,
|
||||
releases: releases.length,
|
||||
assets: releases.reduce((s, r) => s + (r.assets ? r.assets.length : 0), 0),
|
||||
};
|
||||
}
|
||||
function gitLsRemoteCounts(url) {
|
||||
return new Promise((resolve) => {
|
||||
const child = spawn('git', ['ls-remote', '--heads', '--tags', url], {
|
||||
timeout: 30000,
|
||||
env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1' },
|
||||
});
|
||||
let out = '';
|
||||
child.stdout.on('data', (d) => (out += d));
|
||||
child.on('error', () => resolve({ branches: null, tags: null, releases: null, assets: null }));
|
||||
child.on('close', (code) => {
|
||||
if (code !== 0) return resolve({ branches: null, tags: null, releases: null, assets: null });
|
||||
const lines = out.split('\n').filter(Boolean);
|
||||
resolve({
|
||||
branches: lines.filter((l) => l.includes('refs/heads/')).length,
|
||||
tags: lines.filter((l) => l.includes('refs/tags/')).length,
|
||||
releases: null, assets: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- fork side
|
||||
function mapRun(r) {
|
||||
const created = new Date(r.created_at || 0).getTime();
|
||||
const completed = new Date(r.completed_at || 0).getTime();
|
||||
return {
|
||||
id: r.id, event: r.event, status: r.status, conclusion: r.conclusion || null,
|
||||
createdAt: r.created_at, updatedAt: r.updated_at, path: r.path,
|
||||
durationSec: completed > created ? Math.round((completed - created) / 1000) : 0,
|
||||
};
|
||||
}
|
||||
async function runsFor(full, workflow, limit) {
|
||||
const { data } = await gitea('GET', `/repos/${full}/actions/runs?limit=${Math.min(limit * 4, 100)}`);
|
||||
let runs = ((data && data.workflow_runs) || []).map(mapRun);
|
||||
if (workflow) runs = runs.filter((r) => (r.path || '').startsWith(workflow));
|
||||
return runs.slice(0, limit);
|
||||
}
|
||||
async function lastRun(full, workflow) {
|
||||
const runs = await runsFor(full, workflow, 1);
|
||||
return runs[0] || null;
|
||||
}
|
||||
async function sparkFor(full, workflow) {
|
||||
const runs = await runsFor(full, workflow, 20);
|
||||
return runs.map((r) => r.conclusion === 'failure' ? 'failure' : r.status === 'in_progress' ? 'in_progress' : r.status === 'queued' ? 'queued' : 'success');
|
||||
}
|
||||
async function forkCounts(full) {
|
||||
const [branches, tags, releases] = await Promise.all([
|
||||
giteaList(`/repos/${full}/branches`),
|
||||
giteaList(`/repos/${full}/tags`),
|
||||
giteaList(`/repos/${full}/releases`),
|
||||
]);
|
||||
return {
|
||||
branches: branches.length,
|
||||
tags: tags.length,
|
||||
releases: releases.length,
|
||||
assets: releases.reduce((s, r) => s + (r.assets ? r.assets.length : 0), 0),
|
||||
};
|
||||
}
|
||||
function unitsOf(repoObj) {
|
||||
const map = { has_code: 'Code', has_issues: 'Issues', has_pull_requests: 'Pull Requests',
|
||||
has_releases: 'Releases', has_packages: 'Packages', has_projects: 'Projects', has_wiki: 'Wiki' };
|
||||
return Object.entries(map).filter(([k]) => repoObj && repoObj[k]).map(([, v]) => v);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- mirror detection
|
||||
// Limited-concurrency pool (keeps Gitea's connection pool happy, no thundering herd).
|
||||
async function pmap(items, limit, fn) {
|
||||
const out = new Array(items.length);
|
||||
let i = 0;
|
||||
const workers = Array.from({ length: Math.min(limit, items.length) || 1 }, async () => {
|
||||
while (i < items.length) { const idx = i++; out[idx] = await fn(items[idx], idx); }
|
||||
});
|
||||
await Promise.all(workers);
|
||||
return out;
|
||||
}
|
||||
// Shared cache so the 3s queue poll and 15s runner poll don't re-probe 36 repos.
|
||||
const mirrorsCache = { at: 0, data: null, refreshing: false, pending: null };
|
||||
async function detectMirrors(force) {
|
||||
const now = Date.now();
|
||||
const age = mirrorsCache.data ? now - mirrorsCache.at : Infinity;
|
||||
if (!force && age < 15000) return mirrorsCache.data;
|
||||
if (!force && age < 600000) {
|
||||
// stale-while-revalidate: ALWAYS answer instantly from cache. Only start a
|
||||
// background refresh if one isn't already running (never stack recomputes).
|
||||
if (!mirrorsCache.refreshing) {
|
||||
mirrorsCache.refreshing = true;
|
||||
detectMirrors(true).catch(() => {}).finally(() => { mirrorsCache.refreshing = false; });
|
||||
}
|
||||
return mirrorsCache.data;
|
||||
}
|
||||
// Cold / forced: dedupe so N simultaneous first-time callers (mirrors+runners+
|
||||
// queue on page load) share ONE probe round instead of firing 3x ~74 requests.
|
||||
if (mirrorsCache.pending) return mirrorsCache.pending;
|
||||
mirrorsCache.pending = (async () => {
|
||||
try {
|
||||
const repos = await giteaList('/user/repos');
|
||||
const candidates = [];
|
||||
await pmap(repos, 8, async (repo) => {
|
||||
const full = repo.full_name;
|
||||
if (full.toLowerCase() === TEMPLATE.toLowerCase()) return; // never the template
|
||||
try { await gitea('GET', `/repos/${full}/branches/forker`); } catch { return; }
|
||||
try {
|
||||
const { data } = await gitea('GET', `/repos/${full}/actions/variables/UPSTREAM_URL`);
|
||||
if (data && data.data) candidates.push({ repo, upVar: data.data });
|
||||
} catch { /* not a mirror */ }
|
||||
});
|
||||
const out = [];
|
||||
await pmap(candidates, 4, async ({ repo, upVar }) => {
|
||||
const full = repo.full_name;
|
||||
const [lastSync, fc, up, spark] = await Promise.all([
|
||||
lastRun(full, 'sync.yml').catch(() => null),
|
||||
forkCounts(full).catch(() => null),
|
||||
upstreamCounts(upVar).catch(() => null), // 300s-cached; keeps anonymous GitHub calls at ~1/repo/5min
|
||||
sparkFor(full, 'sync.yml').catch(() => []),
|
||||
]);
|
||||
out.push({
|
||||
name: repo.name, full, upstream: upVar,
|
||||
forkUrl: `${(CREDS && CREDS.url ? CREDS.url : '').replace(/\/+$/, '')}/${full}`,
|
||||
defaultBranch: repo.default_branch || 'main',
|
||||
lastSync,
|
||||
parity: fc ? {
|
||||
branches: fc.branches, tags: fc.tags, releases: fc.releases, assets: fc.assets,
|
||||
upstream: up || {},
|
||||
} : null,
|
||||
units: unitsOf(repo),
|
||||
spark,
|
||||
});
|
||||
});
|
||||
out.sort((a, b) => a.name.localeCompare(b.name));
|
||||
mirrorsCache.at = now;
|
||||
mirrorsCache.data = out;
|
||||
return out;
|
||||
} finally {
|
||||
mirrorsCache.pending = null;
|
||||
}
|
||||
})();
|
||||
return mirrorsCache.pending;
|
||||
}
|
||||
// Cheap name list backed by the same cache (queue/runner polls don't re-probe).
|
||||
async function listMirrorNames() {
|
||||
const list = await detectMirrors();
|
||||
return list.map((m) => m.full);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- create mirror
|
||||
// Derive a repo name from an upstream URL — MUST mirror the client's
|
||||
// deriveName (format.ts) so the placeholder shown to the user is exactly the
|
||||
// name that gets created. Gitea rejects repo names matching *.git, so strip a
|
||||
// trailing .git (and lowercase) or the generate step 400s with
|
||||
// "name pattern is not allowed [pattern: *.git]".
|
||||
function deriveRepoName(url) {
|
||||
try {
|
||||
const u = new URL(url);
|
||||
const last = u.pathname.split('/').filter(Boolean).pop() || 'mirror';
|
||||
return last.replace(/\.git$/i, '').toLowerCase() || 'mirror';
|
||||
} catch { return 'mirror'; }
|
||||
}
|
||||
async function createMirror(upstream, name, config) {
|
||||
const owner = (CREDS && CREDS.user) || 'lago';
|
||||
// A provided name keeps its case (only the derived one is lowercased, to
|
||||
// match the placeholder) but a trailing .git is stripped; if that leaves it
|
||||
// empty, fall back to deriving from the URL (which is always non-empty).
|
||||
const repoName = String(name || '').trim().replace(/\.git$/i, '') || deriveRepoName(upstream);
|
||||
const full = `${owner}/${repoName}`;
|
||||
const steps = [];
|
||||
const fail = (stepName, e) => { steps.push({ name: stepName, status: 'error' }); return { ok: false, repo: full, steps, error: String((e && e.message) || e) }; };
|
||||
try {
|
||||
await gitea('POST', `/repos/${TEMPLATE}/generate`, {
|
||||
body: { name: repoName, owner, description: `Mirror of ${upstream} (Repo Forker)`, git_content: true, private: false },
|
||||
});
|
||||
steps.push({ name: 'generate', status: 'ok' });
|
||||
} catch (e) { return fail('generate', e); }
|
||||
try {
|
||||
await gitea('POST', `/repos/${full}/actions/variables/UPSTREAM_URL`, { body: { name: 'UPSTREAM_URL', value: upstream } });
|
||||
steps.push({ name: 'variable', status: 'ok' });
|
||||
} catch (e) { return fail('variable', e); }
|
||||
let def = 'main';
|
||||
try {
|
||||
const u = new URL(upstream);
|
||||
if (u.hostname === 'github.com') {
|
||||
const r = await fetch(`https://api.github.com/repos${u.pathname}`, {
|
||||
headers: { 'User-Agent': 'repo-forker-ui (anonymous)' }, signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
if (r.ok) def = ((await r.json()).default_branch) || 'main';
|
||||
}
|
||||
} catch { /* default main */ }
|
||||
try {
|
||||
await gitea('PATCH', `/repos/${full}`, { body: { default_branch: def } });
|
||||
steps.push({ name: 'default-branch', status: 'ok' });
|
||||
} catch (e) { return fail('default-branch', e); }
|
||||
try {
|
||||
const { data: raw } = await gitea('GET', `/repos/${full}/raw/.forker.yaml?ref=forker`, { raw: true });
|
||||
const parsed = parseFlat(raw);
|
||||
for (const [k, v] of Object.entries(config || {})) {
|
||||
if (v === undefined || v === null || v === '') continue;
|
||||
parsed[k] = v;
|
||||
}
|
||||
validateIncoming(config || {});
|
||||
const next = renderFlat(parsed, raw);
|
||||
if (next !== raw) await updateRepoFile(full, '.forker.yaml', next, 'Configure .forker.yaml', 'forker');
|
||||
steps.push({ name: 'config', status: 'ok' });
|
||||
} catch (e) { return fail('config', e); }
|
||||
try {
|
||||
await gitea('POST', `/repos/${full}/actions/workflows/sync.yml/dispatches`, { body: { ref: 'forker' } });
|
||||
steps.push({ name: 'first-sync', status: 'ok' });
|
||||
} catch (e) { return fail('first-sync', e); }
|
||||
return { ok: true, repo: full, steps };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- mock mode
|
||||
const mock = require('./mock.js');
|
||||
// In MOCK mode the /api handlers below short-circuit to these canned helpers
|
||||
// (no network, no detectMirrors). The gitea() mockCall is only a fallback for
|
||||
// any path the handlers don't special-case.
|
||||
function mockCall(method, apiPath, body) {
|
||||
// Not used by the main handlers in MOCK mode; kept as a safe no-op fallback.
|
||||
return { status: 200, data: {} };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- http server
|
||||
const MIME = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.json': 'application/json', '.map': 'application/json' };
|
||||
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const url = new URL(req.url, 'http://127.0.0.1');
|
||||
const p = url.pathname;
|
||||
const send = (code, obj) => {
|
||||
const data = typeof obj === 'string' ? obj : JSON.stringify(obj);
|
||||
res.writeHead(code, {
|
||||
'Content-Type': typeof obj === 'string' ? 'text/plain; charset=utf-8' : 'application/json',
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
|
||||
'Access-Control-Allow-Methods': 'GET,POST,PUT,DELETE,OPTIONS',
|
||||
});
|
||||
res.end(data);
|
||||
};
|
||||
if (req.method === 'OPTIONS') return send(204, '');
|
||||
const readBody = async () => {
|
||||
const chunks = [];
|
||||
for await (const c of req) chunks.push(c);
|
||||
return chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : null;
|
||||
};
|
||||
|
||||
try {
|
||||
if (p.startsWith('/api/')) {
|
||||
// ---- MOCK short-circuits (canned data, no network) ----
|
||||
if (MOCK) {
|
||||
let m;
|
||||
if (p === '/api/health') return send(200, mock.health());
|
||||
if (p === '/api/settings') return send(200, mock.settings());
|
||||
if (p === '/api/connect' && req.method === 'POST') return send(200, mock.connect());
|
||||
if (p === '/api/mirrors' && req.method === 'GET') return send(200, mock.mirrors());
|
||||
if (p === '/api/mirrors' && req.method === 'POST') { const b = await readBody(); return send(200, mock.createMirror(b)); }
|
||||
if ((m = p.match(/^\/api\/mirrors\/([^/]+)\/runs$/))) return send(200, mock.mirrorRuns(decodeURIComponent(m[1]), parseInt(url.searchParams.get('limit') || '12', 10)));
|
||||
if ((m = p.match(/^\/api\/mirrors\/([^/]+)\/releases$/))) return send(200, mock.mirrorReleases(decodeURIComponent(m[1])));
|
||||
if ((m = p.match(/^\/api\/mirrors\/([^/]+)\/config$/))) return send(200, mock.mirrorConfig(decodeURIComponent(m[1])));
|
||||
if ((m = p.match(/^\/api\/mirrors\/([^/]+)\/variables$/)) && req.method === 'GET') return send(200, mock.mirrorVariables(decodeURIComponent(m[1])));
|
||||
if ((m = p.match(/^\/api\/mirrors\/([^/]+)\/variables$/)) && req.method === 'POST') return send(200, { ok: true });
|
||||
if ((m = p.match(/^\/api\/mirrors\/([^/]+)\/variables\/([^/]+)$/)) && req.method === 'DELETE') return send(200, { ok: true });
|
||||
if ((m = p.match(/^\/api\/mirrors\/([^/]+)\/dispatch$/))) return send(200, { ok: true });
|
||||
if ((m = p.match(/^\/api\/mirrors\/([^/]+)$/)) && req.method === 'DELETE') return send(200, { ok: true });
|
||||
if ((m = p.match(/^\/api\/mirrors\/([^/]+)\/runs\/(\d+)\/log$/))) return send(200, mock.log(decodeURIComponent(m[1]), m[2]));
|
||||
if (p === '/api/runners') return send(200, mock.runners());
|
||||
if (p === '/api/queue') return send(200, mock.queue());
|
||||
return send(404, { ok: false, error: `unknown mock api: ${req.method} ${p}` });
|
||||
}
|
||||
// ---- real Gitea proxy ----
|
||||
if (p === '/api/health') {
|
||||
if (!CREDS) return send(200, { ok: false, gitea: null });
|
||||
try {
|
||||
const { data } = await gitea('GET', '/api/v1/version');
|
||||
return send(200, { ok: true, gitea: { url: CREDS.url, version: (data && data.version) || 'unknown' } });
|
||||
} catch (e) {
|
||||
return send(200, { ok: false, gitea: null, error: String(e.message) });
|
||||
}
|
||||
}
|
||||
if (p === '/api/connect' && req.method === 'POST') {
|
||||
const b = await readBody();
|
||||
const base = String((b && b.url) || '').replace(/\/+$/, '');
|
||||
const tok = String((b && b.token) || '');
|
||||
if (!base || !tok) return send(400, { ok: false, error: 'url and token required' });
|
||||
if (MOCK) { CREDS = { url: base, token: tok, user: 'lago' }; return send(200, { ok: true, user: 'lago', version: '28.1.0' }); }
|
||||
try {
|
||||
const r = await fetch(`${base}/api/v1/user`, { headers: { Authorization: `Bearer ${tok}` }, signal: AbortSignal.timeout(15000) });
|
||||
if (!r.ok) throw new Error(`Gitea replied HTTP ${r.status}`);
|
||||
const u = await r.json();
|
||||
let version = 'unknown';
|
||||
try { version = ((await (await fetch(`${base}/api/v1/version`, { headers: { Authorization: `Bearer ${tok}` } })).json()).version) || 'unknown'; } catch { /* ok */ }
|
||||
CREDS = { url: base, token: tok, user: u.login };
|
||||
saveCreds(CREDS);
|
||||
return send(200, { ok: true, user: u.login, version });
|
||||
} catch (e) {
|
||||
return send(400, { ok: false, error: String(e.message) });
|
||||
}
|
||||
}
|
||||
if (p === '/api/settings') {
|
||||
return send(200, { configured: !!CREDS, url: CREDS ? CREDS.url : '', user: CREDS ? CREDS.user : '', template: TEMPLATE });
|
||||
}
|
||||
if (p === '/api/mirrors' && req.method === 'GET') {
|
||||
const mirrors = await detectMirrors();
|
||||
return send(200, mirrors);
|
||||
}
|
||||
if (p === '/api/mirrors' && req.method === 'POST') {
|
||||
const b = await readBody();
|
||||
if (!b || !b.upstream) return send(400, { ok: false, error: 'upstream required' });
|
||||
const r = await createMirror(b.upstream, b.name, b.config || {});
|
||||
return send(r.ok ? 200 : 400, r);
|
||||
}
|
||||
let m;
|
||||
if ((m = p.match(/^\/api\/mirrors\/([^/]+)\/runs\/(\d+)\/log$/))) {
|
||||
const full = `${CREDS.user}/${decodeURIComponent(m[1])}`;
|
||||
const { data: jobs } = await gitea('GET', `/repos/${full}/actions/runs/${m[2]}/jobs`);
|
||||
const job = (jobs && jobs.jobs && jobs.jobs[0]) || {};
|
||||
if (!job.id) return send(200, { lines: [], cursor: -1 });
|
||||
const { data: text } = await gitea('GET', `/repos/${full}/actions/jobs/${job.id}/logs`, { raw: true });
|
||||
const lines = String(text || '').split('\n').map((text2, i) => ({ t: i, text: text2 }));
|
||||
return send(200, { lines, cursor: lines.length - 1 });
|
||||
}
|
||||
if ((m = p.match(/^\/api\/mirrors\/([^/]+)\/runs$/))) {
|
||||
const full = `${CREDS.user}/${decodeURIComponent(m[1])}`;
|
||||
const limit = parseInt(url.searchParams.get('limit') || '12', 10);
|
||||
const runs = await runsFor(full, null, limit);
|
||||
return send(200, runs);
|
||||
}
|
||||
if ((m = p.match(/^\/api\/mirrors\/([^/]+)\/releases$/))) {
|
||||
const full = `${CREDS.user}/${decodeURIComponent(m[1])}`;
|
||||
const rels = await giteaList(`/repos/${full}/releases`);
|
||||
return send(200, rels.map((r) => ({ id: r.id, tag: r.tag_name, name: r.name || r.tag_name, assets: r.assets ? r.assets.length : 0 })));
|
||||
}
|
||||
if ((m = p.match(/^\/api\/mirrors\/([^/]+)\/config$/))) {
|
||||
const full = `${CREDS.user}/${decodeURIComponent(m[1])}`;
|
||||
if (req.method === 'GET') {
|
||||
const { data } = await gitea('GET', `/repos/${full}/raw/.forker.yaml?ref=forker`, { raw: true });
|
||||
return send(200, { raw: data, parsed: parseFlat(data) });
|
||||
}
|
||||
const b = await readBody();
|
||||
const incoming = (b && b.parsed) || {};
|
||||
validateIncoming(incoming);
|
||||
const { data: raw } = await gitea('GET', `/repos/${full}/raw/.forker.yaml?ref=forker`, { raw: true });
|
||||
const merged = { ...parseFlat(raw), ...incoming };
|
||||
const next = renderFlat(merged, raw);
|
||||
if (next !== raw) await updateRepoFile(full, '.forker.yaml', next, 'Update .forker.yaml', 'forker');
|
||||
return send(200, { raw: next, parsed: merged });
|
||||
}
|
||||
if ((m = p.match(/^\/api\/mirrors\/([^/]+)\/variables\/([^/]+)$/)) && req.method === 'DELETE') {
|
||||
const full = `${CREDS.user}/${decodeURIComponent(m[1])}`;
|
||||
await gitea('DELETE', `/repos/${full}/actions/variables/${decodeURIComponent(m[2])}`);
|
||||
return send(200, { ok: true });
|
||||
}
|
||||
if ((m = p.match(/^\/api\/mirrors\/([^/]+)\/variables$/))) {
|
||||
const full = `${CREDS.user}/${decodeURIComponent(m[1])}`;
|
||||
if (req.method === 'GET') {
|
||||
// this Gitea build has no list-variables endpoint — probe the known names
|
||||
const out = [];
|
||||
for (const n of ['UPSTREAM_URL', 'UPSTREAM_TOKEN']) {
|
||||
try {
|
||||
const { data } = await gitea('GET', `/repos/${full}/actions/variables/${n}`);
|
||||
if (data && data.name) out.push({ name: data.name, value: data.data });
|
||||
} catch { /* not set */ }
|
||||
}
|
||||
return send(200, out);
|
||||
}
|
||||
const b = await readBody();
|
||||
if (!b || !b.name) return send(400, { ok: false, error: 'name required' });
|
||||
await gitea('POST', `/repos/${full}/actions/variables/${encodeURIComponent(b.name)}`, { body: b });
|
||||
return send(200, { ok: true });
|
||||
}
|
||||
if ((m = p.match(/^\/api\/mirrors\/([^/]+)\/dispatch$/)) && req.method === 'POST') {
|
||||
const full = `${CREDS.user}/${decodeURIComponent(m[1])}`;
|
||||
const b = await readBody();
|
||||
const wf = (b && b.workflow) || 'sync.yml';
|
||||
const ref = (b && b.ref) || 'forker';
|
||||
await gitea('POST', `/repos/${full}/actions/workflows/${wf}/dispatches`, { body: { ref } });
|
||||
return send(200, { ok: true });
|
||||
}
|
||||
if ((m = p.match(/^\/api\/mirrors\/([^/]+)$/)) && req.method === 'DELETE') {
|
||||
const full = `${CREDS.user}/${decodeURIComponent(m[1])}`;
|
||||
await gitea('DELETE', `/repos/${full}`);
|
||||
return send(200, { ok: true });
|
||||
}
|
||||
if (p === '/api/runners') {
|
||||
const out = new Map();
|
||||
const add = (r, scopeRepo) => {
|
||||
const prev = out.get(r.id);
|
||||
const repos = prev ? new Set(prev.repoScope) : new Set();
|
||||
if (scopeRepo) repos.add(scopeRepo);
|
||||
out.set(r.id, {
|
||||
id: r.id, name: r.name, status: r.status, busy: !!r.busy, disabled: !!r.disabled,
|
||||
labels: ((r.labels) || []).map((l) => l.name), repoScope: [...repos],
|
||||
});
|
||||
};
|
||||
// repo-scoped list — one representative mirror (or the template) is enough to
|
||||
// discover which runners attach to this user's repos
|
||||
const names = await listMirrorNames().catch(() => []);
|
||||
const probe = names[0] || TEMPLATE;
|
||||
try {
|
||||
const { data } = await gitea('GET', `/repos/${probe}/actions/runners?limit=50`);
|
||||
for (const r of (data && data.runners) || []) add(r, probe);
|
||||
} catch { /* skip */ }
|
||||
try {
|
||||
const { data } = await gitea('GET', '/api/v1/admin/actions/runners?limit=50');
|
||||
for (const r of (data && data.runners) || []) add(r, null);
|
||||
} catch { /* 403 tolerated — not an admin */ }
|
||||
const runners = [...out.values()].map((r) => ({
|
||||
id: r.id, name: r.name, status: r.status, busy: r.busy, labels: r.labels,
|
||||
// repo-scoped list is empty for instance-shared runners on this build,
|
||||
// so admin-only ⇒ shared (serves all repos).
|
||||
type: r.repoScope.length >= 2 ? 'shared' : r.repoScope.length === 1 ? 'repo' : 'shared',
|
||||
repo: r.repoScope.length === 1 ? r.repoScope[0] : undefined,
|
||||
}));
|
||||
return send(200, runners);
|
||||
}
|
||||
if (p === '/api/queue') {
|
||||
const names = await listMirrorNames().catch(() => []);
|
||||
const out = [];
|
||||
for (const full of names) {
|
||||
const runs = await runsFor(full, null, 10).catch(() => []);
|
||||
for (const r of runs) {
|
||||
if (r.status !== 'queued' && r.status !== 'in_progress') continue;
|
||||
out.push({
|
||||
repo: full.split('/')[1], runId: r.id, event: r.event, status: r.status,
|
||||
waitedSec: Math.max(0, Math.round((Date.now() - new Date(r.createdAt).getTime()) / 1000)),
|
||||
});
|
||||
}
|
||||
}
|
||||
out.sort((a, b) => b.waitedSec - a.waitedSec);
|
||||
return send(200, out);
|
||||
}
|
||||
return send(404, { ok: false, error: `unknown api: ${req.method} ${p}` });
|
||||
}
|
||||
|
||||
// ---------- static ----------
|
||||
const base = path.join(__dirname, '..', 'dist');
|
||||
let fp = path.normalize(path.join(base, p === '/' ? 'index.html' : p));
|
||||
if (!fp.startsWith(base)) fp = path.join(base, 'index.html');
|
||||
if (!fs.existsSync(fp) && !path.extname(fp)) fp = path.join(base, 'index.html'); // SPA fallback
|
||||
if (fs.existsSync(fp)) {
|
||||
res.writeHead(200, { 'Content-Type': MIME[path.extname(fp)] || 'application/octet-stream' });
|
||||
return res.end(fs.readFileSync(fp));
|
||||
}
|
||||
return send(404, 'not found');
|
||||
} catch (e) {
|
||||
const status = e && e.status ? e.status : 500;
|
||||
return send(status, { ok: false, error: String((e && e.message) || e).split('\n')[0] });
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- boot
|
||||
function boot() {
|
||||
const host = process.env.HOST || '127.0.0.1';
|
||||
const start = (port) => {
|
||||
server.listen(port, host, () => {
|
||||
console.log(`repo-forker-ui → http://${host === '0.0.0.0' ? '0.0.0.0' : host}:${port}${MOCK ? ' (MOCK mode)' : ''}`);
|
||||
});
|
||||
};
|
||||
const tryPort = (port) => {
|
||||
const probe = http.createServer();
|
||||
probe.once('error', () => { probe.close(); tryPort(port + 1); });
|
||||
probe.once('listening', () => probe.close(() => start(port)));
|
||||
probe.listen(port, host);
|
||||
};
|
||||
tryPort(8731);
|
||||
}
|
||||
if (require.main === module) boot();
|
||||
module.exports = { server, boot };
|
||||
@@ -0,0 +1,82 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { Routes, Route, Navigate } from 'react-router-dom';
|
||||
import { useApp, usePoll } from './lib/app-context';
|
||||
import { api } from './api/client';
|
||||
import { Shell } from './components/Shell';
|
||||
import { Btn, StatusDot } from './components/primitives';
|
||||
import type { Runner } from './api/types';
|
||||
import Dashboard from './pages/Dashboard';
|
||||
import Detail from './pages/Detail';
|
||||
import Wizard from './pages/Wizard';
|
||||
import RunnerView from './pages/RunnerView';
|
||||
import SettingsPage from './pages/Settings';
|
||||
|
||||
function ConnectionGate() {
|
||||
const { connect, settings } = useApp();
|
||||
const [url, setUrl] = useState(settings?.url || '');
|
||||
const [token, setToken] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [err, setErr] = useState('');
|
||||
const submit = async () => {
|
||||
setBusy(true); setErr('');
|
||||
const ok = await connect(url.trim(), token.trim());
|
||||
setBusy(false);
|
||||
if (!ok) setErr('Connection failed — check the URL and token.');
|
||||
};
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-bg p-6"
|
||||
style={{ background: 'radial-gradient(1200px 400px at 50% -10%, #1f2a44 0%, transparent 70%)' }}>
|
||||
<div className="w-full max-w-[440px] rounded-panel border border-border bg-panel p-8">
|
||||
<div className="flex items-center gap-3">
|
||||
<StatusDot color="#58a6ff" />
|
||||
<h1 className="text-[18px] font-semibold">Repo Forker</h1>
|
||||
</div>
|
||||
<p className="mt-2 text-[13px] text-muted">
|
||||
Connect to your Gitea to manage the mirrors generated from <span className="font-mono">repo-forker</span>.
|
||||
The token stays on this machine (<span className="font-mono">~/.repo-forker/credentials</span>) and never touches the repo.
|
||||
</p>
|
||||
<label className="mt-6 block text-[12px] text-muted">Gitea base URL</label>
|
||||
<input value={url} onChange={(e) => setUrl(e.target.value)} placeholder="https://git.lago.dev"
|
||||
className="mt-1 w-full rounded-ctl border border-border bg-panel2 px-3 py-2 font-mono text-[13px] text-text placeholder:text-muted/50 focus:outline-none focus:ring-2 focus:ring-accent/30" />
|
||||
<label className="mt-4 block text-[12px] text-muted">Token</label>
|
||||
<input value={token} onChange={(e) => setToken(e.target.value)} type="password" placeholder="Gitea token"
|
||||
className="mt-1 w-full rounded-ctl border border-border bg-panel2 px-3 py-2 font-mono text-[13px] text-text placeholder:text-muted/50 focus:outline-none focus:ring-2 focus:ring-accent/30" />
|
||||
{err && <div className="mt-3 text-[12px] text-danger">{err}</div>}
|
||||
<div className="mt-6 flex justify-end">
|
||||
<Btn variant="primary" disabled={!url.trim() || !token.trim() || busy} onClick={submit}>
|
||||
{busy ? 'Connecting…' : 'Connect'}
|
||||
</Btn>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AppInner() {
|
||||
const { configured, host } = useApp();
|
||||
const [runner, setRunner] = useState<Runner | null>(null);
|
||||
const pollRunner = useCallback(() => {
|
||||
void api.runners().then((rs) => {
|
||||
setRunner(rs.find((r) => r.name === 'gitea-runner-forker') || rs.find((r) => r.status === 'online') || null);
|
||||
}).catch(() => setRunner(null));
|
||||
}, []);
|
||||
usePoll(pollRunner, 15000);
|
||||
|
||||
if (!configured) return <ConnectionGate />;
|
||||
return (
|
||||
<Shell runner={runner} host={host} mirrorName={undefined}>
|
||||
<Routes>
|
||||
<Route path="/" element={<Dashboard />} />
|
||||
<Route path="/mirrors/:name" element={<Detail />} />
|
||||
<Route path="/new" element={<Wizard />} />
|
||||
<Route path="/runner" element={<RunnerView runner={runner} />} />
|
||||
<Route path="/settings" element={<SettingsPage />} />
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return <AppInner />;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
// Typed client for the local server's /api/* contract (same-origin).
|
||||
import type {
|
||||
Health, Settings, ConnectResult, Mirror, RunInfo, ReleaseInfo,
|
||||
RepoVariable, FlatConfig, Runner, QueueEntry, LogResult, ConfigFile,
|
||||
CreateMirrorResult,
|
||||
} from './types';
|
||||
|
||||
async function req<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const r = await fetch('/api' + path, {
|
||||
headers: { 'Content-Type': 'application/json', ...(init?.headers || {}) },
|
||||
...init,
|
||||
});
|
||||
const body = (await r.json().catch(() => ({}))) as T & { error?: string };
|
||||
if (!r.ok) throw new Error(body.error || `HTTP ${r.status}`);
|
||||
return body;
|
||||
}
|
||||
|
||||
export const api = {
|
||||
health: () => req<Health>('/health'),
|
||||
settings: () => req<Settings>('/settings'),
|
||||
connect: (url: string, token: string) =>
|
||||
req<ConnectResult>('/connect', { method: 'POST', body: JSON.stringify({ url, token }) }),
|
||||
|
||||
mirrors: () => req<Mirror[]>('/mirrors'),
|
||||
mirrorRuns: (name: string, limit = 12) =>
|
||||
req<RunInfo[]>(`/mirrors/${encodeURIComponent(name)}/runs?limit=${limit}`),
|
||||
mirrorReleases: (name: string) =>
|
||||
req<ReleaseInfo[]>(`/mirrors/${encodeURIComponent(name)}/releases`),
|
||||
mirrorConfig: (name: string) =>
|
||||
req<ConfigFile>(`/mirrors/${encodeURIComponent(name)}/config`),
|
||||
saveMirrorConfig: (name: string, parsed: FlatConfig) =>
|
||||
req<ConfigFile>(`/mirrors/${encodeURIComponent(name)}/config`, {
|
||||
method: 'PUT', body: JSON.stringify({ parsed }),
|
||||
}),
|
||||
mirrorVariables: (name: string) =>
|
||||
req<RepoVariable[]>(`/mirrors/${encodeURIComponent(name)}/variables`),
|
||||
createVariable: (name: string, variable: string, value: string) =>
|
||||
req<{ ok: boolean }>(`/mirrors/${encodeURIComponent(name)}/variables`, {
|
||||
method: 'POST', body: JSON.stringify({ name: variable, value }),
|
||||
}),
|
||||
deleteVariable: (name: string, variable: string) =>
|
||||
req<{ ok: boolean }>(`/mirrors/${encodeURIComponent(name)}/variables/${encodeURIComponent(variable)}`, {
|
||||
method: 'DELETE',
|
||||
}),
|
||||
dispatch: (name: string, workflow: string, ref?: string) =>
|
||||
req<{ ok: boolean; runId?: number }>(`/mirrors/${encodeURIComponent(name)}/dispatch`, {
|
||||
method: 'POST', body: JSON.stringify({ workflow, ref }),
|
||||
}),
|
||||
deleteMirror: (name: string) =>
|
||||
req<{ ok: boolean }>(`/mirrors/${encodeURIComponent(name)}`, { method: 'DELETE' }),
|
||||
createMirror: (upstream: string, name: string | undefined, config: FlatConfig) =>
|
||||
req<CreateMirrorResult>('/mirrors', {
|
||||
method: 'POST', body: JSON.stringify({ upstream, name, config }),
|
||||
}),
|
||||
log: (name: string, runId: number) =>
|
||||
req<LogResult>(`/mirrors/${encodeURIComponent(name)}/runs/${runId}/log`),
|
||||
|
||||
runners: () => req<Runner[]>('/runners'),
|
||||
queue: () => req<QueueEntry[]>('/queue'),
|
||||
};
|
||||
@@ -0,0 +1,67 @@
|
||||
// API contract types — mirror DESIGN.md /api/* exactly.
|
||||
|
||||
export interface Health { ok: boolean; gitea: { url: string; version: string } | null; error?: string }
|
||||
export interface Settings { configured: boolean; url: string; user: string; template: string }
|
||||
export interface ConnectResult { ok: boolean; user?: string; version?: string; error?: string }
|
||||
|
||||
export interface RunInfo {
|
||||
id: number;
|
||||
event: string;
|
||||
status: 'queued' | 'in_progress' | 'completed';
|
||||
conclusion: 'success' | 'failure' | 'cancelled' | 'skipped' | string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
durationSec: number;
|
||||
path?: string;
|
||||
}
|
||||
|
||||
export interface Parity {
|
||||
branches: number | null;
|
||||
tags: number | null;
|
||||
releases: number | null;
|
||||
assets: number | null;
|
||||
upstream?: { branches?: number | null; tags?: number | null; releases?: number | null; assets?: number | null };
|
||||
}
|
||||
|
||||
export interface Mirror {
|
||||
name: string;
|
||||
full: string;
|
||||
upstream: string; // origin URL (github.com/… or gitea/codeberg/…)
|
||||
forkUrl: string; // where the mirror lives (https://git.lago.dev/Lago/<name>)
|
||||
defaultBranch: string;
|
||||
lastSync: RunInfo | null;
|
||||
parity: Parity | null;
|
||||
units: string[];
|
||||
spark: (string)[]; // run statuses, oldest→newest, ≤20
|
||||
}
|
||||
|
||||
export interface ReleaseInfo { id: number; tag: string; name: string; assets: number }
|
||||
|
||||
export interface RepoVariable { name: string; value: string }
|
||||
|
||||
export interface FlatConfig { [key: string]: string | boolean }
|
||||
|
||||
export interface Runner {
|
||||
id: number; name: string; status: 'online' | 'offline'; busy: boolean;
|
||||
type: 'shared' | 'repo' | 'shared (unattached)'; labels: string[]; repo?: string;
|
||||
}
|
||||
|
||||
export interface QueueEntry { repo: string; runId: number; event: string; status: 'queued' | 'in_progress'; waitedSec: number }
|
||||
|
||||
export interface LogLine { t: number; text: string }
|
||||
export interface LogResult { lines: LogLine[]; cursor: number }
|
||||
|
||||
export interface ConfigFile { raw: string; parsed: FlatConfig }
|
||||
|
||||
export interface CreateMirrorStep { name: string; status: 'ok' | 'error' }
|
||||
export interface CreateMirrorResult { ok: boolean; repo?: string; steps: CreateMirrorStep[]; error?: string }
|
||||
|
||||
export const KNOWN_CONFIG_KEYS = [
|
||||
'mirror_branches', 'mirror_tags', 'mirror_prune',
|
||||
'mirror_upstream_releases', 'on_new_tag',
|
||||
'build_cmd', 'build_script', 'artifacts',
|
||||
] as const;
|
||||
|
||||
export const BOOLEAN_CONFIG_KEYS = [
|
||||
'mirror_tags', 'mirror_prune', 'mirror_upstream_releases', 'on_new_tag',
|
||||
] as const;
|
||||
@@ -0,0 +1,67 @@
|
||||
import React from 'react';
|
||||
import { NavLink } from 'react-router-dom';
|
||||
import { LayoutGrid, Cpu, Plus, Settings } from 'lucide-react';
|
||||
import type { Runner } from '../api/types';
|
||||
|
||||
const NAV = [
|
||||
{ to: '/', label: 'Mirrors', icon: LayoutGrid, exact: true },
|
||||
{ to: '/new', label: 'New', icon: Plus },
|
||||
{ to: '/runner', label: 'Runner', icon: Cpu },
|
||||
{ to: '/settings', label: 'Settings', icon: Settings },
|
||||
];
|
||||
|
||||
export function Shell({ children, runner, host, mirrorName }: {
|
||||
children: React.ReactNode;
|
||||
runner: Runner | null;
|
||||
host: string;
|
||||
mirrorName?: string;
|
||||
}) {
|
||||
const online = runner?.status === 'online';
|
||||
return (
|
||||
<div className="flex min-h-screen bg-bg text-text" style={{ fontFamily: 'inherit' }}>
|
||||
{/* sidebar */}
|
||||
<aside className="sticky top-0 flex h-screen w-[224px] shrink-0 flex-col border-r border-border bg-panel">
|
||||
<div className="px-4 pb-2 pt-4">
|
||||
<div className="text-[14px] font-semibold tracking-tight">Repo Forker</div>
|
||||
<div className="mt-1 font-mono text-[11px] text-muted">{host || 'not connected'}</div>
|
||||
</div>
|
||||
<nav className="flex flex-col gap-1 px-2 py-2">
|
||||
{NAV.map(({ to, label, icon: Icon, exact }) => (
|
||||
<NavLink key={to} to={to} end={exact}
|
||||
className={({ isActive }) =>
|
||||
`flex items-center gap-3 rounded-ctl px-3 py-2 text-[13px] transition-colors duration-ctl ${
|
||||
isActive ? 'bg-panel2 text-text' : 'text-muted hover:bg-panel2 hover:text-text'
|
||||
}`}>
|
||||
{({ isActive }) => (
|
||||
<>
|
||||
<span className="relative flex">
|
||||
{isActive && <span className="absolute -left-3 top-0 h-full w-[3px] rounded-r bg-accent" />}
|
||||
<Icon size={16} strokeWidth={1.5} className={isActive ? 'text-accent' : ''} />
|
||||
</span>
|
||||
{label}
|
||||
</>
|
||||
)}
|
||||
</NavLink>
|
||||
))}
|
||||
{mirrorName && (
|
||||
<div className="ml-6 mt-1 truncate border-l border-border pl-3 font-mono text-[11px] text-muted" title={mirrorName}>
|
||||
{mirrorName}
|
||||
</div>
|
||||
)}
|
||||
</nav>
|
||||
<div className="mt-auto flex items-center gap-2 border-t border-border px-4 py-3">
|
||||
<span className={`h-2 w-2 rounded-full ${online ? 'bg-ok' : 'bg-muted'}`} />
|
||||
<span className="text-[11px] text-muted">
|
||||
{online ? 'runner online' : runner ? 'runner offline' : 'runner unknown'}
|
||||
</span>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
{/* main */}
|
||||
<main className="min-w-0 flex-1"
|
||||
style={{ background: 'radial-gradient(1200px 400px at 50% -10%, #1f2a44 0%, transparent 70%)' }}>
|
||||
<div className="mx-auto max-w-[1200px] px-6 py-6">{children}</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
import React from 'react';
|
||||
|
||||
// ---- StatusDot: 8px circle + 1px ring at 25% alpha ----
|
||||
export function StatusDot({ color, pulse }: { color: string; pulse?: boolean }) {
|
||||
return (
|
||||
<span className="relative inline-flex h-2 w-2 shrink-0" aria-hidden>
|
||||
<span className="absolute inset-0 rounded-full" style={{ backgroundColor: color }} />
|
||||
{pulse && (
|
||||
<span className="absolute -inset-[3px] rounded-full opacity-25 animate-pulse" style={{ backgroundColor: color }} />
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
// ---- Badge (chip) ----
|
||||
export function Badge({ color, children, dot }: { color?: string; children: React.ReactNode; dot?: string }) {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 rounded-pill border border-border bg-chip px-2 py-[1px] text-[11px] leading-4"
|
||||
style={color ? { color } : undefined}>
|
||||
{dot && <StatusDot color={dot} />}
|
||||
<span className={color ? '' : 'text-muted'}>{children}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
// ---- StatCard ----
|
||||
export function StatCard({ label, value, sub }: { label: string; value: React.ReactNode; sub?: React.ReactNode }) {
|
||||
return (
|
||||
<div className="rounded-panel border border-border bg-panel p-4">
|
||||
<div className="text-[12px] text-muted">{label}</div>
|
||||
<div className="mt-1 font-mono text-[24px] font-semibold leading-none tabular-nums text-text">{value}</div>
|
||||
{sub && <div className="mt-2 text-[11px] text-muted">{sub}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---- Sparkline (inline SVG, one bar per status) ----
|
||||
export function Sparkline({ statuses, width = 56, height = 14, colorOf }: {
|
||||
statuses: string[]; width?: number; height?: number; colorOf: (s: string) => string;
|
||||
}) {
|
||||
const n = statuses.length;
|
||||
if (n === 0) return <span className="text-[11px] text-muted">—</span>;
|
||||
const gap = 1.5;
|
||||
const bw = (width - gap * (n - 1)) / n;
|
||||
return (
|
||||
<svg width={width} height={height} aria-hidden className="shrink-0">
|
||||
{statuses.map((s, i) => (
|
||||
<rect key={i} x={i * (bw + gap)} y={height - 10} width={bw} height={10}
|
||||
rx={1} fill={colorOf(s)} opacity={i === n - 1 ? 1 : 0.75} />
|
||||
))}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
// ---- Toggle ----
|
||||
export function Toggle({ on, onChange, disabled }: { on: boolean; onChange?: (v: boolean) => void; disabled?: boolean }) {
|
||||
return (
|
||||
<button type="button" disabled={disabled} onClick={() => onChange?.(!on)}
|
||||
className={`relative h-[18px] w-8 rounded-pill transition-colors duration-ctl ${on ? 'bg-accent' : 'bg-chip border border-border'} ${disabled ? 'opacity-40' : ''}`}
|
||||
aria-pressed={on}>
|
||||
<span className={`absolute top-[2px] h-[14px] w-[14px] rounded-full bg-bg transition-transform duration-ctl ${on ? 'translate-x-[16px]' : 'translate-x-[2px] left-0'}`} />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
// ---- Btn ----
|
||||
type BtnVariant = 'primary' | 'secondary' | 'ghost' | 'danger' | 'dangerSolid';
|
||||
export function Btn({ variant = 'secondary', className = '', children, ...rest }:
|
||||
React.ButtonHTMLAttributes<HTMLButtonElement> & { variant?: BtnVariant }) {
|
||||
const base = 'inline-flex items-center gap-2 rounded-ctl px-3 py-2 text-[13px] transition-colors duration-ctl disabled:opacity-40 disabled:cursor-not-allowed';
|
||||
const styles: Record<BtnVariant, string> = {
|
||||
primary: 'bg-accent text-bg font-medium',
|
||||
secondary: 'bg-chip border border-border text-text',
|
||||
ghost: 'text-muted hover:text-text hover:bg-panel2',
|
||||
danger: 'text-danger hover:bg-panel2',
|
||||
dangerSolid: 'bg-danger text-bg font-medium',
|
||||
};
|
||||
return <button className={`${base} ${styles[variant]} ${className}`} {...rest}>{children}</button>;
|
||||
}
|
||||
|
||||
// ---- Skeleton row ----
|
||||
export function SkeletonRow() {
|
||||
return (
|
||||
<div className="flex items-center gap-3 border-b border-border px-4 py-3">
|
||||
<div className="h-[10px] w-[10px] rounded-full bg-panel2" />
|
||||
<div className="h-[12px] w-32 bg-panel2 rounded" />
|
||||
<div className="h-[12px] flex-1 bg-panel2 rounded opacity-60" />
|
||||
<div className="h-[12px] w-16 bg-panel2 rounded opacity-40" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---- EmptyState ----
|
||||
export function EmptyState({ title, action }: { title: string; action?: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-3 py-16">
|
||||
<div className="text-[13px] text-muted">{title}</div>
|
||||
{action}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---- ErrorInline: exact failing line + retry ----
|
||||
export function ErrorInline({ message, onRetry }: { message: string; onRetry?: () => void }) {
|
||||
return (
|
||||
<div className="flex items-start gap-3 rounded-panel border border-danger/40 bg-panel px-4 py-3">
|
||||
<StatusDot color="#f85149" />
|
||||
<pre className="m-0 mt-[2px] flex-1 overflow-x-auto whitespace-pre-wrap font-mono text-[11px] text-danger">{message}</pre>
|
||||
{onRetry && <Btn variant="secondary" onClick={onRetry} className="shrink-0">Retry</Btn>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---- OfflineBanner ----
|
||||
export function OfflineBanner({ message }: { message?: string }) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 border-b border-warn/30 bg-warn/10 px-4 py-2 text-[12px] text-warn">
|
||||
<span className="inline-block h-2 w-2 rounded-full bg-warn" />
|
||||
{message || 'Gitea unreachable — showing last cached state'}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---- Panel wrapper ----
|
||||
export function Panel({ title, action, children, className = '' }: {
|
||||
title?: string; action?: React.ReactNode; children: React.ReactNode; className?: string;
|
||||
}) {
|
||||
return (
|
||||
<section className={`rounded-panel border border-border bg-panel p-4 ${className}`}>
|
||||
{title && (
|
||||
<header className="mb-3 flex items-center justify-between border-b border-border pb-2">
|
||||
<h2 className="text-[12px] font-medium uppercase tracking-wide text-muted">{title}</h2>
|
||||
{action}
|
||||
</header>
|
||||
)}
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
// ---- ConfirmDialog (type-the-name for destructive) ----
|
||||
export function ConfirmDialog({ open, name, confirmText, onConfirm, onClose, busy }: {
|
||||
open: boolean; name: string; confirmText?: string;
|
||||
onConfirm: () => void; onClose: () => void; busy?: boolean;
|
||||
}) {
|
||||
const [text, setText] = React.useState('');
|
||||
React.useEffect(() => { if (!open) setText(''); }, [open]);
|
||||
if (!open) return null;
|
||||
const required = confirmText || name;
|
||||
const ready = text === required;
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-bg/80 p-4" onClick={onClose}>
|
||||
<div className="w-full max-w-[420px] rounded-panel border border-border bg-panel p-6 shadow-[0_8px_24px_rgba(0,0,0,0.5)]"
|
||||
onClick={(e) => e.stopPropagation()}>
|
||||
<h3 className="text-[18px] font-semibold text-text">Delete {name}?</h3>
|
||||
<p className="mt-2 text-[13px] text-muted">
|
||||
This permanently deletes the repository and all its branches, tags and releases.
|
||||
The template is not affected.
|
||||
</p>
|
||||
<input value={text} onChange={(e) => setText(e.target.value)}
|
||||
placeholder={`Type ${required} to confirm`}
|
||||
className="mt-4 w-full rounded-ctl border border-border bg-panel2 px-3 py-2 font-mono text-[13px] text-text placeholder:text-muted/50 focus:outline-none focus:ring-2 focus:ring-accent/30" />
|
||||
<div className="mt-4 flex justify-end gap-2">
|
||||
<Btn variant="ghost" onClick={onClose}>Cancel</Btn>
|
||||
<Btn variant="dangerSolid" disabled={!ready || busy} onClick={onConfirm}>
|
||||
{busy ? 'Deleting…' : 'Delete'}
|
||||
</Btn>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---- Toast ----
|
||||
interface Toast { id: number; text: string; kind: 'ok' | 'error' }
|
||||
let toastListeners: ((t: Toast) => void)[] = [];
|
||||
export function toast(text: string, kind: 'ok' | 'error' = 'ok') {
|
||||
const id = Date.now() + Math.random();
|
||||
toastListeners.forEach((l) => l({ id, text, kind }));
|
||||
}
|
||||
export function Toaster() {
|
||||
const [items, setItems] = React.useState<Toast[]>([]);
|
||||
React.useEffect(() => {
|
||||
const l = (t: Toast) => {
|
||||
setItems((p) => [...p, t]);
|
||||
setTimeout(() => setItems((p) => p.filter((x) => x.id !== t.id)), 4000);
|
||||
};
|
||||
toastListeners.push(l);
|
||||
return () => { toastListeners = toastListeners.filter((x) => x !== l); };
|
||||
}, []);
|
||||
return (
|
||||
<div className="fixed right-4 top-4 z-[60] flex flex-col gap-2">
|
||||
{items.map((t) => (
|
||||
<div key={t.id} className={`flex items-center gap-2 rounded-panel border px-4 py-2 text-[13px] transition-opacity duration-ctl ${t.kind === 'ok' ? 'border-ok/40 bg-panel text-ok' : 'border-danger/40 bg-panel text-danger'}`}>
|
||||
{t.text}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
html, body, #root { height: 100%; }
|
||||
body {
|
||||
background: #0d1117;
|
||||
color: #e6edf3;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
.font-mono { font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace; }
|
||||
::selection { background: rgba(88, 166, 255, 0.3); }
|
||||
* { scrollbar-width: thin; scrollbar-color: #30363d transparent; }
|
||||
::-webkit-scrollbar { width: 8px; height: 8px; }
|
||||
::-webkit-scrollbar-thumb { background: #30363d; border-radius: 4px; }
|
||||
@@ -0,0 +1,67 @@
|
||||
import React, { createContext, useContext, useEffect, useState } from 'react';
|
||||
import { api } from '../api/client';
|
||||
import type { Settings } from '../api/types';
|
||||
|
||||
interface AppCtx {
|
||||
settings: Settings | null;
|
||||
configured: boolean;
|
||||
offline: boolean;
|
||||
host: string;
|
||||
reload: () => Promise<void>;
|
||||
connect: (url: string, token: string) => Promise<boolean>;
|
||||
}
|
||||
|
||||
const Ctx = createContext<AppCtx>({
|
||||
settings: null, configured: false, offline: false, host: '', reload: async () => {},
|
||||
connect: async () => false,
|
||||
});
|
||||
|
||||
export function useApp() { return useContext(Ctx); }
|
||||
|
||||
export function AppProvider({ children }: { children: React.ReactNode }) {
|
||||
const [settings, setSettings] = useState<Settings | null>(null);
|
||||
const [offline, setOffline] = useState(false);
|
||||
|
||||
const reload = React.useCallback(async () => {
|
||||
try {
|
||||
const s = await api.settings();
|
||||
setSettings(s);
|
||||
setOffline(false);
|
||||
} catch {
|
||||
setOffline(true);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => { void reload(); }, [reload]);
|
||||
|
||||
const connect = React.useCallback(async (url: string, token: string) => {
|
||||
try {
|
||||
const r = await api.connect(url, token);
|
||||
if (r.ok) { await reload(); return true; }
|
||||
return false;
|
||||
} catch { return false; }
|
||||
}, [reload]);
|
||||
|
||||
return (
|
||||
<Ctx.Provider value={{
|
||||
settings, configured: !!settings?.configured, offline,
|
||||
host: settings?.url ? new URL(settings.url).host : '', reload, connect,
|
||||
}}>
|
||||
{children}
|
||||
</Ctx.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
// shared polling hook: fn every `ms`, paused when tab hidden, cleared on unmount
|
||||
export function usePoll(fn: () => void | Promise<unknown>, ms: number) {
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
let timer: number | undefined;
|
||||
const tick = () => { if (!alive || document.hidden) return; void fn(); };
|
||||
timer = window.setInterval(tick, ms);
|
||||
tick();
|
||||
const vis = () => { if (!document.hidden) tick(); };
|
||||
document.addEventListener('visibilitychange', vis);
|
||||
return () => { alive = false; window.clearInterval(timer); document.removeEventListener('visibilitychange', vis); };
|
||||
}, [fn, ms]);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { Mirror } from '../api/types';
|
||||
|
||||
export type HealthState = 'ok' | 'stale' | 'failed' | 'running' | 'never';
|
||||
|
||||
export const HEALTH_COLORS: Record<HealthState, string> = {
|
||||
ok: '#7ee787', stale: '#f2cc60', failed: '#f85149',
|
||||
running: '#58a6ff', never: '#8b949e',
|
||||
};
|
||||
|
||||
export const RUN_COLORS: Record<string, string> = {
|
||||
success: '#7ee787', failure: '#f85149', cancelled: '#8b949e',
|
||||
skipped: '#8b949e', in_progress: '#58a6ff', queued: '#8b949e',
|
||||
completed: '#7ee787',
|
||||
};
|
||||
|
||||
export function runColor(status: string, conclusion: string | null): string {
|
||||
if (status === 'in_progress') return '#58a6ff';
|
||||
if (status === 'queued') return '#8b949e';
|
||||
if (conclusion === 'failure' || status === 'failure') return '#f85149';
|
||||
if (conclusion === 'cancelled' || conclusion === 'skipped') return '#8b949e';
|
||||
return '#7ee787';
|
||||
}
|
||||
|
||||
const STALE_MS = 30 * 60 * 1000;
|
||||
|
||||
export function health(m: Mirror, runnerOnline: boolean | null): HealthState {
|
||||
const r = m.lastSync;
|
||||
if (!r) return 'never';
|
||||
if (r.status === 'in_progress' || r.status === 'queued') return 'running';
|
||||
if (r.conclusion === 'failure') return 'failed';
|
||||
const age = Date.now() - new Date(r.updatedAt).getTime();
|
||||
if (age > STALE_MS && runnerOnline === true) return 'stale';
|
||||
return age <= STALE_MS ? 'ok' : 'ok';
|
||||
}
|
||||
|
||||
export function timeAgo(iso: string): string {
|
||||
const s = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000);
|
||||
if (s < 60) return `${Math.floor(s)}s ago`;
|
||||
if (s < 3600) return `${Math.floor(s / 60)}m ago`;
|
||||
if (s < 86400) return `${Math.floor(s / 3600)}h ago`;
|
||||
return `${Math.floor(s / 86400)}d ago`;
|
||||
}
|
||||
|
||||
export function duration(sec: number): string {
|
||||
if (sec <= 0) return '—';
|
||||
const m = Math.floor(sec / 60), s = Math.floor(sec % 60);
|
||||
return m > 0 ? `${m}m ${s.toString().padStart(2, '0')}s` : `${s}s`;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import { BrowserRouter } from 'react-router-dom';
|
||||
import App from './App';
|
||||
import { AppProvider } from './lib/app-context';
|
||||
import { Toaster } from './components/primitives';
|
||||
import './index.css';
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<BrowserRouter>
|
||||
<AppProvider>
|
||||
<App />
|
||||
<Toaster />
|
||||
</AppProvider>
|
||||
</BrowserRouter>
|
||||
</React.StrictMode>,
|
||||
);
|
||||
@@ -0,0 +1,270 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import type React from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Plus, RotateCw, ArrowRight, Trash2 } from 'lucide-react';
|
||||
import { api } from '../api/client';
|
||||
import type { Mirror } from '../api/types';
|
||||
import { health, HEALTH_COLORS, runColor, timeAgo, duration } from '../lib/health';
|
||||
import { useApp, usePoll } from '../lib/app-context';
|
||||
import {
|
||||
StatusDot, Badge, StatCard, Sparkline, Btn, SkeletonRow,
|
||||
EmptyState, ErrorInline, OfflineBanner, ConfirmDialog, toast,
|
||||
} from '../components/primitives';
|
||||
import { Spinner } from './dashboard/Spinner';
|
||||
|
||||
const HEADER_CELL = 'px-2 py-2 text-left text-[11px] font-semibold uppercase tracking-wide text-muted';
|
||||
const ROW_CELL = 'px-2 py-3';
|
||||
|
||||
// strip a trailing .git for display; keep the host so the origin is obvious
|
||||
function hostRepo(url: string): { host: string; repo: string } {
|
||||
try {
|
||||
const u = new URL(url);
|
||||
return { host: u.host, repo: u.pathname.replace(/^\/+|\/+$/g, '').replace(/\.git$/, '') };
|
||||
} catch {
|
||||
return { host: '—', repo: String(url || '').replace(/\.git$/, '') };
|
||||
}
|
||||
}
|
||||
|
||||
function ParityChips({ m }: { m: Mirror }) {
|
||||
const p = m.parity;
|
||||
const chip = (label: string, fork: number | null | undefined, upstream: number | null | undefined) => {
|
||||
if (p && fork != null && upstream != null && fork < upstream) {
|
||||
// behind: fork/upstream in danger text
|
||||
return <Badge key={label} color={HEALTH_COLORS.failed}>{label} {fork}/{upstream}</Badge>;
|
||||
}
|
||||
// equal or unknown: plain count in muted (Badge default)
|
||||
return <Badge key={label}>{label} {fork == null ? '—' : fork}</Badge>;
|
||||
};
|
||||
return (
|
||||
<div className="flex items-center gap-1">
|
||||
{chip('br', p?.branches, p?.upstream?.branches)}
|
||||
{chip('tags', p?.tags, p?.upstream?.tags)}
|
||||
{chip('assets', p?.assets, p?.upstream?.assets)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LastSyncCell({ m }: { m: Mirror }) {
|
||||
const r = m.lastSync;
|
||||
let word: React.ReactNode;
|
||||
if (!r) {
|
||||
word = <span className="text-[13px] text-muted">—</span>;
|
||||
} else if (r.status === 'in_progress') {
|
||||
word = <span className="inline-flex items-center gap-1 text-[13px] text-accent">in_progress <Spinner /></span>;
|
||||
} else if (r.status === 'queued') {
|
||||
word = <span className="text-[13px] text-muted">queued</span>;
|
||||
} else if (r.conclusion === 'failure') {
|
||||
word = <span className="text-[13px] text-danger">failure</span>;
|
||||
} else {
|
||||
word = <span className="text-[13px] text-ok">success</span>;
|
||||
}
|
||||
return (
|
||||
<div>
|
||||
{word}
|
||||
{r && <div className="text-[11px] text-muted">{timeAgo(r.updatedAt)}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Dashboard() {
|
||||
const nav = useNavigate();
|
||||
const { host, offline } = useApp();
|
||||
const [mirrors, setMirrors] = useState<Mirror[] | null>(null);
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [runnerOnline, setRunnerOnline] = useState<boolean | null>(null);
|
||||
const [queued, setQueued] = useState(0);
|
||||
const [syncing, setSyncing] = useState<string | null>(null);
|
||||
const [del, setDel] = useState<{ open: boolean; name: string }>({ open: false, name: '' });
|
||||
const [delBusy, setDelBusy] = useState(false);
|
||||
|
||||
// mirrors: 10s poll (ticks immediately on mount)
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
setMirrors(await api.mirrors());
|
||||
setErr(null);
|
||||
} catch (e) {
|
||||
setErr((e as Error).message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
usePoll(load, 10000);
|
||||
|
||||
// runners: 15s poll — online = any runner.status === 'online'
|
||||
const loadRunners = useCallback(async () => {
|
||||
try {
|
||||
const rs = await api.runners();
|
||||
setRunnerOnline(rs.some((r) => r.status === 'online'));
|
||||
} catch { /* keep last known value */ }
|
||||
}, []);
|
||||
usePoll(loadRunners, 15000);
|
||||
|
||||
// queue: 10s poll, best-effort (a queue failure must not wipe the table)
|
||||
const loadQueue = useCallback(async () => {
|
||||
try {
|
||||
setQueued((await api.queue()).length);
|
||||
} catch { /* keep last known value */ }
|
||||
}, []);
|
||||
usePoll(loadQueue, 10000);
|
||||
|
||||
const reSync = async (name: string) => {
|
||||
setSyncing(name);
|
||||
try {
|
||||
await api.dispatch(name, 'sync.yml');
|
||||
toast('sync dispatched');
|
||||
await Promise.all([load(), loadQueue()]);
|
||||
} catch (e) {
|
||||
toast((e as Error).message, 'error');
|
||||
} finally {
|
||||
setSyncing(null);
|
||||
}
|
||||
};
|
||||
|
||||
const doDelete = async () => {
|
||||
const name = del.name;
|
||||
setDelBusy(true);
|
||||
try {
|
||||
await api.deleteMirror(name);
|
||||
setDel({ open: false, name: '' });
|
||||
toast(`deleted ${name}`);
|
||||
await Promise.all([load(), loadQueue()]);
|
||||
} catch (e) {
|
||||
toast((e as Error).message, 'error');
|
||||
} finally {
|
||||
setDelBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const n = mirrors?.length ?? 0;
|
||||
const healthy = mirrors?.filter((m) => health(m, runnerOnline) === 'ok').length ?? 0;
|
||||
const assets = mirrors?.reduce((s, m) => s + (m.parity?.assets ?? 0), 0) ?? 0;
|
||||
|
||||
return (
|
||||
<div>
|
||||
{offline && <div className="mb-4"><OfflineBanner /></div>}
|
||||
|
||||
{/* top row */}
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<h1 className="text-[18px] font-semibold leading-none">Mirrors</h1>
|
||||
<Badge dot={runnerOnline ? HEALTH_COLORS.ok : HEALTH_COLORS.never}>
|
||||
<span className="font-mono">{host || 'not connected'}</span>
|
||||
</Badge>
|
||||
</div>
|
||||
<Btn variant="primary" onClick={() => nav('/new')}>
|
||||
<Plus size={16} strokeWidth={1.5} /> New mirror
|
||||
</Btn>
|
||||
</div>
|
||||
|
||||
{/* stats */}
|
||||
<div className="mt-4 grid grid-cols-2 gap-4 lg:grid-cols-4">
|
||||
<StatCard label="Mirrors" value={mirrors ? n : '…'} sub="generated from template" />
|
||||
<StatCard
|
||||
label="Healthy"
|
||||
value={mirrors ? <>{healthy}<span className="text-[13px] font-normal text-muted">/{n}</span></> : '…'}
|
||||
sub="last sync green < 30m"
|
||||
/>
|
||||
<StatCard label="Queued runs" value={queued} sub="serial runner (maxParallel=1)" />
|
||||
<StatCard label="Assets mirrored" value={assets} sub="across all mirrors" />
|
||||
</div>
|
||||
|
||||
{/* table */}
|
||||
<div className="mt-4">
|
||||
{loading && !mirrors ? (
|
||||
<div>
|
||||
<SkeletonRow />
|
||||
<SkeletonRow />
|
||||
<SkeletonRow />
|
||||
</div>
|
||||
) : err && !mirrors ? (
|
||||
<ErrorInline message={err} onRetry={load} />
|
||||
) : mirrors && mirrors.length === 0 ? (
|
||||
<EmptyState title="No mirrors yet" action={<Btn variant="primary" onClick={() => nav('/new')}><Plus size={16} strokeWidth={1.5} /> New mirror</Btn>} />
|
||||
) : mirrors ? (
|
||||
<table className="w-full text-[13px]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className={HEADER_CELL}>Mirror</th>
|
||||
<th className={HEADER_CELL}>Repositories</th>
|
||||
<th className={HEADER_CELL}>Last sync</th>
|
||||
<th className={HEADER_CELL}>Duration</th>
|
||||
<th className={HEADER_CELL}>Parity</th>
|
||||
<th className={HEADER_CELL}>7-day runs</th>
|
||||
<th className={`${HEADER_CELL} text-right`}>Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{mirrors.map((m) => {
|
||||
const st = health(m, runnerOnline);
|
||||
const u = hostRepo(m.upstream);
|
||||
const f = hostRepo(m.forkUrl || `https://git.lago.dev/${m.full}`);
|
||||
return (
|
||||
<tr key={m.name}
|
||||
onClick={() => nav(`/mirrors/${encodeURIComponent(m.name)}`)}
|
||||
className="cursor-pointer border-b border-border transition-colors duration-ctl hover:bg-panel2">
|
||||
<td className={ROW_CELL}>
|
||||
<span className="inline-flex items-center gap-3">
|
||||
<StatusDot color={HEALTH_COLORS[st]} pulse={st === 'running'} />
|
||||
<span className="font-mono text-[13px]">{m.name}</span>
|
||||
</span>
|
||||
</td>
|
||||
<td className={`${ROW_CELL} max-w-[340px]`}>
|
||||
<div className="flex flex-col gap-1">
|
||||
{/* fork: where the mirror lives */}
|
||||
<a href={m.forkUrl || `https://git.lago.dev/${m.full}`} target="_blank" rel="noreferrer"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
title={m.forkUrl || `https://git.lago.dev/${m.full}`}
|
||||
className="inline-flex items-baseline gap-1 font-mono text-[13px] text-accent hover:underline">
|
||||
<span className="text-[10px] uppercase tracking-wide text-muted">fork</span>
|
||||
<span className="truncate">{f.host}/{f.repo}</span>
|
||||
</a>
|
||||
{/* origin: the source repo */}
|
||||
<a href={m.upstream} target="_blank" rel="noreferrer"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
title={m.upstream}
|
||||
className="inline-flex items-baseline gap-1 font-mono text-[13px] text-muted hover:text-accent hover:underline">
|
||||
<span className="text-[10px] uppercase tracking-wide text-muted">origin</span>
|
||||
<span className="truncate">{u.host}/{u.repo}</span>
|
||||
</a>
|
||||
</div>
|
||||
</td>
|
||||
<td className={ROW_CELL}><LastSyncCell m={m} /></td>
|
||||
<td className={`${ROW_CELL} font-mono text-[11px] text-muted`}>
|
||||
{m.lastSync ? duration(m.lastSync.durationSec) : '—'}
|
||||
</td>
|
||||
<td className={ROW_CELL}><ParityChips m={m} /></td>
|
||||
<td className={ROW_CELL}>
|
||||
<Sparkline statuses={m.spark} colorOf={(s) => runColor(s, null)} />
|
||||
</td>
|
||||
<td className={`${ROW_CELL} text-right`}>
|
||||
<span className="inline-flex items-center gap-1">
|
||||
<Btn variant="ghost" title="Re-sync" aria-label={`Re-sync ${m.name}`}
|
||||
disabled={syncing === m.name}
|
||||
onClick={(e) => { e.stopPropagation(); void reSync(m.name); }}>
|
||||
<RotateCw size={16} strokeWidth={1.5} className={syncing === m.name ? 'animate-spin' : ''} />
|
||||
</Btn>
|
||||
<Btn variant="ghost" title="Detail" aria-label={`Detail ${m.name}`}
|
||||
onClick={(e) => { e.stopPropagation(); nav(`/mirrors/${encodeURIComponent(m.name)}`); }}>
|
||||
<ArrowRight size={16} strokeWidth={1.5} />
|
||||
</Btn>
|
||||
<Btn variant="danger" title="Delete" aria-label={`Delete ${m.name}`}
|
||||
onClick={(e) => { e.stopPropagation(); setDel({ open: true, name: m.name }); }}>
|
||||
<Trash2 size={16} strokeWidth={1.5} />
|
||||
</Btn>
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{/* delete confirm */}
|
||||
<ConfirmDialog open={del.open} name={del.name} busy={delBusy}
|
||||
onConfirm={() => void doDelete()} onClose={() => setDel({ open: false, name: '' })} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { Link, useNavigate, useParams } from 'react-router-dom';
|
||||
import {
|
||||
Btn, StatusDot, ConfirmDialog, OfflineBanner, toast,
|
||||
} from '../components/primitives';
|
||||
import { api } from '../api/client';
|
||||
import { useApp } from '../lib/app-context';
|
||||
import { health, HEALTH_COLORS } from '../lib/health';
|
||||
import { useData } from './detail/useData';
|
||||
import { RunHistoryPanel } from './detail/RunHistory';
|
||||
import { LiveLogPanel } from './detail/LiveLog';
|
||||
import { ParityPanel, ConfigPanel, VariablesPanel, UnitsPanel } from './detail/panels';
|
||||
|
||||
export default function Detail() {
|
||||
const { name = '' } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const { offline } = useApp();
|
||||
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [confirmDel, setConfirmDel] = useState(false);
|
||||
const [delBusy, setDelBusy] = useState(false);
|
||||
|
||||
const mirrors = useData(() => api.mirrors(), 15000, `mirrors`);
|
||||
const runs = useData(() => api.mirrorRuns(name, 12), 10000, `runs:${name}`);
|
||||
const config = useData(() => api.mirrorConfig(name), 15000, `cfg:${name}`);
|
||||
const variables = useData(() => api.mirrorVariables(name), 15000, `vars:${name}`);
|
||||
|
||||
const mirror = mirrors.data?.find((m) => m.name === name) || null;
|
||||
|
||||
// header dot: mirror health color, default ok
|
||||
const healthState = mirror
|
||||
? health(mirror, null)
|
||||
: 'ok';
|
||||
const dotColor = HEALTH_COLORS[healthState];
|
||||
|
||||
const dispatch = async (workflow: string, label: string) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await api.dispatch(name, workflow);
|
||||
toast(`${label} dispatched`);
|
||||
await runs.refresh();
|
||||
} catch (e) {
|
||||
toast(e instanceof Error ? e.message : String(e), 'error');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const doDelete = useCallback(async () => {
|
||||
setDelBusy(true);
|
||||
try {
|
||||
await api.deleteMirror(name);
|
||||
toast('mirror deleted');
|
||||
navigate('/');
|
||||
} catch (e) {
|
||||
toast(e instanceof Error ? e.message : String(e), 'error');
|
||||
setDelBusy(false);
|
||||
setConfirmDel(false);
|
||||
}
|
||||
}, [name, navigate]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
{offline && <OfflineBanner />}
|
||||
|
||||
{/* header */}
|
||||
<div className="flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between">
|
||||
<div className="min-w-0">
|
||||
<div className="font-mono text-[11px] text-muted">
|
||||
<Link to="/" className="hover:text-accent">mirrors</Link>
|
||||
<span> / {name}</span>
|
||||
</div>
|
||||
<div className="mt-1 flex flex-wrap items-center gap-2">
|
||||
<StatusDot color={dotColor} pulse={healthState === 'running'} />
|
||||
<h1 className="text-[18px] font-semibold leading-none text-text">{name}</h1>
|
||||
{mirror?.forkUrl && (
|
||||
<a href={mirror.forkUrl} target="_blank" rel="noreferrer"
|
||||
className="max-w-[360px] truncate font-mono text-[13px] text-accent hover:underline"
|
||||
title={mirror.forkUrl}>
|
||||
{mirror.forkUrl.replace(/^https?:\/\//, '')}
|
||||
</a>
|
||||
)}
|
||||
{mirror?.upstream && (
|
||||
<a href={mirror.upstream} target="_blank" rel="noreferrer"
|
||||
className="max-w-[360px] truncate font-mono text-[13px] text-muted hover:text-accent hover:underline"
|
||||
title={mirror.upstream}>
|
||||
{mirror.upstream.replace(/^https?:\/\//, '').replace(/\.git$/, '')}
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Btn variant="primary" disabled={busy} onClick={() => void dispatch('sync.yml', 're-sync')}>
|
||||
Re-sync
|
||||
</Btn>
|
||||
<Btn variant="secondary" disabled={busy} onClick={() => void dispatch('release.yml', 'release')}>
|
||||
Run release
|
||||
</Btn>
|
||||
<Btn variant="danger" onClick={() => setConfirmDel(true)}>Delete</Btn>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 60/40 grid, stacks under 1024px */}
|
||||
<div className="grid grid-cols-1 gap-4 lg:grid-cols-[3fr_2fr]">
|
||||
{/* left */}
|
||||
<div className="flex min-w-0 flex-col gap-4">
|
||||
<RunHistoryPanel
|
||||
runs={runs.data}
|
||||
loading={runs.loading}
|
||||
error={runs.error}
|
||||
onRetry={runs.refresh}
|
||||
name={name}
|
||||
/>
|
||||
<LiveLogPanel
|
||||
runs={runs.data}
|
||||
loading={runs.loading}
|
||||
error={runs.error}
|
||||
onRetry={runs.refresh}
|
||||
name={name}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* right */}
|
||||
<div className="flex min-w-0 flex-col gap-4">
|
||||
<ParityPanel
|
||||
p={mirror?.parity ?? null}
|
||||
loading={mirrors.loading}
|
||||
error={mirrors.error}
|
||||
onRetry={mirrors.refresh}
|
||||
/>
|
||||
<ConfigPanel
|
||||
parsed={config.data?.parsed ?? null}
|
||||
loading={config.loading}
|
||||
error={config.error}
|
||||
onRetry={config.refresh}
|
||||
name={name}
|
||||
/>
|
||||
<VariablesPanel
|
||||
items={variables.data}
|
||||
loading={variables.loading}
|
||||
error={variables.error}
|
||||
onRetry={variables.refresh}
|
||||
/>
|
||||
<UnitsPanel
|
||||
units={mirror?.units ?? null}
|
||||
loading={mirrors.loading}
|
||||
error={mirrors.error}
|
||||
onRetry={mirrors.refresh}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ConfirmDialog
|
||||
open={confirmDel}
|
||||
name={name}
|
||||
busy={delBusy}
|
||||
onConfirm={() => void doDelete()}
|
||||
onClose={() => setConfirmDel(false)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { Clock } from 'lucide-react';
|
||||
import {
|
||||
Badge, EmptyState, ErrorInline, OfflineBanner, Panel, SkeletonRow, StatusDot,
|
||||
} from '../components/primitives';
|
||||
import { api } from '../api/client';
|
||||
import type { QueueEntry, Runner } from '../api/types';
|
||||
import { useApp, usePoll } from '../lib/app-context';
|
||||
import { Spinner, C } from './shared';
|
||||
import { fmtSec, errMsg } from './format';
|
||||
|
||||
function Th({ children }: { children: ReactNode }) {
|
||||
return <th className="px-2 py-2 text-left font-medium text-[11px] uppercase tracking-wide text-muted">{children}</th>;
|
||||
}
|
||||
|
||||
function StateChip({ status }: { status: QueueEntry['status'] }) {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 rounded-pill border border-border bg-chip px-2 py-[1px] text-[11px] leading-4">
|
||||
{status === 'in_progress' ? (
|
||||
<span className="text-accent"><Spinner size={10} /></span>
|
||||
) : (
|
||||
<Clock size={11} strokeWidth={1.5} className="text-muted" />
|
||||
)}
|
||||
<span className={status === 'in_progress' ? 'text-accent' : 'text-muted'}>
|
||||
{status === 'in_progress' ? 'in_progress' : 'queued'}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export default function RunnerView({ runner }: { runner: Runner | null }) {
|
||||
const { offline } = useApp();
|
||||
const [queue, setQueue] = useState<QueueEntry[] | null>(null);
|
||||
const [runners, setRunners] = useState<Runner[] | null>(null);
|
||||
const [err, setErr] = useState('');
|
||||
|
||||
const loadQueue = useCallback(async () => {
|
||||
try {
|
||||
setQueue(await api.queue());
|
||||
setErr('');
|
||||
} catch (e) {
|
||||
setErr(errMsg(e));
|
||||
}
|
||||
}, []);
|
||||
|
||||
const loadRunners = useCallback(async () => {
|
||||
try {
|
||||
setRunners(await api.runners());
|
||||
} catch (e) {
|
||||
setErr(errMsg(e));
|
||||
}
|
||||
}, []);
|
||||
|
||||
usePoll(loadQueue, 3000);
|
||||
usePoll(loadRunners, 10000);
|
||||
|
||||
const onlineDot = runner ? (runner.status === 'online' ? C.ok : C.muted) : C.muted;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-[16px]">
|
||||
{offline && <OfflineBanner />}
|
||||
|
||||
{/* top row */}
|
||||
<div className="flex items-center justify-between gap-[16px]">
|
||||
<h1 className="text-[18px] font-semibold leading-tight text-text">Runner</h1>
|
||||
<div className="flex items-center gap-[8px]">
|
||||
<StatusDot color={onlineDot} pulse={!!runner && runner.status === 'online' && runner.busy} />
|
||||
<span className="font-mono text-[13px] text-text">{runner ? runner.name : 'no runner'}</span>
|
||||
<Badge color={runner?.status === 'online' ? C.ok : undefined}>
|
||||
{runner ? (runner.busy ? 'busy' : 'idle') : 'offline'}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* concurrency strip */}
|
||||
<div className="flex items-center gap-[8px] text-[12px] text-muted">
|
||||
<span>serial runner (maxParallel=1) — jobs run one at a time</span>
|
||||
<Badge color={C.accent}>1</Badge>
|
||||
</div>
|
||||
|
||||
{err && <ErrorInline message={err} onRetry={() => { void loadQueue(); void loadRunners(); }} />}
|
||||
|
||||
{/* queue */}
|
||||
<Panel title="Queue">
|
||||
{queue === null ? (
|
||||
<div>
|
||||
<SkeletonRow />
|
||||
<SkeletonRow />
|
||||
</div>
|
||||
) : queue.length === 0 ? (
|
||||
<EmptyState title="queue empty — runner idle" />
|
||||
) : (
|
||||
<table className="w-full border-collapse">
|
||||
<thead>
|
||||
<tr>
|
||||
<Th>#</Th><Th>Repo</Th><Th>Run</Th><Th>Event</Th><Th>State</Th><Th>Waited</Th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{queue.map((q, i) => (
|
||||
<tr key={q.runId} className="border-b border-border transition-colors duration-ctl last:border-b-0 hover:bg-panel2">
|
||||
<td className="px-2 py-2 font-mono text-[11px] tabular-nums text-muted">{i + 1}</td>
|
||||
<td className="px-2 py-2">
|
||||
<span className="inline-flex items-center gap-2">
|
||||
<StatusDot color={q.status === 'in_progress' ? C.accent : C.muted} pulse={q.status === 'in_progress'} />
|
||||
<span className="font-mono text-[13px] text-text">{q.repo}</span>
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-2 py-2 font-mono text-[13px] tabular-nums text-text">#{q.runId}</td>
|
||||
<td className="px-2 py-2"><Badge>{q.event}</Badge></td>
|
||||
<td className="px-2 py-2"><StateChip status={q.status} /></td>
|
||||
<td className="px-2 py-2 font-mono text-[11px] tabular-nums text-muted">
|
||||
{q.status === 'in_progress'
|
||||
? `running ${fmtSec(q.waitedSec)}`
|
||||
: `${fmtSec(q.waitedSec)} waited`}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</Panel>
|
||||
|
||||
{/* runners */}
|
||||
<Panel title="Runners">
|
||||
{runners === null ? (
|
||||
<div>
|
||||
<SkeletonRow />
|
||||
<SkeletonRow />
|
||||
</div>
|
||||
) : runners.length === 0 ? (
|
||||
<EmptyState title="no runners registered" />
|
||||
) : (
|
||||
<table className="w-full border-collapse">
|
||||
<thead>
|
||||
<tr>
|
||||
<Th>Name</Th><Th>Status</Th><Th>Type</Th><Th>Busy</Th><Th>Labels</Th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{runners.map((r) => (
|
||||
<tr key={r.id}
|
||||
className={`border-b border-border transition-colors duration-ctl last:border-b-0 hover:bg-panel2 ${
|
||||
r.status === 'offline' ? 'opacity-50' : ''}`}>
|
||||
<td className="px-2 py-2 font-mono text-[13px] text-text">{r.name}</td>
|
||||
<td className="px-2 py-2">
|
||||
<Badge dot={r.status === 'online' ? C.ok : C.muted}>{r.status}</Badge>
|
||||
</td>
|
||||
<td className="px-2 py-2">
|
||||
<Badge>{r.type === 'repo' ? `repo: ${r.repo || '?'}` : r.type}</Badge>
|
||||
</td>
|
||||
<td className="px-2 py-2">
|
||||
<span className="inline-flex items-center gap-2">
|
||||
<span className="font-mono text-[11px] tabular-nums text-muted">
|
||||
{r.busy ? '1/1' : 'idle'}
|
||||
</span>
|
||||
{r.busy && (
|
||||
<span className="inline-block h-[2px] w-[64px] overflow-hidden rounded-pill bg-panel2 align-middle">
|
||||
<span className="block h-full w-1/2 bg-accent" />
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-2 py-2">
|
||||
<span className="flex flex-wrap gap-1">
|
||||
{r.labels.map((l) => <Badge key={l}>{l}</Badge>)}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</Panel>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Btn, Badge, ErrorInline, OfflineBanner, Panel, SkeletonRow, toast } from '../components/primitives';
|
||||
import { api } from '../api/client';
|
||||
import { useApp } from '../lib/app-context';
|
||||
import { MonoInput, C } from './shared';
|
||||
|
||||
export default function Settings() {
|
||||
const { settings, configured, offline, connect } = useApp();
|
||||
const [version, setVersion] = useState('');
|
||||
const [url, setUrl] = useState(settings?.url || '');
|
||||
const [token, setToken] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [err, setErr] = useState('');
|
||||
|
||||
// gitea version is not part of /api/settings — pull it from /api/health
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
if (!configured) { setVersion(''); return; }
|
||||
api.health()
|
||||
.then((h) => { if (alive) setVersion(h.gitea ? h.gitea.version : ''); })
|
||||
.catch(() => { if (alive) setVersion(''); });
|
||||
return () => { alive = false; };
|
||||
}, [configured, settings]);
|
||||
|
||||
const doConnect = async () => {
|
||||
setBusy(true);
|
||||
setErr('');
|
||||
const ok = await connect(url.trim(), token.trim());
|
||||
setBusy(false);
|
||||
if (!ok) { setErr('Connection failed — check the URL and token.'); return; }
|
||||
const s = await api.settings().catch(() => null);
|
||||
toast(`connected as ${s?.user || 'user'}`);
|
||||
setToken('');
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex w-full max-w-[640px] flex-col gap-[16px]">
|
||||
{offline && <OfflineBanner />}
|
||||
|
||||
<h1 className="text-[18px] font-semibold leading-tight text-text">Settings</h1>
|
||||
|
||||
{/* Gitea connection */}
|
||||
<Panel title="Gitea connection">
|
||||
{settings === null ? (
|
||||
<div>
|
||||
<SkeletonRow />
|
||||
<SkeletonRow />
|
||||
</div>
|
||||
) : configured ? (
|
||||
<div className="flex flex-col gap-[8px]">
|
||||
<div className="flex items-center gap-[8px]">
|
||||
<span className="font-mono text-[13px] text-text">{settings.url}</span>
|
||||
<Badge color={C.ok} dot={C.ok}>connected</Badge>
|
||||
</div>
|
||||
<div className="flex items-center gap-[16px]">
|
||||
<span className="font-mono text-[12px] text-muted">{settings.user}</span>
|
||||
{version && <span className="font-mono text-[11px] text-muted">gitea {version}</span>}
|
||||
</div>
|
||||
<div className="text-[11px] text-muted">
|
||||
Stored in <span className="font-mono">~/.repo-forker/credentials</span> (chmod 600).
|
||||
Never uploaded; only sent to the Gitea base URL.
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-[12px]">
|
||||
<label className="block text-[12px] text-muted">Gitea base URL</label>
|
||||
<MonoInput value={url} onChange={(e) => setUrl(e.target.value)} placeholder="https://git.lago.dev" spellCheck={false} />
|
||||
<label className="block text-[12px] text-muted">Token</label>
|
||||
<MonoInput value={token} onChange={(e) => setToken(e.target.value)} type="password" placeholder="Gitea token" spellCheck={false} />
|
||||
{err && <ErrorInline message={err} onRetry={doConnect} />}
|
||||
<div className="flex items-center justify-between gap-[16px]">
|
||||
<div className="text-[11px] text-muted">
|
||||
Stored in <span className="font-mono">~/.repo-forker/credentials</span> (chmod 600).
|
||||
Never uploaded; only sent to the Gitea base URL.
|
||||
</div>
|
||||
<Btn variant="primary" className="shrink-0"
|
||||
disabled={!url.trim() || !token.trim() || busy} onClick={doConnect}>
|
||||
{busy ? 'Connecting…' : 'Connect'}
|
||||
</Btn>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Panel>
|
||||
|
||||
{/* Template */}
|
||||
<Panel title="Template">
|
||||
<div className="text-[12px] text-muted">Mirror generation template</div>
|
||||
{settings === null ? (
|
||||
<div className="mt-[8px]"><SkeletonRow /></div>
|
||||
) : (
|
||||
<div className="mt-[8px] flex flex-col gap-[8px]">
|
||||
<div className="flex items-center gap-[8px]">
|
||||
<span className="font-mono text-[13px] text-text">{settings.template || '—'}</span>
|
||||
<Badge>locked</Badge>
|
||||
</div>
|
||||
<div className="text-[11px] text-muted">
|
||||
all mirrors are generated from this repo; it never appears in the mirror list
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Panel>
|
||||
|
||||
{/* About */}
|
||||
<Panel title="About">
|
||||
<div className="max-w-[60ch] text-[12px] leading-[1.5] text-muted">
|
||||
Repo Forker turns a template repo into live mirrors: each generated fork mirrors an
|
||||
upstream git repo (branches, tags, full history) and builds releases on a Gitea
|
||||
Actions runner.
|
||||
</div>
|
||||
<a href="https://git.lago.dev/Lago/repo-forker" target="_blank" rel="noreferrer"
|
||||
className="mt-[8px] inline-block text-[12px] text-accent hover:underline">
|
||||
repo-forker on Gitea
|
||||
</a>
|
||||
</Panel>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
import { Fragment, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Check } from 'lucide-react';
|
||||
import { Btn, ErrorInline, OfflineBanner, Panel, Toggle } from '../components/primitives';
|
||||
import { api } from '../api/client';
|
||||
import { BOOLEAN_CONFIG_KEYS, KNOWN_CONFIG_KEYS } from '../api/types';
|
||||
import type { FlatConfig } from '../api/types';
|
||||
import { useApp } from '../lib/app-context';
|
||||
import { MonoInput, Spinner } from './shared';
|
||||
import { deriveName, errMsg } from './format';
|
||||
|
||||
const DEFAULTS: FlatConfig = {
|
||||
mirror_branches: '*',
|
||||
mirror_tags: true,
|
||||
mirror_prune: true,
|
||||
mirror_upstream_releases: false,
|
||||
on_new_tag: true,
|
||||
build_cmd: '',
|
||||
build_script: '',
|
||||
artifacts: '',
|
||||
};
|
||||
|
||||
// The 5 fixed creation steps (DESIGN.md page 3). The server resolves the
|
||||
// createMirror call when the whole sequence is done, so completion is
|
||||
// revealed step by step as the call settles.
|
||||
const STEP_NAMES = ['generate', 'variable', 'default-branch', 'config', 'first-sync'] as const;
|
||||
|
||||
type WizStep = { name: string; status: 'ok' | 'error' | 'pending' };
|
||||
type Phase = 'form' | 'creating' | 'done' | 'error';
|
||||
|
||||
const isBool = (k: string) => (BOOLEAN_CONFIG_KEYS as readonly string[]).includes(k);
|
||||
|
||||
function StepIndicator({ step }: { step: number }) {
|
||||
const labels = ['Upstream', 'Config', 'Progress'];
|
||||
return (
|
||||
<div className="flex items-start gap-[12px]">
|
||||
{labels.map((label, i) => {
|
||||
const n = i + 1;
|
||||
const done = step > n;
|
||||
const current = step === n;
|
||||
return (
|
||||
<Fragment key={label}>
|
||||
<div className="flex flex-col items-center gap-[4px]">
|
||||
<div className={`flex h-[32px] w-[32px] items-center justify-center rounded-full font-mono text-[13px] ${
|
||||
done ? 'bg-ok text-bg' : current ? 'bg-accent text-bg' : 'border border-border text-muted'}`}>
|
||||
{done ? <Check size={16} /> : n}
|
||||
</div>
|
||||
<div className="text-[12px] text-muted">{label}</div>
|
||||
</div>
|
||||
{n < 3 && <div className={`mt-[16px] h-px min-w-[24px] flex-1 ${step > n ? 'bg-ok' : 'bg-border'}`} />}
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Wizard() {
|
||||
const { offline } = useApp();
|
||||
const navigate = useNavigate();
|
||||
const [step, setStep] = useState(1);
|
||||
const [url, setUrl] = useState('');
|
||||
const [name, setName] = useState('');
|
||||
const [config, setConfig] = useState<FlatConfig>({ ...DEFAULTS });
|
||||
const [phase, setPhase] = useState<Phase>('form');
|
||||
const [steps, setSteps] = useState<WizStep[]>([]);
|
||||
const [repo, setRepo] = useState('');
|
||||
const [err, setErr] = useState('');
|
||||
const startedRef = useRef(false);
|
||||
|
||||
const valid = /^https?:\/\/.+/.test(url);
|
||||
const finalName = name.trim() || deriveName(url);
|
||||
|
||||
const start = async () => {
|
||||
if (startedRef.current) return;
|
||||
startedRef.current = true;
|
||||
setStep(3);
|
||||
setPhase('creating');
|
||||
setErr('');
|
||||
setSteps(STEP_NAMES.map((n) => ({ name: n, status: 'pending' as const })));
|
||||
try {
|
||||
const r = await api.createMirror(url, name.trim() || undefined, config);
|
||||
const server = r.steps.length
|
||||
? r.steps
|
||||
: STEP_NAMES.map((n, i) => ({
|
||||
name: n,
|
||||
status: r.ok ? ('ok' as const) : (i === STEP_NAMES.length - 1 ? ('error' as const) : ('pending' as const)),
|
||||
}));
|
||||
let i = 0;
|
||||
const t = window.setInterval(() => {
|
||||
i += 1;
|
||||
setSteps((prev) => prev.map((s, j) => (j < i ? { ...s, status: server[j]?.status ?? s.status } : s)));
|
||||
if (i >= server.length) {
|
||||
window.clearInterval(t);
|
||||
if (r.ok) { setRepo(r.repo || `Lago/${finalName}`); setPhase('done'); }
|
||||
else { setErr(r.error || 'create failed'); setPhase('error'); }
|
||||
}
|
||||
}, 350);
|
||||
} catch (e) {
|
||||
setSteps(STEP_NAMES.map((n, j) => ({ name: n, status: j === 0 ? ('error' as const) : ('pending' as const) })));
|
||||
setErr(errMsg(e));
|
||||
setPhase('error');
|
||||
}
|
||||
};
|
||||
|
||||
const retry = () => {
|
||||
startedRef.current = false;
|
||||
setStep(1);
|
||||
setPhase('form');
|
||||
setErr('');
|
||||
setSteps([]);
|
||||
setRepo('');
|
||||
};
|
||||
|
||||
const activeIdx =
|
||||
phase === 'creating' && !steps.some((s) => s.status === 'error')
|
||||
? steps.findIndex((s) => s.status === 'pending')
|
||||
: -1;
|
||||
const repoName = repo ? repo.split('/').pop() || finalName : finalName;
|
||||
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-[640px]">
|
||||
{offline && <OfflineBanner />}
|
||||
<StepIndicator step={step} />
|
||||
|
||||
{step === 1 && (
|
||||
<Panel className="mt-[24px]">
|
||||
<label className="block text-[12px] text-muted">Upstream git URL</label>
|
||||
<MonoInput className="mt-[4px]" value={url} onChange={(e) => setUrl(e.target.value)}
|
||||
placeholder="https://github.com/owner/repo.git" spellCheck={false} />
|
||||
<div className="mt-[4px] max-w-[52ch] text-[11px] text-muted">
|
||||
Works with GitHub, Gitea, Codeberg, or any git host — public repos are fetched anonymously.
|
||||
</div>
|
||||
<label className="mt-[16px] block text-[12px] text-muted">Name (optional)</label>
|
||||
<MonoInput className="mt-[4px]" value={name} onChange={(e) => setName(e.target.value)}
|
||||
placeholder={deriveName(url)} spellCheck={false} />
|
||||
<div className="mt-[16px] flex justify-end">
|
||||
<Btn variant="primary" disabled={!valid} onClick={() => setStep(2)}>Continue</Btn>
|
||||
</div>
|
||||
</Panel>
|
||||
)}
|
||||
|
||||
{step === 2 && (
|
||||
<Panel title="Config (flat schema)" className="mt-[24px]">
|
||||
<div>
|
||||
{KNOWN_CONFIG_KEYS.map((key) => (
|
||||
<div key={key} className="flex items-center justify-between gap-[16px] border-b border-border py-[8px] last:border-b-0">
|
||||
<span className="w-[192px] shrink-0 font-mono text-[12px] text-muted">{key}</span>
|
||||
{isBool(key) ? (
|
||||
<Toggle on={!!config[key]} onChange={(v) => setConfig((c) => ({ ...c, [key]: v }))} />
|
||||
) : (
|
||||
<MonoInput className="w-[280px] flex-1" value={String(config[key] ?? '')}
|
||||
onChange={(e) => setConfig((c) => ({ ...c, [key]: e.target.value }))}
|
||||
placeholder={key === 'mirror_branches' ? '*' : 'empty = refs only'} spellCheck={false} />
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-[8px] text-[11px] text-muted">
|
||||
The parser is a simple grep — flat key: value only, no nesting.
|
||||
</div>
|
||||
<div className="mt-[16px] flex gap-[8px]">
|
||||
<Btn variant="ghost" onClick={() => setStep(1)}>Back</Btn>
|
||||
<Btn variant="primary" onClick={start}>Continue</Btn>
|
||||
</div>
|
||||
</Panel>
|
||||
)}
|
||||
|
||||
{step === 3 && (
|
||||
<Panel title="Creating…" className="mt-[24px]">
|
||||
<div>
|
||||
{steps.map((s, i) => {
|
||||
const active = i === activeIdx;
|
||||
return (
|
||||
<div key={s.name} className="flex items-center gap-[8px] py-[8px]">
|
||||
<span className={`flex h-[24px] w-[24px] shrink-0 items-center justify-center rounded-full ${
|
||||
s.status === 'ok' ? 'bg-ok text-bg' : active ? 'text-accent' : 'border border-border'}`}>
|
||||
{s.status === 'ok' ? <Check size={16} /> : active ? <Spinner size={14} /> : null}
|
||||
</span>
|
||||
<span className={`font-mono text-[13px] ${s.status === 'error' ? 'text-danger' : ''}`}>{s.name}</span>
|
||||
<span className="text-[11px] text-muted">
|
||||
{s.status === 'ok' ? 'done' : active ? 'running…' : s.status === 'error' ? 'failed' : 'pending'}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{phase !== 'done' && (
|
||||
<div className="mt-[8px] text-[11px] text-muted">
|
||||
this runs generate → variable → default branch → config → first sync
|
||||
</div>
|
||||
)}
|
||||
|
||||
{phase === 'error' && (
|
||||
<div className="mt-[16px] flex flex-col gap-[12px]">
|
||||
<ErrorInline message={err} />
|
||||
<div className="flex justify-end">
|
||||
<Btn variant="ghost" onClick={retry}>Try again</Btn>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{phase === 'done' && (
|
||||
<div className="mt-[16px] rounded-panel border border-ok/40 bg-panel p-[16px]">
|
||||
<div className="text-[14px] text-ok">Mirror {repo} created</div>
|
||||
<div className="mt-[16px]">
|
||||
<Btn variant="primary" onClick={() => navigate(`/mirrors/${repoName}`)}>Open {repoName}</Btn>
|
||||
</div>
|
||||
<div className="mt-[8px] text-[11px] text-muted">the first sync is queued on the runner</div>
|
||||
</div>
|
||||
)}
|
||||
</Panel>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
// Small inline spinner (accent) used for in_progress states — 12px, currentColor.
|
||||
export function Spinner({ size = 12 }: { size?: number }) {
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" aria-hidden
|
||||
className="shrink-0 animate-spin text-accent">
|
||||
<circle cx="12" cy="12" r="9" stroke="currentColor" strokeOpacity="0.25" strokeWidth="3" />
|
||||
<path d="M21 12a9 9 0 0 0-9-9" stroke="currentColor" strokeWidth="3" strokeLinecap="round" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { Panel, SkeletonRow, EmptyState, ErrorInline, StatusDot } from '../../components/primitives';
|
||||
import { api } from '../../api/client';
|
||||
import { usePoll } from '../../lib/app-context';
|
||||
import type { RunInfo, LogLine } from '../../api/types';
|
||||
import { renderLogLines } from './log';
|
||||
|
||||
// ---------------------------------------------------------------- Live log
|
||||
// Selects the last 5 runs; the live <pre> auto-scrolls to the tail unless the
|
||||
// user scrolled up (pinned ref), and re-fetches every 3s only while the
|
||||
// selected run is in_progress.
|
||||
export function LiveLogPanel({ runs, loading, error, onRetry, name }: {
|
||||
runs: RunInfo[] | null; loading: boolean; error: string | null;
|
||||
onRetry: () => void; name: string;
|
||||
}) {
|
||||
const defaultId = runs && runs.length > 0
|
||||
? (runs.find((r) => r.status === 'in_progress') || runs[0]).id
|
||||
: null;
|
||||
const [sel, setSel] = useState<number | null>(defaultId);
|
||||
const [lines, setLines] = useState<LogLine[] | null>(null);
|
||||
const [logErr, setLogErr] = useState<string | null>(null);
|
||||
const [logLoading, setLogLoading] = useState(true);
|
||||
|
||||
const pinned = useRef(true);
|
||||
const preRef = useRef<HTMLPreElement | null>(null);
|
||||
|
||||
const effectiveSel = sel !== null && runs?.some((r) => r.id === sel) ? sel : defaultId;
|
||||
const selected = runs?.find((r) => r.id === effectiveSel) || null;
|
||||
|
||||
const fetchLog = useCallback(async () => {
|
||||
if (effectiveSel === null) return;
|
||||
const id = effectiveSel;
|
||||
try {
|
||||
const r = await api.log(name, id);
|
||||
setLines(r.lines);
|
||||
setLogErr(null);
|
||||
} catch (e) {
|
||||
setLogErr(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setLogLoading(false);
|
||||
}
|
||||
}, [name, effectiveSel]);
|
||||
|
||||
// reset to the latest when the run list changes (poll) and no valid pick
|
||||
useEffect(() => {
|
||||
if (sel !== null && !runs?.some((r) => r.id === sel)) {
|
||||
setSel(defaultId);
|
||||
}
|
||||
}, [runs, sel, defaultId]);
|
||||
|
||||
// fetch on selection change
|
||||
useEffect(() => {
|
||||
setLines(null);
|
||||
setLogErr(null);
|
||||
setLogLoading(true);
|
||||
pinned.current = true;
|
||||
void fetchLog();
|
||||
}, [effectiveSel, fetchLog]);
|
||||
|
||||
// live tail: only while the selected run is in_progress
|
||||
const live = selected?.status === 'in_progress';
|
||||
const tickLog = useCallback(() => {
|
||||
if (live) void fetchLog();
|
||||
}, [live, fetchLog]);
|
||||
usePoll(tickLog, 3000);
|
||||
|
||||
// keep pinned at the tail; user scroll-up unpins, scroll to bottom re-pins
|
||||
useEffect(() => {
|
||||
const el = preRef.current;
|
||||
if (!el) return;
|
||||
if (pinned.current) el.scrollTop = el.scrollHeight;
|
||||
}, [lines]);
|
||||
|
||||
const onScroll = () => {
|
||||
const el = preRef.current;
|
||||
if (!el) return;
|
||||
const atBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 8;
|
||||
pinned.current = atBottom;
|
||||
if (atBottom) el.scrollTop = el.scrollHeight;
|
||||
};
|
||||
const unpin = () => { pinned.current = false; };
|
||||
|
||||
return (
|
||||
<Panel title="Live log">
|
||||
<div className="mb-3">
|
||||
<select
|
||||
value={effectiveSel ?? ''}
|
||||
onChange={(e) => setSel(Number(e.target.value))}
|
||||
disabled={!runs || runs.length === 0}
|
||||
className="w-full rounded-ctl border border-border bg-panel2 p-2 font-mono text-[13px] text-text focus:outline-none focus:ring-2 focus:ring-accent/30">
|
||||
{!runs || runs.length === 0 ? (
|
||||
<option value="">no runs</option>
|
||||
) : runs.slice(0, 5).map((r) => (
|
||||
<option key={r.id} value={r.id}>
|
||||
run #{r.id} — {r.conclusion || r.status}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{loading && runs === null ? (
|
||||
<div>
|
||||
<SkeletonRow />
|
||||
<SkeletonRow />
|
||||
</div>
|
||||
) : error ? (
|
||||
<ErrorInline message={error} onRetry={onRetry} />
|
||||
) : !runs || runs.length === 0 ? (
|
||||
<EmptyState title="No runs yet" />
|
||||
) : (
|
||||
<>
|
||||
{logErr && <div className="mb-2"><ErrorInline message={logErr} onRetry={() => void fetchLog()} /></div>}
|
||||
<pre
|
||||
ref={preRef}
|
||||
onScroll={onScroll}
|
||||
onWheel={unpin}
|
||||
onTouchMove={unpin}
|
||||
onKeyDown={unpin}
|
||||
className="max-h-[420px] overflow-auto rounded-panel bg-chip p-4 font-mono text-[11px] leading-5 whitespace-pre text-text">
|
||||
{logLoading && !lines
|
||||
? 'loading log…'
|
||||
: lines
|
||||
? renderLogLines(lines)
|
||||
: 'no log'}
|
||||
{live && (
|
||||
<span className="mt-2 flex items-center gap-2 text-[11px] text-muted">
|
||||
<StatusDot color="#58a6ff" pulse /> streaming — run #{effectiveSel}
|
||||
</span>
|
||||
)}
|
||||
</pre>
|
||||
</>
|
||||
)}
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { ChevronDown } from 'lucide-react';
|
||||
import { Panel, Badge, StatusDot, Btn, SkeletonRow, EmptyState, ErrorInline } from '../../components/primitives';
|
||||
import { api } from '../../api/client';
|
||||
import type { RunInfo } from '../../api/types';
|
||||
import { runColor, duration, timeAgo } from '../../lib/health';
|
||||
|
||||
const CONCLUSION_COLOR: Record<string, string> = {
|
||||
success: '#7ee787', failure: '#f85149',
|
||||
cancelled: '#8b949e', skipped: '#8b949e',
|
||||
};
|
||||
|
||||
function lastIdx(lines: string[]): number {
|
||||
for (let i = lines.length - 1; i >= 0; i--) {
|
||||
if (lines[i].includes('fatal:') || lines[i].includes('::error::')) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
// expandable failure log: last 12 lines of the run's log, the failing line
|
||||
// (last line containing 'fatal:' or '::error::') rendered in danger
|
||||
export function FailureLog({ name, runId }: { name: string; runId: number }) {
|
||||
const [lines, setLines] = useState<string[] | null>(null);
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
const tried = useRef(false);
|
||||
|
||||
const load = async (force = false) => {
|
||||
if (tried.current && !force) return;
|
||||
tried.current = true;
|
||||
setErr(null);
|
||||
try {
|
||||
const r = await api.log(name, runId);
|
||||
setLines(r.lines.map((l) => l.text).slice(-12));
|
||||
} catch (e) {
|
||||
setErr(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
if (err) return <ErrorInline message={err} onRetry={() => void load(true)} />;
|
||||
if (!lines) {
|
||||
return (
|
||||
<div className="mt-2 rounded-[8px] border border-danger/40 bg-chip p-3 font-mono text-[11px] leading-5 text-muted">
|
||||
loading log…
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const fi = lastIdx(lines);
|
||||
return (
|
||||
<div className="mt-2 rounded-[8px] border border-danger/40 bg-chip p-3 font-mono text-[11px] leading-5">
|
||||
{lines.map((t, i) => (
|
||||
<div key={i} className={i === fi ? 'text-danger' : 'text-text'}>{t}</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RunRow({ name, r }: { name: string; r: RunInfo }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const failed = r.conclusion === 'failure';
|
||||
return (
|
||||
<div className="border-b border-border py-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<StatusDot color={runColor(r.status, r.conclusion)} pulse={r.status === 'in_progress'} />
|
||||
<span className="font-mono text-[13px] text-text">run #{r.id}</span>
|
||||
<Badge>{r.event}</Badge>
|
||||
{r.conclusion && (
|
||||
<span className="text-[13px]" style={{ color: CONCLUSION_COLOR[r.conclusion] || '#8b949e' }}>
|
||||
{r.conclusion}
|
||||
</span>
|
||||
)}
|
||||
<span className="ml-auto font-mono text-[11px] text-muted">{duration(r.durationSec)}</span>
|
||||
<span className="w-16 text-right font-mono text-[11px] text-muted">{timeAgo(r.updatedAt)}</span>
|
||||
{failed && (
|
||||
<Btn variant="ghost" className="px-2 py-0.5 text-[12px]"
|
||||
onClick={() => setOpen((v) => !v)} aria-expanded={open}>
|
||||
View log
|
||||
<ChevronDown size={16} strokeWidth={1.5}
|
||||
className={`transition-transform duration-ctl ${open ? 'rotate-180' : ''}`} />
|
||||
</Btn>
|
||||
)}
|
||||
</div>
|
||||
{failed && open && <FailureLog name={name} runId={r.id} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function RunHistoryPanel({ runs, loading, error, onRetry, name }: {
|
||||
runs: RunInfo[] | null; loading: boolean; error: string | null;
|
||||
onRetry: () => void; name: string;
|
||||
}) {
|
||||
return (
|
||||
<Panel title="Run history">
|
||||
{loading && runs === null ? (
|
||||
<div>
|
||||
<SkeletonRow />
|
||||
<SkeletonRow />
|
||||
</div>
|
||||
) : error ? (
|
||||
<ErrorInline message={error} onRetry={onRetry} />
|
||||
) : !runs || runs.length === 0 ? (
|
||||
<EmptyState title="No runs yet" />
|
||||
) : (
|
||||
<div className="-mx-4">
|
||||
{runs.map((r) => (
|
||||
<RunRow key={r.id} name={name} r={r} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import type { LogLine } from '../../api/types';
|
||||
|
||||
const GROUP = /^\s*::group::(.*)$/;
|
||||
const ENDGROUP = /^\s*::endgroup::/;
|
||||
const MSG = /^\s*::(notice|warning|error)::(.*)$/;
|
||||
const MSG_COLOR: Record<string, string> = {
|
||||
notice: '#58a6ff',
|
||||
warning: '#f2cc60',
|
||||
error: '#f85149',
|
||||
};
|
||||
|
||||
// index of the LAST line containing 'fatal:' or '::error::' (-1 = none)
|
||||
export function failIdx(lines: LogLine[]): number {
|
||||
for (let i = lines.length - 1; i >= 0; i--) {
|
||||
const t = lines[i].text;
|
||||
if (t.includes('fatal:') || t.includes('::error::')) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function renderLine(text: string, key: number): ReactNode {
|
||||
const m = text.match(MSG);
|
||||
if (m) {
|
||||
const c = MSG_COLOR[m[1]];
|
||||
return (
|
||||
<div key={key}>
|
||||
<span className="inline-block w-full border-l-2 pl-2" style={{ borderColor: c, color: c }}>
|
||||
{m[2]}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return <div key={key}>{text}</div>;
|
||||
}
|
||||
|
||||
// Render a raw job log: ::group::X … ::endgroup:: collapses into a <details>,
|
||||
// ::notice:: / ::warning:: / ::error:: get a colored 2px left border.
|
||||
// Each line is a block div so <pre> line structure is preserved.
|
||||
export function renderLogLines(lines: LogLine[]): ReactNode[] {
|
||||
const out: ReactNode[] = [];
|
||||
let k = 0;
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const g = lines[i].text.match(GROUP);
|
||||
if (g) {
|
||||
const body: ReactNode[] = [];
|
||||
i++;
|
||||
while (i < lines.length && !ENDGROUP.test(lines[i].text)) {
|
||||
body.push(renderLine(lines[i].text, k++));
|
||||
i++;
|
||||
}
|
||||
out.push(
|
||||
<details key={k++} className="my-1">
|
||||
<summary className="flex min-h-[24px] cursor-pointer items-center gap-2 select-none text-[12px] text-muted">
|
||||
{g[1]}
|
||||
</summary>
|
||||
{body.length > 0 && <div className="ml-4">{body}</div>}
|
||||
</details>,
|
||||
);
|
||||
} else {
|
||||
out.push(renderLine(lines[i].text, k++));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
import { useState } from 'react';
|
||||
import { Copy } from 'lucide-react';
|
||||
import {
|
||||
Panel, Badge, Btn, SkeletonRow, EmptyState, ErrorInline, Toggle, toast,
|
||||
} from '../../components/primitives';
|
||||
import { api } from '../../api/client';
|
||||
import { KNOWN_CONFIG_KEYS, BOOLEAN_CONFIG_KEYS } from '../../api/types';
|
||||
import type { FlatConfig, Parity, RepoVariable } from '../../api/types';
|
||||
|
||||
const BOOL_KEYS: readonly string[] = [...BOOLEAN_CONFIG_KEYS];
|
||||
|
||||
// ---------------------------------------------------------------- Parity
|
||||
const PARITY_ROWS = [
|
||||
{ key: 'branches', label: 'branches' },
|
||||
{ key: 'tags', label: 'tags' },
|
||||
{ key: 'releases', label: 'releases' },
|
||||
{ key: 'assets', label: 'assets' },
|
||||
] as const;
|
||||
|
||||
function fmt(n: number | null | undefined): string {
|
||||
return n === null || n === undefined ? '—' : String(n);
|
||||
}
|
||||
|
||||
function DeltaBadge({ row, p }: { row: (typeof PARITY_ROWS)[number]; p: Parity }) {
|
||||
const up = p.upstream?.[row.key] ?? null;
|
||||
const fk = p[row.key];
|
||||
if (up === null || fk === null) {
|
||||
return <Badge>—</Badge>;
|
||||
}
|
||||
if (fk < up) {
|
||||
return <Badge color="#f85149" dot="#f85149">-{up - fk}</Badge>;
|
||||
}
|
||||
return <Badge color="#7ee787" dot="#7ee787">in sync</Badge>;
|
||||
}
|
||||
|
||||
export function ParityPanel({ p, loading, error, onRetry }: {
|
||||
p: Parity | null; loading: boolean; error: string | null; onRetry: () => void;
|
||||
}) {
|
||||
return (
|
||||
<Panel title="Parity">
|
||||
{loading && p === null ? (
|
||||
<SkeletonRow />
|
||||
) : error ? (
|
||||
<ErrorInline message={error} onRetry={onRetry} />
|
||||
) : !p ? (
|
||||
<EmptyState title="No parity data" />
|
||||
) : (
|
||||
<div className="grid grid-cols-2 gap-x-4 gap-y-2">
|
||||
<div className="text-[11px] uppercase text-muted">upstream</div>
|
||||
<div className="text-right text-[11px] uppercase text-muted">fork</div>
|
||||
{PARITY_ROWS.map((row) => (
|
||||
<div key={row.key} className="contents">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="font-mono text-[13px] text-muted">{row.label}</span>
|
||||
<span className="font-mono text-[13px] tabular-nums text-text">
|
||||
{fmt(p.upstream?.[row.key])}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<span className="font-mono text-[13px] tabular-nums text-text">{fmt(p[row.key])}</span>
|
||||
<DeltaBadge row={row} p={p} />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Config
|
||||
const inputCls =
|
||||
'w-full rounded-ctl border border-border bg-panel2 px-3 py-2 font-mono text-[13px] text-text placeholder:text-muted/50 focus:outline-none focus:ring-2 focus:ring-accent/30';
|
||||
|
||||
function displayValue(v: string | boolean | undefined): string {
|
||||
if (typeof v === 'boolean') return v ? 'true' : 'false';
|
||||
return v ?? '';
|
||||
}
|
||||
|
||||
export function ConfigPanel({ parsed, loading, error, onRetry, name }: {
|
||||
parsed: FlatConfig | null; loading: boolean; error: string | null;
|
||||
onRetry: () => void; name: string;
|
||||
}) {
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [draft, setDraft] = useState<FlatConfig | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
|
||||
const startEdit = () => {
|
||||
setDraft(JSON.parse(JSON.stringify(parsed || {})) as FlatConfig);
|
||||
setErr(null);
|
||||
setEditing(true);
|
||||
};
|
||||
|
||||
const save = async () => {
|
||||
if (!draft) return;
|
||||
setBusy(true);
|
||||
setErr(null);
|
||||
try {
|
||||
await api.saveMirrorConfig(name, draft);
|
||||
toast('config saved');
|
||||
setEditing(false);
|
||||
setDraft(null);
|
||||
onRetry(); // refresh
|
||||
} catch (e) {
|
||||
setErr(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Panel
|
||||
title="Config"
|
||||
action={
|
||||
!editing && parsed !== null && (
|
||||
<Btn variant="ghost" className="px-2 py-0.5 text-[12px]" onClick={startEdit}>Edit</Btn>
|
||||
)
|
||||
}>
|
||||
{loading && parsed === null ? (
|
||||
<SkeletonRow />
|
||||
) : error ? (
|
||||
<ErrorInline message={error} onRetry={onRetry} />
|
||||
) : !parsed ? (
|
||||
<EmptyState title="No config" />
|
||||
) : editing && draft ? (
|
||||
<div className="flex flex-col gap-2">
|
||||
{KNOWN_CONFIG_KEYS.map((k) => (
|
||||
<div key={k} className="flex items-center gap-2">
|
||||
<span className="w-40 shrink-0 font-mono text-[13px] text-muted">{k}</span>
|
||||
{BOOL_KEYS.includes(k) ? (
|
||||
<Toggle
|
||||
on={draft[k] === true}
|
||||
onChange={(v) => setDraft({ ...draft, [k]: v })}
|
||||
disabled={busy}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
value={displayValue(draft[k])}
|
||||
onChange={(e) => setDraft({ ...draft, [k]: e.target.value })}
|
||||
placeholder="(empty)"
|
||||
disabled={busy}
|
||||
className={inputCls}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
<div className="text-[11px] text-muted">flat schema — known keys only, no nesting</div>
|
||||
{err && <ErrorInline message={err} />}
|
||||
<div className="mt-1 flex justify-end gap-2">
|
||||
<Btn variant="ghost" disabled={busy} onClick={() => { setEditing(false); setDraft(null); }}>
|
||||
Cancel
|
||||
</Btn>
|
||||
<Btn variant="primary" disabled={busy} onClick={() => void save()}>
|
||||
{busy ? 'Saving…' : 'Save'}
|
||||
</Btn>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
{KNOWN_CONFIG_KEYS.map((k) => {
|
||||
const val = displayValue(parsed[k]);
|
||||
return (
|
||||
<div key={k} className="flex items-center gap-2">
|
||||
<span className="w-[192px] shrink-0 font-mono text-[13px] text-muted" title={k}>
|
||||
{k}
|
||||
</span>
|
||||
<span className="min-w-0 truncate font-mono text-[13px] text-text" title={val}>
|
||||
{val === '' ? '—' : val}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Variables
|
||||
export function VariablesPanel({ items, loading, error, onRetry }: {
|
||||
items: RepoVariable[] | null; loading: boolean; error: string | null; onRetry: () => void;
|
||||
}) {
|
||||
const copy = async (v: RepoVariable) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(v.value);
|
||||
toast('copied');
|
||||
} catch {
|
||||
toast('copy failed', 'error');
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Panel title="Variables">
|
||||
{loading && items === null ? (
|
||||
<SkeletonRow />
|
||||
) : error ? (
|
||||
<ErrorInline message={error} onRetry={onRetry} />
|
||||
) : !items || items.length === 0 ? (
|
||||
<EmptyState title="No variables" />
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
{items.map((v) => {
|
||||
const masked = /_TOKEN$|SECRET/.test(v.name);
|
||||
return (
|
||||
<div key={v.name} className="flex items-center gap-2">
|
||||
<span className="w-40 shrink-0 truncate font-mono text-[13px] text-muted" title={v.name}>
|
||||
{v.name}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate font-mono text-[13px] text-text"
|
||||
title={masked ? undefined : v.value}>
|
||||
{masked ? '••••••' : v.value}
|
||||
</span>
|
||||
<Btn variant="ghost" className="shrink-0 px-2 py-0.5" title="Copy value"
|
||||
onClick={() => void copy(v)}>
|
||||
<Copy size={16} strokeWidth={1.5} />
|
||||
</Btn>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Units
|
||||
export function UnitsPanel({ units, loading, error, onRetry }: {
|
||||
units: string[] | null; loading: boolean; error: string | null; onRetry: () => void;
|
||||
}) {
|
||||
return (
|
||||
<Panel title="Units">
|
||||
{loading && units === null ? (
|
||||
<SkeletonRow />
|
||||
) : error ? (
|
||||
<ErrorInline message={error} onRetry={onRetry} />
|
||||
) : !units || units.length === 0 ? (
|
||||
<EmptyState title="No units" />
|
||||
) : (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{units.map((u) => (
|
||||
<Badge key={u} dot="#7ee787">{u}</Badge>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { usePoll } from '../../lib/app-context';
|
||||
|
||||
// Fetch + poll a data slice. `key` (e.g. the route param) resets the slice when
|
||||
// it changes. On error: last good data is kept and the exact error message is
|
||||
// exposed so panels can render an inline ErrorInline + retry.
|
||||
export function useData<T>(fn: () => Promise<T>, ms: number, key?: string) {
|
||||
const [data, setData] = useState<T | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const fnRef = useRef(fn);
|
||||
fnRef.current = fn;
|
||||
const busy = useRef(false);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (busy.current) return;
|
||||
busy.current = true;
|
||||
try {
|
||||
const d = await fnRef.current();
|
||||
setData(d);
|
||||
setError(null);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
busy.current = false;
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
void load();
|
||||
}, [key, load]);
|
||||
|
||||
const tick = useCallback(() => {
|
||||
if (!busy.current) void load();
|
||||
}, [load]);
|
||||
usePoll(tick, ms);
|
||||
|
||||
return { data, loading, error, refresh: load };
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// Shared formatting / derivation helpers for Wizard / RunnerView / Settings.
|
||||
|
||||
// Derive a default mirror name from an upstream git URL.
|
||||
export function deriveName(url: string): string {
|
||||
const path = url.replace(/^https?:\/\//i, '');
|
||||
const seg = path.split('/').filter(Boolean);
|
||||
const last = seg[seg.length - 1] || 'new-mirror';
|
||||
return last.replace(/\.git$/i, '').toLowerCase() || 'new-mirror';
|
||||
}
|
||||
|
||||
// Seconds → "Mm Ss" (mono, tabular-nums keeps it aligned).
|
||||
export function fmtSec(totalSec: number): string {
|
||||
const s = Math.max(0, Math.floor(totalSec));
|
||||
const m = Math.floor(s / 60);
|
||||
const rem = s % 60;
|
||||
return `${m}m ${rem}s`;
|
||||
}
|
||||
|
||||
// Exact failing line for ErrorInline.
|
||||
export function errMsg(e: unknown): string {
|
||||
return e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// Small shared controls for Wizard / RunnerView / Settings (new files only —
|
||||
// primitives.tsx and app-context.tsx are not modified).
|
||||
import React from 'react';
|
||||
|
||||
const INPUT =
|
||||
'w-full rounded-ctl border border-border bg-panel2 px-2 py-2 font-mono text-[13px] text-text ' +
|
||||
'placeholder:text-muted/50 focus:outline-none focus:ring-2 focus:ring-accent/30 transition-colors duration-ctl';
|
||||
|
||||
export function MonoInput({ className = '', ...rest }: React.InputHTMLAttributes<HTMLInputElement>) {
|
||||
return <input {...rest} className={`${INPUT} ${className}`} />;
|
||||
}
|
||||
|
||||
// Accent spinner: small svg circle with a stroke-dasharray arc, 1s spin.
|
||||
export function Spinner({ size = 12 }: { size?: number }) {
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 12 12" className="animate-spin" aria-hidden>
|
||||
<circle
|
||||
cx="6" cy="6" r="5" fill="none" stroke="currentColor" strokeWidth="1.5"
|
||||
strokeDasharray="21 11" strokeLinecap="round"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
// Locked token hexes (DESIGN.md) — no new colors.
|
||||
export const C = {
|
||||
ok: '#7ee787',
|
||||
muted: '#8b949e',
|
||||
accent: '#58a6ff',
|
||||
danger: '#f85149',
|
||||
warn: '#f2cc60',
|
||||
} as const;
|
||||
@@ -0,0 +1,22 @@
|
||||
module.exports = {
|
||||
content: ['./index.html', './src/**/*.{ts,tsx}'],
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
bg: '#0d1117', panel: '#161b22', panel2: '#1c2333', chip: '#21262d',
|
||||
border: '#30363d', text: '#e6edf3', muted: '#8b949e', accent: '#58a6ff',
|
||||
ok: '#7ee787', warn: '#f2cc60', danger: '#f85149'
|
||||
},
|
||||
fontFamily: {
|
||||
ui: ['-apple-system', 'BlinkMacSystemFont', '"Segoe UI"', 'Helvetica', 'Arial', 'sans-serif'],
|
||||
mono: ['ui-monospace', 'SFMono-Regular', 'SF Mono', 'Menlo', 'Consolas', 'monospace']
|
||||
},
|
||||
// NOTE: no `spacing` override — Tailwind's default 4px-stepped scale maps
|
||||
// exactly to the DESIGN.md grid (p-1=4, p-2=8, p-3=12, p-4=16, p-6=24,
|
||||
// p-8=32, p-12=48). Overriding it clobbered p-4→4px etc.
|
||||
borderRadius: { panel: '8px', ctl: '6px', pill: '999px' },
|
||||
transitionDuration: { ctl: '120ms' }
|
||||
}
|
||||
},
|
||||
plugins: []
|
||||
};
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
server: { port: 8731 },
|
||||
build: { outDir: 'dist', sourcemap: false },
|
||||
});
|
||||