grit-lib 0.5.18

Core library for the grit Git implementation
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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
//! Repository state machine — HEAD resolution, branch status, and
//! in-progress operation detection.
//!
//! # Overview
//!
//! Git repositories can be in various states beyond just "clean":
//! merging, rebasing, cherry-picking, reverting, bisecting, etc.
//! This module detects those states by checking for sentinel files
//! (e.g. `MERGE_HEAD`, `rebase-merge/`) in the `.git` directory.
//!
//! It also resolves `HEAD` to determine the current branch and commit,
//! and provides working tree / index diff summaries used by `status`,
//! `commit`, and other porcelain commands.
//!
//! Library guide: [state](https://grit-scm.com/docs/library/repository)
//!
//! ```rust
//! use grit_lib::repo::{InitOptions, Repository};
//! # fn main() -> grit_lib::error::Result<()> {
//! let dir = tempfile::tempdir()?;
//! let _repo = Repository::init(dir.path(), &InitOptions::default())?;
//! use grit_lib::state::resolve_head; let _ = resolve_head(_repo.git_dir())?;
//!
//! # Ok(())
//! # }
//! ```

use std::fs;
use std::path::Path;

use crate::check_ref_format::{check_refname_format, RefNameOptions};
use crate::error::{Error, Result};
use crate::objects::ObjectId;
use crate::reflog;
use crate::refs::store::RefStoreError;
use crate::repo::Repository;

/// The current state of HEAD.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HeadState {
    /// HEAD points to a branch via a symbolic ref (e.g. `ref: refs/heads/main`).
    Branch {
        /// The full ref name (e.g. `refs/heads/main`).
        refname: String,
        /// The short branch name (e.g. `main`).
        short_name: String,
        /// The commit OID that the branch points to, or `None` if the
        /// branch is unborn (no commits yet).
        oid: Option<ObjectId>,
    },
    /// HEAD is detached — pointing directly at a commit.
    Detached {
        /// The commit OID.
        oid: ObjectId,
    },
    /// HEAD is in an invalid or unreadable state.
    Invalid,
}

impl HeadState {
    /// Return the commit OID if HEAD resolves to one.
    #[must_use]
    pub fn oid(&self) -> Option<&ObjectId> {
        match self {
            Self::Branch { oid, .. } => oid.as_ref(),
            Self::Detached { oid } => Some(oid),
            Self::Invalid => None,
        }
    }

    /// Return the branch name if HEAD is on a branch.
    #[must_use]
    pub fn branch_name(&self) -> Option<&str> {
        match self {
            Self::Branch { short_name, .. } => Some(short_name),
            _ => None,
        }
    }

    /// Whether HEAD is on an unborn branch (no commits yet).
    #[must_use]
    pub fn is_unborn(&self) -> bool {
        matches!(self, Self::Branch { oid: None, .. })
    }

    /// Whether HEAD is detached.
    #[must_use]
    pub fn is_detached(&self) -> bool {
        matches!(self, Self::Detached { .. })
    }
}

/// An in-progress operation that the repository is in the middle of.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InProgressOperation {
    /// A merge is in progress (`MERGE_HEAD` exists).
    Merge,
    /// An interactive rebase is in progress (`rebase-merge/` exists).
    RebaseInteractive,
    /// A non-interactive rebase is in progress (`rebase-apply/` exists).
    Rebase,
    /// A cherry-pick is in progress (`CHERRY_PICK_HEAD` exists).
    CherryPick,
    /// A revert is in progress (`REVERT_HEAD` exists).
    Revert,
    /// A bisect is in progress (`BISECT_LOG` exists).
    Bisect,
    /// An `am` (apply mailbox) is in progress (`rebase-apply/applying` exists).
    Am,
}

impl InProgressOperation {
    /// Human-readable description of the operation.
    #[must_use]
    pub fn description(&self) -> &'static str {
        match self {
            Self::Merge => "merge",
            Self::RebaseInteractive => "interactive rebase",
            Self::Rebase => "rebase",
            Self::CherryPick => "cherry-pick",
            Self::Revert => "revert",
            Self::Bisect => "bisect",
            Self::Am => "am",
        }
    }
}

/// A suggested follow-up action while an operation is paused.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NextStep {
    /// Edit conflicted files in the worktree (inspect with `grit diff`).
    ResolveConflicts,
    /// Stage resolved paths after editing.
    StageResolved,
    /// Record the merge or sequencer result.
    Commit,
    /// Cancel the in-progress operation.
    Abort(InProgressOperation),
    /// Advance a sequencer operation after conflicts are resolved.
    Continue(InProgressOperation),
    /// Skip the current sequencer step.
    Skip(InProgressOperation),
}

impl NextStep {
    /// Render a non-interactive `grit` invocation for this step, when one exists.
    #[must_use]
    pub fn grit_command(&self) -> Option<String> {
        match self {
            Self::ResolveConflicts => Some("grit diff".to_owned()),
            Self::StageResolved => Some("grit add .".to_owned()),
            Self::Commit => Some("grit commit \"message\"".to_owned()),
            Self::Continue(InProgressOperation::Merge) => Some("grit merge --continue".to_owned()),
            Self::Abort(InProgressOperation::Merge) => Some("grit merge --abort".to_owned()),
            Self::Abort(InProgressOperation::CherryPick) => Some("grit pick --abort".to_owned()),
            Self::Abort(InProgressOperation::Revert) => Some("grit revert --abort".to_owned()),
            Self::Continue(InProgressOperation::CherryPick) => {
                Some("grit pick --continue".to_owned())
            }
            Self::Continue(InProgressOperation::Revert) => {
                Some("grit revert --continue".to_owned())
            }
            Self::Skip(InProgressOperation::CherryPick) => Some("grit pick --skip".to_owned()),
            Self::Skip(InProgressOperation::Revert) => Some("grit revert --skip".to_owned()),
            Self::Continue(InProgressOperation::Rebase) => {
                Some("grit rebase --continue".to_owned())
            }
            Self::Abort(InProgressOperation::Rebase) => Some("grit rebase --abort".to_owned()),
            Self::Skip(InProgressOperation::Rebase) => Some("grit rebase --skip".to_owned()),
            Self::Abort(
                InProgressOperation::RebaseInteractive
                | InProgressOperation::Am
                | InProgressOperation::Bisect,
            )
            | Self::Continue(
                InProgressOperation::RebaseInteractive
                | InProgressOperation::Am
                | InProgressOperation::Bisect,
            )
            | Self::Skip(InProgressOperation::Merge)
            | Self::Skip(
                InProgressOperation::RebaseInteractive
                | InProgressOperation::Am
                | InProgressOperation::Bisect,
            ) => None,
        }
    }
}

/// In-progress operation plus the steps grit can suggest today.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Operation {
    /// Which operation is paused.
    pub kind: InProgressOperation,
    /// Ordered follow-ups (for example resolve → stage → commit).
    pub next_steps: Vec<NextStep>,
    /// Mutually exclusive options (for example abort the merge instead of finishing).
    pub alternatives: Vec<NextStep>,
}

/// Map [`WtStatusState`] to the primary paused operation, if any.
#[must_use]
pub fn primary_in_progress_operation(state: &WtStatusState) -> Option<InProgressOperation> {
    if state.merge_in_progress {
        return Some(InProgressOperation::Merge);
    }
    if state.rebase_interactive_in_progress {
        return Some(InProgressOperation::RebaseInteractive);
    }
    if state.rebase_in_progress {
        return Some(InProgressOperation::Rebase);
    }
    if state.am_in_progress {
        return Some(InProgressOperation::Am);
    }
    if state.cherry_pick_in_progress {
        return Some(InProgressOperation::CherryPick);
    }
    if state.revert_in_progress {
        return Some(InProgressOperation::Revert);
    }
    if state.bisect_in_progress {
        return Some(InProgressOperation::Bisect);
    }
    None
}

/// Next steps when a pick/revert sequencer stopped on an empty commit (`--empty stop`).
#[must_use]
pub fn operation_next_steps_empty(kind: InProgressOperation) -> Vec<NextStep> {
    match kind {
        InProgressOperation::CherryPick | InProgressOperation::Revert => {
            vec![NextStep::Skip(kind)]
        }
        other => operation_next_steps(other, false),
    }
}

/// Ordered next steps for a paused operation given whether unmerged index entries remain.
#[must_use]
pub fn operation_next_steps(
    kind: InProgressOperation,
    has_unmerged_conflicts: bool,
) -> Vec<NextStep> {
    match kind {
        InProgressOperation::Merge => {
            if has_unmerged_conflicts {
                vec![NextStep::ResolveConflicts, NextStep::StageResolved]
            } else {
                vec![NextStep::Continue(InProgressOperation::Merge)]
            }
        }
        InProgressOperation::CherryPick | InProgressOperation::Revert => {
            if has_unmerged_conflicts {
                vec![
                    NextStep::ResolveConflicts,
                    NextStep::StageResolved,
                    NextStep::Continue(kind),
                ]
            } else {
                vec![NextStep::Continue(kind)]
            }
        }
        InProgressOperation::Rebase => {
            if has_unmerged_conflicts {
                vec![
                    NextStep::ResolveConflicts,
                    NextStep::StageResolved,
                    NextStep::Continue(InProgressOperation::Rebase),
                ]
            } else {
                vec![NextStep::Continue(InProgressOperation::Rebase)]
            }
        }
        InProgressOperation::RebaseInteractive
        | InProgressOperation::Am
        | InProgressOperation::Bisect => vec![],
    }
}

/// Steps that cancel or bypass the ordered [`operation_next_steps`] sequence.
#[must_use]
pub fn operation_alternatives(kind: InProgressOperation) -> Vec<NextStep> {
    match kind {
        InProgressOperation::Merge => vec![NextStep::Abort(InProgressOperation::Merge)],
        InProgressOperation::CherryPick => vec![
            NextStep::Abort(InProgressOperation::CherryPick),
            NextStep::Skip(InProgressOperation::CherryPick),
        ],
        InProgressOperation::Revert => vec![
            NextStep::Abort(InProgressOperation::Revert),
            NextStep::Skip(InProgressOperation::Revert),
        ],
        InProgressOperation::Rebase => vec![
            NextStep::Abort(InProgressOperation::Rebase),
            NextStep::Skip(InProgressOperation::Rebase),
        ],
        InProgressOperation::RebaseInteractive
        | InProgressOperation::Am
        | InProgressOperation::Bisect => vec![],
    }
}

/// [`Operation`] guidance for [`StatusModel`](crate::porcelain::status::StatusModel).
///
/// Merge, cherry-pick, revert, and grit rebase sessions expose continue/abort/skip hints when
/// grit implements the matching commands. Other in-progress states detected via [`WtStatusState`]
/// omit `operation` until grit implements them.
#[must_use]
pub fn status_operation(state: &WtStatusState, has_unmerged_conflicts: bool) -> Option<Operation> {
    let kind = if state.merge_in_progress {
        InProgressOperation::Merge
    } else if state.grit_rebase_in_progress {
        InProgressOperation::Rebase
    } else if let Some(kind) = state.grit_replay_kind {
        kind
    } else if state.cherry_pick_in_progress {
        InProgressOperation::CherryPick
    } else if state.revert_in_progress {
        InProgressOperation::Revert
    } else {
        return None;
    };
    let next_steps = if state.grit_replay_empty_stop && !has_unmerged_conflicts {
        operation_next_steps_empty(kind)
    } else {
        operation_next_steps(kind, has_unmerged_conflicts)
    };
    Some(Operation {
        kind,
        next_steps,
        alternatives: operation_alternatives(kind),
    })
}

/// Full snapshot of a repository's state.
///
/// This is the information that porcelain commands like `status` need to
/// display the repository's current situation.
#[derive(Debug, Clone)]
pub struct RepoState {
    /// Current HEAD state.
    pub head: HeadState,
    /// In-progress operations (there can be multiple, e.g. rebase + merge).
    pub in_progress: Vec<InProgressOperation>,
    /// Whether the repository is bare.
    pub is_bare: bool,
}

/// Resolve HEAD from the given git directory.
///
/// Reads `HEAD`, follows symbolic refs, and resolves the final OID.
///
/// # Parameters
///
/// - `git_dir` — path to the `.git` directory.
///
/// # Errors
///
/// Returns [`Error::Io`] if files cannot be read.
pub fn resolve_head(git_dir: &Path) -> Result<HeadState> {
    resolve_head_impl(git_dir, None)
}

/// Resolve `HEAD` using the repository's cached ref store (avoids re-reading local `config`).
pub fn resolve_head_for_repository(repo: &crate::repo::Repository) -> Result<HeadState> {
    resolve_head_impl(repo.git_dir(), Some(repo))
}

fn resolve_head_impl(git_dir: &Path, repo: Option<&crate::repo::Repository>) -> Result<HeadState> {
    let resolve_named = |refname: &str| -> Result<Option<crate::objects::ObjectId>> {
        if let Some(r) = repo {
            return r.references().resolve_if_exists(refname);
        }
        match crate::refs::resolve_ref(git_dir, refname) {
            Ok(oid) => Ok(Some(oid)),
            Err(Error::RefStore(RefStoreError::NotFound { .. })) => Ok(None),
            Err(e) => Err(e),
        }
    };
    let read_symbolic = |refname: &str| -> Result<Option<String>> {
        if let Some(r) = repo {
            crate::refs::read_symbolic_ref_for_repository(r, refname)
        } else {
            crate::refs::read_symbolic_ref(git_dir, refname)
        }
    };
    let head_path = git_dir.join("HEAD");
    let content = match fs::read_link(&head_path) {
        Ok(link_target) => {
            let rendered = link_target.to_string_lossy();
            if link_target.is_absolute() || rendered.starts_with("refs/") {
                format!("ref: {rendered}")
            } else {
                fs::read_to_string(&head_path).map_err(Error::Io)?
            }
        }
        Err(_) => match fs::read_to_string(&head_path) {
            Ok(c) => c,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(HeadState::Invalid),
            Err(e) => return Err(Error::Io(e)),
        },
    };

    let trimmed = content.trim();

    if let Some(refname) = trimmed.strip_prefix("ref: ") {
        let refname = if refname == "refs/heads/.invalid" {
            if let Ok(Some(target)) = read_symbolic("HEAD") {
                target
            } else if let Ok(Some(oid)) = resolve_named("HEAD") {
                // Detached HEAD: Git keeps the `.invalid` stub on disk while the OID lives in reftable.
                return Ok(HeadState::Detached { oid });
            } else {
                match crate::refs::read_ref_file(&git_dir.join("refs").join("heads")) {
                    Ok(crate::refs::Ref::Symbolic(target)) => target,
                    _ => refname.to_owned(),
                }
            }
        } else {
            refname.to_owned()
        };
        if check_refname_format(&refname, &RefNameOptions::default()).is_err() {
            return Ok(HeadState::Invalid);
        }
        let short_name = refname
            .strip_prefix("refs/heads/")
            .unwrap_or(&refname)
            .to_owned();

        // Resolve the branch tip via the shared refs backend (worktrees, packed-refs).
        // Missing `refs/heads/*` => unborn branch (`None`). A symref to a non-branch
        // target that cannot be resolved (e.g. HEAD -> `.broken`) is invalid, matching
        // Git `refs_resolve_ref_unsafe` returning no target for `worktree list`.
        let oid = match resolve_named(&refname)? {
            Some(oid) => Some(oid),
            None if refname.starts_with("refs/heads/") => None,
            None => return Ok(HeadState::Invalid),
        };

        Ok(HeadState::Branch {
            refname,
            short_name,
            oid,
        })
    } else {
        // Detached HEAD — should be a hex OID
        match ObjectId::from_hex(trimmed) {
            Ok(oid) => Ok(HeadState::Detached { oid }),
            Err(_) => Ok(HeadState::Invalid),
        }
    }
}

/// True when grit owns the in-progress rebase (`.git/rebase-merge/grit-plan`).
fn grit_rebase_plan_active(rebase_merge: &Path) -> bool {
    rebase_merge.join("grit-plan").is_file()
}

/// Detect in-progress operations by checking for sentinel files.
///
/// # Parameters
///
/// - `git_dir` — path to the `.git` directory.
///
/// # Returns
///
/// A list of detected in-progress operations.
pub fn detect_in_progress(git_dir: &Path) -> Vec<InProgressOperation> {
    let mut ops = Vec::new();

    if git_dir.join("MERGE_HEAD").exists() {
        ops.push(InProgressOperation::Merge);
    }

    // Interactive rebase: rebase-merge/ directory
    let rebase_merge = git_dir.join("rebase-merge");
    if rebase_merge.is_dir() {
        if rebase_merge.join("interactive").exists() && !grit_rebase_plan_active(&rebase_merge) {
            ops.push(InProgressOperation::RebaseInteractive);
        } else {
            ops.push(InProgressOperation::Rebase);
        }
    }

    // Non-interactive rebase or am: rebase-apply/ directory
    let rebase_apply = git_dir.join("rebase-apply");
    if rebase_apply.is_dir() {
        if rebase_apply.join("applying").exists() {
            ops.push(InProgressOperation::Am);
        } else {
            ops.push(InProgressOperation::Rebase);
        }
    }

    if git_dir.join("CHERRY_PICK_HEAD").exists() {
        ops.push(InProgressOperation::CherryPick);
    }

    if git_dir.join("REVERT_HEAD").exists() {
        ops.push(InProgressOperation::Revert);
    }

    let bisect_log = crate::refs::common_dir(git_dir)
        .unwrap_or_else(|| git_dir.to_path_buf())
        .join("BISECT_LOG");
    if bisect_log.exists() {
        ops.push(InProgressOperation::Bisect);
    }

    ops
}

/// Snapshot of repository state used by `git status` long-format output (`wt-status.c`).
///
/// This mirrors Git's `struct wt_status_state` closely enough for advice lines and
/// branch headers (merge, rebase, cherry-pick, revert, bisect, am, detached HEAD).
#[derive(Debug, Clone, Default)]
pub struct WtStatusState {
    /// `MERGE_HEAD` exists (merge or merge+rebase).
    pub merge_in_progress: bool,
    /// `.git/rebase-merge/` exists and `interactive` is present.
    pub rebase_interactive_in_progress: bool,
    /// Rebase without interactive marker (`rebase-merge` non-interactive or `rebase-apply`).
    pub rebase_in_progress: bool,
    /// Display string for the branch being rebased (from `head-name`, may be absent).
    pub rebase_branch: Option<String>,
    /// Display string for the rebase onto commit (from `onto`, abbreviated OID or name).
    pub rebase_onto: Option<String>,
    /// `rebase-apply/applying` exists.
    pub am_in_progress: bool,
    /// Empty patch in `am` session (`rebase-apply/patch` has size 0).
    pub am_empty_patch: bool,
    /// `CHERRY_PICK_HEAD` or sequencer pick without head.
    pub cherry_pick_in_progress: bool,
    /// Commit being cherry-picked; `None` when only the sequencer records progress.
    pub cherry_pick_head_oid: Option<ObjectId>,
    /// `REVERT_HEAD` or sequencer revert without head.
    pub revert_in_progress: bool,
    /// Commit being reverted when [`Self::revert_in_progress`] is true.
    pub revert_head_oid: Option<ObjectId>,
    /// `BISECT_LOG` exists (checked under common dir).
    pub bisect_in_progress: bool,
    /// Label read from `BISECT_LOG` for status output when bisecting.
    pub bisecting_from: Option<String>,
    /// Detached HEAD: human label (`wt_status_get_detached_from`).
    pub detached_from: Option<String>,
    /// True when `HEAD` OID equals the detached tip OID.
    pub detached_at: bool,
    /// Grit wrote `.git/sequencer/grit-opts` for this replay (show pick/revert operation hints).
    pub grit_replay_sequencer: bool,
    /// When [`Self::grit_replay_sequencer`] is true, the persisted pick/revert kind from `grit-opts`.
    pub grit_replay_kind: Option<InProgressOperation>,
    /// Grit `--empty stop` pause without index conflicts (suggest `--skip`, not `--continue`).
    pub grit_replay_empty_stop: bool,
    /// Grit wrote `.git/rebase-merge/grit-plan` for a resumable rebase session.
    pub grit_rebase_in_progress: bool,
}

fn abbrev_oid(oid: &ObjectId) -> String {
    oid.to_hex()[..7].to_string()
}

fn read_trimmed_line(path: &Path) -> Option<String> {
    let s = fs::read_to_string(path).ok()?;
    let mut line = s.lines().next()?.to_string();
    while line.ends_with('\n') || line.ends_with('\r') {
        line.pop();
    }
    if line.is_empty() {
        None
    } else {
        Some(line)
    }
}

/// Read a single-line ref/OID file like Git `get_branch()` in `wt-status.c`.
fn get_branch_display(git_dir: &Path, rel: &str) -> Option<String> {
    let path = git_dir.join(rel);
    let mut sb = read_trimmed_line(&path)?;
    if let Some(branch_name) = sb.strip_prefix("refs/heads/") {
        sb = branch_name.to_string();
    } else if sb.starts_with("refs/") {
        // keep full ref for remotes etc.
    } else if ObjectId::from_hex(&sb).is_ok() {
        let oid = ObjectId::from_hex(&sb).ok()?;
        sb = abbrev_oid(&oid);
    } else if sb == "detached HEAD" {
        return None;
    }
    Some(sb)
}

fn strip_ref_for_display(full: &str) -> String {
    if let Some(s) = full.strip_prefix("refs/tags/") {
        return s.to_string();
    }
    if let Some(s) = full.strip_prefix("refs/remotes/") {
        return s.to_string();
    }
    if let Some(s) = full.strip_prefix("refs/heads/") {
        return s.to_string();
    }
    full.to_string()
}

fn ref_name_exists(git_dir: &Path, refname: &str) -> bool {
    git_dir.join(refname).exists()
        || crate::refs::packed_refs_entry_exists(git_dir, refname).unwrap_or(false)
}

fn dwim_detach_label(git_dir: &Path, target: &str, noid: ObjectId) -> String {
    if target == "HEAD" {
        return abbrev_oid(&noid);
    }
    if target.starts_with("refs/") {
        if let Ok(oid) = crate::refs::resolve_ref(git_dir, target) {
            if oid == noid {
                return strip_ref_for_display(target);
            }
        }
    }
    for candidate in [
        format!("refs/heads/{target}"),
        format!("refs/tags/{target}"),
        format!("refs/remotes/{target}"),
    ] {
        if candidate.starts_with("refs/tags/") && ref_name_exists(git_dir, &candidate) {
            return strip_ref_for_display(&candidate);
        }
        if let Ok(oid) = crate::refs::resolve_ref(git_dir, &candidate) {
            if oid == noid {
                return strip_ref_for_display(&candidate);
            }
        }
    }
    if ObjectId::is_hex_len(target.len()) {
        if let Ok(oid) = ObjectId::from_hex(target) {
            if oid == noid {
                return abbrev_oid(&noid);
            }
        }
    }
    // `checkout … to <abbrev>` records the object name from the user's input; show that
    // abbreviation (Git does not substitute a tag name here — see t3203 detached HEAD).
    if !target.is_empty()
        && target.chars().all(|c| c.is_ascii_hexdigit())
        && target.len() <= noid.algo().hex_len()
        && noid.to_hex().starts_with(target)
    {
        return target.to_owned();
    }
    abbrev_oid(&noid)
}

fn wt_status_get_detached_from(git_dir: &Path, head_oid: ObjectId) -> Option<(String, bool)> {
    let entries = reflog::read_reflog(git_dir, "HEAD").ok()?;
    for entry in entries.iter().rev() {
        let msg = entry.message.trim();
        let Some(rest) = msg.strip_prefix("checkout: moving from ") else {
            continue;
        };
        let Some(idx) = rest.rfind(" to ") else {
            continue;
        };
        let target = rest[idx + 4..].trim();
        let noid = entry.new_oid;
        let label = dwim_detach_label(git_dir, target, noid);
        let detached_at = head_oid == noid;
        return Some((label, detached_at));
    }
    None
}

fn wt_status_check_rebase(git_dir: &Path, state: &mut WtStatusState) -> bool {
    let apply = git_dir.join("rebase-apply");
    if apply.is_dir() {
        if apply.join("applying").exists() {
            state.am_in_progress = true;
            let patch = apply.join("patch");
            if let Ok(meta) = patch.metadata() {
                if meta.len() == 0 {
                    state.am_empty_patch = true;
                }
            }
        } else {
            state.rebase_in_progress = true;
            state.rebase_branch = get_branch_display(git_dir, "rebase-apply/head-name");
            state.rebase_onto = get_branch_display(git_dir, "rebase-apply/onto");
        }
        return true;
    }
    let merge = git_dir.join("rebase-merge");
    if merge.is_dir() {
        let grit_plan = grit_rebase_plan_active(&merge);
        if merge.join("interactive").exists() && !grit_plan {
            state.rebase_interactive_in_progress = true;
        } else {
            state.rebase_in_progress = true;
        }
        state.grit_rebase_in_progress = grit_plan;
        state.rebase_branch = get_branch_display(git_dir, "rebase-merge/head-name");
        state.rebase_onto = get_branch_display(git_dir, "rebase-merge/onto");
        return true;
    }
    false
}

fn sequencer_first_replay(git_dir: &Path) -> Option<bool> {
    let path = git_dir.join("sequencer").join("todo");
    if !path.is_file() {
        return None;
    }
    let content = fs::read_to_string(&path).ok()?;
    for line in content.lines() {
        let t = line.trim();
        if t.is_empty() || t.starts_with('#') {
            continue;
        }
        let mut parts = t.split_whitespace();
        let cmd = parts.next()?;
        return match cmd {
            "pick" | "p" => Some(true),
            "revert" | "r" => Some(false),
            _ => None,
        };
    }
    None
}

/// Fill [`WtStatusState`] the same way Git `wt_status_get_state` does (without sparse checkout %).
///
/// `get_detached_from` matches Git's third parameter: when true and `head` is detached, populate
/// `detached_from` / `detached_at` from the `HEAD` reflog.
pub fn wt_status_get_state(
    git_dir: &Path,
    head: &HeadState,
    get_detached_from: bool,
) -> Result<WtStatusState> {
    let mut state = WtStatusState::default();

    if git_dir.join("MERGE_HEAD").exists() {
        wt_status_check_rebase(git_dir, &mut state);
        state.merge_in_progress = true;
    } else if wt_status_check_rebase(git_dir, &mut state) {
        // rebase/am state already filled
    } else if let Some(oid) = read_cherry_pick_head(git_dir)? {
        state.cherry_pick_in_progress = true;
        state.cherry_pick_head_oid = Some(oid);
    }

    let bisect_base = crate::refs::common_dir(git_dir).unwrap_or_else(|| git_dir.to_path_buf());
    if bisect_base.join("BISECT_LOG").exists() {
        state.bisect_in_progress = true;
        state.bisecting_from = get_branch_display(&bisect_base, "BISECT_START");
    }

    if let Some(oid) = read_revert_head(git_dir)? {
        state.revert_in_progress = true;
        state.revert_head_oid = Some(oid);
    }

    if let Some(is_pick) = sequencer_first_replay(git_dir) {
        if is_pick && !state.cherry_pick_in_progress {
            state.cherry_pick_in_progress = true;
            state.cherry_pick_head_oid = None;
        } else if !is_pick && !state.revert_in_progress {
            state.revert_in_progress = true;
            state.revert_head_oid = None;
        }
    }

    if get_detached_from {
        if let HeadState::Detached { oid } = head {
            if let Some((label, at)) = wt_status_get_detached_from(git_dir, *oid) {
                state.detached_from = Some(label);
                state.detached_at = at;
            }
        }
    }

    state.grit_replay_sequencer = git_dir.join("sequencer").join("grit-opts").is_file();
    if state.grit_replay_sequencer {
        if let Some((kind, empty_stop)) = read_grit_replay_status_hints(git_dir) {
            state.grit_replay_kind = Some(kind);
            state.grit_replay_empty_stop = empty_stop;
            match kind {
                InProgressOperation::CherryPick => {
                    state.revert_in_progress = false;
                    state.revert_head_oid = None;
                    if !state.cherry_pick_in_progress {
                        state.cherry_pick_in_progress = true;
                    }
                }
                InProgressOperation::Revert => {
                    state.cherry_pick_in_progress = false;
                    state.cherry_pick_head_oid = None;
                    if !state.revert_in_progress {
                        state.revert_in_progress = true;
                    }
                }
                _ => {}
            }
        }
    }

    Ok(state)
}

fn read_grit_replay_status_hints(git_dir: &Path) -> Option<(InProgressOperation, bool)> {
    let path = git_dir.join("sequencer").join("grit-opts");
    let content = fs::read_to_string(&path).ok()?;
    let mut direction = None;
    let mut empty = "stop";
    for line in content.lines() {
        let line = line.trim();
        let Some((key, value)) = line.split_once('=') else {
            continue;
        };
        match key.trim() {
            "direction" => {
                direction = Some(if value.trim() == "revert" {
                    InProgressOperation::Revert
                } else {
                    InProgressOperation::CherryPick
                });
            }
            "empty" => empty = value.trim(),
            _ => {}
        }
    }
    let kind = direction?;
    let empty_stop = empty == "stop"
        && (read_cherry_pick_head(git_dir).ok().flatten().is_some()
            || read_revert_head(git_dir).ok().flatten().is_some());
    Some((kind, empty_stop))
}

/// Whether a split commit is in progress during interactive rebase (`wt-status.c` `split_commit_in_progress`).
pub fn split_commit_in_progress(git_dir: &Path, head: &HeadState) -> bool {
    let HeadState::Detached { oid: head_oid } = head else {
        return false;
    };
    let Some(amend_line) = read_trimmed_line(&git_dir.join("rebase-merge/amend")) else {
        return false;
    };
    let Some(orig_line) = read_trimmed_line(&git_dir.join("rebase-merge/orig-head")) else {
        return false;
    };
    let Ok(amend_oid) = ObjectId::from_hex(amend_line.trim()) else {
        return false;
    };
    let Ok(orig_head_oid) = ObjectId::from_hex(orig_line.trim()) else {
        return false;
    };
    if amend_line == orig_line {
        head_oid != &amend_oid
    } else if let Ok(Some(cur_orig)) = read_orig_head(git_dir) {
        cur_orig != orig_head_oid
    } else {
        false
    }
}

/// Build a complete [`RepoState`] snapshot for a repository.
///
/// # Parameters
///
/// - `git_dir` — path to the `.git` directory.
/// - `is_bare` — whether this is a bare repository.
///
/// # Errors
///
/// Returns [`Error::Io`] on filesystem failures.
pub fn repo_state(git_dir: &Path, is_bare: bool) -> Result<RepoState> {
    let head = resolve_head(git_dir)?;
    let in_progress = detect_in_progress(git_dir);

    Ok(RepoState {
        head,
        in_progress,
        is_bare,
    })
}

/// Read the MERGE_HEAD file and return the OIDs listed.
///
/// # Parameters
///
/// - `git_dir` — path to the `.git` directory.
///
/// # Returns
///
/// A vector of merge parent OIDs, or empty if not in a merge.
pub fn read_merge_heads(git_dir: &Path) -> Result<Vec<ObjectId>> {
    let path = git_dir.join("MERGE_HEAD");
    let content = match fs::read_to_string(&path) {
        Ok(c) => c,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(e) => return Err(Error::Io(e)),
    };

    let mut oids = Vec::new();
    for line in content.lines() {
        let trimmed = line.trim();
        if !trimmed.is_empty() {
            oids.push(ObjectId::from_hex(trimmed)?);
        }
    }
    Ok(oids)
}

/// Read the MERGE_MSG file.
///
/// # Parameters
///
/// - `git_dir` — path to the `.git` directory.
///
/// # Returns
///
/// The merge message text, or `None` if not in a merge.
pub fn read_merge_msg(git_dir: &Path) -> Result<Option<String>> {
    let path = git_dir.join("MERGE_MSG");
    match fs::read_to_string(&path) {
        Ok(c) => Ok(Some(c)),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(e) => Err(Error::Io(e)),
    }
}

/// Remove merge-in-progress sentinel files after a successful merge commit.
///
/// Prefer [`finish_merge_state`] for merge commits; it also restores autostash and clears rerere.
///
/// # Parameters
///
/// - `git_dir` — path to the `.git` directory.
///
/// # Errors
///
/// Returns [`Error::Io`] if a present sentinel file cannot be removed.
pub fn clear_merge_state(git_dir: &Path) -> Result<()> {
    for name in merge_completion_sentinels() {
        let path = git_dir.join(name);
        if path.exists() {
            fs::remove_file(&path).map_err(Error::Io)?;
        }
    }
    Ok(())
}

/// Sentinel filenames Git removes when a merge concludes with `git commit`.
#[must_use]
pub fn merge_completion_sentinels() -> &'static [&'static str] {
    &[
        "MERGE_HEAD",
        "MERGE_MSG",
        "MERGE_MODE",
        "MERGE_LOG",
        "AUTO_MERGE",
        "SQUASH_MSG",
        "MERGE_AUTOSTASH",
    ]
}

/// Complete merge auxiliary state after a successful merge commit.
///
/// Applies `MERGE_AUTOSTASH` (when present), clears rerere merge records, then removes merge
/// sentinel files via [`clear_merge_state`].
///
/// # Returns
///
/// `true` when applying the merge autostash left conflicts (the autostash entry is kept).
///
/// # Errors
///
/// Propagates autostash apply, rerere, and I/O failures.
pub fn finish_merge_state(repo: &Repository) -> Result<bool> {
    let autostash_conflicts = crate::porcelain::stash::apply_merge_autostash(repo)?;
    let _ = crate::rerere::finish_merge_rerere(repo)?;
    clear_merge_state(repo.git_dir())?;
    Ok(autostash_conflicts)
}

/// Read CHERRY_PICK_HEAD when it contains a valid 40-hex OID; `None` if missing, empty, or invalid
/// (Git ignores malformed `CHERRY_PICK_HEAD` for the "commit $abbrev" line; sequencer still applies).
pub fn read_cherry_pick_head(git_dir: &Path) -> Result<Option<ObjectId>> {
    read_oid_head_file_optional(&git_dir.join("CHERRY_PICK_HEAD"))
}

/// Read REVERT_HEAD when it contains a valid OID; `None` if missing, empty, or invalid.
pub fn read_revert_head(git_dir: &Path) -> Result<Option<ObjectId>> {
    read_oid_head_file_optional(&git_dir.join("REVERT_HEAD"))
}

fn read_oid_head_file_optional(path: &Path) -> Result<Option<ObjectId>> {
    match fs::read_to_string(path) {
        Ok(content) => {
            let trimmed = content.trim();
            if trimmed.is_empty() {
                Ok(None)
            } else {
                Ok(ObjectId::from_hex(trimmed).ok())
            }
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(e) => Err(Error::Io(e)),
    }
}

/// Read ORIG_HEAD.
pub fn read_orig_head(git_dir: &Path) -> Result<Option<ObjectId>> {
    read_single_oid_file(&git_dir.join("ORIG_HEAD"))
}

/// Read a file that contains a single OID on its first line.
fn read_single_oid_file(path: &Path) -> Result<Option<ObjectId>> {
    match fs::read_to_string(path) {
        Ok(content) => {
            let trimmed = content.trim();
            if trimmed.is_empty() {
                Ok(None)
            } else {
                Ok(Some(ObjectId::from_hex(trimmed)?))
            }
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(e) => Err(Error::Io(e)),
    }
}

#[cfg(test)]
mod merge_sentinel_tests {
    #![allow(clippy::unwrap_used)]

    use super::{clear_merge_state, merge_completion_sentinels};
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn clear_merge_state_removes_every_completion_sentinel() {
        let tmp = TempDir::new().unwrap();
        let git = tmp.path().join(".git");
        fs::create_dir_all(&git).unwrap();
        for name in merge_completion_sentinels() {
            fs::write(git.join(name), b"x").unwrap();
        }
        clear_merge_state(&git).unwrap();
        for name in merge_completion_sentinels() {
            assert!(!git.join(name).exists(), "expected {name} to be removed");
        }
    }
}

#[cfg(test)]
mod head_state_tests {
    #![allow(clippy::unwrap_used)]

    use super::{resolve_head, resolve_head_for_repository, HeadState};
    use crate::repo::init_repository;
    use crate::RefStorageFormat;
    use tempfile::TempDir;

    fn unborn_main() -> HeadState {
        HeadState::Branch {
            refname: "refs/heads/main".to_owned(),
            short_name: "main".to_owned(),
            oid: None,
        }
    }

    #[test]
    fn unborn_branch_resolves_without_oid_on_every_backend() {
        for format in [RefStorageFormat::Files, RefStorageFormat::Reftable] {
            let tmp = TempDir::new().unwrap();
            let repo = init_repository(tmp.path(), false, "main", None, format).unwrap();
            assert_eq!(resolve_head(repo.git_dir()).unwrap(), unborn_main());
            assert_eq!(resolve_head_for_repository(&repo).unwrap(), unborn_main());
        }
    }

    #[test]
    fn head_symref_to_missing_non_branch_is_invalid() {
        let tmp = TempDir::new().unwrap();
        let repo =
            init_repository(tmp.path(), false, "main", None, RefStorageFormat::Files).unwrap();
        std::fs::write(repo.git_dir().join("HEAD"), "ref: refs/tags/missing\n").unwrap();
        assert_eq!(resolve_head(repo.git_dir()).unwrap(), HeadState::Invalid);
        assert_eq!(
            resolve_head_for_repository(&repo).unwrap(),
            HeadState::Invalid
        );
    }
}