railyard/apps/gitea/scripts/lib/bulk-migrate.sh
caelum0x ec98430794
Some checks failed
ci / cargo test (abacus) (push) Has been cancelled
ci / cargo test (agent-runtime) (push) Has been cancelled
ci / cargo test (context-passport) (push) Has been cancelled
ci / cargo test (game-economy) (push) Has been cancelled
ci / cargo test (ledgerline) (push) Has been cancelled
ci / cargo test (mint) (push) Has been cancelled
ci / cargo test (rago) (push) Has been cancelled
ci / cargo test (relay) (push) Has been cancelled
ci / cargo test (toolgate) (push) Has been cancelled
ci / cargo test (turnstile) (push) Has been cancelled
ci / cargo test (vend) (push) Has been cancelled
ci / node suites (push) Has been cancelled
feat(rit,gitea): zero-manual-step GitHub->Rithub import (login, CLI, agent) + orphan-comment migrate bug fix
- apps/rit: `rit login` (PKCE OAuth2 against a new first-party "Rit CLI"
  Gitea app, loopback callback, no token paste) and `rit import github`
  (lists own repos+forks via `gh auth token`, smallest-first, skip-
  existing, mirror=true). Wired as a transparent credential fallback into
  remote.rs so push/fetch/pull/clone/issue/pr all work after one login.
  `rit push` also syncs a `github` remote if present via system git.
- apps/gitea/scripts: oauth-auto-import.sh (path 1, cron-driven, triggered
  by Gitea's own GitHub OAuth login source, flock+load-gated) and
  rithub-agent.sh (path 3, plain-words trigger) share lib/bulk-migrate.sh
  as their core.
- Found+fixed two real API bugs via live testing against rithub.dev
  (MigrateRepoOptions.service is a string not an int; a bash bool-
  interpolation bug), and one real production bug (orphan GitHub comments
  on a deleted issue/PR 500 Gitea's comment-import phase even though the
  repo+code already landed -- now detected and reported as a partial
  success with a note instead of a false failure).
- Full real end-to-end verification with a throwaway mail.tm Rithub user,
  fully cleaned up after. 121/121 existing rit tests still pass.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-19 00:12:57 +03:00

160 lines
7.5 KiB
Bash

#!/usr/bin/env bash
# Shared core for server-side GitHub -> Rithub bulk migration. Sourced by
# oauth-auto-import.sh (path 1: automatic, triggered by a GitHub sign-in)
# and rithub-agent.sh (path 3: plain-words request). Same endpoint, same
# request shape, same defaults as the client-side `rit import github`
# (apps/rit/src/import_cmd.rs) — verified against the live server
# 2026-11-18 (plans/railyard.md): Gitea's `MigrateRepoOptions.service` is
# the string "github" on this build, not a numeric service_type.
#
# Never echoes a token. Concurrency and load-awareness are the *caller's*
# job (flock + /proc/loadavg before calling into this file) since both
# callers need to coordinate with each other, not just with themselves.
set -euo pipefail
RITHUB_HOST="${RITHUB_HOST:-rithub.dev}"
# _gitea_api METHOD URL GITEA_USER GITEA_TOKEN [BODY_JSON] -> prints http
# status, leaves the response body in /tmp/.bulk-migrate-resp.$$ for the
# caller to read and remove. HTTP Basic auth with the token as the
# password — same scheme already proven working by `existing_rithub_repos`
# below and by `rit`'s own CLI (apps/rit/src/import_cmd.rs::rithub_request).
# An earlier version of this function used an `Authorization: token`
# header instead and was never actually exercised against the live server;
# a direct curl check against it during this fix's own verification came
# back empty, so this was corrected before shipping, not left as a latent
# second bug.
_gitea_api() {
local method="$1" url="$2" user="$3" token="$4" body="${5:-}"
if [ -n "$body" ]; then
curl -s -o /tmp/.bulk-migrate-resp.$$ -w '%{http_code}' \
-X "$method" "$url" -u "${user}:${token}" -H "User-Agent: rithub-bulk-migrate" \
-H "Content-Type: application/json" --data-binary "$body"
else
curl -s -o /tmp/.bulk-migrate-resp.$$ -w '%{http_code}' \
-X "$method" "$url" -u "${user}:${token}" -H "User-Agent: rithub-bulk-migrate"
fi
}
# List full_name + size(KB), tab-separated, sorted smallest-first. Own repos
# + forks only (no org/starred — same conservative default as the CLI).
list_github_repos() {
local token="$1" page=1
while true; do
local resp
resp=$(curl -s -H "Authorization: Bearer $token" -H "User-Agent: rithub-bulk-migrate" \
"https://api.github.com/user/repos?per_page=100&page=${page}&affiliation=owner&sort=full_name")
local count
count=$(echo "$resp" | python3 -c "import json,sys;print(len(json.load(sys.stdin)))" 2>/dev/null || echo 0)
[ "$count" -eq 0 ] && break
echo "$resp" | python3 -c "
import json,sys
for r in json.load(sys.stdin):
# Python-capitalized True/False on purpose: this field is interpolated
# directly into a Python dict literal below, not parsed as JSON/bash —
# lowercase 'false' here was a real bug (NameError: name 'false' is not
# defined), found 2026-11-19 by actually running this against a real
# GitHub account (451 repos) rather than just reading the code.
print(f\"{r['full_name']}\t{r.get('size',0)}\t{r['clone_url']}\t{str(r.get('private',False))}\")
"
[ "$count" -lt 100 ] && break
page=$((page + 1))
done | sort -t$'\t' -k2 -n
}
# Existing repo names for a Rithub user (for resumable skip-existing).
existing_rithub_repos() {
local user="$1" token="$2" page=1
while true; do
local resp
resp=$(curl -s -u "${user}:${token}" "https://${RITHUB_HOST}/api/v1/users/${user}/repos?limit=50&page=${page}")
local names
names=$(echo "$resp" | python3 -c "
import json,sys
try:
for r in json.load(sys.stdin):
print(r['name'])
except Exception:
pass
" 2>/dev/null)
[ -z "$names" ] && break
echo "$names"
local count
count=$(echo "$names" | wc -l | tr -d ' ')
[ "$count" -lt 50 ] && break
page=$((page + 1))
done
}
# bulk_migrate_user GITEA_USER GITEA_TOKEN GITHUB_TOKEN
# Migrates every owner+fork repo for GITHUB_TOKEN's account onto Rithub
# under GITEA_USER, smallest-first, skipping anything already present.
# Prints one progress line per repo to stdout (read-only list, no prompts).
bulk_migrate_user() {
local gitea_user="$1" gitea_token="$2" github_token="$3"
echo "[$gitea_user] reading GitHub repos..."
local repos existing
repos=$(list_github_repos "$github_token")
existing=$(existing_rithub_repos "$gitea_user" "$gitea_token")
local total=0 done_count=0 first_visible_at="" start
start=$(date +%s)
total=$(echo "$repos" | grep -c . || true)
echo "[$gitea_user] $total GitHub repo(s) found."
while IFS=$'\t' read -r full_name size_kb clone_url private; do
[ -z "$full_name" ] && continue
local name="${full_name##*/}"
if echo "$existing" | grep -qx "$name"; then
echo "[$gitea_user] skip (already on $RITHUB_HOST): $full_name"
continue
fi
local body status
body=$(python3 -c "
import json
print(json.dumps({
'clone_addr': '$clone_url',
'auth_token': '$github_token',
'repo_name': '$name',
'repo_owner': '$gitea_user',
'service': 'github',
'mirror': True,
'mirror_interval': '8h',
'private': $private,
'wiki': True, 'issues': True, 'pull_requests': True,
'releases': True, 'labels': True, 'milestones': True,
}))
")
status=$(_gitea_api POST "https://${RITHUB_HOST}/api/v1/repos/migrate" "$gitea_user" "$gitea_token" "$body")
resp_body=$(cat /tmp/.bulk-migrate-resp.$$ 2>/dev/null || true)
rm -f /tmp/.bulk-migrate-resp.$$ 2>/dev/null || true
if [ "$status" -ge 200 ] && [ "$status" -lt 300 ]; then
done_count=$((done_count + 1))
[ -z "$first_visible_at" ] && first_visible_at=$(($(date +%s) - start))
echo "[$gitea_user] migrated ($done_count/$total): $full_name (visible now, history fills in the background)"
elif echo "$resp_body" | grep -q "comment references non existent IssueIndex"; then
# Real bug (c5, 2026-11-18/19): Gitea's comment-import phase 500s on a
# GitHub comment whose own issue/PR was deleted upstream -- but only
# AFTER the repo + full git history already landed (verified live:
# erebos-labs/expo-journal, scribase/orion, caelum0x/immortal-bnb all
# exist non-empty right after this exact "FAIL"). Re-migrating would
# hit the identical bug again and can't resume just the issue phase,
# so check whether the repo is really there before calling it a
# failure -- same fix as apps/rit/src/import_cmd.rs::migrate_one.
check_status=$(_gitea_api GET "https://${RITHUB_HOST}/api/v1/repos/${gitea_user}/${name}" "$gitea_user" "$gitea_token")
check_body=$(cat /tmp/.bulk-migrate-resp.$$ 2>/dev/null || true)
rm -f /tmp/.bulk-migrate-resp.$$ 2>/dev/null || true
is_empty=$(echo "$check_body" | python3 -c "import json,sys;print(json.load(sys.stdin).get('empty',True))" 2>/dev/null || echo True)
if [ "$check_status" = "200" ] && [ "$is_empty" = "False" ]; then
done_count=$((done_count + 1))
[ -z "$first_visible_at" ] && first_visible_at=$(($(date +%s) - start))
echo "[$gitea_user] migrated ($done_count/$total): $full_name -- note: code + most issues/PRs migrated; a few comments on an already-deleted GitHub issue/PR were skipped"
else
echo "[$gitea_user] FAILED: $full_name (HTTP $status, orphan-comment bug, repo did not actually land) $(echo "$resp_body" | head -c 200)"
fi
else
echo "[$gitea_user] FAILED: $full_name (HTTP $status) $(echo "$resp_body" | head -c 200)"
fi
done <<<"$repos"
local elapsed=$(($(date +%s) - start))
echo "[$gitea_user] done: $done_count/$total migrated. time to first visible: ${first_visible_at:-0}s, total: ${elapsed}s."
}