grit-lib 0.5.19

Core library for the grit Git implementation
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
//! Reflog listing, deletion, and expiry for one [`Repository`](crate::repo::Repository).

use std::ops::ControlFlow;
use std::path::Path;

use crate::error::{Error, Result};
use crate::reflog::{
    delete_reflog_entries, delete_reflog_entries_rechain, expire_reflog_git, list_reflog_refs,
    load_gc_reflog_expire_config, parse_reflog_expire_spec, parse_reflog_line_for_store,
    reflog_exists, reflog_identity_timestamp, reflog_path, MessageMatcher, ReflogEntry,
    ReflogExpireParams, ReflogExpireResult,
};
use crate::refs::resolve_ref_dwim;
use crate::refs::store::RefName;
use crate::repo::Repository;

/// Options for [`RepositoryReflogs::expire`].
#[derive(Debug, Clone)]
pub struct ExpireOptions {
    /// Current time as Unix seconds (never read from the system clock inside the library).
    pub now: i64,
    /// Explicit reachable expiry (`--expire`); `None` uses merged `gc.reflogExpire` config.
    pub expire: Option<String>,
    /// Explicit unreachable expiry (`--expire-unreachable`); `None` uses gc config.
    pub expire_unreachable: Option<String>,
    /// When true, process every ref under `refs/` that exists (Git `--all`); otherwise only refs with reflog files.
    pub all: bool,
    /// When true, report what would be pruned without rewriting reflog files.
    pub dry_run: bool,
}

/// Per-ref prune count from [`RepositoryReflogs::expire`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RefExpireResult {
    /// Full ref name (for example `refs/heads/main` or `HEAD`).
    pub ref_name: String,
    /// Entries removed (or that would be removed when [`ExpireOptions::dry_run`] is set).
    pub pruned: usize,
}

/// Summary returned by [`RepositoryReflogs::expire`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReflogExpireOutcome {
    /// Total reflog entries removed across all processed refs.
    pub entries_pruned: usize,
    /// Mirrors [`ExpireOptions::dry_run`].
    pub dry_run: bool,
    /// One row per processed ref, in sorted ref-name order.
    pub refs: Vec<RefExpireResult>,
}

/// One reflog line with its newest-first index (`0` is the latest entry).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IndexedReflogEntry {
    /// Index in newest-first order (`ref@{{index}}`).
    pub index: usize,
    /// Parsed reflog fields.
    pub entry: ReflogEntry,
}

/// Filters for [`RepositoryReflogs::query`].
#[derive(Debug, Clone, Default)]
pub struct ReflogQuery {
    /// Maximum matching entries to return (newest first).
    pub limit: Option<usize>,
    /// Exclude entries with identity timestamp strictly before this Unix second.
    pub since: Option<i64>,
    /// Exclude entries with identity timestamp strictly after this Unix second.
    pub until: Option<i64>,
    /// Optional message substring filter.
    pub grep: Option<MessageMatcher>,
    /// Wall-clock anchor passed by the caller (not read from the system clock here).
    pub now: i64,
}

/// One page of reflog query results.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReflogPage {
    /// Matching entries in newest-first order with global reflog indices.
    pub entries: Vec<IndexedReflogEntry>,
    /// `true` when scanning stopped before the oldest entry (typically because `limit` was reached).
    pub truncated: bool,
}

/// Reflog read/write helpers scoped to an open repository.
#[derive(Debug, Copy, Clone)]
pub struct RepositoryReflogs<'repo> {
    repo: &'repo Repository,
}

impl<'repo> RepositoryReflogs<'repo> {
    pub(crate) fn new(repo: &'repo Repository) -> Self {
        Self { repo }
    }

    /// Borrow the underlying repository.
    #[must_use]
    pub fn repository(&self) -> &'repo Repository {
        self.repo
    }

    /// List refs that currently have a reflog file or reftable log.
    ///
    /// # Errors
    ///
    /// Propagates ref-store and I/O errors while scanning logs.
    pub fn refs(&self) -> Result<Vec<RefName>> {
        let git_dir = self.repo.git_dir();
        let mut out = Vec::new();
        for name in list_reflog_refs(git_dir)? {
            if name == "HEAD" {
                out.push(
                    RefName::try_from("HEAD")
                        .map_err(|e| Error::Message(format!("invalid HEAD ref name: {e}")))?,
                );
                continue;
            }
            if let Ok(parsed) = RefName::try_from(name.as_str()) {
                out.push(parsed);
            }
        }
        out.sort_by(|a, b| a.as_str().cmp(b.as_str()));
        Ok(out)
    }

    /// Reflog entries for `ref_name`, newest first with indices starting at `0`.
    ///
    /// Returns an empty vector when the ref exists but its reflog is empty.
    ///
    /// # Errors
    ///
    /// Returns [`Error::ReflogUnknownRef`] when the ref cannot be resolved and has no reflog.
    pub fn entries(&self, ref_name: &RefName) -> Result<Vec<IndexedReflogEntry>> {
        let page = self.query(ref_name, &ReflogQuery::default())?;
        Ok(page.entries)
    }

    /// Reflog entries for `ref_name` matching `query`, newest first.
    ///
    /// Indices match Git's `ref@{{n}}` numbering on the full reflog (not renumbered after
    /// filtering). Scanning stops once `limit` matches are collected.
    ///
    /// # Errors
    ///
    /// Returns [`Error::ReflogUnknownRef`] when the ref cannot be resolved and has no reflog.
    pub fn query(&self, ref_name: &RefName, query: &ReflogQuery) -> Result<ReflogPage> {
        let canonical = self.resolve_reflog_canonical(ref_name.as_str())?;
        if query.limit == Some(0) {
            return Ok(ReflogPage {
                entries: Vec::new(),
                truncated: false,
            });
        }
        let git_dir = self.repo.git_dir();
        let mut state = QueryScanState {
            query,
            entries: Vec::new(),
            stopped_at_limit: false,
            more_older_lines_remain: false,
        };
        let storage_format = crate::refs::store::open_ref_store(git_dir)?.format();
        if storage_format == crate::refs::store::RefStorageFormat::Files {
            scan_loose_reflog_newest_first(git_dir, &canonical, &mut state)?;
        } else {
            scan_store_reflog_newest_first(self.repo, &canonical, &mut state)?;
        }
        let truncated = state.truncated();
        Ok(ReflogPage {
            entries: state.entries,
            truncated,
        })
    }

    fn resolve_reflog_canonical(&self, user_ref: &str) -> Result<String> {
        let git_dir = self.repo.git_dir();
        for candidate in dwim_reflog_candidates(user_ref) {
            if crate::reflog::reflog_has_entries_for_dwim(git_dir, &candidate)? {
                return Ok(candidate);
            }
        }
        if !reflog_ref_known(git_dir, user_ref)? {
            return Err(Error::ReflogUnknownRef {
                refname: user_ref.to_owned(),
            });
        }
        canonical_reflog_ref(git_dir, user_ref)
    }

    /// Delete reflog entries by newest-first `indices`.
    ///
    /// When `rewrite` is true, surviving entries are re-chained (Git `EXPIRE_REFLOGS_REWRITE`).
    ///
    /// # Errors
    ///
    /// Returns [`Error::ReflogIndexOutOfRange`] when any index is out of range, or
    /// [`Error::ReflogUnknownRef`] when the ref does not exist.
    pub fn delete(&self, ref_name: &RefName, indices: &[usize], rewrite: bool) -> Result<()> {
        if indices.is_empty() {
            return Ok(());
        }
        let (canonical, entries) = self.load_reflog(ref_name.as_str())?;
        let len = entries.len();
        for &idx in indices {
            if idx >= len {
                return Err(Error::ReflogIndexOutOfRange {
                    refname: canonical,
                    index: idx,
                });
            }
        }
        let git_dir = self.repo.git_dir();
        if rewrite {
            delete_reflog_entries_rechain(git_dir, &canonical, indices)?;
        } else {
            delete_reflog_entries(git_dir, &canonical, indices)?;
        }
        Ok(())
    }

    /// Expire reflog entries using Git-compatible `gc.reflogExpire*` rules.
    ///
    /// # Errors
    ///
    /// Propagates config load failures, invalid expiry strings, and reflog rewrite errors.
    pub fn expire(&self, options: &ExpireOptions) -> Result<ReflogExpireOutcome> {
        let cfg = self.repo.config()?;
        let gc = load_gc_reflog_expire_config(&cfg, options.now);
        let explicit_total = options
            .expire
            .as_deref()
            .map(|s| parse_reflog_expire_spec(s, options.now))
            .transpose()?;
        let explicit_unreachable = options
            .expire_unreachable
            .as_deref()
            .map(|s| parse_reflog_expire_spec(s, options.now))
            .transpose()?;
        let params = ReflogExpireParams {
            stale_fix: false,
            dry_run: options.dry_run,
            verbose: false,
        };
        let git_dir = self.repo.git_dir();
        let refnames = expire_target_refs(git_dir, options.all)?;
        let mut total = 0usize;
        let mut refs = Vec::with_capacity(refnames.len());
        for refname in refnames {
            let ReflogExpireResult { pruned, .. } = expire_reflog_git(
                self.repo,
                git_dir,
                &refname,
                &params,
                explicit_total,
                explicit_unreachable,
                &gc.patterns,
                gc.global_total,
                gc.global_unreachable,
                options.now,
            )?;
            total += pruned;
            refs.push(RefExpireResult {
                ref_name: refname,
                pruned,
            });
        }
        Ok(ReflogExpireOutcome {
            entries_pruned: total,
            dry_run: options.dry_run,
            refs,
        })
    }

    fn load_reflog(&self, user_ref: &str) -> Result<(String, Vec<ReflogEntry>)> {
        let git_dir = self.repo.git_dir();
        for candidate in dwim_reflog_candidates(user_ref) {
            let entries = read_reflog_via_store(self.repo, &candidate)?;
            if !entries.is_empty() {
                return Ok((candidate, entries));
            }
        }
        if !reflog_ref_known(git_dir, user_ref)? {
            return Err(Error::ReflogUnknownRef {
                refname: user_ref.to_owned(),
            });
        }
        let canonical = canonical_reflog_ref(git_dir, user_ref)?;
        Ok((canonical, Vec::new()))
    }
}

fn read_reflog_via_store(repo: &Repository, refname: &str) -> Result<Vec<ReflogEntry>> {
    let mut entries = Vec::new();
    repo.refs()
        .for_each_reflog_entry(refname, false, &mut |entry| {
            entries.push(entry.clone());
            ControlFlow::Continue(())
        })?;
    Ok(entries)
}

struct QueryScanState<'a> {
    query: &'a ReflogQuery,
    entries: Vec<IndexedReflogEntry>,
    stopped_at_limit: bool,
    more_older_lines_remain: bool,
}

impl QueryScanState<'_> {
    fn truncated(&self) -> bool {
        self.stopped_at_limit && self.more_older_lines_remain
    }

    fn visit(&mut self, index: usize, entry: &ReflogEntry) -> ControlFlow<()> {
        if !entry_matches_query(entry, self.query) {
            return ControlFlow::Continue(());
        }
        if self.query.limit == Some(0) {
            self.stopped_at_limit = true;
            return ControlFlow::Break(());
        }
        self.entries.push(IndexedReflogEntry {
            index,
            entry: entry.clone(),
        });
        if self
            .query
            .limit
            .is_some_and(|limit| limit > 0 && self.entries.len() >= limit)
        {
            self.stopped_at_limit = true;
            return ControlFlow::Break(());
        }
        ControlFlow::Continue(())
    }
}

fn entry_matches_query(entry: &ReflogEntry, query: &ReflogQuery) -> bool {
    if let Some(since) = query.since {
        if reflog_identity_timestamp(&entry.identity).is_some_and(|ts| ts < since) {
            return false;
        }
    }
    if let Some(until) = query.until {
        if reflog_identity_timestamp(&entry.identity).is_some_and(|ts| ts > until) {
            return false;
        }
    }
    if let Some(grep) = &query.grep {
        if !grep.matches(&entry.message) {
            return false;
        }
    }
    let _ = query.now;
    true
}

fn scan_loose_reflog_newest_first(
    git_dir: &Path,
    refname: &str,
    state: &mut QueryScanState<'_>,
) -> Result<()> {
    let path = reflog_path(git_dir, refname);
    let Some(mut reader) = crate::reflog::ReverseReflogLineReader::open(&path)? else {
        return Ok(());
    };
    let mut index_from_newest = 0usize;
    while let Some(line_bytes) = reader.next_nonempty_line()? {
        let line = std::str::from_utf8(&line_bytes).unwrap_or("");
        let Some(entry) = parse_reflog_line_for_store(line) else {
            continue;
        };
        let index = index_from_newest;
        index_from_newest += 1;
        if state.visit(index, &entry).is_break() {
            state.more_older_lines_remain = reader.has_older_bytes();
            break;
        }
    }
    Ok(())
}

fn scan_store_reflog_newest_first(
    repo: &Repository,
    refname: &str,
    state: &mut QueryScanState<'_>,
) -> Result<()> {
    let mut index = 0usize;
    repo.refs()
        .for_each_reflog_entry(refname, true, &mut |entry| {
            let flow = state.visit(index, entry);
            index += 1;
            if flow.is_break() {
                state.more_older_lines_remain = true;
            }
            flow
        })?;
    Ok(())
}

fn dwim_reflog_candidates(user_ref: &str) -> Vec<String> {
    let mut out = vec![user_ref.to_owned()];
    if user_ref != "HEAD" && !user_ref.starts_with("refs/") {
        out.push(format!("refs/{user_ref}"));
        out.push(format!("refs/heads/{user_ref}"));
    }
    out
}

fn canonical_reflog_ref(git_dir: &Path, user_ref: &str) -> Result<String> {
    for candidate in dwim_reflog_candidates(user_ref) {
        if reflog_exists(git_dir, &candidate) {
            return Ok(candidate);
        }
    }
    if reflog_ref_known(git_dir, user_ref)? {
        if user_ref.starts_with("refs/") || user_ref == "HEAD" {
            return Ok(user_ref.to_owned());
        }
        return Ok(format!("refs/heads/{user_ref}"));
    }
    Err(Error::ReflogUnknownRef {
        refname: user_ref.to_owned(),
    })
}

fn reflog_ref_known(git_dir: &Path, user_ref: &str) -> Result<bool> {
    if user_ref == "HEAD" {
        return Ok(true);
    }
    for candidate in dwim_reflog_candidates(user_ref) {
        if reflog_exists(git_dir, &candidate) {
            return Ok(true);
        }
        let (_, oid) = resolve_ref_dwim(git_dir, &candidate);
        if oid.is_some() {
            return Ok(true);
        }
    }
    let (_, oid) = resolve_ref_dwim(git_dir, user_ref);
    Ok(oid.is_some())
}

fn expire_target_refs(git_dir: &Path, all: bool) -> Result<Vec<String>> {
    if !all {
        let mut names = list_reflog_refs(git_dir)?;
        names.sort();
        return Ok(names);
    }
    let mut names: Vec<String> = crate::refs::list_refs(git_dir, "refs/")?
        .into_iter()
        .map(|(name, _)| name)
        .collect();
    if reflog_exists(git_dir, "HEAD") {
        names.push("HEAD".to_owned());
    }
    names.sort();
    names.dedup();
    Ok(names)
}

#[cfg(test)]
mod tests {
    use std::fs;

    use super::*;
    use crate::refs::append_reflog;
    use crate::repo::{InitOptions, Repository};

    fn init_repo() -> (tempfile::TempDir, Repository) {
        let dir = tempfile::tempdir().expect("tempdir");
        let repo = Repository::init(dir.path(), &InitOptions::default()).expect("init");
        (dir, repo)
    }

    #[test]
    fn query_limit_zero_returns_empty_without_reading_entries() {
        let (_dir, repo) = init_repo();
        let git_dir = repo.git_dir().to_path_buf();
        let refname = "refs/heads/main";
        append_reflog(
            &git_dir,
            refname,
            &crate::objects::ObjectId::zero(),
            &crate::objects::ObjectId::from_hex("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
                .expect("oid"),
            "T <t@example.com> 1000000000 +0000",
            "commit: one",
            true,
        )
        .expect("append");
        let name = RefName::try_from(refname).expect("valid");
        let page = repo
            .reflogs()
            .query(
                &name,
                &ReflogQuery {
                    limit: Some(0),
                    ..ReflogQuery::default()
                },
            )
            .expect("query");
        assert!(page.entries.is_empty());
        assert!(!page.truncated);
    }

    #[test]
    fn loose_scan_index_skips_unparseable_lines_without_renumbering() {
        let (_dir, repo) = init_repo();
        let git_dir = repo.git_dir().to_path_buf();
        let refname = "refs/heads/x";
        let oid = crate::objects::ObjectId::from_hex("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")
            .expect("oid");
        let body = format!(
            "not-a-valid-reflog-line\n0000000000000000000000000000000000000000 {oid} T <t@e.com> 2000 +0000\tcommit: newest\n"
        );
        // Newest line is valid (index 0); the unparseable line is older and does not consume an index.
        let path = crate::reflog::reflog_path(&git_dir, refname);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).expect("mkdir");
        }
        fs::write(&path, body).expect("write");
        let name = RefName::try_from(refname).expect("valid");
        let page = repo
            .reflogs()
            .query(&name, &ReflogQuery::default())
            .expect("query");
        assert_eq!(page.entries.len(), 1);
        assert_eq!(page.entries[0].index, 0);
    }

    #[test]
    fn loose_scan_index_skips_unparseable_newer_line_without_renumbering() {
        let (_dir, repo) = init_repo();
        let git_dir = repo.git_dir().to_path_buf();
        let refname = "refs/heads/y";
        let oid = crate::objects::ObjectId::from_hex("cccccccccccccccccccccccccccccccccccccccc")
            .expect("oid");
        // Newest line is unparseable; the valid entry is older and must stay at index 0.
        let body = format!(
            "0000000000000000000000000000000000000000 {oid} T <t@e.com> 2000 +0000\tcommit: older\nnot-a-valid-reflog-line\n"
        );
        let path = crate::reflog::reflog_path(&git_dir, refname);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).expect("mkdir");
        }
        fs::write(&path, body).expect("write");
        let name = RefName::try_from(refname).expect("valid");
        let page = repo
            .reflogs()
            .query(&name, &ReflogQuery::default())
            .expect("query");
        assert_eq!(page.entries.len(), 1);
        assert_eq!(page.entries[0].index, 0);
    }

    #[test]
    fn delete_out_of_range_returns_typed_error() {
        let (_dir, repo) = init_repo();
        let git_dir = repo.git_dir().to_path_buf();
        let refname = "refs/heads/main";
        append_reflog(
            &git_dir,
            refname,
            &crate::objects::ObjectId::zero(),
            &crate::objects::ObjectId::zero(),
            "T <t@example.com> 1000000000 +0000",
            "only",
            true,
        )
        .expect("append");
        let name = RefName::try_from(refname).expect("valid");
        let err = repo
            .reflogs()
            .delete(&name, &[1], false)
            .expect_err("out of range");
        match err {
            Error::ReflogIndexOutOfRange { refname, index } => {
                assert_eq!(refname, "refs/heads/main");
                assert_eq!(index, 1);
            }
            other => panic!("expected ReflogIndexOutOfRange, got {other:?}"),
        }
    }

    #[test]
    fn expire_outcome_refs_are_sorted() {
        let (_dir, repo) = init_repo();
        let git_dir = repo.git_dir();
        let zero = crate::objects::ObjectId::zero();
        let identity = "T <t@example.com> 1700000000 +0000";
        for refname in ["refs/heads/zebra", "refs/heads/alpha"] {
            append_reflog(git_dir, refname, &zero, &zero, identity, "seed", true).expect("append");
        }
        let outcome = repo
            .reflogs()
            .expire(&ExpireOptions {
                now: 1_700_000_000,
                expire: Some("never".into()),
                expire_unreachable: Some("never".into()),
                all: false,
                dry_run: true,
            })
            .expect("expire");
        let names: Vec<_> = outcome.refs.iter().map(|r| r.ref_name.as_str()).collect();
        let mut sorted = names.clone();
        sorted.sort();
        assert_eq!(names, sorted);
        assert!(names.iter().any(|n| *n == "refs/heads/alpha"));
        assert!(names.iter().any(|n| *n == "refs/heads/zebra"));
    }
}