girt 0.6.1

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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::SystemTime;
use std::{fs, io};

use super::RetentionPolicy;
use crate::{ObjectId, Repository};

/// Acquires caller-owned exclusion of every writer and dependent reader.
///
/// The returned guard must hold its isolation boundary until dropped. It must exclude external
/// Git processes, not just girt callers, and readers that may still need an old loose object. It
/// must also account for repositories using this object store as an alternate. Girt cannot
/// discover or enforce those external relationships. Return an error if the boundary cannot be
/// established. A lock observed only by girt is insufficient.
pub trait MaintenanceIsolation {
    /// Guard whose lifetime holds the repository-wide exclusion boundary.
    type Guard;

    /// Acquires the boundary before any maintenance scan or mutation.
    fn acquire(&mut self, repository: &Repository) -> io::Result<Self::Guard>;
}

/// Loose object identities removed from the primary object store.
#[derive(Clone, Debug, Default)]
pub struct PruneReport {
    /// Successfully removed identities, in path order.
    pub deleted: Vec<ObjectId>,
}

/// Why a loose-object sweep stopped.
#[derive(Debug, thiserror::Error)]
pub enum PruneCause {
    /// A pinned pack or index changed before this mutation boundary.
    #[error(transparent)]
    PackChanged(Box<crate::ObjectReadError>),
    /// Caller isolation could not be established.
    #[error("maintenance isolation unavailable")]
    Isolation(#[source] io::Error),
    /// A root, object or storage scan was incomplete.
    #[error("retention scan incomplete: {0}")]
    Incomplete(String),
    /// The observed roots or loose-object generation changed before mutation.
    #[error("maintenance generation changed")]
    Changed,
    /// Cancellation was observed; inspect the report for completed deletions.
    #[error("maintenance cancelled")]
    Cancelled,
    /// A filesystem operation failed; inspect the report for completed deletions.
    #[error("maintenance I/O")]
    Io(#[source] io::Error),
}

/// A failed sweep retains the known successful deletion prefix and any uncertain unlink.
#[derive(Debug, thiserror::Error)]
#[error("loose object pruning failed")]
pub struct PruneFailure {
    /// The reason the sweep stopped.
    #[source]
    pub cause: PruneCause,
    /// Successfully removed objects before the failure.
    pub report: PruneReport,
    /// Identity at a failed unlink boundary; inspect storage before retrying.
    pub uncertain: Option<ObjectId>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub(super) struct Candidate {
    id: ObjectId,
    path: PathBuf,
    len: u64,
    modified: SystemTime,
}

impl Repository {
    /// Removes old unreachable loose objects from this repository's primary store.
    ///
    /// The caller supplies a repository-wide isolation boundary through `isolation`. Inside that
    /// boundary this operation inventories primary loose entries. If none are older than
    /// `recent_cutoff`, it returns an empty report without validating object history. Otherwise it
    /// builds one complete plan, inventories loose entries twice, and revalidates root-bearing
    /// metadata and storage fingerprints before the first deletion. All reflog candidates are
    /// retained regardless of the policy's expiry cutoffs; this operation does not expire reflogs,
    /// repack, or remove packs or alternate storage. It removes only regular primary loose files
    /// older than `recent_cutoff` whose identities are outside the complete reachable closure. This
    /// does not depend on R32's additive publication for object availability. Files exactly at the
    /// cutoff are retained; Git's inclusive prune expiry can remove them ([tracking
    /// issue](https://github.com/joshka/girt/issues/109)).
    ///
    /// A complete scan or matching generations cannot exclude an external Git process. The
    /// isolation implementation must exclude those processes and old readers until the returned
    /// guard is dropped; otherwise acquisition must refuse. Cancellation or I/O after a deletion
    /// returns the known completed prefix in [`PruneFailure::report`]. An unlink error identifies
    /// its uncertain target in [`PruneFailure::uncertain`]. A retry must rescan from scratch.
    /// Deletion is not crash atomic; interruption can leave any prefix removed. Since no reachable
    /// object is removed, directory synchronization is unnecessary for object availability.
    ///
    /// # Errors
    ///
    /// Isolation refusal, incomplete scans, changed observations, cancellation and I/O are
    /// reported with the known completed prefix. Before the first deletion it is empty.
    pub fn prune_unreachable_loose<I: MaintenanceIsolation>(
        &self,
        isolation: &mut I,
        policy: &RetentionPolicy,
        cancel: &AtomicBool,
    ) -> Result<PruneReport, PruneFailure> {
        let _guard = isolation
            .acquire(self)
            .map_err(|error| failure(PruneCause::Isolation(error), PruneReport::default()))?;
        self.prune_unreachable_loose_exclusive(policy, cancel)
    }

    pub(super) fn prune_unreachable_loose_exclusive(
        &self,
        policy: &RetentionPolicy,
        cancel: &AtomicBool,
    ) -> Result<PruneReport, PruneFailure> {
        let report = self.prune_unreachable_loose_at(
            policy,
            cancel,
            || {},
            || {},
            |path| fs::remove_file(path),
        )?;
        self.finish_prune(report)
    }

    fn finish_prune(&self, report: PruneReport) -> Result<PruneReport, PruneFailure> {
        if !report.deleted.is_empty() {
            // This derived-data cleanup needs no pack freshness proof: removing a commit-graph
            // cannot remove an object. It can name pruned commits; Git rebuilds it when needed.
            let info = self.object_dir().join("info");
            let remove = |result: io::Result<()>| match result {
                Err(error) if error.kind() != io::ErrorKind::NotFound => {
                    Err(failure(PruneCause::Io(error), report.clone()))
                }
                _ => Ok(()),
            };
            remove(fs::remove_file(info.join("commit-graph")))?;
            remove(fs::remove_dir_all(info.join("commit-graphs")))?;
        }
        Ok(report)
    }

    // Checkpoints keep generation changes and post-deletion cancellation deterministic in tests.
    fn prune_unreachable_loose_at(
        &self,
        policy: &RetentionPolicy,
        cancel: &AtomicBool,
        after_plan: impl FnOnce(),
        after_delete: impl FnMut(),
        remove: impl FnMut(&std::path::Path) -> io::Result<()>,
    ) -> Result<PruneReport, PruneFailure> {
        self.prune_planned_at(
            policy,
            cancel,
            None,
            (|| {}, after_plan, after_delete),
            remove,
        )
    }

    #[cfg(unix)]
    pub(super) fn prune_planned(
        &self,
        policy: &RetentionPolicy,
        cancel: &AtomicBool,
        session: &super::inputs::Session,
    ) -> Result<PruneReport, PruneFailure> {
        let report = self.prune_planned_at(
            policy,
            cancel,
            Some(session),
            (|| {}, || {}, || {}),
            |path| fs::remove_file(path),
        )?;
        self.finish_prune(report)
    }

    fn prune_planned_at(
        &self,
        policy: &RetentionPolicy,
        cancel: &AtomicBool,
        session: Option<&super::inputs::Session>,
        checkpoints: (impl FnOnce(), impl FnOnce(), impl FnMut()),
        mut remove: impl FnMut(&std::path::Path) -> io::Result<()>,
    ) -> Result<PruneReport, PruneFailure> {
        let _headers = crate::pack::HeaderScope::new();
        let (before_plan, after_plan, mut after_delete) = checkpoints;
        let mut report = PruneReport::default();
        check(cancel, &report)?;
        // Repository::open refreshes shallow roots and configuration that this handle may have
        // observed before the isolation boundary was acquired.
        let current = Repository::open(self.git_dir())
            .map_err(|error| failure(PruneCause::Incomplete(error.to_string()), report.clone()))?;
        if current.object_dir() != self.object_dir()
            || current.object_format() != self.object_format()
        {
            return Err(failure(PruneCause::Changed, report));
        }
        let observed = candidates(&current, policy, cancel)
            .map_err(|cause| failure(cause, PruneReport::default()))?;
        before_plan();
        if session.is_none() && observed.is_empty() {
            // Caller isolation holds through this complete inventory. No unlink is possible,
            // so unvisited history need not supply deletion evidence.
            check(cancel, &report)?;
            return Ok(report);
        }
        let owned = if session.is_none() {
            Some(
                super::inputs::Session::new(&current, policy, cancel).map_err(|reason| {
                    failure(
                        if cancel.load(Ordering::Relaxed) {
                            PruneCause::Cancelled
                        } else {
                            PruneCause::Incomplete(reason)
                        },
                        report.clone(),
                    )
                })?,
            )
        } else {
            None
        };
        let session = session.or(owned.as_ref()).expect("retention session");
        let first = &session.plan;
        after_plan();
        check(cancel, &report)?;
        let refreshed = Repository::open(self.git_dir())
            .map_err(|error| failure(PruneCause::Incomplete(error.to_string()), report.clone()))?;
        if refreshed.object_dir() != current.object_dir()
            || refreshed.object_format() != current.object_format()
            || !refreshed
                .shallow_roots()
                .iter()
                .eq(current.shallow_roots().iter())
        {
            return Err(failure(PruneCause::Changed, report));
        }
        session
            .plan
            .check_packs_unchanged(cancel)
            .map_err(|error| failure(PruneCause::PackChanged(Box::new(error)), report.clone()))?;
        session.validate(&refreshed, policy, cancel).map_err(|_| {
            failure(
                if cancel.load(Ordering::Relaxed) {
                    PruneCause::Cancelled
                } else {
                    PruneCause::Changed
                },
                report.clone(),
            )
        })?;
        let repeated = candidates(&refreshed, policy, cancel)
            .map_err(|cause| failure(cause, report.clone()))?;
        if observed != repeated {
            return Err(failure(PruneCause::Changed, report));
        }
        for candidate in observed {
            check(cancel, &report)?;
            if first.reachable.contains(&candidate.id)
                || first.protected_objects.contains(&candidate.id)
            {
                continue;
            }
            let metadata = fs::symlink_metadata(&candidate.path)
                .map_err(|error| failure(PruneCause::Io(error), report.clone()))?;
            let modified = metadata
                .modified()
                .map_err(|error| failure(PruneCause::Io(error), report.clone()))?;
            if !metadata.is_file()
                || metadata.len() != candidate.len
                || modified != candidate.modified
            {
                return Err(failure(PruneCause::Changed, report));
            }
            session
                .plan
                .check_packs_unchanged(cancel)
                .map_err(|error| {
                    failure(PruneCause::PackChanged(Box::new(error)), report.clone())
                })?;
            remove(&candidate.path).map_err(|error| PruneFailure {
                cause: PruneCause::Io(error),
                report: report.clone(),
                uncertain: Some(candidate.id),
            })?;
            report.deleted.push(candidate.id);
            after_delete();
        }
        Ok(report)
    }
}

pub(super) fn candidates(
    repository: &Repository,
    policy: &RetentionPolicy,
    cancel: &AtomicBool,
) -> Result<Vec<Candidate>, PruneCause> {
    let mut result = Vec::new();
    let mut visited = 0usize;
    for entry in fs::read_dir(repository.object_dir()).map_err(PruneCause::Io)? {
        check_count(&mut visited, policy.max_entries)?;
        check_cancel(cancel)?;
        let entry = entry.map_err(PruneCause::Io)?;
        let name = entry.file_name();
        if name == "pack" || name == "info" {
            continue;
        }
        let Some(prefix) = name.to_str() else {
            return Err(PruneCause::Incomplete("non-UTF-8 object fanout".into()));
        };
        if prefix.len() != 2 || !prefix.bytes().all(|byte| byte.is_ascii_hexdigit()) {
            return Err(PruneCause::Incomplete(
                "unknown object directory entry".into(),
            ));
        }
        if !fs::symlink_metadata(entry.path())
            .map_err(PruneCause::Io)?
            .is_dir()
        {
            return Err(PruneCause::Incomplete("non-directory object fanout".into()));
        }
        for file in fs::read_dir(entry.path()).map_err(PruneCause::Io)? {
            check_count(&mut visited, policy.max_entries)?;
            check_cancel(cancel)?;
            let file = file.map_err(PruneCause::Io)?;
            let path = file.path();
            let metadata = fs::symlink_metadata(&path).map_err(PruneCause::Io)?;
            if !metadata.is_file() {
                return Err(PruneCause::Incomplete("non-file loose object".into()));
            }
            let Some(suffix) = file.file_name().to_str().map(str::to_owned) else {
                return Err(PruneCause::Incomplete("non-UTF-8 loose object".into()));
            };
            let id = ObjectId::from_hex(repository.object_format(), &format!("{prefix}{suffix}"))
                .map_err(|error| PruneCause::Incomplete(error.to_string()))?;
            let modified = metadata.modified().map_err(PruneCause::Io)?;
            if modified < policy.recent_cutoff {
                result.push(Candidate {
                    id,
                    path,
                    len: metadata.len(),
                    modified,
                });
            }
        }
    }
    result.sort_by(|a, b| a.path.cmp(&b.path));
    Ok(result)
}

fn check_count(visited: &mut usize, limit: usize) -> Result<(), PruneCause> {
    *visited += 1;
    if *visited > limit {
        Err(PruneCause::Incomplete("loose object entry limit".into()))
    } else {
        Ok(())
    }
}

fn check_cancel(cancel: &AtomicBool) -> Result<(), PruneCause> {
    if cancel.load(Ordering::Relaxed) {
        Err(PruneCause::Cancelled)
    } else {
        Ok(())
    }
}

fn check(cancel: &AtomicBool, report: &PruneReport) -> Result<(), PruneFailure> {
    check_cancel(cancel).map_err(|cause| {
        failure(
            cause,
            PruneReport {
                deleted: report.deleted.clone(),
            },
        )
    })
}

fn failure(cause: PruneCause, report: PruneReport) -> PruneFailure {
    PruneFailure {
        cause,
        report,
        uncertain: None,
    }
}

#[cfg(test)]
mod tests {
    use std::io::Write;
    use std::path::Path;
    use std::process::{Command, Stdio};
    use std::sync::atomic::Ordering;
    use std::time::Duration;

    use 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"))
            .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()
    }

    fn fixture() -> (tempfile::TempDir, Repository, RetentionPolicy) {
        let root = tempfile::tempdir().unwrap();
        git(root.path(), &["init", "--bare", "--template=", "."], b"");
        let repo = Repository::open(root.path()).unwrap();
        let policy = RetentionPolicy {
            recent_cutoff: SystemTime::now() + Duration::from_secs(60),
            ..Default::default()
        };
        (root, repo, policy)
    }

    #[test]
    fn new_root_between_scans_refuses_before_deletion() {
        let (root, repo, policy) = fixture();
        let id = git(root.path(), &["hash-object", "-w", "--stdin"], b"candidate");
        let cancel = AtomicBool::new(false);
        let result = repo.prune_unreachable_loose_at(
            &policy,
            &cancel,
            || {
                git(root.path(), &["update-ref", "refs/tags/blob", &id], b"");
            },
            || {},
            |path| fs::remove_file(path),
        );
        let error = result.unwrap_err();
        assert!(matches!(error.cause, PruneCause::Changed));
        assert!(error.report.deleted.is_empty());
        assert_eq!(git(root.path(), &["cat-file", "-t", &id], b""), "blob");
    }

    #[test]
    fn new_loose_root_between_inventory_and_plan_refuses_before_deletion() {
        let (root, repo, policy) = fixture();
        let old = git(
            root.path(),
            &["hash-object", "-w", "--stdin"],
            b"old candidate",
        );
        let cancel = AtomicBool::new(false);
        let result = repo.prune_planned_at(
            &policy,
            &cancel,
            None,
            (
                || {
                    let added = git(root.path(), &["hash-object", "-w", "--stdin"], b"new root");
                    git(root.path(), &["update-ref", "refs/tags/added", &added], b"");
                },
                || {},
                || {},
            ),
            |path| fs::remove_file(path),
        );
        let error = result.unwrap_err();
        assert!(matches!(error.cause, PruneCause::Changed));
        assert!(error.report.deleted.is_empty());
        assert_eq!(
            git(root.path(), &["cat-file", "blob", "refs/tags/added"], b""),
            "new root"
        );
        assert_eq!(
            git(root.path(), &["cat-file", "blob", &old], b""),
            "old candidate"
        );
    }

    #[test]
    fn cancellation_after_first_unlink_reports_partial_prefix() {
        let (root, repo, policy) = fixture();
        let first = git(root.path(), &["hash-object", "-w", "--stdin"], b"first");
        let second = git(root.path(), &["hash-object", "-w", "--stdin"], b"second");
        let cancel = AtomicBool::new(false);
        let error = repo
            .prune_unreachable_loose_at(
                &policy,
                &cancel,
                || {},
                || cancel.store(true, Ordering::Relaxed),
                |path| fs::remove_file(path),
            )
            .unwrap_err();
        assert!(matches!(error.cause, PruneCause::Cancelled));
        assert_eq!(error.report.deleted.len(), 1);
        let deleted = error.report.deleted[0].to_string();
        assert!(deleted == first || deleted == second);
        let survivor = if deleted == first { second } else { first };
        assert_eq!(
            git(root.path(), &["cat-file", "-t", &survivor], b""),
            "blob"
        );
    }

    #[test]
    fn unlink_fault_reports_known_prefix_and_uncertain_target() {
        let (root, repo, policy) = fixture();
        let first = git(root.path(), &["hash-object", "-w", "--stdin"], b"first");
        let second = git(root.path(), &["hash-object", "-w", "--stdin"], b"second");
        let mut calls = 0;
        let error = repo
            .prune_unreachable_loose_at(
                &policy,
                &AtomicBool::new(false),
                || {},
                || {},
                |path| {
                    calls += 1;
                    if calls == 2 {
                        Err(io::ErrorKind::PermissionDenied.into())
                    } else {
                        fs::remove_file(path)
                    }
                },
            )
            .unwrap_err();
        assert!(matches!(error.cause, PruneCause::Io(_)));
        assert_eq!(error.report.deleted.len(), 1);
        let deleted = error.report.deleted[0].to_string();
        let uncertain = error.uncertain.unwrap().to_string();
        assert!(deleted == first || deleted == second);
        assert!(uncertain == first || uncertain == second);
        assert_ne!(deleted, uncertain);
        assert_eq!(
            git(root.path(), &["cat-file", "-t", &uncertain], b""),
            "blob"
        );
    }
    #[cfg(unix)]
    #[rstest::rstest]
    #[case::truncate(true)]
    #[case::overwrite(false)]
    fn warmed_pack_change_refuses_prune(#[case] truncate: bool) {
        let (_root, repo, policy, pack) = super::super::walk_tests::header_fixture();
        let error = repo
            .prune_unreachable_loose_at(
                &policy,
                &AtomicBool::new(false),
                || super::super::walk_tests::change_pack(&pack, truncate),
                || {},
                |_| panic!("must not unlink"),
            )
            .unwrap_err();
        assert!(matches!(&error.cause, PruneCause::PackChanged(source)
            if matches!(source.as_ref(), crate::ObjectReadError::PackChanged { path } if path == &pack)));
        assert!(error.report.deleted.is_empty());
    }
}