Scripts and automation¶
Small pieces of automation that keep the technical setup tidy and safe with almost no effort: a script that keeps every repo on a computer up to date, a check that stops passwords from being saved by mistake, a GitHub Action that keeps a repo's contents table current, checks that run on every change, a way to keep shared rules the same in every repo, a ping on your phone when the assistant needs you, and a copy of every repo at home. Each one is short enough to read in full, and each one follows the same rules as everything else: a dry run first, and you run the first real test yourself.
- The sync script
- A check that catches secrets
- A contents table that keeps itself up to date
- Checks on every change
- Keeping shared rules the same
- A ping when the assistant needs you
- A copy of every repo at home
- Adding your own
The sync script¶
sync.sh lives in the library repo, next to repos.txt. Run it on any computer and
it downloads every repo on the list that isn't there yet, and brings the rest up to
date. It never overwrites anything: a repo with unsaved changes, or one that has
changes GitHub doesn't, is skipped with a note saying why.
It works out your GitHub account from the address library was downloaded from, so
there's nothing to set up. A line in repos.txt can be a plain name (notes, a repo
in your own account) or account/name (a repo in another account or organization you
belong to).
# repos.txt: one repo per line. Anything after # is ignored.
notes
house
cooking
a-club-you-belong-to/newsletter
Running it looks like this:
$ ./sync.sh --dry-run
Dry run: nothing will change.
would download cooking
would update notes
skipped house (has unsaved changes; commit or put them aside first)
Done: 1 to download, 1 to update, 0 already current, 1 skipped.
$ ./sync.sh
downloaded cooking
updated notes
skipped house (has unsaved changes; commit or put them aside first)
Done: 1 downloaded, 1 updated, 0 already current, 1 skipped.
Here's the whole script. It runs with the older version of bash that comes with macOS, as well as on Linux.
#!/usr/bin/env bash
# sync.sh: download every repo in repos.txt that you don't have yet, and
# bring the rest up to date. Lives in the library repo; the subject repos go
# next to it.
#
# ./sync.sh do it
# ./sync.sh --dry-run show what it would do, change nothing
# ./sync.sh --dir PATH put the repos in PATH instead of next to library
#
# repos.txt holds one repo per line: "notes" means a repo under the same
# account as library, "someone/notes" means that account's repo. Blank lines
# and anything after # are ignored.
#
# It never overwrites anything: a repo with unsaved changes, or one that has
# gone its own way, is skipped with a note. Works with the bash that ships
# with macOS.
set -u
here="$(cd "$(dirname "$0")" && pwd)"
dir="$(dirname "$here")"
dry_run=0
usage() { sed -n '2,13p' "$0" | sed 's/^# \{0,1\}//'; }
while [ $# -gt 0 ]; do
case "$1" in
--dry-run) dry_run=1 ;;
--dir) shift; dir="${1:?--dir needs a folder}" ;;
-h|--help) usage; exit 0 ;;
*) echo "Unknown option: $1" >&2; usage >&2; exit 2 ;;
esac
shift
done
list="$here/repos.txt"
[ -f "$list" ] || { echo "Can't find $list" >&2; exit 2; }
# Work out the account and address from library's own address, so the
# script needs no settings. Handles https://host/account/library(.git) and
# git@host:account/library(.git).
origin="$(git -C "$here" remote get-url origin 2>/dev/null)" ||
{ echo "library has no 'origin' address; was it cloned with git?" >&2; exit 2; }
origin="${origin%.git}"
case "$origin" in
*://*) host="${origin%/*/*}/"; account="${origin%/*}"; account="${account##*/}" ;;
*:*) host="${origin%%:*}:"; account="${origin#*:}"; account="${account%%/*}" ;;
*) echo "Don't understand library's address: $origin" >&2; exit 2 ;;
esac
address_for() {
case "$1" in
*/*) echo "${host}$1.git" ;;
*) echo "${host}${account}/$1.git" ;;
esac
}
cloned=0; updated=0; current=0; skipped=0
[ "$dry_run" = 1 ] && echo "Dry run: nothing will change."
while IFS= read -r line || [ -n "$line" ]; do
line="${line%%#*}"
line="$(printf '%s' "$line" | tr -d '[:space:]')"
[ -z "$line" ] && continue
name="${line##*/}"
path="$dir/$name"
if [ "$path" = "$here" ]; then
continue # that's library itself
elif [ ! -e "$path" ]; then
if [ "$dry_run" = 1 ]; then
echo "would download $name"
else
git clone -q "$(address_for "$line")" "$path" &&
echo "downloaded $name" || { echo "FAILED $name (check the name and your access)"; skipped=$((skipped+1)); continue; }
fi
cloned=$((cloned+1))
elif [ ! -d "$path/.git" ]; then
echo "skipped $name ($path is there but isn't a git repo)"
skipped=$((skipped+1))
elif [ -n "$(git -C "$path" status --porcelain)" ]; then
echo "skipped $name (has unsaved changes; commit or put them aside first)"
skipped=$((skipped+1))
else
git -C "$path" fetch -q || { echo "skipped $name (couldn't reach it)"; skipped=$((skipped+1)); continue; }
if [ -z "$(git -C "$path" rev-parse --abbrev-ref --symbolic-full-name '@{u}' 2>/dev/null)" ]; then
echo "skipped $name (this branch isn't linked to one on GitHub)"
skipped=$((skipped+1))
elif [ "$(git -C "$path" rev-parse HEAD)" = "$(git -C "$path" rev-parse '@{u}')" ]; then
current=$((current+1))
elif git -C "$path" merge-base --is-ancestor HEAD '@{u}'; then
if [ "$dry_run" = 1 ]; then
echo "would update $name"
else
git -C "$path" merge -q --ff-only '@{u}' && echo "updated $name"
fi
updated=$((updated+1))
else
echo "skipped $name (has changes GitHub doesn't; push or sort them out first)"
skipped=$((skipped+1))
fi
fi
done < "$list"
if [ "$dry_run" = 1 ]; then
echo "Done: $cloned to download, $updated to update, $current already current, $skipped skipped."
else
echo "Done: $cloned downloaded, $updated updated, $current already current, $skipped skipped."
fi
[ "$skipped" = 0 ]
A few things worth knowing:
- It only fast-forwards. "Updating" means adding the new saved changes from GitHub on top of yours. If both sides have changes the other doesn't, it stops and leaves that repo for you, rather than trying to combine them.
- It only touches the branch you're on. If you left a repo on a test branch, that's the branch it updates.
- Its exit code says whether anything was skipped (0 for a clean run, 1 if something was skipped), so you can use it in another script if you like.
- A small device can take one folder of a repo, rather than the whole thing, with
Git's sparse checkout. Ask your assistant to add a
repo:folderform torepos.txtif you need it.
A check that catches secrets¶
Git remembers everything, so a password saved by mistake stays in the history even after you delete it. A Git "hook" is a small script Git runs at certain moments. This one runs just before each commit, looks at the lines being added, and stops the commit if any of them look like a password, key or token.
#!/bin/sh
# Stop a commit that looks like it holds a password, key or token.
# Save as .git/hooks/pre-commit in a repo and make it executable.
# A false alarm? Commit with: git commit --no-verify
pattern='(password|passwd|secret|api[_-]?key|token)[[:space:]]*[:=][[:space:]]*[^[:space:]]{8,}|BEGIN [A-Z ]*PRIVATE KEY'
if git diff --cached -U0 --no-color | grep '^+' | grep -Ei "$pattern" >/dev/null; then
echo "Stopped: this change looks like it contains a password, key or token." >&2
echo "Move it into an ignored settings file, then commit again." >&2
echo "If it's a false alarm, commit with --no-verify." >&2
exit 1
fi
To use it, save it as .git/hooks/pre-commit in a repo and make it executable with
chmod +x .git/hooks/pre-commit. Hooks live inside your own copy of the repo and
don't travel with it, so add it on each computer. Your assistant can add a line to
sync.sh that copies it into each repo it downloads.
It's a safety net, not a guarantee. It looks for common patterns, so leave the values
empty in config.example files rather than writing a pretend password, and keep the
habit of having the assistant check old files before they go into Git for the first
time. If something does slip through, change that password or key straight away,
since the old one stays in the history.
A contents table that keeps itself up to date¶
Once a repo has a dozen or so folders, the table in its top README.md that lists
them becomes a nuisance: two changes that each add a row collide, and someone has to
sort it out. The fix is to stop editing the table by hand.
- Each folder's
README.mdcarries its own one-line description in a hidden comment, right under its heading:<!-- contents: What it is, in one line -->. - The top
README.mdhas two markers,<!-- contents:start -->and<!-- contents:end -->, where the table goes. - A small script reads the descriptions and rebuilds the table between the markers.
- A GitHub Action runs that script. On every pull request it only checks that each
folder has a description. After every change to
mainit rebuilds the table and saves it as its own commit.
Because the Action adds a commit of its own after each change to main, pull before
you start work, or let sync.sh do it.
The Action, saved as .github/workflows/contents-table.yml:
name: contents-table
on:
pull_request:
push:
branches: [main]
workflow_dispatch:
concurrency:
group: contents-table-${{ github.ref }}
cancel-in-progress: false
jobs:
check:
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v4
- name: Every folder has a contents line
run: python3 contents-table/build_contents.py --check
rebuild:
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v4
- name: Rebuild the table
run: python3 contents-table/build_contents.py
- name: Commit it if it changed
run: |
if git diff --quiet -- README.md; then
echo "Table already up to date."
exit 0
fi
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add README.md
git commit -m "Contents: rebuild the table from the folder READMEs"
git push
The script, saved as contents-table/build_contents.py (that folder needs its own
README.md with a contents line too, like every other folder):
#!/usr/bin/env python3
"""Build the Contents table in the root README.md from the folder READMEs.
Each top-level folder's README.md carries its own one-line description in a
comment, usually right under its heading:
# my-project
<!-- contents: What it is, in one line -->
Use `<!-- contents: skip -->` for a folder that shouldn't be listed.
The table is written between `<!-- contents:start -->` and
`<!-- contents:end -->` in the root README.md, one row per folder, sorted by
folder name. Nothing else in the README is touched.
Usage:
build_contents.py rewrite the table if it changed
build_contents.py --dry-run show what would change, change nothing
build_contents.py --check only check every folder has a valid
description; change nothing
Options:
--repo PATH repo root (default: this script's repo)
Exit codes: 0 fine, 1 a folder is missing or has a bad description,
2 the root README has no start/end markers.
"""
import argparse
import difflib
import re
import sys
from pathlib import Path
START = "<!-- contents:start -->"
END = "<!-- contents:end -->"
MARKER = re.compile(r"^<!--\s*contents:\s*(.*?)\s*-->\s*$", re.M)
FENCE = re.compile(r"^(```|~~~).*?^\1[^\S\n]*$", re.M | re.S)
HEADER ="| Folder | What it is |\n|--------|------------|\n"
class Problem(Exception):
pass
def folders(repo):
"""Top-level folders, skipping hidden ones like .git and .github."""
return sorted(
(p for p in repo.iterdir() if p.is_dir() and not p.name.startswith(".")),
key=lambda p: p.name.lower(),
)
def description(folder):
"""The folder's description, None for skip. Raises Problem if invalid."""
readme = folder / "README.md"
if not readme.is_file():
raise Problem(f"{folder.name}/: no README.md")
# Examples inside ``` code blocks don't count.
text = FENCE.sub("", readme.read_text(encoding="utf-8"))
found = MARKER.findall(text)
if not found:
raise Problem(f"{folder.name}/README.md: no <!-- contents: ... --> line")
if len(found) > 1:
raise Problem(f"{folder.name}/README.md: more than one contents line")
text = found[0]
if text.lower() == "skip":
return None
if not text:
raise Problem(f"{folder.name}/README.md: contents line is empty")
if "|" in text:
raise Problem(f"{folder.name}/README.md: contents line has a '|', which breaks the table")
return text
def collect(repo):
rows, problems = [], []
for folder in folders(repo):
try:
text = description(folder)
except Problem as e:
problems.append(str(e))
continue
if text is not None:
rows.append(f"| [{folder.name}]({folder.name}/) | {text} |\n")
return rows, problems
def build(readme_text, rows):
"""Return readme_text with the table between the markers replaced."""
start = readme_text.find(START)
end = readme_text.find(END)
if start == -1 or end == -1 or end < start:
raise Problem(f"root README.md needs {START} and {END}, in that order")
head = readme_text[: start + len(START)]
tail = readme_text[end:]
return head + "\n" + HEADER + "".join(rows) + tail
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
mode = parser.add_mutually_exclusive_group()
mode.add_argument("--dry-run", action="store_true",
help="show what would change, change nothing")
mode.add_argument("--check", action="store_true",
help="only check the folder descriptions, change nothing")
parser.add_argument("--repo", type=Path,
default=Path(__file__).resolve().parent.parent,
help="repo root (default: this script's repo)")
args = parser.parse_args(argv)
repo = args.repo.resolve()
rows, problems = collect(repo)
if problems:
print("These folders need a description line:", file=sys.stderr)
for p in problems:
print(f" {p}", file=sys.stderr)
print("Add one under the heading, e.g. <!-- contents: What it is -->,"
" or <!-- contents: skip --> to leave it out.", file=sys.stderr)
return 1
if args.check:
print(f"All {len(rows)} listed folders have a description.")
return 0
readme = repo / "README.md"
old = readme.read_text(encoding="utf-8")
try:
new = build(old, rows)
except Problem as e:
print(e, file=sys.stderr)
return 2
if new == old:
print("Contents table is already up to date.")
return 0
diff = difflib.unified_diff(old.splitlines(keepends=True),
new.splitlines(keepends=True),
"README.md (now)", "README.md (rebuilt)")
if args.dry_run:
print("Dry run: would make this change to README.md:\n")
sys.stdout.writelines(diff)
return 0
readme.write_text(new, encoding="utf-8")
print(f"Rebuilt the Contents table: {len(rows)} folders.")
return 0
if __name__ == "__main__":
sys.exit(main())
Try it locally first with python3 contents-table/build_contents.py --dry-run, which
shows the new table without changing anything. If the Action's commit step fails with
a permission error, look in the repo's settings on GitHub under Actions, then General,
then Workflow permissions.
Checks on every change¶
Tests only help if something runs them. A GitHub Action can run them on every pull request, along with a secret scan and a check of every script, so a mistake shows up as a red cross on the pull request before it's merged, whoever opened it. Private repos get a monthly allowance of free minutes, which small checks like these stay well inside.
It finds tests by name, so keep them named the same way in every folder, like
tests/test-*.sh. Save this as .github/workflows/checks.yml:
# Runs the repo's checks on every pull request: every test, shellcheck on every
# script, and a secret scan of the pull request's commits.
name: checks
on:
pull_request:
permissions:
contents: read
jobs:
checks:
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install the tools
run: sudo apt-get update -qq && sudo apt-get install -y -qq shellcheck gitleaks
- name: Run every test
run: |
failed=0
while IFS= read -r t; do
echo "== $t"
bash "$t" < /dev/null || { echo "FAILED: $t"; failed=1; }
done < <(git ls-files '*tests/test-*.sh')
exit "$failed"
- name: Shellcheck every script
run: git ls-files -z '*.sh' | xargs -0 -r shellcheck
- name: Scan this pull request's commits for secrets
env:
BASE: ${{ github.event.pull_request.base.sha }}
run: gitleaks detect --source . --redact --no-banner --log-opts="$BASE..HEAD"
A few things worth knowing:
- Ask the assistant to wait for the checks before it hands a pull request over,
and to read the log when one fails.
gh pr checksshows where they stand, andgh run view --log-failedshows what went wrong. - A test can pass on your computer and fail there. The Action runs on a fresh computer, which may be missing a tool or have a stricter security setting. Read the log, fix the cause in the workflow with a comment saying why, and don't loosen the test to make it pass.
- Red doesn't stop a merge on its own. On a paid plan, branch protection can make the check required. On the free plan with a private repo, a red cross is your cue to look before you say "merge it".
- The first run may be red if older scripts have shellcheck warnings. Ask the assistant to fix them on a branch, or to check only the scripts each pull request changes.
- Notes that go straight to
mainskip it, which is fine for documents. To check those too, ask the assistant to add pushes tomainto the workflow.
Keeping shared rules the same¶
If most of your rules are the same in every repo, the copies drift: you improve one
and forget the others, and a rule quietly stops applying in one place. Linking every
repo to one shared file doesn't help much, because some sessions, cloud ones
especially, only read the repo's own CLAUDE.md. So keep the copies, and let a script
tell you when one has fallen behind.
check-rules.sh lives in the library repo next to sync.sh. It compares the shared
sections of each repo's CLAUDE.md with template/CLAUDE.md, heading by heading, and
names the repos that differ. Sections that belong to one repo, like its layout, are
left alone. It only reads, so it needs no dry run.
$ ./check-rules.sh
differs house (Git)
differs cooking (no CLAUDE.md)
Done: 2 repo(s) differ from the template.
#!/usr/bin/env bash
# check-rules.sh: compare the shared sections of each repo's CLAUDE.md with
# template/CLAUDE.md, and name the repos whose copy has fallen behind.
# Lives in the library repo next to sync.sh, and looks for the repos where
# sync.sh puts them. It only reads, so it has no dry run.
#
# ./check-rules.sh name the repos that differ
# ./check-rules.sh --diff show what's different too
#
# Works with the bash that ships with macOS.
set -u
# The "## " headings every repo shares, one per line. The rest of a repo's
# CLAUDE.md (its layout, for one) is its own.
shared='Scripts
Secrets and personal details
Git'
here="$(cd "$(dirname "$0")" && pwd)"
dir="$(dirname "$here")"
template="$here/template/CLAUDE.md"
show_diff=0
[ "${1:-}" = "--diff" ] && show_diff=1
[ -f "$template" ] || { echo "Can't find $template" >&2; exit 2; }
# Print one "## Heading" section of a file, up to the next "## " heading,
# without the blank lines at its end.
section() {
awk -v want="## $2" '
$0 == want { inside = 1; print; next }
inside && /^## / { exit }
inside && /^[[:space:]]*$/ { gap = gap "\n"; next } # hold blank lines
inside { printf "%s", gap; gap = ""; print }
' "$1"
}
tmp="$(mktemp -d)" || exit 2
trap 'rm -rf "$tmp"' EXIT
differ=0
while IFS= read -r line || [ -n "$line" ]; do
line="${line%%#*}"
line="$(printf '%s' "$line" | tr -d '[:space:]')"
[ -z "$line" ] && continue
name="${line##*/}"
rules="$dir/$name/CLAUDE.md"
[ -d "$dir/$name/.git" ] || continue # not downloaded here
if [ ! -f "$rules" ]; then
echo "differs $name (no CLAUDE.md)"; differ=$((differ+1)); continue
fi
off=""
while IFS= read -r heading; do
section "$template" "$heading" > "$tmp/want"
section "$rules" "$heading" > "$tmp/have"
if ! cmp -s "$tmp/want" "$tmp/have"; then
off="$off, $heading"
[ "$show_diff" = 1 ] && diff -u "$tmp/want" "$tmp/have" \
| sed "1s|.*|--- template/CLAUDE.md|;2s|.*|+++ $name/CLAUDE.md|"
fi
done <<< "$shared"
if [ -n "$off" ]; then
echo "differs $name (${off#, })"; differ=$((differ+1))
fi
done < "$here/repos.txt"
echo "Done: $differ repo(s) differ from the template."
[ "$differ" = 0 ]
Run it after sync.sh, and again whenever you change the template. When a repo
differs, ./check-rules.sh --diff shows the lines, and the fix is usually "copy
the template's section into that repo", which can go straight to main like any note.
Two more habits keep the rules working:
- Keep must-follow rules in the main
CLAUDE.mdat the top of the repo. Rules files in subfolders, or rules that only apply to some files, are skipped by some cloud sessions. - Keep each
CLAUDE.mdshort. Anthropic suggests under 200 lines. Long files get followed less closely.
A ping when the assistant needs you¶
When you work with the assistant in a terminal, it often stops to ask before a command, or finishes while you're in another room. A Claude Code "hook" (a small script Claude Code runs at certain moments) can send a notification to your phone when that happens. This one uses ntfy, a free notification app that you can also run on your own server.
Save the script as ~/.claude/hooks/notify.sh and make it executable with
chmod +x ~/.claude/hooks/notify.sh. It needs curl, and uses jq for the message
if it's installed:
#!/usr/bin/env bash
# notify.sh: a Claude Code hook that sends a notification to your phone, through
# ntfy, when a session is waiting for you. The address it sends to is in
# notify.env next to it, which lives outside every repo.
set -u
NTFY_URL=""
conf="$(dirname "$0")/notify.env"
# shellcheck source=/dev/null
[ -r "$conf" ] && . "$conf"
[ -n "$NTFY_URL" ] || exit 0 # not set up yet: stay quiet
message="$(jq -r '.message // empty' 2>/dev/null)"
curl -fsS -m 10 -o /dev/null -H "Title: Claude Code" \
--data-binary "${message:-Claude Code is waiting for you.}" "$NTFY_URL" || true
exit 0
Put your topic's address in ~/.claude/hooks/notify.env, as one line like
NTFY_URL=https://ntfy.sh/<a-long-random-topic-name>, and subscribe to the same topic
in the ntfy app on your phone. On the public server anyone who guesses the topic name
can read it, so make the name long and random, or run your own server.
Then tell Claude Code about it in ~/.claude/settings.json, which covers every repo
on that computer:
{
"hooks": {
"Notification": [
{
"matcher": "permission_prompt|idle_prompt",
"hooks": [
{ "type": "command", "command": "$HOME/.claude/hooks/notify.sh", "timeout": 15 }
]
}
]
}
}
permission_prompt is "waiting for your yes", and idle_prompt is "finished, and
you haven't typed anything for about a minute". To try it without Claude Code, run
echo '{"message":"Test"}' | ~/.claude/hooks/notify.sh and look at your phone.
Hooks only run where Claude Code reads your settings, so this works for sessions in your terminal, not for cloud sessions.
A copy of every repo at home¶
GitHub keeps your repos safe from a broken computer, but not from everything: a force
push that overwrites main, a repo deleted by mistake, or a locked account. A copy on
a machine at home covers those. mirror-repos.sh keeps one of every repo in
repos.txt, with every branch, tag and old version, and it never deletes anything:
a branch deleted on GitHub stays in the copy, and so does the old version of a branch
that was overwritten.
#!/usr/bin/env bash
# mirror-repos.sh: keep a full copy, with every branch, tag and old version, of
# each repo in repos.txt. Lives in the library repo next to sync.sh; run it
# every night on a machine at home.
#
# ./mirror-repos.sh --dry-run show what it would do, change nothing
# ./mirror-repos.sh make the missing copies, update the rest
#
# Copies go in ~/repo-mirror, or the folder in MIRROR_DIR. It never deletes:
# a branch deleted on GitHub stays in the copy, and so does the old version of
# a branch that was overwritten. Works with the bash that ships with macOS.
set -u
here="$(cd "$(dirname "$0")" && pwd)"
dest="${MIRROR_DIR:-$HOME/repo-mirror}"
dry_run=0
[ "${1:-}" = "--dry-run" ] && dry_run=1
# The same address logic as sync.sh: from library's own address.
origin="$(git -C "$here" remote get-url origin 2>/dev/null)" ||
{ echo "library has no 'origin' address; was it cloned with git?" >&2; exit 2; }
origin="${origin%.git}"
case "$origin" in
*://*) host="${origin%/*/*}/"; account="${origin%/*}"; account="${account##*/}" ;;
*:*) host="${origin%%:*}:"; account="${origin#*:}"; account="${account%%/*}" ;;
*) echo "Don't understand library's address: $origin" >&2; exit 2 ;;
esac
# A new copy: a bare repo that fetches every branch and tag as they are, never
# prunes, and keeps every old version (reflogs and loose objects never expire).
new_copy() {
git init -q --bare "$1" &&
git -C "$1" config remote.origin.url "$2" &&
git -C "$1" config remote.origin.fetch '+refs/heads/*:refs/heads/*' &&
git -C "$1" config --add remote.origin.fetch '+refs/tags/*:refs/tags/*' &&
git -C "$1" config remote.origin.prune false &&
git -C "$1" config core.logAllRefUpdates always &&
git -C "$1" config gc.reflogExpire never &&
git -C "$1" config gc.reflogExpireUnreachable never &&
git -C "$1" config gc.pruneExpire never
}
[ "$dry_run" = 1 ] && echo "Dry run: nothing will change."
made=0; updated=0; failed=0
while IFS= read -r line || [ -n "$line" ]; do
line="${line%%#*}"
line="$(printf '%s' "$line" | tr -d '[:space:]')"
[ -z "$line" ] && continue
case "$line" in */*) full="$line" ;; *) full="$account/$line" ;; esac
copy="$dest/$full.git"
if [ -d "$copy" ]; then
kind=updated
else
kind=copied
if [ "$dry_run" = 0 ] && ! { mkdir -p "$(dirname "$copy")" && new_copy "$copy" "${host}$full.git"; }; then
echo "FAILED $full (couldn't make $copy)"; failed=$((failed+1)); continue
fi
fi
if [ "$dry_run" = 1 ]; then
[ "$kind" = copied ] && echo "would copy $full" || echo "would update $full"
elif git -C "$copy" fetch -q origin; then
printf '%-16s%s\n' "$kind" "$full"
else
echo "FAILED $full (check the name and this machine's access)"
[ "$kind" = copied ] && rm -rf "$copy" # don't keep an empty copy
failed=$((failed+1)); continue
fi
if [ "$kind" = copied ]; then made=$((made+1)); else updated=$((updated+1)); fi
done < "$here/repos.txt"
echo "Done: $made new, $updated updated, $failed failed."
[ "$failed" = 0 ]
Set it up on a machine at home that's always on, like a small server or a NAS that can run scripts:
- Clone
librarythere. - Give that machine read-only access to GitHub. Make a fine-grained token on GitHub
with read-only access to Contents, for the repos it should copy. Sign
in with it using
gh auth login, then rungh auth setup-gitso Git uses it. The token stays in the GitHub tool's own settings, outside every repo. These tokens expire, so put a reminder in your calendar. - Run
./mirror-repos.sh --dry-run, then./mirror-repos.shonce yourself. - Run it every night with cron (
crontab -e), adding a line like30 3 * * * $HOME/src/library/mirror-repos.sh >> $HOME/repo-mirror.log 2>&1. - Put the copies' folder somewhere your normal backups already cover.
A fine-grained token covers one account or one organization. If repos.txt mixes
them, ask the assistant to adapt the script to use one token for each.
To see what main used to be, run
git -C ~/repo-mirror/<account>/<repo>.git reflog main. Each line is a version it
had, newest first. Putting an old version back on GitHub is itself a force push, so
ask the assistant to walk you through it, and run that step yourself.
Adding your own¶
Anything else you automate gets the same treatment as the pieces above:
- A dry run first, and you run the first real one yourself.
- A README that says what it does, when it runs, and how to stop it.
- Settings in an ignored file, with a
config.examplenext to it. - On a branch, for you to look over before it's merged.
- Anything on a schedule gets a review date. After a month, ask whether it still earns its keep, and switch it off if not.
← Back: Working with Git · Next: The technical edition → · Back to the start