GitHub Repo Manager (API-first)
Use this skill to operate a GitHub repo without git push. Typical trigger: the sandbox can reach
api.github.com but connections to github.com (git smart-http) hang or time out. Verify quickly
(urllib to https://api.github.com/zen vs a git ls-remote attempt) and fall back to normal git
whenever git actually works — this API path exists only as a workaround.
Auth
- Ask the user for a Personal Access Token (
reposcope;workflowscope needed to edit.github/workflows). - Never write the token to disk, memory, or any file. Keep it in a session variable only.
- Always warn the user once per session if the token was pasted in chat: recommend revoking it (Settings → Developer settings → PATs) after the work is done.
Core helper (Python, stdlib only)
import json, base64, urllib.request, urllib.error, urllib.parse
TOKEN = '<user-provided-pat>'
def gh(path, method='GET', payload=None, accept='application/vnd.github+json'):
req = urllib.request.Request(
f'https://api.github.com{path}',
data=json.dumps(payload).encode() if payload is not None else None,
method=method,
headers={'Authorization': 'Bearer ' + TOKEN, 'Accept': accept,
'Content-Type': 'application/json', 'User-Agent': 'repo-manager'})
with urllib.request.urlopen(req, timeout=30) as r:
return json.loads(r.read()) if r.status != 204 else {}
Authenticated rate limit is 5000/h — plenty. Unauthenticated is 60/h; always send the token.
Recipes
1. Read the tree (needed before any file update)
tree = gh(f'/repos/{OWNER}/{REPO}/git/trees/{BRANCH}?recursive=1')
sha = {t['path']: t['sha'] for t in tree['tree'] if t['type'] == 'blob'}
2. Create or update a file — one commit per file
payload = {'message': 'update: ' + path, 'branch': BRANCH,
'content': base64.b64encode(open(path, 'rb').read()).decode()}
if rel in sha: # existing file MUST carry its current sha, else HTTP 409
payload['sha'] = sha[rel]
gh(f'/repos/{OWNER}/{REPO}/contents/{urllib.parse.quote(rel)}', 'PUT', payload)
New files: omit sha. Deleting a file: use method='DELETE' with payload
{'message', 'sha', 'branch'}.
Side effect: history becomes one commit per file. Use Recipe 7 to squash later.
3. Sync a local directory
Walk the directory (skip .git, node_modules, *.zip), PUT each file with the tree's SHA
(re-fetch the tree if you changed >a few files), time.sleep(0.25) between calls.
4. Repo settings
- Create:
POST /user/repos{'name': ..., 'private': True, 'description': ...} - Public/private:
PATCH /repos/{o}/{r}{'private': False} - Never force-push/rewrite history via API; don't touch branch protection unless asked.
5. Actions
- List runs:
GET /repos/{o}/{r}/actions/runs?per_page=5→ each run hasstatus/conclusion/head_sha. - Jobs:
GET /repos/{o}/{r}/actions/runs/{id}/jobs(shows which job/step failed). - Logs:
GET /repos/{o}/{r}/actions/runs/{id}/logsreturns 302 to a signed zip URL — do NOT follow redirects with the Authorization header; captureLocationvia a no-redirect opener, then GET it plain and unzip. Preflight (OPTIONS) responses makeawait r.text()throw — filter byr.method() == 'POST'when capturing request bodies. - Re-run failures:
POST /repos/{o}/{r}/actions/runs/{id}/rerun-failed-jobswith{}. - Manual trigger:
POST /repos/{o}/{r}/actions/workflows/{file}/dispatches{'ref': 'main'}(requires the workflow to declareworkflow_dispatch:).
6. GitHub Pages
- Enable with Actions source:
POST /repos/{o}/{r}/pages{'build_type': 'workflow'}(409 = already on). - Repo variable for workflows:
POST /repos/{o}/{r}/actions/variables{'name': 'API_BASE', 'value': ...}(PATCH /repos/{o}/{r}/actions/variables/{name}to update). - SPA fallback: after build,
cp dist/index.html dist/404.html— Pages serves it for unknown paths. - Project-page asset prefix: set the bundler's base to
/<repo>/whenGITHUB_PAGES=true(e.g. rsbuildoutput.assetPrefix), else assets 404.
7. Squash history into one commit (Git Data API, no clone needed)
When the repo is young / has no collaborators and you want to collapse "one commit per file" into a single clean root commit:
# 1. one blob per file
blobs = {p: gh(f'/repos/{o}/{r}/git/blobs', 'POST',
{'content': base64.b64encode(c.encode()).decode(), 'encoding': 'base64'})['sha']
for p, c in files.items()}
# 2. tree of blobs (no base_tree -> orphan root)
tree = gh(f'/repos/{o}/{r}/git/trees', 'POST',
{'tree': [{'path': p, 'mode': '100644', 'type': 'blob', 'sha': s}
for p, s in blobs.items()]})['sha']
# 3. commit with parents: [] (no parent = brand-new root; passing the current head sha
# here instead yields a NORMAL multi-file commit appended to history — no force needed)
commit = gh(f'/repos/{o}/{r}/git/commits', 'POST',
{'message': 'squash: clean history', 'tree': tree, 'parents': []})['sha']
# 4. point the branch at it: PATCH + force:true (history diverged). On a ZERO-commit repo
# the branch ref does not exist yet — use POST /git/refs {'ref': 'refs/heads/main', 'sha'}
gh(f'/repos/{o}/{r}/git/refs/heads/main', 'PATCH', {'sha': commit, 'force': True})
Caveats: every prior commit becomes a dangling object (GitHub GCs them); anyone who cloned must delete and re-clone; never do this on a repo with collaborators or open PRs.
Known traps (all hit in the wild)
- "in progress deployment — cancel ... or wait": Pages serializes deployments; back-to-back
pushes collide. Fix:
rerun-failed-jobsafter the previous deploy finishes. - Tree-shaken pages in single-page bundles: if you push file A (exports X) and file B (imports X)
in separate commits, the build triggered by A's push may legitimately lack X — tree-shaking drops
unimported exports. Verify the FINAL deployed artifact, not intermediate builds; when in doubt
trigger
workflow_dispatchon the latest commit and re-check. - CDN lag: after a successful deploy,
index.htmlmay still reference the old bundle hash for 1–2 minutes. Compare the JS hash in served HTML before concluding a deploy "didn't take". - Empty repo git endpoints 409/404: on a repo with zero commits,
git/refs/*andgit/trees/{branch}fail — create the first file via the Contents API (Recipe 2); Recipe 7's step 4 must use POST /git/refs to create the branch. - Output-dir permissions: files created by the assistant's file tools may not be overwritable
from the Python sandbox (
PermissionError) —os.remove()then rewrite usually works. - Do not paste tokens into committed files (
.env, workflow files); use repo Secrets/Variables.
When NOT to use
- Normal
git clone/add/commit/pushworks (user's own machine): prefer it. - Bulk history rewriting, merges, or rebases: API is the wrong tool.