Skip to content

Commit 88a4553

Browse files
committed
Build production-ready GitHub backup service
1 parent cc3ae3a commit 88a4553

28 files changed

Lines changed: 3140 additions & 1 deletion

‎.dockerignore‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
.git
2+
.github
3+
.venv
4+
__pycache__
5+
*.pyc
6+
backups
7+
build
8+
dist
9+
tests

‎.github/workflows/ci.yml‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
name: CI
2+
3+
on:
4+
push:
5+
branches: [main]
6+
pull_request:
7+
8+
permissions:
9+
contents: read
10+
11+
jobs:
12+
test:
13+
runs-on: ubuntu-latest
14+
strategy:
15+
fail-fast: false
16+
matrix:
17+
python-version: ["3.11", "3.12", "3.13"]
18+
steps:
19+
- uses: actions/checkout@v4
20+
- uses: actions/setup-python@v5
21+
with:
22+
python-version: ${{ matrix.python-version }}
23+
cache: pip
24+
- run: python -m pip install '.[dev,s3]'
25+
- run: ruff check .
26+
- run: mypy src
27+
- run: pytest --cov=github_backup --cov-report=term-missing --cov-fail-under=80

‎.gitignore‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
__pycache__/
2+
*.py[cod]
3+
*.egg-info/
4+
.coverage
5+
.mypy_cache/
6+
.pytest_cache/
7+
.ruff_cache/
8+
.venv/
9+
build/
10+
dist/
11+
htmlcov/
12+
github-backup.toml
13+
backups/

‎Dockerfile‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
FROM python:3.13-slim-bookworm AS builder
2+
3+
ENV PIP_DISABLE_PIP_VERSION_CHECK=1 \
4+
PIP_NO_CACHE_DIR=1
5+
6+
WORKDIR /build
7+
COPY pyproject.toml README.md LICENSE ./
8+
COPY src ./src
9+
RUN python -m pip wheel --wheel-dir /wheels '.[s3]'
10+
11+
FROM python:3.13-slim-bookworm
12+
13+
ENV PYTHONDONTWRITEBYTECODE=1 \
14+
PYTHONUNBUFFERED=1 \
15+
GITHUB_BACKUP_DESTINATION=/backups
16+
17+
RUN apt-get update \
18+
&& apt-get install --no-install-recommends -y ca-certificates git \
19+
&& rm -rf /var/lib/apt/lists/* \
20+
&& groupadd --gid 10001 ghbackup \
21+
&& useradd --uid 10001 --gid ghbackup --create-home ghbackup
22+
23+
COPY --from=builder /wheels /wheels
24+
RUN python -m pip install --no-cache-dir /wheels/* && rm -rf /wheels
25+
26+
USER ghbackup
27+
WORKDIR /home/ghbackup
28+
ENTRYPOINT ["github-backup"]
29+
CMD ["run"]

‎README.md‎

Lines changed: 209 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,210 @@
11
# github-backup
2-
A simple backup-project for all public and private Github repositories
2+
3+
`github-backup` discovers every repository visible to an authenticated GitHub user and backs up its complete Git object database and refs. It also backs up the authenticated user's public and secret gists.
4+
5+
The defaults match the safest low-overhead setup:
6+
7+
- local disk or a mounted NAS;
8+
- every repository the token can access (owned, collaborator, and organization membership);
9+
- incremental bare mirrors;
10+
- public and secret gists included.
11+
12+
The user can select filesystem or S3-compatible storage, repository scope, and incremental or immutable snapshot mode at execution time or in TOML.
13+
14+
## What is backed up
15+
16+
- all Git refs and objects exposed by each repository's clone endpoint;
17+
- owned, collaborator, and organization repositories allowed by the token;
18+
- public and private repositories;
19+
- public and secret gists belonging to the authenticated user;
20+
- resource metadata and a detailed manifest for every run.
21+
22+
GitHub issues, pull-request discussions, releases, Actions artifacts, packages, wikis, and Git LFS payloads are separate services and are not included in version `0.1`. Normal Git commits, branches, tags, notes, and pull-request refs exposed by the clone endpoint are included. Submodule pointers are included; the referenced repository is backed up when the token can discover it independently.
23+
24+
## Requirements
25+
26+
- Python 3.11 or later;
27+
- Git 2.30 or later;
28+
- a GitHub token;
29+
- `boto3` only when using S3-compatible storage.
30+
31+
For GitHub.com, a classic personal access token normally needs `repo` for private repositories and `gist` for secret gists. Fine-grained tokens must be granted access to the intended repositories with read access to repository metadata and contents. Organization SAML/SSO policies may require the token to be authorized separately.
32+
33+
Never put the token in the TOML file or a command argument. The application reads it from an environment variable, injects it into Git only for the matching HTTPS host, and does not save it in remotes, logs, metadata, or manifests.
34+
35+
## Installation
36+
37+
```bash
38+
python3 -m venv .venv
39+
. .venv/bin/activate
40+
python -m pip install .
41+
```
42+
43+
For S3 support use `python -m pip install '.[s3]'`. For development use `python -m pip install '.[dev,s3]'`.
44+
45+
## Quick start
46+
47+
Export the token through your shell, secret manager, or workload secret injection:
48+
49+
```bash
50+
export GITHUB_TOKEN='github_pat_...'
51+
```
52+
53+
Preview what the token can access and run the default incremental backup:
54+
55+
```bash
56+
github-backup list
57+
github-backup run --destination /mnt/backups/github
58+
```
59+
60+
Back up only repositories owned by the authenticated user:
61+
62+
```bash
63+
github-backup run --scope owned --destination /mnt/backups/github
64+
```
65+
66+
Back up selected organizations as an immutable point-in-time snapshot:
67+
68+
```bash
69+
github-backup run \
70+
--scope organizations \
71+
--organization example-inc \
72+
--organization second-org \
73+
--mode snapshot \
74+
--destination /mnt/backups/github
75+
```
76+
77+
Upload to AWS S3:
78+
79+
```bash
80+
github-backup run \
81+
--storage s3 \
82+
--s3-bucket company-backups \
83+
--s3-prefix github/engineering \
84+
--cache-dir /var/cache/github-backup
85+
```
86+
87+
For MinIO, Ceph, Backblaze B2, or another S3-compatible service, also pass `--s3-endpoint-url`. Standard AWS credential environment variables, profiles, instance roles, and workload identities are handled by the AWS SDK.
88+
89+
## Configuration
90+
91+
Copy [`github-backup.example.toml`](github-backup.example.toml) to `github-backup.toml`, edit it, and run:
92+
93+
```bash
94+
github-backup --config github-backup.toml run
95+
```
96+
97+
When `./github-backup.toml` exists, it is loaded automatically. Command-line flags override TOML. The following environment variables override basic settings: `GITHUB_BACKUP_DESTINATION`, `GITHUB_BACKUP_STORAGE`, `GITHUB_BACKUP_SCOPE`, `GITHUB_BACKUP_MODE`, and `GITHUB_BACKUP_CACHE_DIR`.
98+
99+
The token variable name itself is configurable with `github.token_env`; its default is `GITHUB_TOKEN`.
100+
101+
### Runtime choices
102+
103+
| Decision | Values | Default | Tradeoff |
104+
|---|---|---|---|
105+
| Storage | `filesystem`, `s3` | `filesystem` | Filesystem/NAS mirrors update in place efficiently. S3 uses a persistent local mirror cache and uploads self-contained artifacts. |
106+
| Scope | `accessible`, `owned`, `organizations` | `accessible` | Accessible is comprehensive. Owned is narrower. Organizations requires one or more `--organization` values. |
107+
| Mode | `incremental`, `snapshot` | `incremental` | Incremental keeps the latest mirror and prunes refs deleted upstream. Snapshot creates immutable point-in-time artifacts and uses more storage. |
108+
| Gists | `--gists`, `--no-gists` | included | Secret gists require suitable token access. |
109+
110+
On S3, Git cannot update a remote bundle in place. A persistent local bare-mirror cache still makes GitHub downloads incremental. The application only packages and uploads a new `latest` artifact when refs changed or the remote object is absent. Snapshot mode uploads an immutable artifact on every run.
111+
112+
## Storage layout
113+
114+
Filesystem and NAS destinations use this layout:
115+
116+
```text
117+
backups/
118+
├── manifests/
119+
│ ├── latest.json
120+
│ └── 20261021T120000.000000Z.json
121+
├── metadata/
122+
│ ├── repos/OWNER/REPOSITORY.json
123+
│ └── gists/GIST_ID.json
124+
├── mirrors/
125+
│ ├── repos/OWNER/REPOSITORY.git/
126+
│ └── gists/GIST_ID.git/
127+
└── snapshots/ # snapshot mode only
128+
└── RUN_ID/.../*.git.bundle
129+
```
130+
131+
Empty repositories have no refs and cannot be represented by a Git bundle, so snapshot mode stores them as `.empty.tar.gz` archives. Writes to JSON and local snapshot artifacts use same-filesystem atomic replacement. A process lock prevents overlapping runs against the same destination/cache. Stale local locks are recovered when their process no longer exists.
132+
133+
Every completed run writes an immutable manifest and replaces `latest.json`. A partial per-resource failure returns exit code `2`, records the failure in the manifest, and leaves successful backups usable. Configuration, authentication, discovery, or storage setup failures return exit code `1`.
134+
135+
## Restore
136+
137+
Restore from an incremental filesystem mirror:
138+
139+
```bash
140+
git clone /mnt/backups/github/mirrors/repos/OWNER/REPOSITORY.git restored-repository
141+
```
142+
143+
Restore all refs into an existing empty remote:
144+
145+
```bash
146+
git clone --mirror /mnt/backups/github/mirrors/repos/OWNER/REPOSITORY.git recovered.git
147+
git -C recovered.git push --mirror https://github.com/OWNER/NEW-REPOSITORY.git
148+
```
149+
150+
Restore from a snapshot bundle:
151+
152+
```bash
153+
git clone /mnt/backups/github/snapshots/RUN_ID/repos/OWNER/REPOSITORY.git.bundle restored-repository
154+
```
155+
156+
For S3, download the selected `.bundle` first and use the same command. Extract an `.empty.tar.gz` archive directly when restoring an empty repository. Always test restores periodically; a successful upload is not a substitute for a restore drill.
157+
158+
## Scheduling
159+
160+
Use an external scheduler so credentials remain under the platform's secret-management policy. A systemd service can execute:
161+
162+
```ini
163+
[Service]
164+
Type=oneshot
165+
EnvironmentFile=/etc/github-backup/environment
166+
ExecStart=/opt/github-backup/.venv/bin/github-backup --config /etc/github-backup/config.toml run
167+
User=github-backup
168+
Group=github-backup
169+
PrivateTmp=true
170+
NoNewPrivileges=true
171+
```
172+
173+
Run it from a systemd timer, Kubernetes CronJob, CI scheduler, or equivalent. Do not place the token directly in a crontab command.
174+
175+
## Container
176+
177+
```bash
178+
docker build -t github-backup:local .
179+
docker run --rm \
180+
-e GITHUB_TOKEN \
181+
-v /mnt/backups/github:/backups \
182+
github-backup:local run --destination /backups
183+
```
184+
185+
The image runs as an unprivileged user. Ensure the mounted directory is writable by UID/GID `10001` or adapt ownership to your container platform.
186+
187+
## Operational behavior
188+
189+
- GitHub API calls are paginated and serialized to reduce secondary-rate-limit pressure.
190+
- `Retry-After` and primary rate-limit reset headers are honored; transient API failures use bounded retries.
191+
- Git transfers run in a bounded worker pool. Four workers is the default; lower it on a slow NAS or constrained GitHub Enterprise Server.
192+
- Initial clones are written to a temporary sibling and atomically renamed only after Git succeeds.
193+
- Existing backups are verified as bare repositories before update.
194+
- Deleted upstream refs are pruned in incremental mode. Use snapshots when you must retain deleted branches or tags.
195+
- S3 uploads use the AWS SDK's adaptive retries and optional server-side encryption/storage-class settings.
196+
- Human-readable logs are the default; `--json-logs` emits one JSON object per line.
197+
198+
## Development
199+
200+
```bash
201+
python -m unittest discover -s tests -v
202+
ruff check .
203+
mypy src
204+
```
205+
206+
The integration tests create real local repositories and exercise initial mirror creation, incremental updates, bundle verification, manifest writing, and credential non-persistence.
207+
208+
## License
209+
210+
GNU General Public License v3.0. See [`LICENSE`](LICENSE).

‎github-backup.example.toml‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
[backup]
2+
# The defaults are filesystem, every repository accessible to the token,
3+
# incremental mirrors, and authenticated-user gists.
4+
storage = "filesystem" # "filesystem" or "s3"
5+
destination = "/mnt/backups/github" # local disk or mounted NAS
6+
cache_dir = "~/.cache/github-backup" # required as working storage for S3
7+
scope = "accessible" # "accessible", "owned", or "organizations"
8+
organizations = [] # required when scope = "organizations"
9+
mode = "incremental" # "incremental" or "snapshot"
10+
include_gists = true
11+
workers = 4
12+
git_timeout_seconds = 3600
13+
lock_timeout_seconds = 0
14+
15+
[github]
16+
api_url = "https://api.github.com"
17+
api_version = "2022-11-28"
18+
token_env = "GITHUB_TOKEN"
19+
timeout_seconds = 30
20+
max_retries = 5
21+
22+
[s3]
23+
bucket = ""
24+
prefix = "github-backup"
25+
# endpoint_url = "https://s3.example.com"
26+
# region = "eu-central-1"
27+
# storage_class = "STANDARD_IA"
28+
# server_side_encryption = "AES256"

‎pyproject.toml‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
[build-system]
2+
requires = ["hatchling>=1.25"]
3+
build-backend = "hatchling.build"
4+
5+
[project]
6+
name = "github-backup"
7+
version = "0.1.0"
8+
description = "Production-oriented backups for GitHub repositories and gists"
9+
readme = "README.md"
10+
requires-python = ">=3.11"
11+
license = { file = "LICENSE" }
12+
authors = [{ name = "github-backup contributors" }]
13+
classifiers = [
14+
"Development Status :: 3 - Alpha",
15+
"Environment :: Console",
16+
"License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
17+
"Programming Language :: Python :: 3",
18+
"Programming Language :: Python :: 3.11",
19+
"Programming Language :: Python :: 3.12",
20+
"Programming Language :: Python :: 3.13",
21+
"Topic :: System :: Archiving :: Backup",
22+
]
23+
dependencies = []
24+
25+
[project.optional-dependencies]
26+
s3 = ["boto3>=1.34,<2"]
27+
dev = [
28+
"mypy>=1.11,<2",
29+
"pytest>=8.3,<9",
30+
"pytest-cov>=5,<7",
31+
"ruff>=0.7,<1",
32+
"types-boto3[s3]>=1.34,<2",
33+
]
34+
35+
[project.scripts]
36+
github-backup = "github_backup.cli:main"
37+
38+
[tool.hatch.build.targets.wheel]
39+
packages = ["src/github_backup"]
40+
41+
[tool.pytest.ini_options]
42+
addopts = "-ra --strict-markers --strict-config"
43+
testpaths = ["tests"]
44+
45+
[tool.ruff]
46+
line-length = 100
47+
target-version = "py311"
48+
49+
[tool.ruff.lint]
50+
select = ["E", "F", "I", "UP", "B", "SIM", "RUF"]
51+
52+
[tool.mypy]
53+
python_version = "3.11"
54+
strict = true
55+
packages = ["github_backup"]

‎src/github_backup/__init__.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
"""Back up GitHub repositories and gists."""
2+
3+
__version__ = "0.1.0"

‎src/github_backup/__main__.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
from github_backup.cli import main
2+
3+
if __name__ == "__main__":
4+
main()

0 commit comments

Comments
 (0)