grit-lib 0.1.3

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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
//! Reflog reading and management.
//!
//! The reflog records updates to refs.  Each ref's log is stored at
//! `<git-dir>/logs/<refname>` (e.g. `logs/HEAD`, `logs/refs/heads/main`).
//! Each line has the format:
//!
//! ```text
//! <old-sha> <new-sha> <name> <<email>> <timestamp> <timezone>\t<message>
//! ```

use std::collections::{HashMap, HashSet};
use std::fs;
use std::io;
use std::path::{Path, PathBuf};

use crate::config::ConfigSet;
use crate::diff::zero_oid;
use crate::error::{Error, Result};
use crate::merge_base;
use crate::objects::{parse_commit, parse_tree, ObjectId, ObjectKind};
use crate::refs;
use crate::repo::Repository;
use crate::wildmatch::{wildmatch, WM_PATHNAME};

/// A single reflog entry.
#[derive(Debug, Clone)]
pub struct ReflogEntry {
    /// Previous object ID.
    pub old_oid: ObjectId,
    /// New object ID.
    pub new_oid: ObjectId,
    /// Identity string: `"Name <email> timestamp tz"`.
    pub identity: String,
    /// The log message.
    pub message: String,
}

/// Return the filesystem path for a ref's reflog.
pub fn reflog_path(git_dir: &Path, refname: &str) -> PathBuf {
    git_dir.join("logs").join(refname)
}

/// Check whether a reflog exists for the given ref.
pub fn reflog_exists(git_dir: &Path, refname: &str) -> bool {
    if crate::reftable::is_reftable_repo(git_dir) {
        return crate::reftable::reftable_reflog_exists(git_dir, refname);
    }
    let path = reflog_path(git_dir, refname);
    path.is_file()
}

/// Read all reflog entries for the given ref, in file order (oldest first).
///
/// Returns an empty vec if the reflog file does not exist.
pub fn read_reflog(git_dir: &Path, refname: &str) -> Result<Vec<ReflogEntry>> {
    if crate::reftable::is_reftable_repo(git_dir) {
        return crate::reftable::reftable_read_reflog(git_dir, refname);
    }
    let path = reflog_path(git_dir, refname);
    let content = match fs::read_to_string(&path) {
        Ok(c) => c,
        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(e) => return Err(Error::Io(e)),
    };

    let mut entries = Vec::new();
    for line in content.lines() {
        if line.is_empty() {
            continue;
        }
        if let Some(entry) = parse_reflog_line(line) {
            entries.push(entry);
        }
    }
    Ok(entries)
}

/// Parse a single reflog line.
///
/// Format: `<old-hex> <new-hex> <identity>\t<message>`
fn parse_reflog_line(line: &str) -> Option<ReflogEntry> {
    // Split on tab first to separate identity from message
    let (before_tab, message) = if let Some(pos) = line.find('\t') {
        (&line[..pos], line[pos + 1..].to_string())
    } else {
        (line, String::new())
    };

    // The first 40 chars are old OID, then space, then 40 chars new OID, then space, then identity
    if before_tab.len() < 83 {
        // 40 + 1 + 40 + 1 + at least 1 char identity
        return None;
    }

    let old_hex = &before_tab[..40];
    let new_hex = &before_tab[41..81];
    let identity = before_tab[82..].to_string();

    let old_oid = old_hex.parse::<ObjectId>().ok()?;
    let new_oid = new_hex.parse::<ObjectId>().ok()?;

    Some(ReflogEntry {
        old_oid,
        new_oid,
        identity,
        message,
    })
}

/// Collect every non-null object ID mentioned in any file under `logs/` (recursive).
///
/// Used by `fsck` to validate reflog entries. Skips reftable-backed repos (no file logs).
pub fn all_reflog_oids(git_dir: &Path) -> Result<HashSet<ObjectId>> {
    if crate::reftable::is_reftable_repo(git_dir) {
        return Ok(HashSet::new());
    }
    let mut out = HashSet::new();
    let logs = git_dir.join("logs");
    if !logs.is_dir() {
        return Ok(out);
    }
    let z = zero_oid();
    walk_reflog_files(&logs, &mut out, &z)?;
    Ok(out)
}

fn walk_reflog_files(dir: &Path, out: &mut HashSet<ObjectId>, zero: &ObjectId) -> Result<()> {
    for entry in fs::read_dir(dir).map_err(Error::Io)? {
        let entry = entry.map_err(Error::Io)?;
        let path = entry.path();
        if path.is_dir() {
            walk_reflog_files(&path, out, zero)?;
        } else if path.is_file() {
            let content = fs::read_to_string(&path).map_err(Error::Io)?;
            for line in content.lines() {
                if let Some(e) = parse_reflog_line(line) {
                    if e.old_oid != *zero {
                        out.insert(e.old_oid);
                    }
                    if e.new_oid != *zero {
                        out.insert(e.new_oid);
                    }
                }
            }
        }
    }
    Ok(())
}

/// Delete specific reflog entries by index (0-based, newest-first order).
///
/// Rewrites the reflog file, omitting entries at the given indices.
pub fn delete_reflog_entries(git_dir: &Path, refname: &str, indices: &[usize]) -> Result<()> {
    let mut entries = read_reflog(git_dir, refname)?;
    if entries.is_empty() {
        return Ok(());
    }

    // Indices are in newest-first order (like show), so reverse the entries
    // to map indices correctly.
    entries.reverse();

    let indices_set: std::collections::HashSet<usize> = indices.iter().copied().collect();

    let path = reflog_path(git_dir, refname);
    let remaining: Vec<&ReflogEntry> = entries
        .iter()
        .enumerate()
        .filter(|(i, _)| !indices_set.contains(i))
        .map(|(_, e)| e)
        .collect();

    // Write back in file order (oldest first), so reverse again
    let mut lines = Vec::new();
    for entry in remaining.iter().rev() {
        lines.push(format_reflog_entry(entry));
    }

    fs::write(&path, lines.join(""))?;
    Ok(())
}

/// Expire (prune) reflog entries older than a given timestamp (Unix seconds).
///
/// If `expire_time` is `None`, removes all entries.
pub fn expire_reflog(git_dir: &Path, refname: &str, expire_time: Option<i64>) -> Result<usize> {
    let entries = read_reflog(git_dir, refname)?;
    if entries.is_empty() {
        return Ok(0);
    }

    let path = reflog_path(git_dir, refname);
    let mut kept = Vec::new();
    let mut pruned = 0usize;

    for entry in &entries {
        let ts = parse_timestamp_from_identity(&entry.identity);
        let dominated = match (expire_time, ts) {
            (Some(cutoff), Some(t)) => t < cutoff,
            (None, _) => true,        // expire all
            (Some(_), None) => false, // can't parse => keep
        };
        if dominated {
            pruned += 1;
        } else {
            kept.push(format_reflog_entry(entry));
        }
    }

    fs::write(&path, kept.join(""))?;
    Ok(pruned)
}

/// Expire reflog entries whose `new_oid` is not an ancestor of the current ref tip
/// and whose identity timestamp is older than `cutoff` (Unix seconds).
///
/// Entries with an all-zero `new_oid` are never removed by this pass.
///
/// When `cutoff` is `None`, no entries are removed.
///
/// Reftable-backed repositories are skipped until reflog rewrite is implemented there.
pub fn expire_reflog_unreachable(
    repo: &Repository,
    git_dir: &Path,
    refname: &str,
    cutoff: Option<i64>,
) -> Result<usize> {
    let Some(cutoff) = cutoff else {
        return Ok(0);
    };
    if crate::reftable::is_reftable_repo(git_dir) {
        return Ok(0);
    }
    let tip = match refs::resolve_ref(git_dir, refname) {
        Ok(o) => o,
        Err(_) => return Ok(0),
    };
    let ancestors = match merge_base::ancestor_closure(repo, tip) {
        Ok(a) => a,
        Err(_) => return Ok(0),
    };

    let entries = read_reflog(git_dir, refname)?;
    if entries.is_empty() {
        return Ok(0);
    }

    let path = reflog_path(git_dir, refname);
    let mut kept = Vec::new();
    let mut pruned = 0usize;

    for entry in &entries {
        let ts = parse_timestamp_from_identity(&entry.identity);
        let unreachable = !entry.new_oid.is_zero() && !ancestors.contains(&entry.new_oid);
        let should_prune = unreachable && matches!(ts, Some(t) if t < cutoff);
        if should_prune {
            pruned += 1;
        } else {
            kept.push(format_reflog_entry(entry));
        }
    }

    fs::write(&path, kept.join(""))?;
    Ok(pruned)
}

/// Format a reflog entry back into the on-disk line format.
fn format_reflog_entry(entry: &ReflogEntry) -> String {
    format!(
        "{} {} {}\t{}\n",
        entry.old_oid, entry.new_oid, entry.identity, entry.message
    )
}

/// Extract the Unix timestamp from an identity string.
///
/// Identity format: `Name <email> <timestamp> <tz>`
fn parse_timestamp_from_identity(identity: &str) -> Option<i64> {
    // Walk backwards: last token is tz (+0000), second-to-last is timestamp
    let parts: Vec<&str> = identity.rsplitn(3, ' ').collect();
    if parts.len() >= 2 {
        parts[1].parse::<i64>().ok()
    } else {
        None
    }
}

/// Copy `logs/<branch_refname>` to `logs/HEAD` when keeping symbolic-HEAD reflogs aligned with
/// the checked-out branch (matches Git).
pub fn mirror_branch_reflog_to_head(git_dir: &Path, branch_refname: &str) -> Result<()> {
    if crate::reftable::is_reftable_repo(git_dir) {
        return Ok(());
    }
    let src = reflog_path(git_dir, branch_refname);
    if !src.is_file() {
        return Ok(());
    }
    let content = fs::read_to_string(&src).map_err(Error::Io)?;
    let dst = reflog_path(git_dir, "HEAD");
    if let Some(parent) = dst.parent() {
        fs::create_dir_all(parent).map_err(Error::Io)?;
    }
    fs::write(&dst, content).map_err(Error::Io)?;
    Ok(())
}

/// List all refs that have reflogs.
pub fn list_reflog_refs(git_dir: &Path) -> Result<Vec<String>> {
    let logs_dir = git_dir.join("logs");
    let mut refs = Vec::new();

    // Check HEAD
    if logs_dir.join("HEAD").is_file() {
        refs.push("HEAD".to_string());
    }

    // Walk logs/refs/
    let refs_logs = logs_dir.join("refs");
    if refs_logs.is_dir() {
        collect_reflog_refs(&refs_logs, "refs", &mut refs)?;
    }

    Ok(refs)
}

fn collect_reflog_refs(dir: &Path, prefix: &str, out: &mut Vec<String>) -> Result<()> {
    let read_dir = match fs::read_dir(dir) {
        Ok(rd) => rd,
        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
        Err(e) => return Err(Error::Io(e)),
    };

    for entry in read_dir {
        let entry = entry.map_err(Error::Io)?;
        let name = entry.file_name().to_string_lossy().to_string();
        let full_name = format!("{prefix}/{name}");
        let ft = entry.file_type().map_err(Error::Io)?;
        if ft.is_dir() {
            collect_reflog_refs(&entry.path(), &full_name, out)?;
        } else if ft.is_file() {
            out.push(full_name);
        }
    }
    Ok(())
}

// --- `git reflog expire` -----------------------------------------------------

/// Options for [`expire_reflog_git`].
#[derive(Debug, Clone)]
pub struct ReflogExpireParams {
    /// Prune entries whose commits fail a completeness walk (missing objects).
    pub stale_fix: bool,
    pub dry_run: bool,
    pub verbose: bool,
}

/// Per-ref `gc.<pattern>.reflogExpire*` rule from config.
#[derive(Debug, Clone)]
pub struct GcReflogPattern {
    pattern: String,
    expire_total: i64,
    expire_unreachable: i64,
}

fn collect_gc_reflog_patterns(config: &ConfigSet, now: i64) -> Vec<GcReflogPattern> {
    let mut by_pattern: HashMap<String, GcReflogPattern> = HashMap::new();
    for e in config.entries() {
        let key = e.key.as_str();
        let Some(rest) = key.strip_prefix("gc.") else {
            continue;
        };
        // Per-ref: `gc.<wildmatch-pattern>.reflogExpire` (pattern may contain dots).
        // Global `gc.reflogExpire` has no pattern segment — see [`global_gc_reflog_expiry`].
        let Some((pat, suffix)) = rest.rsplit_once('.') else {
            continue;
        };
        if !suffix.eq_ignore_ascii_case("reflogexpire")
            && !suffix.eq_ignore_ascii_case("reflogexpireunreachable")
        {
            continue;
        }
        let Some(val) = e.value.as_deref() else {
            continue;
        };
        let Ok(ts) = parse_gc_reflog_expiry(val, now) else {
            continue;
        };
        let ent = by_pattern
            .entry(pat.to_string())
            .or_insert(GcReflogPattern {
                pattern: pat.to_string(),
                expire_total: i64::MAX,
                expire_unreachable: i64::MAX,
            });
        if suffix.eq_ignore_ascii_case("reflogexpire") {
            ent.expire_total = ts;
        } else {
            ent.expire_unreachable = ts;
        }
    }
    by_pattern.into_values().collect()
}

fn global_gc_reflog_expiry(config: &ConfigSet, now: i64) -> (Option<i64>, Option<i64>) {
    let total = config
        .get("gc.reflogExpire")
        .and_then(|v| parse_gc_reflog_expiry(&v, now).ok());
    let unreach = config
        .get("gc.reflogExpireUnreachable")
        .and_then(|v| parse_gc_reflog_expiry(&v, now).ok());
    (total, unreach)
}

/// Parse `gc.reflogExpire` values: `never` / `false` → keep forever (`0`), else days or epoch.
fn parse_gc_reflog_expiry(raw: &str, now: i64) -> Result<i64> {
    let s = raw.trim();
    if s.eq_ignore_ascii_case("never") || s.eq_ignore_ascii_case("false") {
        return Ok(0);
    }
    if let Ok(days) = s.parse::<u64>() {
        if days == 0 {
            return Ok(0);
        }
        return Ok(now - (days as i64 * 86400));
    }
    s.parse::<i64>()
        .map_err(|_| Error::Message(format!("invalid reflog expiry: {raw:?}")))
}

fn default_expire_total(now: i64) -> i64 {
    now - 30 * 86400
}

fn default_expire_unreachable(now: i64) -> i64 {
    now - 90 * 86400
}

fn resolve_expire_for_ref(
    refname: &str,
    explicit_total: Option<i64>,
    explicit_unreachable: Option<i64>,
    patterns: &[GcReflogPattern],
    default_total: i64,
    default_unreachable: i64,
) -> (i64, i64) {
    let mut expire_total = explicit_total.unwrap_or(default_total);
    let mut expire_unreachable = explicit_unreachable.unwrap_or(default_unreachable);
    if explicit_total.is_some() && explicit_unreachable.is_some() {
        return (expire_total, expire_unreachable);
    }
    for ent in patterns {
        if wildmatch(ent.pattern.as_bytes(), refname.as_bytes(), WM_PATHNAME) {
            // Partial per-pattern config only sets one key; the other stays `i64::MAX` as sentinel.
            if explicit_total.is_none() && ent.expire_total != i64::MAX {
                expire_total = ent.expire_total;
            }
            if explicit_unreachable.is_none() && ent.expire_unreachable != i64::MAX {
                expire_unreachable = ent.expire_unreachable;
            }
            return (expire_total, expire_unreachable);
        }
    }
    if refname == "refs/stash" {
        if explicit_total.is_none() {
            expire_total = 0;
        }
        if explicit_unreachable.is_none() {
            expire_unreachable = 0;
        }
    }
    (expire_total, expire_unreachable)
}

fn tree_fully_complete(repo: &Repository, oid: ObjectId, depth: usize) -> bool {
    if depth > 65536 {
        return false;
    }
    let Ok(obj) = repo.odb.read(&oid) else {
        return false;
    };
    match obj.kind {
        ObjectKind::Blob => true,
        ObjectKind::Tree => {
            let Ok(entries) = parse_tree(&obj.data) else {
                return false;
            };
            for e in entries {
                if !tree_fully_complete(repo, e.oid, depth + 1) {
                    return false;
                }
            }
            true
        }
        _ => false,
    }
}

fn commit_chain_complete(repo: &Repository, oid: ObjectId, depth: usize) -> bool {
    if oid.is_zero() {
        return true;
    }
    if depth > 65536 {
        return false;
    }
    let Ok(obj) = repo.odb.read(&oid) else {
        return false;
    };
    if obj.kind != ObjectKind::Commit {
        return false;
    }
    let Ok(c) = parse_commit(&obj.data) else {
        return false;
    };
    if !tree_fully_complete(repo, c.tree, depth + 1) {
        return false;
    }
    for p in &c.parents {
        if !commit_chain_complete(repo, *p, depth + 1) {
            return false;
        }
    }
    true
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum UnreachableKind {
    Always,
    Normal,
    Head,
}

fn is_head_ref(refname: &str) -> bool {
    refname == "HEAD" || refname.ends_with("/HEAD")
}

fn tip_commits_for_reflog(repo: &Repository, git_dir: &Path, refname: &str) -> Vec<ObjectId> {
    let mut tips = Vec::new();
    if is_head_ref(refname) {
        if let Ok(oid) = refs::resolve_ref(git_dir, "HEAD") {
            tips.push(oid);
        }
        if let Ok(refs) = refs::list_refs(git_dir, "refs/") {
            for (_, oid) in refs {
                tips.push(oid);
            }
        }
    } else if let Ok(oid) = refs::resolve_ref(git_dir, refname) {
        tips.push(oid);
    }
    tips.sort();
    tips.dedup();
    tips.retain(|o| commit_chain_complete(repo, *o, 0));
    tips
}

fn reachable_commit_set(repo: &Repository, tips: &[ObjectId]) -> HashSet<ObjectId> {
    let mut acc = HashSet::new();
    for t in tips {
        if let Ok(cl) = merge_base::ancestor_closure(repo, *t) {
            acc.extend(cl);
        }
    }
    acc
}

fn is_unreachable_oid(
    repo: &Repository,
    reachable: &HashSet<ObjectId>,
    kind: UnreachableKind,
    oid: ObjectId,
) -> bool {
    if oid.is_zero() {
        return false;
    }
    if reachable.contains(&oid) {
        return false;
    }
    if kind == UnreachableKind::Always {
        return true;
    }
    let Ok(obj) = repo.odb.read(&oid) else {
        return true;
    };
    obj.kind == ObjectKind::Commit
}

fn should_drop_reflog_entry(
    repo: &Repository,
    entry: &ReflogEntry,
    expire_total: i64,
    expire_unreachable: i64,
    unreachable_kind: UnreachableKind,
    reachable: &HashSet<ObjectId>,
    stale_fix: bool,
) -> bool {
    let ts = parse_timestamp_from_identity(&entry.identity).unwrap_or(i64::MAX);
    if expire_total > 0 && ts < expire_total {
        return true;
    }
    if stale_fix
        && (!commit_chain_complete(repo, entry.old_oid, 0)
            || !commit_chain_complete(repo, entry.new_oid, 0))
    {
        return true;
    }
    if expire_unreachable > 0 && ts < expire_unreachable {
        match unreachable_kind {
            UnreachableKind::Always => return true,
            UnreachableKind::Normal | UnreachableKind::Head => {
                if is_unreachable_oid(repo, reachable, unreachable_kind, entry.old_oid)
                    || is_unreachable_oid(repo, reachable, unreachable_kind, entry.new_oid)
                {
                    return true;
                }
            }
        }
    }
    false
}

/// Git-compatible reflog expiry for one ref.
pub fn expire_reflog_git(
    repo: &Repository,
    git_dir: &Path,
    refname: &str,
    params: &ReflogExpireParams,
    explicit_total: Option<i64>,
    explicit_unreachable: Option<i64>,
    gc_patterns: &[GcReflogPattern],
    gc_global_total: Option<i64>,
    gc_global_unreachable: Option<i64>,
    now: i64,
) -> Result<usize> {
    if crate::reftable::is_reftable_repo(git_dir) {
        return Ok(0);
    }
    let base_total = gc_global_total.unwrap_or_else(|| default_expire_total(now));
    let base_unreachable = gc_global_unreachable.unwrap_or_else(|| default_expire_unreachable(now));
    let (expire_total, expire_unreachable) = resolve_expire_for_ref(
        refname,
        explicit_total,
        explicit_unreachable,
        gc_patterns,
        base_total,
        base_unreachable,
    );

    let unreachable_kind = if expire_unreachable <= expire_total {
        UnreachableKind::Always
    } else if expire_unreachable == 0 || is_head_ref(refname) {
        UnreachableKind::Head
    } else {
        match refs::resolve_ref(git_dir, refname) {
            Ok(t) if commit_chain_complete(repo, t, 0) => UnreachableKind::Normal,
            _ => UnreachableKind::Always,
        }
    };

    let tips = tip_commits_for_reflog(repo, git_dir, refname);
    let reachable = if matches!(unreachable_kind, UnreachableKind::Always) {
        HashSet::new()
    } else {
        reachable_commit_set(repo, &tips)
    };

    let entries = read_reflog(git_dir, refname)?;
    if entries.is_empty() {
        return Ok(0);
    }
    let path = reflog_path(git_dir, refname);
    let mut kept = Vec::new();
    let mut pruned = 0usize;

    for entry in &entries {
        let drop = should_drop_reflog_entry(
            repo,
            entry,
            expire_total,
            expire_unreachable,
            unreachable_kind,
            &reachable,
            params.stale_fix,
        );
        if drop {
            pruned += 1;
            if params.verbose {
                if params.dry_run {
                    println!("would prune {}", entry.message);
                } else {
                    println!("prune {}", entry.message);
                }
            }
        } else {
            if params.verbose {
                println!("keep {}", entry.message);
            }
            kept.push(format_reflog_entry(entry));
        }
    }

    if !params.dry_run && pruned > 0 {
        fs::write(&path, kept.join(""))?;
    }
    Ok(pruned)
}

/// Per-ref `gc.<pattern>.reflogExpire*` rules plus global `gc.reflogExpire` / `gc.reflogExpireUnreachable`.
#[derive(Debug, Clone)]
pub struct GcReflogExpireConfig {
    pub patterns: Vec<GcReflogPattern>,
    pub global_total: Option<i64>,
    pub global_unreachable: Option<i64>,
}

/// Load gc reflog expiry rules from merged config (same layering as Git `reflog_expire_config`).
#[must_use]
pub fn load_gc_reflog_expire_config(config: &ConfigSet, now: i64) -> GcReflogExpireConfig {
    let (global_total, global_unreachable) = global_gc_reflog_expiry(config, now);
    GcReflogExpireConfig {
        patterns: collect_gc_reflog_patterns(config, now),
        global_total,
        global_unreachable,
    }
}

/// Best-effort object set for `--stale-fix` (refs + reflog mentions).
pub fn mark_stalefix_reachable(repo: &Repository, git_dir: &Path) -> Result<HashSet<ObjectId>> {
    let mut seeds: Vec<ObjectId> = Vec::new();
    if let Ok(oid) = refs::resolve_ref(git_dir, "HEAD") {
        seeds.push(oid);
    }
    if let Ok(refs) = refs::list_refs(git_dir, "refs/") {
        for (_, oid) in refs {
            seeds.push(oid);
        }
    }
    if let Ok(names) = list_reflog_refs(git_dir) {
        for r in names {
            if let Ok(ent) = read_reflog(git_dir, &r) {
                for e in ent {
                    if !e.old_oid.is_zero() {
                        seeds.push(e.old_oid);
                    }
                    if !e.new_oid.is_zero() {
                        seeds.push(e.new_oid);
                    }
                }
            }
        }
    }
    seeds.sort();
    seeds.dedup();

    let mut seen = HashSet::new();
    let mut queue: std::collections::VecDeque<ObjectId> = seeds.into_iter().collect();
    while let Some(oid) = queue.pop_front() {
        if oid.is_zero() || !seen.insert(oid) {
            continue;
        }
        let Ok(obj) = repo.odb.read(&oid) else {
            continue;
        };
        match obj.kind {
            ObjectKind::Commit => {
                if let Ok(c) = parse_commit(&obj.data) {
                    queue.push_back(c.tree);
                    for p in c.parents {
                        queue.push_back(p);
                    }
                }
            }
            ObjectKind::Tree => {
                if let Ok(entries) = parse_tree(&obj.data) {
                    for te in entries {
                        queue.push_back(te.oid);
                    }
                }
            }
            ObjectKind::Tag | ObjectKind::Blob => {}
        }
    }
    Ok(seen)
}