girt 0.14.0

An incremental, idiomatic Rust implementation of Git
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
//! Storage-access bounds for the retention walk, observed on a Git-generated, deltified pack.
use std::io::Write;
use std::path::Path;
use std::process::{Command, Stdio};
use std::sync::atomic::AtomicBool;
use std::time::{Duration, SystemTime};

use crate::pack::counters;
use crate::retention::RetentionPolicy;
use crate::{PackLimits, Repository};

pub(super) fn git(root: &Path, args: &[&str], input: &[u8]) -> String {
    let mut child = Command::new("git")
        .current_dir(root)
        .env("GIT_CONFIG_NOSYSTEM", "1")
        .env("GIT_CONFIG_GLOBAL", root.join("absent-config"))
        .env("GIT_AUTHOR_NAME", "A")
        .env("GIT_AUTHOR_EMAIL", "a@example.com")
        .env("GIT_COMMITTER_NAME", "A")
        .env("GIT_COMMITTER_EMAIL", "a@example.com")
        .env("GIT_AUTHOR_DATE", "@1700000000 +0000")
        .env("GIT_COMMITTER_DATE", "@1700000000 +0000")
        .args(args)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    child.stdin.take().unwrap().write_all(input).unwrap();
    let output = child.wait_with_output().unwrap();
    assert!(
        output.status.success(),
        "git {args:?}: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    String::from_utf8(output.stdout).unwrap().trim().into()
}

/// History whose trees and blobs Git stores mostly as deltas, in a single pack.
fn deltified_history(root: &Path) -> usize {
    git(root, &["init", "-q", "--initial-branch=main", "."], b"");
    // Wide directories make each round's trees near copies of the last, so Git deltifies them.
    for round in 0..24 {
        for file in 0..60 {
            if round > 0 && file % 12 != round % 12 {
                continue;
            }
            let directory = root.join(format!("dir{}", file % 3));
            std::fs::create_dir_all(&directory).unwrap();
            let content: String = (0..40)
                .map(|line| format!("file {file} line {line} {}\n", (line == 0) as usize * round))
                .collect();
            std::fs::write(directory.join(format!("f{file}")), content).unwrap();
        }
        git(root, &["add", "-A"], b"");
        git(
            root,
            &[
                "-c",
                "commit.gpgsign=false",
                "commit",
                "-q",
                "-m",
                &format!("r{round}"),
            ],
            b"",
        );
    }
    git(
        root,
        &[
            "-c",
            "pack.threads=1",
            "repack",
            "-a",
            "-d",
            "-f",
            "-q",
            "--window=50",
            "--depth=50",
        ],
        b"",
    );
    git(root, &["prune-packed"], b"");
    // Without reflogs the strong and weak root sets are equal, so the plan walks once.
    std::fs::remove_dir_all(root.join(".git/logs")).unwrap();
    let count = git(root, &["count-objects", "-v"], b"");
    let line = count
        .lines()
        .find(|line| line.starts_with("in-pack: "))
        .unwrap();
    line["in-pack: ".len()..].parse().unwrap()
}

/// The walk inflates each pack entry at most once (bases come from the delta base cache) and
/// reads a typical entry's header and stream with a single positioned read.
#[test]
fn retention_walk_reads_each_entry_once() {
    let dir = tempfile::tempdir().unwrap();
    let entries = deltified_history(dir.path());
    let listing = git(
        dir.path(),
        &["verify-pack", "-v", &{
            let pack = std::fs::read_dir(dir.path().join(".git/objects/pack"))
                .unwrap()
                .map(|entry| entry.unwrap().path())
                .find(|path| path.extension().is_some_and(|ext| ext == "idx"))
                .unwrap();
            pack.to_string_lossy().into_owned()
        }],
        b"",
    );
    let deltas = |kind: &str| {
        listing
            .lines()
            .map(|line| line.split_whitespace().collect::<Vec<_>>())
            .filter(|fields| fields.len() == 7 && fields[1] == kind)
            .count()
    };
    assert!(
        deltas("tree") > 24 && deltas("blob") > 24,
        "fixture must deltify trees and blobs:\n{listing}"
    );
    let repository = Repository::open(dir.path()).unwrap();
    let policy = RetentionPolicy {
        recent_cutoff: Some(SystemTime::now() + Duration::from_secs(60)),
        packs: PackLimits::trusted(),
        ..RetentionPolicy::trusted()
    };
    counters::reset();
    let plan = repository.plan_retention(&policy, &AtomicBool::new(false));
    assert!(plan.is_complete(), "{:?}", plan.outcome);
    assert_eq!(plan.reachable.len(), entries);
    let expected: std::collections::BTreeSet<crate::ObjectId> =
        git(dir.path(), &["rev-list", "--objects", "--all"], b"")
            .lines()
            .map(|line| line.split_whitespace().next().unwrap().parse().unwrap())
            .collect();
    assert_eq!(plan.reachable, expected);
    let repeated: Vec<_> = counters::INFLATIONS.with(|map| {
        map.borrow()
            .iter()
            .filter(|(_, count)| **count > 1)
            .map(|(offset, count)| (*offset, *count))
            .collect()
    });
    assert!(
        repeated.is_empty(),
        "entries inflated more than once: {repeated:?}"
    );
    // Operation-scoped windows amortize entry-header reads; streams and pack opening add a few.
    let reads = counters::OS_READS.with(|reads| reads.get());
    assert!(
        reads < entries / 4,
        "{reads} system reads for {entries} entries"
    );
}

/// Independently generated pack with a reachable blob and an old loose pruning candidate.
#[cfg(unix)]
pub(super) fn header_fixture() -> (
    tempfile::TempDir,
    Repository,
    RetentionPolicy,
    std::path::PathBuf,
) {
    let root = tempfile::tempdir().unwrap();
    git(root.path(), &["init", "-q", "--template=", "."], b"");
    let id = git(
        root.path(),
        &["hash-object", "-w", "--stdin"],
        b"packed survivor",
    );
    git(root.path(), &["update-ref", "refs/tags/blob", &id], b"");
    git(root.path(), &["repack", "-adq"], b"");
    let orphan = git(
        root.path(),
        &["hash-object", "-w", "--stdin"],
        b"loose orphan",
    );
    let orphan_path = root
        .path()
        .join(".git/objects")
        .join(&orphan[..2])
        .join(&orphan[2..]);
    std::fs::File::open(orphan_path)
        .unwrap()
        .set_modified(std::time::UNIX_EPOCH)
        .unwrap();
    git(root.path(), &["fsck", "--full"], b"");
    let repo = Repository::open(root.path()).unwrap();
    let pack = std::fs::read_dir(repo.object_dir().join("pack"))
        .unwrap()
        .map(|entry| entry.unwrap().path())
        .find(|path| path.extension().is_some_and(|ext| ext == "pack"))
        .unwrap();
    let policy = RetentionPolicy {
        recent_cutoff: Some(std::time::UNIX_EPOCH + Duration::from_secs(1)),
        ..RetentionPolicy::trusted()
    };
    (root, repo, policy, pack)
}

#[cfg(unix)]
pub(super) fn change_pack(path: &Path, truncate: bool) {
    use std::io::{Seek, SeekFrom};
    use std::os::unix::fs::PermissionsExt;
    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o644)).unwrap();
    let mut file = std::fs::OpenOptions::new().write(true).open(path).unwrap();
    if truncate {
        file.set_len(12).unwrap();
    } else {
        // Change a warmed entry header without changing the file length.
        let original = std::fs::read(path).unwrap()[12];
        file.seek(SeekFrom::Start(12)).unwrap();
        file.write_all(&[original ^ 1]).unwrap();
    }
    // Deterministic even on filesystems with coarse timestamp precision.
    file.set_modified(std::time::UNIX_EPOCH + Duration::from_secs(42))
        .unwrap();
}

#[cfg(unix)]
use crate::pack_git;

#[cfg(unix)]
#[rstest::rstest]
#[case::sha1(crate::ObjectFormat::Sha1)]
#[case::sha256(crate::ObjectFormat::Sha256)]
fn damage_rescued_after_complete_plan_refuses_prune(#[case] format: crate::ObjectFormat) {
    let fixture = pack_git::Fixture::new(format, true, 4);
    let expected = fixture
        .records
        .iter()
        .find(|record| record.0 == fixture.ordinary)
        .unwrap();
    // Git skips writing already packed data; temporarily hide the index to generate a loose
    // rescue copy before taking the retention snapshot.
    let hidden = fixture.root.path().join("hidden.idx");
    std::fs::rename(&fixture.index_path, &hidden).unwrap();
    pack_git::git(
        fixture.root.path(),
        &["hash-object", "-w", "--stdin"],
        &expected.2,
    );
    std::fs::rename(hidden, &fixture.index_path).unwrap();
    let orphan = pack_git::git(
        fixture.root.path(),
        &["hash-object", "-w", "--stdin"],
        b"deletable orphan",
    );
    let mut index = std::fs::read(&fixture.index_path).unwrap();
    let width = format.digest_len();
    let count = fixture.records.len();
    let position = index[1032..1032 + count * width]
        .chunks_exact(width)
        .position(|name| name == fixture.ordinary.as_bytes())
        .unwrap();
    index[1032 + count * width + position * 4] ^= 1;
    let end = index.len() - width;
    let checksum = format.checksum(&index[..end]);
    index[end..].copy_from_slice(checksum.as_bytes());
    std::fs::remove_file(&fixture.index_path).unwrap();
    std::fs::write(&fixture.index_path, index).unwrap();
    let policy = RetentionPolicy {
        recent_cutoff: Some(SystemTime::now() + Duration::from_secs(60)),
        ..Default::default()
    };
    let cancel = AtomicBool::new(false);
    let session = super::inputs::Session::new(&fixture.repo, &policy, &cancel).unwrap();
    assert!(session.plan.is_complete());
    let store = session.plan.store.as_ref().unwrap();
    assert_eq!(
        store
            .read_with(fixture.ordinary, crate::ReadLimits::default())
            .unwrap()
            .unwrap()
            .data(),
        expected.2
    );
    let error = fixture
        .repo
        .prune_planned(&policy, &cancel, &session)
        .unwrap_err();
    assert!(
        matches!(error.cause, super::PruneCause::PackChanged(ref source)
        if matches!(source.as_ref(), crate::ObjectReadError::Path { source, .. } if source.kind() == std::io::ErrorKind::InvalidData))
    );
    assert!(error.report.deleted.is_empty());
    assert_eq!(
        pack_git::git(
            fixture.root.path(),
            &[
                "cat-file",
                "blob",
                std::str::from_utf8(&orphan).unwrap().trim()
            ],
            b""
        ),
        b"deletable orphan"
    );
    assert!(
        store
            .read_with(fixture.delta, crate::ReadLimits::default())
            .is_err()
    );
}

/// One commit, referenced by `refs/heads/main`, whose root tree has `entries`.
///
/// Trees are written with girt because Git refuses entries whose mode contradicts the target's
/// kind; `entries` can name the commit itself through `None`.
fn kind_fixture(
    root: &Path,
    entries: &[(crate::EntryMode, &str, Option<crate::ObjectId>)],
) -> (Repository, crate::ObjectId) {
    use crate::{Commit, CommitFields, Signature, Tree, TreeEntry};
    git(root, &["init", "-q"], b"");
    let repository = Repository::open(root).unwrap();
    let loose = repository.loose_objects();
    let format = repository.object_format();
    let person = Signature {
        name: b"A".to_vec(),
        email: b"a@example.com".to_vec(),
        seconds: 1_700_000_000,
        offset_minutes: 0,
    };
    let commit_for = |tree| {
        Commit::new(CommitFields {
            tree,
            parents: vec![],
            author: person.clone(),
            committer: person.clone(),
            extra_headers: vec![],
            message: b"kinds\n".to_vec(),
        })
        .unwrap()
    };
    // A commit cannot name a tree that names the commit, so self-references use a parent commit
    // whose tree is empty; the tip's tree then names that parent.
    let parent = commit_for(
        loose
            .write_tree(&Tree::new(format, vec![]).unwrap())
            .unwrap(),
    );
    let parent_id = loose.write_commit(&parent).unwrap();
    let tree = Tree::new(
        format,
        entries
            .iter()
            .map(|&(mode, name, id)| TreeEntry {
                mode,
                name: name.as_bytes().to_vec(),
                id: id.unwrap_or(parent_id),
            })
            .collect(),
    )
    .unwrap();
    let mut tip = commit_for(loose.write_tree(&tree).unwrap());
    if entries.iter().any(|entry| entry.2.is_none()) {
        tip = Commit::new(CommitFields {
            tree: tree.id(),
            parents: vec![parent_id],
            author: person.clone(),
            committer: person.clone(),
            extra_headers: vec![],
            message: b"kinds\n".to_vec(),
        })
        .unwrap();
    }
    let tip = loose.write_commit(&tip).unwrap();
    git(
        root,
        &["update-ref", "refs/heads/main", &tip.to_string()],
        b"",
    );
    (repository, parent_id)
}

fn plan_outcome(repository: &Repository) -> crate::retention::RetentionPlan {
    let policy = RetentionPolicy {
        recent_cutoff: Some(SystemTime::now() + Duration::from_secs(60)),
        ..RetentionPolicy::trusted()
    };
    repository.plan_retention(&policy, &AtomicBool::new(false))
}

/// Every edge checks its kind, including edges to an identity the walk already queued or read.
#[test]
fn retention_walk_checks_kinds_of_repeated_edges() {
    use crate::EntryMode::{Blob, Executable, Tree};
    use crate::retention::{RetentionError, RetentionOutcome};
    let blob = |root: &Path| -> crate::ObjectId {
        git(root, &["init", "-q"], b"");
        git(root, &["hash-object", "-w", "--stdin"], b"content\n")
            .parse()
            .unwrap()
    };

    // Repeated names of one blob, with either file mode, are one reachable object.
    let dir = tempfile::tempdir().unwrap();
    let id = blob(dir.path());
    let (repository, _) = kind_fixture(
        dir.path(),
        &[
            (Blob, "a", Some(id)),
            (Executable, "b", Some(id)),
            (Blob, "c", Some(id)),
        ],
    );
    let plan = plan_outcome(&repository);
    assert!(plan.is_complete(), "{:?}", plan.outcome);
    assert!(plan.reachable.contains(&id));
    assert_eq!(plan.reachable.len(), 3, "one commit, one tree and one blob");

    // A queued identity named again with another kind.
    let dir = tempfile::tempdir().unwrap();
    let id = blob(dir.path());
    let (repository, _) = kind_fixture(dir.path(), &[(Blob, "a", Some(id)), (Tree, "b", Some(id))]);
    assert!(matches!(
        plan_outcome(&repository).outcome,
        RetentionOutcome::Incomplete(RetentionError::ConflictingObjectKind(conflict)) if conflict == id
    ));

    // An edge asserting a tree whose target is read as a blob.
    let dir = tempfile::tempdir().unwrap();
    let id = blob(dir.path());
    let (repository, _) = kind_fixture(dir.path(), &[(Tree, "a", Some(id))]);
    assert!(matches!(
        plan_outcome(&repository).outcome,
        RetentionOutcome::Incomplete(RetentionError::WrongObjectKind(wrong)) if wrong == id
    ));

    // An edge naming, as a blob, a commit the walk has already read.
    let dir = tempfile::tempdir().unwrap();
    let (repository, parent) = kind_fixture(dir.path(), &[(Blob, "a", None)]);
    git(
        dir.path(),
        &["update-ref", "refs/heads/parent", &parent.to_string()],
        b"",
    );
    assert!(matches!(
        plan_outcome(&repository).outcome,
        RetentionOutcome::Incomplete(RetentionError::WrongObjectKind(wrong)) if wrong == parent
    ));
}