Compare commits

..
1 Commits
Author SHA1 Message Date
Lago 0b6b40eed8 Initial commit 2026-10-14 18:57:47 +02:00
290 changed files with 8619 additions and 820 deletions

No files matched your search

+49
View File
@@ -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: ""
+38
View File
@@ -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 }}
+35
View File
@@ -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.")'
+82
View File
@@ -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 }}
+23
View File
@@ -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
Binary file not shown.

Before

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 151 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 155 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 105 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 105 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 105 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 113 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 95 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 239 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 324 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 95 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 158 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 106 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 126 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 144 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 69 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 66 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 149 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 197 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 210 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 169 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 190 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 369 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 523 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 344 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 150 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 222 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 244 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 493 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 497 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 549 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 274 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 484 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 176 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 146 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 178 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 210 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 147 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 179 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 210 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 140 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 177 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 206 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 71 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 272 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 557 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 158 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 93 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 107 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 666 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 MiB

+151
View File
@@ -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)
+43
View File
@@ -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
+221
View File
@@ -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.
+102
View File
@@ -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.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 573 KiB

Loaded 100 of 290 files, more files were not shown because too many files have changed in this diff. Show more