git-ark 0.3.0

A write-only backup vault that fronts your own git host
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
use anyhow::{anyhow, Result};
use std::io::Write;
use std::path::Path;

use crate::clock::Clock;
use crate::config::Config;
use crate::store::ObjectStore;
use crate::{crypto, git};

pub fn repo_name(repos_root: &Path, repo: &Path) -> Result<String> {
    let rel = repo.strip_prefix(repos_root).map_err(|_| {
        anyhow!(
            "repo {} not under root {}",
            repo.display(),
            repos_root.display()
        )
    })?;
    let s = rel.to_string_lossy();
    Ok(s.strip_suffix(".git").unwrap_or(&s).to_string())
}

pub fn latest_key(prefix: &str, name: &str) -> String {
    format!("{prefix}/{name}/latest.age")
}

pub fn history_key(prefix: &str, name: &str, ts: &str) -> String {
    format!("{prefix}/{name}/history/{ts}.age")
}

/// Parse post-receive stdin (`<old-sha> <new-sha> <refname>` per line) into the
/// list of updated ref names.
pub fn parse_receive_refs(input: &str) -> Vec<String> {
    input
        .lines()
        .filter_map(|l| l.split_whitespace().nth(2).map(str::to_string))
        .collect()
}

/// Does a ref name (e.g. `refs/heads/main`) match a `backup_refs` pattern?
/// `**`/`*` match everything; a full ref matches exactly; a bare branch name
/// (`main`) matches `refs/heads/<name>`.
pub fn ref_matches(refname: &str, pattern: &str) -> bool {
    pattern == "**"
        || pattern == "*"
        || pattern == refname
        || format!("refs/heads/{pattern}") == refname
}

/// Should a push that updated `updated_refs` trigger the S3 backup, given the
/// configured `backup_refs`?
pub fn should_back_up(updated_refs: &[String], backup_refs: &[String]) -> bool {
    updated_refs
        .iter()
        .any(|r| backup_refs.iter().any(|p| ref_matches(r, p)))
}

/// Which refs the S3 bundle should contain, derived from the effective
/// `backup_refs`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BundleSelection {
    /// Bundle every ref (`git bundle create - --all`) — the `**`/`*` case.
    All,
    /// Bundle exactly these concrete, existing refs (may be empty → no-op).
    Refs(Vec<String>),
}

/// Resolve the effective `backup_refs` into a concrete bundle selection so the
/// S3 bundle contains ONLY the selected branches (a non-selected branch is then
/// genuinely absent from S3).
///
/// A `**`/`*` pattern means "everything" → [`BundleSelection::All`]. Otherwise
/// each pattern is resolved to a concrete, existing ref: a full `refs/…` is used
/// as-is when it exists; a bare name (`main`) becomes `refs/heads/<name>` when it
/// exists; patterns whose ref doesn't exist are dropped. Order is preserved and
/// duplicates removed. An empty result is a no-op (the caller handles it).
pub fn resolve_bundle_refs(repo: &Path, backup_refs: &[String]) -> Result<BundleSelection> {
    if backup_refs.iter().any(|p| p == "**" || p == "*") {
        return Ok(BundleSelection::All);
    }
    let mut refs: Vec<String> = Vec::new();
    for pattern in backup_refs {
        let candidate = if pattern.starts_with("refs/") {
            pattern.clone()
        } else {
            format!("refs/heads/{pattern}")
        };
        if git::ref_exists(repo, &candidate) && !refs.contains(&candidate) {
            refs.push(candidate);
        }
    }
    Ok(BundleSelection::Refs(refs))
}

/// Build the per-ref summary block printed to the hook's stdout after a push —
/// one line per pushed ref (in receive order) showing which durable tiers it
/// reached.
///
/// Every pushed ref lands on the host (NAS). A ref additionally shows "encrypted
/// S3" when it matches the effective `backup_refs`, and "GitHub" when its branch
/// is among the mirror's configured branches. `✓` marks a ref that went beyond
/// NAS; `○` marks a NAS-only ref. The ref column is left-aligned and padded to
/// the longest pushed ref name (min 14).
pub fn summarize_refs(
    updated: &[String],
    effective_backup_refs: &[String],
    github_branches: &[String],
) -> String {
    // Display name: drop `refs/heads/`; other refs (e.g. tags) are shown whole.
    let display = |r: &str| r.strip_prefix("refs/heads/").unwrap_or(r).to_string();
    let names: Vec<String> = updated.iter().map(|r| display(r)).collect();
    let width = names
        .iter()
        .map(|n| n.chars().count())
        .max()
        .unwrap_or(0)
        .max(14);

    let mut lines = Vec::with_capacity(updated.len());
    for (r, name) in updated.iter().zip(&names) {
        let s3 = effective_backup_refs.iter().any(|p| ref_matches(r, p));
        let gh = github_branches
            .iter()
            .any(|b| r.strip_prefix("refs/heads/") == Some(b.as_str()) || b == r);

        let mut tiers = vec!["NAS"];
        if s3 {
            tiers.push("encrypted S3");
        }
        if gh {
            tiers.push("GitHub");
        }
        let mark = if s3 || gh { "✓" } else { "○" };
        let tier_str = if tiers.len() == 1 {
            "NAS only".to_string()
        } else {
            tiers.join(" + ")
        };
        lines.push(format!("{mark} {name:<width$}  {tier_str}"));
    }
    lines.join("\n")
}

/// A host-level disk line for the push summary. `✓` when healthy, `⚠ … low`
/// when the caller judged it low. Informational — never affects the backup.
pub fn disk_line(usage: crate::disk::DiskUsage, low: bool) -> String {
    let free = human_bytes(usage.free_bytes);
    let pct = usage.percent_free();
    if low {
        format!("⚠ disk           {free} free ({pct}%) — running low")
    } else {
        format!("✓ disk           {free} free ({pct}%)")
    }
}

/// Human-readable bytes, binary units, one decimal (e.g. "1.8 GB", "56.0 TB").
/// `pub(crate)` so `hostcmd::format_status_row` can reuse it for `status`'s
/// free-size column instead of re-implementing the same formatting.
pub(crate) fn human_bytes(n: u64) -> String {
    const U: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
    let mut v = n as f64;
    let mut i = 0;
    while v >= 1024.0 && i < U.len() - 1 {
        v /= 1024.0;
        i += 1;
    }
    format!("{v:.1} {}", U[i])
}

pub fn run_backup(
    cfg: &Config,
    repo: &Path,
    backup_refs: &[String],
    store: &dyn ObjectStore,
    clock: &dyn Clock,
    out: &mut dyn Write,
) -> Result<()> {
    let name = repo_name(&cfg.repos_root, repo)?;

    // Bundle only the selected refs (not the whole repo) so a non-selected
    // branch stays off S3 entirely.
    let selection = resolve_bundle_refs(repo, backup_refs)?;

    writeln!(out, "bundling {name} …").ok();
    out.flush().ok();
    let bundle = match &selection {
        BundleSelection::All => git::bundle_all(repo)?,
        BundleSelection::Refs(refs) => {
            if refs.is_empty() {
                // Nothing selected exists — a no-op. run_backup is only reached
                // when a pushed ref matched, so this is defensive.
                writeln!(out, "○ nothing to back up — no selected refs exist").ok();
                out.flush().ok();
                return Ok(());
            }
            git::bundle_refs(repo, refs)?
        }
    };

    writeln!(out, "encrypting {} bytes …", bundle.len()).ok();
    out.flush().ok();
    let ciphertext = crypto::encrypt(&cfg.age_recipient, &bundle)?;

    let ts = clock.timestamp();
    let hist = history_key(&cfg.s3.prefix, &name, &ts);
    let latest = latest_key(&cfg.s3.prefix, &name);
    // History first, then latest — latest is the "known-good newest" pointer.
    store.put(&hist, &ciphertext)?;
    store.put(&latest, &ciphertext)?;

    writeln!(
        out,
        "✓ backup → s3://{}/{}  +  {}",
        cfg.s3.bucket, latest, hist
    )
    .ok();
    out.flush().ok();
    Ok(())
}

#[cfg(test)]
mod key_tests {
    use super::*;
    use std::path::Path;
    #[test]
    fn repo_name_strips_root_and_git() {
        let n = repo_name(
            Path::new("/srv/repos"),
            Path::new("/srv/repos/team/app.git"),
        )
        .unwrap();
        assert_eq!(n, "team/app");
    }
    #[test]
    fn key_layout() {
        assert_eq!(latest_key("git-ark", "app"), "git-ark/app/latest.age");
        assert_eq!(
            history_key("git-ark", "app", "2026-01-02T03-04-05Z"),
            "git-ark/app/history/2026-01-02T03-04-05Z.age"
        );
    }
}

#[cfg(test)]
mod gate_tests {
    use super::*;

    fn defaults() -> Vec<String> {
        vec![
            "refs/heads/main".to_string(),
            "refs/heads/master".to_string(),
        ]
    }
    fn refs(items: &[&str]) -> Vec<String> {
        items.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn parses_receive_ref_lines() {
        let input = "aaa bbb refs/heads/main\nccc ddd refs/heads/feature\n";
        assert_eq!(
            parse_receive_refs(input),
            refs(&["refs/heads/main", "refs/heads/feature"])
        );
    }

    #[test]
    fn ref_matching_rules() {
        assert!(ref_matches("refs/heads/main", "main"));
        assert!(ref_matches("refs/heads/main", "refs/heads/main"));
        assert!(ref_matches("refs/heads/anything", "**"));
        assert!(!ref_matches("refs/heads/feature", "main"));
        assert!(!ref_matches("refs/tags/v1", "main"));
    }

    #[test]
    fn gates_on_main_master_by_default() {
        assert!(should_back_up(&refs(&["refs/heads/main"]), &defaults()));
        assert!(should_back_up(&refs(&["refs/heads/master"]), &defaults()));
        assert!(!should_back_up(&refs(&["refs/heads/feature"]), &defaults()));
        // A push touching several refs including main is gated in.
        assert!(should_back_up(
            &refs(&["refs/heads/feature", "refs/heads/main"]),
            &defaults()
        ));
    }

    #[test]
    fn double_star_backs_up_every_ref() {
        let all = vec!["**".to_string()];
        assert!(should_back_up(&refs(&["refs/heads/feature"]), &all));
        assert!(should_back_up(&refs(&["refs/tags/v1"]), &all));
    }
}

#[cfg(test)]
mod bundle_selection_tests {
    use super::*;
    use std::process::Command;

    /// A repo with a `main` and a `feature` branch.
    fn repo_with_branches(dir: &Path) {
        let g = |args: &[&str]| {
            assert!(
                Command::new("git")
                    .args(args)
                    .current_dir(dir)
                    .status()
                    .unwrap()
                    .success(),
                "git {args:?}"
            );
        };
        g(&["init", "-q", "-b", "main"]);
        g(&["config", "user.email", "t@t"]);
        g(&["config", "user.name", "t"]);
        std::fs::write(dir.join("a.txt"), "a").unwrap();
        g(&["add", "."]);
        g(&["commit", "-qm", "a"]);
        g(&["branch", "feature"]);
    }

    fn strs(items: &[&str]) -> Vec<String> {
        items.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn double_star_or_star_selects_all() {
        let d = tempfile::tempdir().unwrap();
        repo_with_branches(d.path());
        assert_eq!(
            resolve_bundle_refs(d.path(), &strs(&["**"])).unwrap(),
            BundleSelection::All
        );
        assert_eq!(
            resolve_bundle_refs(d.path(), &strs(&["*"])).unwrap(),
            BundleSelection::All
        );
        // A `**` anywhere in the list wins.
        assert_eq!(
            resolve_bundle_refs(d.path(), &strs(&["main", "**"])).unwrap(),
            BundleSelection::All
        );
    }

    #[test]
    fn resolves_bare_and_full_refs_that_exist() {
        let d = tempfile::tempdir().unwrap();
        repo_with_branches(d.path());
        let sel = resolve_bundle_refs(d.path(), &strs(&["main", "refs/heads/feature"])).unwrap();
        assert_eq!(
            sel,
            BundleSelection::Refs(strs(&["refs/heads/main", "refs/heads/feature"]))
        );
    }

    #[test]
    fn drops_nonexistent_and_dedups() {
        let d = tempfile::tempdir().unwrap();
        repo_with_branches(d.path());
        // `main` exists (listed twice → deduped); `nope` and `refs/heads/ghost`
        // don't exist and are dropped.
        let sel = resolve_bundle_refs(
            d.path(),
            &strs(&["main", "nope", "refs/heads/ghost", "refs/heads/main"]),
        )
        .unwrap();
        assert_eq!(sel, BundleSelection::Refs(strs(&["refs/heads/main"])));
    }

    #[test]
    fn empty_when_nothing_selected_exists() {
        let d = tempfile::tempdir().unwrap();
        repo_with_branches(d.path());
        let sel = resolve_bundle_refs(d.path(), &strs(&["ghost", "refs/tags/none"])).unwrap();
        assert_eq!(sel, BundleSelection::Refs(Vec::new()));
    }
}

#[cfg(test)]
mod disk_line_tests {
    use super::*;
    use crate::disk::DiskUsage;

    #[test]
    fn healthy_disk_line_uses_check_mark() {
        let u = DiskUsage {
            total_bytes: 56_000_000_000_000,
            free_bytes: 55_000_000_000_000,
        };
        let line = disk_line(u, false);
        assert!(line.starts_with("✓ disk"), "got: {line}");
        assert!(line.contains("free"));
    }

    #[test]
    fn low_disk_line_warns() {
        let u = DiskUsage {
            total_bytes: 20_000_000_000,
            free_bytes: 1_000_000_000,
        };
        let line = disk_line(u, true);
        assert!(line.starts_with("⚠ disk"), "got: {line}");
        assert!(line.to_lowercase().contains("low"));
    }

    #[test]
    fn human_bytes_formats_binary_units() {
        assert_eq!(human_bytes(1_500_000_000), "1.4 GB");
    }
}

#[cfg(test)]
mod summary_tests {
    use super::*;

    fn strs(items: &[&str]) -> Vec<String> {
        items.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn three_tier_example() {
        let updated = strs(&[
            "refs/heads/main",
            "refs/heads/big-feature",
            "refs/heads/scratch",
        ]);
        let backup_refs = strs(&["main", "big-feature"]);
        let github = strs(&["main"]);
        let out = summarize_refs(&updated, &backup_refs, &github);
        // Column padded to the longest name (`big-feature`, 11) but min 14, then
        // two spaces before the tier list.
        let expected = "\
✓ main            NAS + encrypted S3 + GitHub
✓ big-feature     NAS + encrypted S3
○ scratch         NAS only";
        assert_eq!(out, expected);
    }

    #[test]
    fn branch_only_push_is_all_nas_only() {
        // Nothing matches backup_refs or github → every ref is ○ NAS only.
        let updated = strs(&["refs/heads/scratch", "refs/heads/wip"]);
        let out = summarize_refs(&updated, &strs(&["main"]), &[]);
        let expected = "\
○ scratch         NAS only
○ wip             NAS only";
        assert_eq!(out, expected);
    }

    #[test]
    fn double_star_marks_every_ref_s3() {
        let updated = strs(&["refs/heads/main", "refs/tags/v1"]);
        let out = summarize_refs(&updated, &strs(&["**"]), &[]);
        // Tags keep their full name; both go to S3 under `**`.
        assert!(out.contains("✓ main"));
        assert!(out.lines().all(|l| l.starts_with('✓')));
        assert!(out.contains("refs/tags/v1"));
        assert!(out.lines().all(|l| l.contains("NAS + encrypted S3")));
    }
}