Skip to main content

gitwig_core/
lib.rs

1//! Filesystem + git repository inspection.
2//!
3//! This module owns both the "is this a git repo?" classification used by
4//! the per-card indicator AND the richer detail collection used by the
5//! Detail view. They share a single `collect_summary` helper so the same
6//! libgit2 work doesn't run twice.
7//!
8//! The cheap `is_dir()` + `.git`-existence check still gates everything —
9//! we only spin up libgit2 when both checks pass.
10
11#![deny(unsafe_code)]
12#![deny(unused_imports, unused_must_use, dead_code, unused_assignments)]
13#![deny(clippy::all, clippy::perf)]
14#![allow(clippy::collapsible_if, clippy::collapsible_else_if)]
15#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::panic))]
16
17use std::path::{Path, PathBuf};
18use std::time::{Duration, SystemTime, UNIX_EPOCH};
19
20use git2::{Repository, StatusOptions, StatusShow};
21
22// ── Card-level status ──────────────────────────────────────────────────────
23
24/// Per-item filesystem classification carried alongside `config.items`.
25/// `GitRepo`'s inner `Option` is `None` when `.git` exists but libgit2
26/// couldn't open or read the repo — we know it's a repo, we just can't
27/// summarize its state.
28#[derive(Debug, Clone)]
29pub enum ItemStatus {
30    Missing,
31    Directory,
32    GitRepo(Option<RepoSummary>),
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
36pub enum RepoState {
37    #[default]
38    Clean,
39    Merge,
40    Revert,
41    CherryPick,
42    Bisect,
43    Rebase,
44    ApplyMailbox,
45}
46
47/// Compact summary used to draw the per-card indicator. Also embedded in
48/// `RepoInfo` so the Detail view doesn't re-collect the same data.
49#[derive(Debug, Default, Clone)]
50pub struct RepoSummary {
51    /// Current branch shorthand (e.g. `"main"`). `None` for detached HEAD
52    /// or when the ref cannot be read.
53    pub branch: Option<String>,
54    pub staged: usize,
55    pub modified: usize,
56    pub untracked: usize,
57    pub conflicted: usize,
58    pub ahead: usize,
59    pub behind: usize,
60    pub state: RepoState,
61    pub last_commit_time: Option<i64>,
62}
63
64impl RepoSummary {
65    pub fn is_clean(&self) -> bool {
66        self.staged + self.modified + self.untracked + self.conflicted == 0
67    }
68    pub fn is_synced(&self) -> bool {
69        self.ahead + self.behind == 0
70    }
71    pub fn unchanged(&self) -> bool {
72        self.is_clean() && self.is_synced()
73    }
74}
75
76// ── Detail view ────────────────────────────────────────────────────────────
77
78#[derive(Debug, Clone)]
79pub enum ItemDetail {
80    Missing { resolved: PathBuf },
81    Directory { resolved: PathBuf },
82    Repo { resolved: PathBuf, info: Box<RepoInfo> },
83    Error { resolved: PathBuf, message: String },
84}
85
86#[derive(Debug, Clone, Default)]
87pub struct BranchInfo {
88    pub name: String,
89    pub is_head: bool,
90    pub short_sha: String,
91    pub short_message: String,
92}
93
94#[derive(Debug, Clone, Default)]
95pub struct FileRevision {
96    pub commit_oid: String,
97    pub author: String,
98    pub date: String,
99    pub when: String,
100    pub summary: String,
101}
102
103#[derive(Debug, Clone, Default)]
104pub struct StashInfo {
105    pub index: usize,
106    pub message: String,
107    pub commit_id: String,
108    pub files: Vec<FileEntry>,
109}
110
111#[derive(Debug, Clone, Default)]
112pub struct CommitterStat {
113    pub name: String,
114    pub email: String,
115    pub count: usize,
116}
117
118#[derive(Debug, Clone, PartialEq, Eq, Default)]
119pub enum TabData<T> {
120    #[default]
121    NotLoaded,
122    Loading,
123    Loaded(T),
124    Error(String),
125}
126
127impl<T> TabData<T> {
128    pub fn is_not_loaded(&self) -> bool {
129        matches!(self, TabData::NotLoaded)
130    }
131    pub fn is_loading(&self) -> bool {
132        matches!(self, TabData::Loading)
133    }
134    #[allow(dead_code)]
135    pub fn is_loaded(&self) -> bool {
136        matches!(self, TabData::Loaded(_))
137    }
138    pub fn as_ref(&self) -> Option<&T> {
139        match self {
140            TabData::Loaded(val) => Some(val),
141            _ => None,
142        }
143    }
144}
145
146impl<T> TabData<Vec<T>> {
147    pub fn len(&self) -> usize {
148        self.as_ref().map(|v| v.len()).unwrap_or(0)
149    }
150    pub fn is_empty(&self) -> bool {
151        self.as_ref().map(|v| v.is_empty()).unwrap_or(true)
152    }
153    pub fn first(&self) -> Option<&T> {
154        self.as_ref().and_then(|v| v.first())
155    }
156    pub fn get(&self, index: usize) -> Option<&T> {
157        self.as_ref().and_then(|v| v.get(index))
158    }
159    pub fn iter(&self) -> std::slice::Iter<'_, T> {
160        match self {
161            TabData::Loaded(v) => v.iter(),
162            _ => [].iter(),
163        }
164    }
165    pub fn as_slice(&self) -> &[T] {
166        match self {
167            TabData::Loaded(v) => v.as_slice(),
168            _ => &[],
169        }
170    }
171}
172
173#[derive(Debug, Clone, Default, PartialEq, Eq)]
174pub struct WorktreeInfo {
175    pub name: String,
176    pub path: PathBuf,
177    pub branch: Option<String>,
178    pub is_locked: bool,
179    pub lock_reason: Option<String>,
180}
181
182#[derive(Debug, Clone, Default, PartialEq, Eq)]
183pub struct SubmoduleInfo {
184    pub name: String,
185    pub path: PathBuf,
186    pub url: String,
187    pub commit_id: Option<String>,
188    pub head_id: Option<String>,
189    pub is_initialized: bool,
190    pub is_dirty: bool,
191}
192
193#[derive(Debug, Clone)]
194pub enum TabPayload {
195    Files(Result<Vec<String>, String>),
196    Graph(Result<Vec<GraphLine>, String>),
197    Branches { local: Result<Vec<BranchInfo>, String>, remote: Result<Vec<BranchInfo>, String> },
198    Tags { local: Result<Vec<BranchInfo>, String>, remote: Result<Vec<BranchInfo>, String> },
199    Remotes(Result<Vec<RemoteInfo>, String>),
200    Stashes(Result<Vec<StashInfo>, String>),
201    Overview(Result<(Vec<CommitterStat>, bool), String>),
202    Worktrees(Result<Vec<WorktreeInfo>, String>),
203    Submodules(Result<Vec<SubmoduleInfo>, String>),
204}
205
206#[derive(Debug, Default, Clone)]
207pub struct RepoInfo {
208    pub branch: Option<String>,
209    pub head: Option<HeadInfo>,
210    pub remotes: TabData<Vec<RemoteInfo>>,
211    /// Configured upstream branch (e.g. "origin/main") if HEAD tracks one.
212    pub upstream: Option<String>,
213    pub summary: RepoSummary,
214    /// File-level changes, populated by `collect_info` for the Detail view.
215    pub changes: WorktreeChanges,
216    /// Recent commits in this repository.
217    pub commits: Vec<CommitEntry>,
218    /// Graph view lines for the repository.
219    pub graph_lines: TabData<Vec<GraphLine>>,
220    /// Local branches in the repository.
221    pub local_branches: TabData<Vec<BranchInfo>>,
222    /// Remote branches in the repository.
223    pub remote_branches: TabData<Vec<BranchInfo>>,
224    /// Local tags in the repository.
225    pub local_tags: TabData<Vec<BranchInfo>>,
226    /// Remote tags in the repository.
227    pub remote_tags: TabData<Vec<BranchInfo>>,
228    /// Whether remote tags have been loaded from the remote repository.
229    pub remote_tags_loaded: bool,
230    /// Whether a remote tag fetch has been attempted in this session.
231    pub remote_tags_attempted: bool,
232    /// Tracked files in the repository.
233    pub files: TabData<Vec<String>>,
234    /// Available stashes in the repository.
235    pub stashes: TabData<Vec<StashInfo>>,
236    /// Available worktrees in the repository.
237    pub worktrees: TabData<Vec<WorktreeInfo>>,
238    /// Configured submodules in the repository.
239    pub submodules: TabData<Vec<SubmoduleInfo>>,
240    /// Committer statistics.
241    pub committer_stats: TabData<Vec<CommitterStat>>,
242    /// Whether the committer statistics walk was capped by the limit.
243    pub committer_stats_limit_reached: bool,
244    /// Timestamps when each tab was loaded (index matches tab_idx)
245    pub tab_loaded_at: [Option<std::time::Instant>; 9],
246    /// Whether each tab is currently loading in the background (index matches tab_idx)
247    pub tab_loading: [bool; 9],
248}
249
250#[derive(Debug, Clone)]
251pub struct HeadInfo {
252    pub short_id: String,
253    pub summary: String,
254    pub author: String,
255    pub when: String,
256}
257
258#[derive(Debug, Clone)]
259pub struct RemoteInfo {
260    pub name: String,
261    pub url: String,
262    pub push_url: Option<String>,
263    pub refspecs: Vec<String>,
264}
265
266#[derive(Debug, Clone)]
267pub struct CommitEntry {
268    /// Short 7-char display ID.
269    pub id: String,
270    /// Full 40-char hex OID — used for diff lookup.
271    pub oid: String,
272    pub author: String,
273    pub when: String,
274    pub date: String,
275    pub summary: String,
276    pub message: String,
277    /// Local branch names and tags pointing at this commit.
278    /// Tags are prefixed with `"tag:"`, remote branches with `"remote:"`.
279    pub refs: Vec<String>,
280    /// Files changed in this commit (diff against first parent, or empty tree).
281    pub files: Vec<FileEntry>,
282    /// GPG/SSH signature status.
283    pub signature_status: String,
284}
285
286#[derive(Debug, Clone)]
287pub struct GraphLine {
288    pub graph: String,
289    pub commit: Option<GraphCommit>,
290}
291
292#[derive(Debug, Clone)]
293pub struct GraphCommit {
294    pub oid: String,
295    pub decoration: String,
296    pub summary: String,
297    pub author: String,
298    pub date: String,
299    /// GPG/SSH signature status.
300    pub signature_status: String,
301}
302
303/// One changed file in the working tree or index.
304#[derive(Debug, Clone)]
305pub struct FileEntry {
306    /// Path relative to the repository root.
307    pub path: String,
308    /// Short human-readable label: "N", "M", "D", "R", "T", "?", or "C".
309    pub label: &'static str,
310}
311
312/// File-level working-tree state collected for the Detail view.
313/// Split into four buckets so the UI can render them as separate sections.
314#[derive(Debug, Default, Clone)]
315pub struct WorktreeChanges {
316    pub staged: Vec<FileEntry>,
317    pub unstaged: Vec<FileEntry>,
318    pub untracked: Vec<FileEntry>,
319    pub conflicted: Vec<FileEntry>,
320}
321
322// ── Per-file diff ──────────────────────────────────────────────────────────
323
324/// The type of a single line in a unified diff.
325#[derive(Debug, Clone, PartialEq)]
326pub enum DiffLineKind {
327    /// `@@ ... @@` hunk header.
328    Header,
329    /// `+` added line.
330    Added,
331    /// `-` removed line.
332    Removed,
333    /// Unchanged context line.
334    Context,
335    /// Line in OURS section of a conflict.
336    ConflictOurs,
337    /// Line in THEIRS section of a conflict.
338    ConflictTheirs,
339    /// Conflict marker line (<<<<<<<, =======, >>>>>>>).
340    ConflictSeparator,
341}
342
343/// One line of a unified diff, as rendered in the Diff panel.
344#[derive(Debug, Clone)]
345pub struct DiffLine {
346    pub kind: DiffLineKind,
347    /// Raw content (already includes the leading +/−/space prefix character).
348    pub content: String,
349}
350
351/// Return the unified diff of `file_path` as it changed in `commit_oid`
352/// (hex string) inside the repository at `repo_path`.
353/// Returns an empty Vec on any error.
354pub fn get_commit_file_diff(repo_path: &Path, commit_oid: &str, file_path: &str) -> Vec<DiffLine> {
355    get_file_diff_inner(repo_path, commit_oid, file_path).unwrap_or_default()
356}
357
358/// Return the diff for `file_path` in the working tree.
359///
360/// - `staged = true`:  diff between HEAD and the index (what would be committed).
361/// - `staged = false`: diff between the index and the working directory (unstaged changes).
362///
363/// Returns an empty Vec on any error.
364pub fn get_worktree_file_diff(repo_path: &Path, file_path: &str, staged: bool) -> Vec<DiffLine> {
365    get_worktree_diff_inner(repo_path, file_path, staged).unwrap_or_default()
366}
367
368/// Add `file_path` to the index (equivalent to `git add <file>`).
369/// Returns a human-readable error string on failure.
370pub fn stage_file(repo_path: &Path, file_path: &str) -> Result<(), String> {
371    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
372    let mut index = repo.index().map_err(|e| e.to_string())?;
373    let full_path = repo_path.join(file_path);
374    if full_path.exists() {
375        index.add_path(Path::new(file_path)).map_err(|e| e.to_string())?;
376    } else {
377        index.remove_path(Path::new(file_path)).map_err(|e| e.to_string())?;
378    }
379    index.write().map_err(|e| e.to_string())?;
380    Ok(())
381}
382
383/// Remove `file_path` from the index (equivalent to `git restore --staged <file>`).
384/// When HEAD exists the index entry is reset to the HEAD tree value; for a brand-new
385/// repo with no commits the entry is simply removed from the index.
386/// Returns a human-readable error string on failure.
387pub fn unstage_file(repo_path: &Path, file_path: &str) -> Result<(), String> {
388    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
389    // Prefer reset_default (git reset HEAD -- <file>) when a HEAD commit exists.
390    if let Some(commit) = repo.head().ok().and_then(|h| h.peel_to_commit().ok()) {
391        repo.reset_default(Some(commit.as_object()), std::iter::once(file_path))
392            .map_err(|e| e.to_string())?;
393    } else {
394        // New repo with no commits: just remove the entry from the index.
395        let mut index = repo.index().map_err(|e| e.to_string())?;
396        index.remove_path(Path::new(file_path)).map_err(|e| e.to_string())?;
397        index.write().map_err(|e| e.to_string())?;
398    }
399    Ok(())
400}
401
402pub fn sanitize_text(s: &str) -> String {
403    let mut result = String::with_capacity(s.len());
404    let bytes = s.as_bytes();
405    let mut i = 0;
406    while i < bytes.len() {
407        if bytes[i] == 0x1B {
408            // Escape character: let's skip the sequence
409            i += 1;
410            if i < bytes.len() && bytes[i] == b'[' {
411                i += 1;
412                while i < bytes.len() {
413                    let c = bytes[i];
414                    i += 1;
415                    // ANSI escape sequences end with letters (A-Z, a-z)
416                    if c.is_ascii_alphabetic() {
417                        break;
418                    }
419                }
420            } else {
421                // Single ESC character or other VT100: skip it
422                while i < bytes.len() {
423                    let c = bytes[i];
424                    i += 1;
425                    if c == b' ' || c.is_ascii_alphabetic() {
426                        break;
427                    }
428                }
429            }
430        } else {
431            let c = bytes[i];
432            // Replace non-printable control characters except \n, \r, \t
433            if c < 0x20 && c != b'\n' && c != b'\r' && c != b'\t' {
434                result.push(' ');
435            } else {
436                result.push(c as char);
437            }
438            i += 1;
439        }
440    }
441    result
442}
443
444pub fn safe_sha_slice(sha: &str, len: usize) -> &str {
445    let mut end = len.min(sha.len());
446    while end > 0 && !sha.is_char_boundary(end) {
447        end -= 1;
448    }
449    &sha[..end]
450}
451
452fn ssh_command_val() -> &'static str {
453    if std::env::var("GITWIG_SSH_STRICT").map(|v| v == "1").unwrap_or(false) {
454        "ssh -o StrictHostKeyChecking=yes"
455    } else {
456        "ssh -o StrictHostKeyChecking=accept-new"
457    }
458}
459
460fn git_command() -> std::process::Command {
461    let mut cmd = std::process::Command::new("git");
462    cmd.env("GIT_TERMINAL_PROMPT", "0");
463    cmd.env("GIT_SSH_COMMAND", ssh_command_val());
464    cmd.env("GIT_ALLOW_PROTOCOL", "https:ssh:git:file");
465    cmd.env("GIT_PROTOCOL_FROM_USER", "0");
466    cmd
467}
468
469pub fn safe_ref(r: &str) -> Result<&str, String> {
470    let trimmed = r.trim();
471    if trimmed.starts_with('-') {
472        return Err(format!("Invalid ref name: '{}' (ref names cannot start with '-')", r));
473    }
474    if trimmed.is_empty() {
475        return Err("Ref name cannot be empty".to_string());
476    }
477    Ok(trimmed)
478}
479
480/// Stage all unstaged/untracked changes (equivalent to `git add -A`).
481pub fn stage_all_changes(repo_path: &Path) -> Result<(), String> {
482    let output = git_command()
483        .arg("add")
484        .arg("-A")
485        .current_dir(repo_path)
486        .output()
487        .map_err(|e| e.to_string())?;
488
489    if output.status.success() {
490        Ok(())
491    } else {
492        Err(String::from_utf8_lossy(&output.stderr).trim().to_string())
493    }
494}
495
496/// Unstage all staged changes (equivalent to `git reset`).
497pub fn unstage_all_changes(repo_path: &Path) -> Result<(), String> {
498    let output =
499        git_command().arg("reset").current_dir(repo_path).output().map_err(|e| e.to_string())?;
500
501    if output.status.success() {
502        Ok(())
503    } else {
504        Err(String::from_utf8_lossy(&output.stderr).trim().to_string())
505    }
506}
507
508/// Discard all staged, unstaged, and untracked changes in the repository.
509pub fn discard_all_changes(repo_path: &Path) -> Result<(), String> {
510    // 1. Unstage all first so everything is in the working tree
511    let _ = git_command().arg("reset").current_dir(repo_path).output();
512
513    // 2. Discard all tracked modifications
514    let checkout_out = git_command()
515        .arg("checkout")
516        .arg("--")
517        .arg(".")
518        .current_dir(repo_path)
519        .output()
520        .map_err(|e| e.to_string())?;
521
522    if !checkout_out.status.success() {
523        return Err(String::from_utf8_lossy(&checkout_out.stderr).trim().to_string());
524    }
525
526    // 3. Clean all untracked files/folders
527    let clean_out = git_command()
528        .arg("clean")
529        .arg("-fd")
530        .current_dir(repo_path)
531        .output()
532        .map_err(|e| e.to_string())?;
533
534    if !clean_out.status.success() {
535        return Err(String::from_utf8_lossy(&clean_out.stderr).trim().to_string());
536    }
537
538    Ok(())
539}
540
541/// Stage a single hunk of unstaged changes (equivalent to `git apply --cached -`).
542pub fn stage_hunk(repo_path: &Path, file_path: &str, hunk: &[DiffLine]) -> Result<(), String> {
543    apply_hunk_patch(repo_path, file_path, hunk, false, true)
544}
545
546/// Unstage a single hunk of staged changes (equivalent to `git apply --cached --reverse -`).
547pub fn unstage_hunk(repo_path: &Path, file_path: &str, hunk: &[DiffLine]) -> Result<(), String> {
548    apply_hunk_patch(repo_path, file_path, hunk, true, true)
549}
550
551/// Discard a single hunk of unstaged changes in the working tree (equivalent to `git apply --reverse -`).
552pub fn discard_hunk(repo_path: &Path, file_path: &str, hunk: &[DiffLine]) -> Result<(), String> {
553    apply_hunk_patch(repo_path, file_path, hunk, true, false)
554}
555
556/// Stage a single line from the Unstaged diff.
557pub fn stage_line(
558    repo_path: &Path,
559    file_path: &str,
560    hunk: &[DiffLine],
561    selected_line_idx: usize,
562) -> Result<(), String> {
563    apply_line_patch_inner(repo_path, file_path, hunk, selected_line_idx, false, false, true)
564}
565
566/// Unstage a single line from the Staged diff.
567pub fn unstage_line(
568    repo_path: &Path,
569    file_path: &str,
570    hunk: &[DiffLine],
571    selected_line_idx: usize,
572) -> Result<(), String> {
573    apply_line_patch_inner(repo_path, file_path, hunk, selected_line_idx, true, true, true)
574}
575
576/// Discard a single line from the Unstaged diff in the working tree.
577pub fn discard_line(
578    repo_path: &Path,
579    file_path: &str,
580    hunk: &[DiffLine],
581    selected_line_idx: usize,
582) -> Result<(), String> {
583    apply_line_patch_inner(repo_path, file_path, hunk, selected_line_idx, true, true, false)
584}
585
586fn parse_hunk_header(header: &str) -> Option<(usize, usize, usize, usize)> {
587    if !header.starts_with("@@") {
588        return None;
589    }
590    let parts: Vec<&str> = header.split("@@").collect();
591    if parts.len() < 3 {
592        return None;
593    }
594    let meta = parts[1].trim();
595    let subparts: Vec<&str> = meta.split_whitespace().collect();
596    if subparts.len() < 2 {
597        return None;
598    }
599
600    let parse_part = |p: &str| -> (usize, usize) {
601        let s = p.trim_start_matches(['-', '+']);
602        let comps: Vec<&str> = s.split(',').collect();
603        let start = comps[0].parse::<usize>().unwrap_or(0);
604        let count = if comps.len() > 1 { comps[1].parse::<usize>().unwrap_or(1) } else { 1 };
605        (start, count)
606    };
607
608    let (old_start, old_count) = parse_part(subparts[0]);
609    let (new_start, new_count) = parse_part(subparts[1]);
610    Some((old_start, old_count, new_start, new_count))
611}
612
613fn apply_line_patch_inner(
614    repo_path: &Path,
615    file_path: &str,
616    hunk: &[DiffLine],
617    selected_line_idx_in_hunk: usize,
618    revert: bool,
619    target_has_modification: bool,
620    cached: bool,
621) -> Result<(), String> {
622    use std::io::Write;
623    use std::process::{Command, Stdio};
624
625    let path_check = std::path::Path::new(file_path);
626    if path_check.is_absolute()
627        || path_check.components().any(|c| c == std::path::Component::ParentDir)
628    {
629        return Err("Path escapes repository root".to_string());
630    }
631
632    if hunk.is_empty() {
633        return Err("Empty hunk".to_string());
634    }
635
636    let selected_line = match hunk.get(selected_line_idx_in_hunk) {
637        Some(line) => line,
638        None => return Err("Invalid line index".to_string()),
639    };
640
641    if selected_line.kind != DiffLineKind::Added && selected_line.kind != DiffLineKind::Removed {
642        return Err("Selected line is not a modification (must be + or -)".to_string());
643    }
644
645    let header_line = &hunk[0];
646    let (old_start, _old_count, new_start, _new_count) =
647        match parse_hunk_header(&header_line.content) {
648            Some(coords) => coords,
649            None => return Err(format!("Invalid hunk header: {}", header_line.content)),
650        };
651
652    let mut patch_lines = Vec::new();
653    let mut new_old_count = 0;
654    let mut new_new_count = 0;
655
656    for (i, line) in hunk.iter().enumerate() {
657        if i == 0 {
658            continue;
659        }
660
661        if i == selected_line_idx_in_hunk {
662            if revert {
663                match line.kind {
664                    DiffLineKind::Added => {
665                        patch_lines.push(DiffLine {
666                            kind: DiffLineKind::Removed,
667                            content: line.content.clone(),
668                        });
669                        new_old_count += 1;
670                    }
671                    DiffLineKind::Removed => {
672                        patch_lines.push(DiffLine {
673                            kind: DiffLineKind::Added,
674                            content: line.content.clone(),
675                        });
676                        new_new_count += 1;
677                    }
678                    _ => {}
679                }
680            } else {
681                match line.kind {
682                    DiffLineKind::Added => {
683                        patch_lines.push(DiffLine {
684                            kind: DiffLineKind::Added,
685                            content: line.content.clone(),
686                        });
687                        new_new_count += 1;
688                    }
689                    DiffLineKind::Removed => {
690                        patch_lines.push(DiffLine {
691                            kind: DiffLineKind::Removed,
692                            content: line.content.clone(),
693                        });
694                        new_old_count += 1;
695                    }
696                    _ => {}
697                }
698            }
699        } else {
700            match line.kind {
701                DiffLineKind::Context => {
702                    patch_lines.push(line.clone());
703                    new_old_count += 1;
704                    new_new_count += 1;
705                }
706                DiffLineKind::Added => {
707                    if target_has_modification {
708                        patch_lines.push(DiffLine {
709                            kind: DiffLineKind::Context,
710                            content: line.content.clone(),
711                        });
712                        new_old_count += 1;
713                        new_new_count += 1;
714                    } else {
715                        // Omit
716                    }
717                }
718                DiffLineKind::Removed => {
719                    if target_has_modification {
720                        // Omit
721                    } else {
722                        patch_lines.push(DiffLine {
723                            kind: DiffLineKind::Context,
724                            content: line.content.clone(),
725                        });
726                        new_old_count += 1;
727                        new_new_count += 1;
728                    }
729                }
730                _ => {}
731            }
732        }
733    }
734
735    let mut patch = String::new();
736    patch.push_str(&format!("diff --git a/{} b/{}\n", file_path, file_path));
737    patch.push_str(&format!("--- a/{}\n", file_path));
738    patch.push_str(&format!("+++ b/{}\n", file_path));
739    patch.push_str(&format!(
740        "@@ -{},{} +{},{} @@\n",
741        old_start, new_old_count, new_start, new_new_count
742    ));
743
744    for line in patch_lines {
745        let prefix = match line.kind {
746            DiffLineKind::Added => "+",
747            DiffLineKind::Removed => "-",
748            DiffLineKind::Context => " ",
749            DiffLineKind::Header => "",
750            _ => "",
751        };
752        patch.push_str(prefix);
753        patch.push_str(&line.content);
754        patch.push('\n');
755    }
756
757    let mut args = vec!["apply"];
758    if cached {
759        args.push("--cached");
760    }
761    args.push("-");
762
763    let mut cmd = Command::new("git");
764    let mut child = cmd
765        .env("GIT_TERMINAL_PROMPT", "0")
766        .env("GIT_SSH_COMMAND", ssh_command_val())
767        .args(&args)
768        .current_dir(repo_path)
769        .stdin(Stdio::piped())
770        .stdout(Stdio::piped())
771        .stderr(Stdio::piped())
772        .spawn()
773        .map_err(|e| format!("Failed to spawn git apply: {}", e))?;
774
775    if let Some(mut stdin) = child.stdin.take() {
776        stdin
777            .write_all(patch.as_bytes())
778            .map_err(|e| format!("Failed to write patch to stdin: {}", e))?;
779    }
780
781    let output =
782        child.wait_with_output().map_err(|e| format!("Failed to wait for git apply: {}", e))?;
783
784    if !output.status.success() {
785        let err_msg = String::from_utf8_lossy(&output.stderr).to_string();
786        return Err(format!("git apply failed: {}", err_msg.trim()));
787    }
788
789    Ok(())
790}
791
792fn apply_hunk_patch(
793    repo_path: &Path,
794    file_path: &str,
795    hunk: &[DiffLine],
796    reverse: bool,
797    cached: bool,
798) -> Result<(), String> {
799    use std::io::Write;
800    use std::process::{Command, Stdio};
801
802    let path_check = std::path::Path::new(file_path);
803    if path_check.is_absolute()
804        || path_check.components().any(|c| c == std::path::Component::ParentDir)
805    {
806        return Err("Path escapes repository root".to_string());
807    }
808
809    let mut patch = String::new();
810    patch.push_str(&format!("diff --git a/{} b/{}\n", file_path, file_path));
811    patch.push_str(&format!("--- a/{}\n", file_path));
812    patch.push_str(&format!("+++ b/{}\n", file_path));
813    for line in hunk {
814        let prefix = match line.kind {
815            DiffLineKind::Added => "+",
816            DiffLineKind::Removed => "-",
817            DiffLineKind::Context => " ",
818            DiffLineKind::Header => "",
819            _ => "",
820        };
821        patch.push_str(prefix);
822        patch.push_str(&line.content);
823        patch.push('\n');
824    }
825
826    let mut args = vec!["apply"];
827    if cached {
828        args.push("--cached");
829    }
830    if reverse {
831        args.push("--reverse");
832    }
833    args.push("-");
834
835    let mut cmd = Command::new("git");
836    let mut child = cmd
837        .env("GIT_TERMINAL_PROMPT", "0")
838        .env("GIT_SSH_COMMAND", ssh_command_val())
839        .args(&args)
840        .current_dir(repo_path)
841        .stdin(Stdio::piped())
842        .stdout(Stdio::piped())
843        .stderr(Stdio::piped())
844        .spawn()
845        .map_err(|e| format!("Failed to spawn git apply: {}", e))?;
846
847    if let Some(mut stdin) = child.stdin.take() {
848        stdin
849            .write_all(patch.as_bytes())
850            .map_err(|e| format!("Failed to write patch to stdin: {}", e))?;
851    }
852
853    let output =
854        child.wait_with_output().map_err(|e| format!("Failed to wait for git apply: {}", e))?;
855
856    if !output.status.success() {
857        let err_msg = String::from_utf8_lossy(&output.stderr).to_string();
858        return Err(format!("git apply failed: {}", err_msg.trim()));
859    }
860
861    Ok(())
862}
863
864/// Discards uncommitted changes in `file_path`.
865/// - If the file is untracked, it is deleted from the filesystem.
866/// - If the file is tracked and modified/deleted, it is restored from the index.
867/// - If the file is staged, it is first unstaged (reset to HEAD) and then restored from index.
868pub fn discard_file_changes(repo_path: &Path, file_path: &str, staged: bool) -> Result<(), String> {
869    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
870
871    if staged {
872        // First unstage it (reset to HEAD)
873        unstage_file(repo_path, file_path)?;
874    }
875
876    // Now check if the file is untracked
877    let is_untracked = if let Ok(status) = repo.status_file(Path::new(file_path)) {
878        status.contains(git2::Status::WT_NEW)
879    } else {
880        false
881    };
882
883    if is_untracked {
884        let full_path = repo_path.join(file_path);
885        if full_path.exists() {
886            if full_path.is_file() {
887                std::fs::remove_file(&full_path).map_err(|e| e.to_string())?;
888            } else if full_path.is_dir() {
889                std::fs::remove_dir_all(&full_path).map_err(|e| e.to_string())?;
890            }
891        }
892    } else {
893        // Tracked file: checkout from index to working tree
894        let mut checkout_opts = git2::build::CheckoutBuilder::new();
895        checkout_opts.path(Path::new(file_path));
896        checkout_opts.force();
897        repo.checkout_index(None, Some(&mut checkout_opts)).map_err(|e| e.to_string())?;
898    }
899
900    Ok(())
901}
902
903/// Create a commit in the repository with the given message.
904/// Returns a human-readable error string on failure.
905pub fn commit_changes(repo_path: &Path, message: &str) -> Result<(), String> {
906    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
907    let mut index = repo.index().map_err(|e| e.to_string())?;
908    let tree_id = index.write_tree().map_err(|e| e.to_string())?;
909    let tree = repo.find_tree(tree_id).map_err(|e| e.to_string())?;
910
911    let signature = repo
912        .signature()
913        .map_err(|e| format!("Failed to get signature. Check user.name/email config: {}", e))?;
914
915    // Find parent commits
916    let mut parents = Vec::new();
917    let mut has_head = false;
918    if let Ok(head) = repo.head() {
919        if let Ok(parent_commit) = head.peel_to_commit() {
920            has_head = true;
921            // Check if there are changes staged compared to HEAD
922            let parent_tree = parent_commit.tree().map_err(|e| e.to_string())?;
923            if parent_tree.id() == tree_id {
924                return Err("No staged changes to commit".to_string());
925            }
926            parents.push(parent_commit);
927        }
928    }
929
930    if !has_head && index.is_empty() {
931        return Err("No staged changes to commit (index is empty)".to_string());
932    }
933
934    let parent_refs: Vec<&git2::Commit> = parents.iter().collect();
935
936    repo.commit(Some("HEAD"), &signature, &signature, message, &tree, &parent_refs)
937        .map_err(|e| e.to_string())?;
938
939    Ok(())
940}
941
942// ── Public entry points ────────────────────────────────────────────────────
943
944/// Expand a leading `~` or `~/` in a user-supplied path to the user's home
945/// directory. Returns the input unchanged if there is no home dir or no
946/// tilde to expand.
947pub fn expand_tilde(s: &str) -> PathBuf {
948    if s == "~" {
949        return dirs::home_dir().unwrap_or_else(|| PathBuf::from(s));
950    }
951    if let Some(stripped) = s.strip_prefix("~/")
952        && let Some(home) = dirs::home_dir()
953    {
954        return home.join(stripped);
955    }
956    PathBuf::from(s)
957}
958
959/// Add a new git remote.
960pub fn remote_add(repo_path: &std::path::Path, name: &str, url: &str) -> Result<(), git2::Error> {
961    let repo = Repository::open(repo_path)?;
962    repo.remote(name, url)?;
963    Ok(())
964}
965
966/// Delete an existing git remote.
967pub fn remote_delete(repo_path: &std::path::Path, name: &str) -> Result<(), git2::Error> {
968    let repo = Repository::open(repo_path)?;
969    repo.remote_delete(name)?;
970    Ok(())
971}
972
973/// Classify `item` and produce a card-level summary. Used by the list view.
974pub fn inspect_summary(item: &str) -> ItemStatus {
975    let path = expand_tilde(item);
976    if !path.is_dir() {
977        return ItemStatus::Missing;
978    }
979    if !path.join(".git").exists() {
980        return ItemStatus::Directory;
981    }
982    match Repository::open(&path) {
983        Ok(repo) => ItemStatus::GitRepo(Some(collect_summary(&repo))),
984        Err(_) => ItemStatus::GitRepo(None),
985    }
986}
987
988/// Inspect `item` and produce the rich detail report shown on Enter.
989pub fn inspect_detail(
990    item: &str,
991    commit_limit: usize,
992    graph_max_commits: usize,
993    enable_commit_signatures: bool,
994) -> ItemDetail {
995    let resolved = expand_tilde(item);
996    if !resolved.is_dir() {
997        return ItemDetail::Missing { resolved };
998    }
999    if !resolved.join(".git").exists() {
1000        return ItemDetail::Directory { resolved };
1001    }
1002    match collect_info(&resolved, commit_limit, graph_max_commits, enable_commit_signatures) {
1003        Ok(info) => ItemDetail::Repo { resolved, info: Box::new(info) },
1004        Err(e) => ItemDetail::Error { resolved, message: e.to_string() },
1005    }
1006}
1007
1008fn collect_signatures(repo_path: &Path, limit: usize) -> std::collections::HashMap<String, String> {
1009    let mut sigs = std::collections::HashMap::new();
1010    let mut cmd = std::process::Command::new("git");
1011    cmd.env("GIT_TERMINAL_PROMPT", "0")
1012        .env("GIT_SSH_COMMAND", ssh_command_val())
1013        .arg("log")
1014        .arg("--all");
1015
1016    if limit > 0 {
1017        cmd.arg(format!("-n{}", limit));
1018    }
1019
1020    cmd.arg("--pretty=format:%H %G?").current_dir(repo_path);
1021
1022    if let Ok(out) = cmd.output() {
1023        if out.status.success() {
1024            let stdout_str = String::from_utf8_lossy(&out.stdout);
1025            for line in stdout_str.lines() {
1026                let parts: Vec<&str> = line.split_whitespace().collect();
1027                if parts.len() == 2 {
1028                    sigs.insert(parts[0].to_string(), parts[1].to_string());
1029                } else if parts.len() == 1 {
1030                    sigs.insert(parts[0].to_string(), "N".to_string());
1031                }
1032            }
1033        }
1034    }
1035    sigs
1036}
1037
1038#[derive(serde::Serialize, serde::Deserialize, Clone)]
1039struct CachedCommit {
1040    id: String,
1041    author: String,
1042    date: String,
1043    summary: String,
1044    message: String,
1045    time: i64,
1046}
1047
1048fn hash_path(path: &Path) -> String {
1049    use std::collections::hash_map::DefaultHasher;
1050    use std::hash::{Hash, Hasher};
1051    let mut hasher = DefaultHasher::new();
1052    path.hash(&mut hasher);
1053    format!("{:x}", hasher.finish())
1054}
1055
1056fn collect_commits(
1057    repo: &Repository,
1058    limit: usize,
1059    repo_path: &Path,
1060    enable_commit_signatures: bool,
1061) -> Result<Vec<CommitEntry>, git2::Error> {
1062    let mut walk = repo.revwalk()?;
1063    if walk.push_head().is_err() {
1064        return Ok(Vec::new());
1065    }
1066    walk.set_sorting(git2::Sort::TOPOLOGICAL | git2::Sort::TIME)?;
1067
1068    let mut commits = Vec::new();
1069    let oids: Vec<Result<git2::Oid, git2::Error>> =
1070        if limit > 0 { walk.take(limit).collect() } else { walk.collect() };
1071
1072    let sig_map = if enable_commit_signatures {
1073        collect_signatures(repo_path, limit)
1074    } else {
1075        std::collections::HashMap::new()
1076    };
1077    let ref_map = get_cached_ref_map(repo, repo_path);
1078
1079    // Load commit cache
1080    let cache_dir = dirs::home_dir().map(|h| h.join(".gitwig/commit_cache"));
1081    if let Some(ref dir) = cache_dir {
1082        let _ = std::fs::create_dir_all(dir);
1083    }
1084    let hash = hash_path(repo_path);
1085    let cache_file = cache_dir.as_ref().map(|d| d.join(format!("{}.json", hash)));
1086    let mut cache: std::collections::HashMap<String, CachedCommit> = cache_file
1087        .as_ref()
1088        .and_then(|f| std::fs::read_to_string(f).ok())
1089        .and_then(|s| serde_json::from_str(&s).ok())
1090        .unwrap_or_default();
1091
1092    let mut cache_updated = false;
1093
1094    for id in oids {
1095        let oid = id?;
1096        let oid_str = oid.to_string();
1097        let sig_status = sig_map.get(&oid_str).cloned().unwrap_or_else(|| "N".to_string());
1098        let refs = ref_map.get(&oid).cloned().unwrap_or_default();
1099        let files = Vec::new();
1100
1101        if let Some(cached) = cache.get(&oid_str) {
1102            let when = format_relative_time(cached.time);
1103            commits.push(CommitEntry {
1104                id: cached.id.clone(),
1105                oid: oid_str,
1106                author: sanitize_text(&cached.author),
1107                when,
1108                date: cached.date.clone(),
1109                summary: sanitize_text(&cached.summary),
1110                message: sanitize_text(&cached.message),
1111                refs,
1112                files,
1113                signature_status: sig_status,
1114            });
1115        } else if let Ok(commit) = repo.find_commit(oid) {
1116            let short_id = format!("{:.7}", commit.id());
1117            let summary =
1118                sanitize_text(commit.summary().ok().flatten().unwrap_or("(no commit message)"));
1119            let author = commit.author();
1120            let author_name = author.name().unwrap_or("?");
1121            let author_email = author.email().unwrap_or("?");
1122            let author_str = sanitize_text(&format!("{} <{}>", author_name, author_email));
1123            let time_secs = commit.time().seconds();
1124            let when = format_relative_time(time_secs);
1125            let date = format_utc_date(time_secs);
1126            let message = sanitize_text(commit.message().unwrap_or("(no commit message)"));
1127
1128            let cached = CachedCommit {
1129                id: short_id.clone(),
1130                author: author_str.clone(),
1131                date: date.clone(),
1132                summary: summary.clone(),
1133                message: message.clone(),
1134                time: time_secs,
1135            };
1136            cache.insert(oid_str.clone(), cached);
1137            cache_updated = true;
1138
1139            commits.push(CommitEntry {
1140                id: short_id,
1141                oid: oid_str,
1142                author: author_str,
1143                when,
1144                date,
1145                summary,
1146                message,
1147                refs,
1148                files,
1149                signature_status: sig_status,
1150            });
1151        }
1152    }
1153
1154    if cache_updated {
1155        if let Some(ref f) = cache_file {
1156            if let Ok(json) = serde_json::to_string(&cache) {
1157                let _ = std::fs::write(f, json);
1158            }
1159        }
1160    }
1161
1162    Ok(commits)
1163}
1164
1165pub fn get_file_history(repo_path: &Path, file_path: &str) -> Result<Vec<FileRevision>, String> {
1166    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
1167    let mut walk = repo.revwalk().map_err(|e| e.to_string())?;
1168    if walk.push_head().is_err() {
1169        return Ok(Vec::new());
1170    }
1171    walk.set_sorting(git2::Sort::TOPOLOGICAL | git2::Sort::TIME).map_err(|e| e.to_string())?;
1172
1173    let mut revisions = Vec::new();
1174
1175    for oid_res in walk {
1176        let oid = oid_res.map_err(|e| e.to_string())?;
1177        let commit = repo.find_commit(oid).map_err(|e| e.to_string())?;
1178
1179        let commit_tree = commit.tree().map_err(|e| e.to_string())?;
1180        let mut modified = false;
1181
1182        if commit.parent_count() > 0 {
1183            for i in 0..commit.parent_count() {
1184                if let Ok(parent) = commit.parent(i) {
1185                    if let Ok(parent_tree) = parent.tree() {
1186                        let mut diff_opts = git2::DiffOptions::new();
1187                        diff_opts.pathspec(file_path);
1188                        if let Ok(diff) = repo.diff_tree_to_tree(
1189                            Some(&parent_tree),
1190                            Some(&commit_tree),
1191                            Some(&mut diff_opts),
1192                        ) {
1193                            if diff.deltas().len() > 0 {
1194                                modified = true;
1195                                break;
1196                            }
1197                        }
1198                    }
1199                }
1200            }
1201        } else {
1202            let mut diff_opts = git2::DiffOptions::new();
1203            diff_opts.pathspec(file_path);
1204            if let Ok(diff) = repo.diff_tree_to_tree(None, Some(&commit_tree), Some(&mut diff_opts))
1205            {
1206                if diff.deltas().len() > 0 {
1207                    modified = true;
1208                }
1209            }
1210        }
1211
1212        if modified {
1213            let author = commit.author();
1214            let author_name = author.name().unwrap_or("?");
1215            let author_email = author.email().unwrap_or("?");
1216            let author_str = sanitize_text(&format!("{} <{}>", author_name, author_email));
1217            let time_secs = commit.time().seconds();
1218            let when = format_relative_time(time_secs);
1219            let date = format_utc_date(time_secs);
1220            let summary =
1221                sanitize_text(commit.summary().ok().flatten().unwrap_or("(no commit message)"));
1222
1223            revisions.push(FileRevision {
1224                commit_oid: oid.to_string(),
1225                author: author_str,
1226                date,
1227                when,
1228                summary,
1229            });
1230        }
1231    }
1232
1233    Ok(revisions)
1234}
1235
1236fn collect_committer_stats(
1237    repo: &Repository,
1238    limit: usize,
1239) -> Result<(Vec<CommitterStat>, bool), git2::Error> {
1240    let mut walk = repo.revwalk()?;
1241    if walk.push_head().is_err() {
1242        return Ok((Vec::new(), false));
1243    }
1244    let mut counts = std::collections::HashMap::new();
1245    let mut count = 0;
1246    let mut limit_reached = false;
1247    for id in walk {
1248        let oid = id?;
1249        if let Ok(commit) = repo.find_commit(oid) {
1250            let author = commit.author();
1251            let name = author.name().unwrap_or("?").to_string();
1252            let email = author.email().unwrap_or("?").to_string();
1253            let key = (name, email);
1254            *counts.entry(key).or_insert(0) += 1;
1255            count += 1;
1256            if count >= limit {
1257                limit_reached = true;
1258                break;
1259            }
1260        }
1261    }
1262
1263    let mut stats: Vec<CommitterStat> = counts
1264        .into_iter()
1265        .map(|((name, email), count)| CommitterStat { name, email, count })
1266        .collect();
1267
1268    stats.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.name.cmp(&b.name)));
1269
1270    Ok((stats, limit_reached))
1271}
1272
1273/// Diff `commit` against its first parent (or against an empty tree for the
1274/// initial commit) and return the list of changed files. Capped at
1275/// `MAX_FILES_PER_SECTION` entries.
1276fn commit_changed_files(repo: &Repository, commit: &git2::Commit) -> Vec<FileEntry> {
1277    let commit_tree = match commit.tree() {
1278        Ok(t) => t,
1279        Err(_) => return Vec::new(),
1280    };
1281    // For the initial commit parent_tree is None — libgit2 treats that as an
1282    // empty tree, so all files appear as "added".
1283    let parent_tree = commit.parent(0).ok().and_then(|p| p.tree().ok());
1284
1285    let diff = match repo.diff_tree_to_tree(parent_tree.as_ref(), Some(&commit_tree), None) {
1286        Ok(d) => d,
1287        Err(_) => return Vec::new(),
1288    };
1289
1290    let mut files = Vec::new();
1291    for delta in diff.deltas() {
1292        if files.len() >= MAX_FILES_PER_SECTION {
1293            break;
1294        }
1295        let path = delta
1296            .new_file()
1297            .path()
1298            .or_else(|| delta.old_file().path())
1299            .map(|p| p.to_string_lossy().into_owned())
1300            .unwrap_or_else(|| "(unknown)".to_string());
1301
1302        let label: &'static str = match delta.status() {
1303            git2::Delta::Added => "N",
1304            git2::Delta::Deleted => "D",
1305            git2::Delta::Modified => "M",
1306            git2::Delta::Renamed => "R",
1307            git2::Delta::Typechange => "T",
1308            _ => "M",
1309        };
1310        files.push(FileEntry { path, label });
1311    }
1312    files
1313}
1314
1315pub fn get_commit_files(repo_path: &Path, oid: &str) -> Result<Vec<FileEntry>, String> {
1316    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
1317    let oid = git2::Oid::from_str(oid).map_err(|e| e.to_string())?;
1318    let commit = repo.find_commit(oid).map_err(|e| e.to_string())?;
1319    Ok(commit_changed_files(&repo, &commit))
1320}
1321
1322// ── Internal collection ────────────────────────────────────────────────────
1323
1324fn collect_info(
1325    path: &Path,
1326    commit_limit: usize,
1327    _graph_max_commits: usize,
1328    enable_commit_signatures: bool,
1329) -> Result<RepoInfo, git2::Error> {
1330    let repo = Repository::open(path)?;
1331    let mut summary = RepoSummary::default();
1332    if let Ok(head) = repo.head() {
1333        summary.branch = head.shorthand().ok().map(String::from);
1334    }
1335    populate_ahead_behind(&repo, &mut summary);
1336
1337    let mut info = RepoInfo { summary, ..RepoInfo::default() };
1338
1339    if let Ok(head) = repo.head() {
1340        info.branch = head.shorthand().ok().map(String::from);
1341
1342        if let Ok(commit) = head.peel_to_commit() {
1343            let short_id = format!("{:.7}", commit.id());
1344            let summary_text =
1345                sanitize_text(commit.summary().ok().flatten().unwrap_or("(no commit message)"));
1346            let author = commit.author();
1347            let author_str = sanitize_text(&format!(
1348                "{} <{}>",
1349                author.name().unwrap_or("?"),
1350                author.email().unwrap_or("?")
1351            ));
1352            let when = format_relative_time(commit.time().seconds());
1353            info.head =
1354                Some(HeadInfo { short_id, summary: summary_text, author: author_str, when });
1355        }
1356
1357        if let Ok(head_name) = head.name() {
1358            info.upstream = upstream_short_name(&repo, head_name);
1359        }
1360    }
1361
1362    if let Ok(commits) = collect_commits(&repo, commit_limit, path, enable_commit_signatures) {
1363        info.commits = commits;
1364    }
1365
1366    populate_summary_and_file_changes(&repo, &mut info);
1367
1368    if let Ok(remotes) = load_tab_remotes(path) {
1369        info.remotes = TabData::Loaded(remotes);
1370        info.tab_loaded_at[5] = Some(std::time::Instant::now());
1371    }
1372
1373    Ok(info)
1374}
1375
1376pub fn load_tab_files(repo_path: &Path) -> Result<Vec<String>, String> {
1377    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
1378    let mut files = Vec::new();
1379    if let Ok(index) = repo.index() {
1380        for entry in index.iter() {
1381            if let Ok(path_str) = std::str::from_utf8(&entry.path) {
1382                files.push(path_str.to_string());
1383            }
1384        }
1385    }
1386    Ok(files)
1387}
1388
1389pub fn load_tab_graph_stream(
1390    repo_path: &Path,
1391    graph_max_commits: usize,
1392    repo_resolved_path: String,
1393    tab_idx: usize,
1394    tx: std::sync::mpsc::Sender<(String, usize, TabPayload)>,
1395) -> Result<Vec<GraphLine>, String> {
1396    let mut graph_lines = Vec::new();
1397    let format_str = "%H__TWIG_SEP__%d__TWIG_SEP__%s__TWIG_SEP__%an__TWIG_SEP__%ad__TWIG_SEP__%G?";
1398
1399    let mut args = vec![
1400        "log".to_string(),
1401        "--graph".to_string(),
1402        "--all".to_string(),
1403        "--date=relative".to_string(),
1404    ];
1405    if graph_max_commits > 0 {
1406        args.push(format!("--max-count={}", graph_max_commits));
1407    }
1408    args.push(format!("--pretty=format:{}", format_str));
1409    args.push("--color=never".to_string());
1410
1411    let mut child = std::process::Command::new("git")
1412        .env("GIT_TERMINAL_PROMPT", "0")
1413        .env("GIT_SSH_COMMAND", ssh_command_val())
1414        .args(&args)
1415        .current_dir(repo_path)
1416        .stdout(std::process::Stdio::piped())
1417        .spawn()
1418        .map_err(|e| e.to_string())?;
1419
1420    let stdout = child.stdout.take().ok_or_else(|| "Failed to open stdout".to_string())?;
1421    let reader = std::io::BufReader::new(stdout);
1422    use std::io::BufRead;
1423
1424    for (idx, line_res) in reader.lines().enumerate() {
1425        let line = line_res.map_err(|e| e.to_string())?;
1426        let parsed = parse_graph_line(&line);
1427        graph_lines.push(parsed);
1428
1429        // Every 200 lines, send a cloned batch to UI
1430        if (idx + 1) % 200 == 0 {
1431            let _ = tx.send((
1432                repo_resolved_path.clone(),
1433                tab_idx,
1434                TabPayload::Graph(Ok(graph_lines.clone())),
1435            ));
1436        }
1437    }
1438
1439    // Wait for the child process to exit
1440    let status = child.wait().map_err(|e| e.to_string())?;
1441    if !status.success() && graph_lines.is_empty() {
1442        return Err("git log failed".to_string());
1443    }
1444
1445    Ok(graph_lines)
1446}
1447
1448pub fn load_tab_branches(
1449    repo_path: &Path,
1450) -> (Result<Vec<BranchInfo>, String>, Result<Vec<BranchInfo>, String>) {
1451    let repo = match Repository::open(repo_path) {
1452        Ok(r) => r,
1453        Err(e) => return (Err(e.to_string()), Err(e.to_string())),
1454    };
1455
1456    let mut local_branches = Vec::new();
1457    if let Ok(branches) = repo.branches(Some(git2::BranchType::Local)) {
1458        for (branch, _) in branches.flatten() {
1459            if let Ok(Some(name)) = branch.name() {
1460                let is_head = branch.is_head();
1461                let mut short_sha = String::new();
1462                let mut short_message = String::new();
1463                if let Ok(target) = branch.get().peel_to_commit() {
1464                    let id = target.id();
1465                    let id_str = id.to_string();
1466                    short_sha = safe_sha_slice(&id_str, 7).to_string();
1467                    if let Ok(Some(summary)) = target.summary() {
1468                        short_message = summary.to_string();
1469                    }
1470                }
1471                local_branches.push(BranchInfo {
1472                    name: sanitize_text(name),
1473                    is_head,
1474                    short_sha,
1475                    short_message: sanitize_text(&short_message),
1476                });
1477            }
1478        }
1479    }
1480    local_branches.sort_by(|a, b| b.is_head.cmp(&a.is_head).then_with(|| a.name.cmp(&b.name)));
1481
1482    let mut remote_branches = Vec::new();
1483    if let Ok(branches) = repo.branches(Some(git2::BranchType::Remote)) {
1484        for (branch, _) in branches.flatten() {
1485            if let Ok(Some(name)) = branch.name() {
1486                if !name.ends_with("/HEAD") {
1487                    let is_head = branch.is_head();
1488                    let mut short_sha = String::new();
1489                    let mut short_message = String::new();
1490                    if let Ok(target) = branch.get().peel_to_commit() {
1491                        let id = target.id();
1492                        let id_str = id.to_string();
1493                        short_sha = safe_sha_slice(&id_str, 7).to_string();
1494                        if let Ok(Some(summary)) = target.summary() {
1495                            short_message = summary.to_string();
1496                        }
1497                    }
1498                    remote_branches.push(BranchInfo {
1499                        name: sanitize_text(name),
1500                        is_head,
1501                        short_sha,
1502                        short_message: sanitize_text(&short_message),
1503                    });
1504                }
1505            }
1506        }
1507    }
1508    remote_branches.sort_by(|a, b| a.name.cmp(&b.name));
1509
1510    (Ok(local_branches), Ok(remote_branches))
1511}
1512
1513pub fn load_tab_tags(
1514    repo_path: &Path,
1515) -> (Result<Vec<BranchInfo>, String>, Result<Vec<BranchInfo>, String>) {
1516    let repo = match Repository::open(repo_path) {
1517        Ok(r) => r,
1518        Err(e) => return (Err(e.to_string()), Err(e.to_string())),
1519    };
1520
1521    let mut local_tags = Vec::new();
1522    if let Ok(tags) = repo.tag_names(None) {
1523        for tag_opt in tags.iter() {
1524            if let Ok(Some(tag)) = tag_opt {
1525                let mut short_sha = String::new();
1526                let mut short_message = String::new();
1527                if let Ok(reference) = repo.find_reference(&format!("refs/tags/{}", tag)) {
1528                    if let Ok(target) = reference.peel_to_commit() {
1529                        let id = target.id();
1530                        let id_str = id.to_string();
1531                        short_sha = safe_sha_slice(&id_str, 7).to_string();
1532                        if let Ok(Some(summary)) = target.summary() {
1533                            short_message = summary.to_string();
1534                        }
1535                    }
1536                }
1537                local_tags.push(BranchInfo {
1538                    name: sanitize_text(tag),
1539                    is_head: false,
1540                    short_sha,
1541                    short_message: sanitize_text(&short_message),
1542                });
1543            }
1544        }
1545    }
1546    local_tags.sort_by(|a, b| b.name.cmp(&a.name));
1547
1548    (Ok(local_tags), Ok(Vec::new()))
1549}
1550
1551pub fn load_tab_remotes(repo_path: &Path) -> Result<Vec<RemoteInfo>, String> {
1552    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
1553    let mut remotes_list = Vec::new();
1554    if let Ok(remotes) = repo.remotes() {
1555        for name in remotes.iter() {
1556            let Ok(Some(name)) = name else { continue };
1557            if let Ok(remote) = repo.find_remote(name) {
1558                let push_url = remote.pushurl().ok().flatten().map(String::from);
1559                let mut refspecs = Vec::new();
1560                for r in remote.refspecs() {
1561                    if let Ok(s) = r.str() {
1562                        refspecs.push(s.to_string());
1563                    }
1564                }
1565                remotes_list.push(RemoteInfo {
1566                    name: name.to_string(),
1567                    url: remote.url().unwrap_or("(no url)").to_string(),
1568                    push_url,
1569                    refspecs,
1570                });
1571            }
1572        }
1573    }
1574    Ok(remotes_list)
1575}
1576
1577pub fn load_tab_stashes(repo_path: &Path) -> Result<Vec<StashInfo>, String> {
1578    let mut repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
1579    let mut temp_stashes = Vec::new();
1580    let _ = repo.stash_foreach(|index, message, oid| {
1581        temp_stashes.push((index, message.to_string(), *oid));
1582        true
1583    });
1584
1585    let mut stashes = Vec::new();
1586    for (index, message, oid) in temp_stashes {
1587        let mut files = Vec::new();
1588        if let Ok(commit) = repo.find_commit(oid) {
1589            files = commit_changed_files(&repo, &commit);
1590        }
1591        stashes.push(StashInfo {
1592            index,
1593            message: sanitize_text(&message),
1594            commit_id: oid.to_string(),
1595            files,
1596        });
1597    }
1598    Ok(stashes)
1599}
1600
1601pub fn load_tab_overview(
1602    repo_path: &Path,
1603    commit_limit: usize,
1604) -> Result<(Vec<CommitterStat>, bool), String> {
1605    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
1606    let stats_limit = if commit_limit > 0 { commit_limit.min(10000) } else { 10000 };
1607    let (stats, limit_reached) =
1608        collect_committer_stats(&repo, stats_limit).map_err(|e| e.to_string())?;
1609    Ok((stats, limit_reached))
1610}
1611
1612pub fn load_tab_submodules(repo_path: &Path) -> Result<Vec<SubmoduleInfo>, String> {
1613    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
1614    let submodules = repo.submodules().map_err(|e| e.to_string())?;
1615    let mut list = Vec::new();
1616    for sub in submodules {
1617        let name = sub.name().unwrap_or("").to_string();
1618        let path = sub.path().to_path_buf();
1619        let url = sub.url().unwrap_or(None).unwrap_or("").to_string();
1620        let commit_id = sub.index_id().map(|id| id.to_string());
1621        let head_id = sub.head_id().map(|id| id.to_string());
1622
1623        let mut is_initialized = true;
1624        let mut is_dirty = false;
1625
1626        if let Ok(status) = repo.submodule_status(&name, git2::SubmoduleIgnore::None) {
1627            is_initialized = !status.contains(git2::SubmoduleStatus::WD_UNINITIALIZED);
1628            is_dirty = status.contains(git2::SubmoduleStatus::WD_MODIFIED)
1629                || status.contains(git2::SubmoduleStatus::WD_WD_MODIFIED)
1630                || status.contains(git2::SubmoduleStatus::WD_UNTRACKED)
1631                || status.contains(git2::SubmoduleStatus::WD_INDEX_MODIFIED)
1632                || status.contains(git2::SubmoduleStatus::INDEX_MODIFIED);
1633        }
1634
1635        list.push(SubmoduleInfo { name, path, url, commit_id, head_id, is_initialized, is_dirty });
1636    }
1637    Ok(list)
1638}
1639
1640/// Build a map from commit `Oid` → list of ref names that point to it.
1641/// Local branches are stored as plain names (e.g. `"main"`).
1642/// Lightweight and annotated tags are stored with a `"tag:"` prefix
1643/// (e.g. `"tag:v1.0"`) so the UI can colour them differently.
1644fn build_ref_map(repo: &Repository) -> std::collections::HashMap<git2::Oid, Vec<String>> {
1645    let mut map: std::collections::HashMap<git2::Oid, Vec<String>> =
1646        std::collections::HashMap::new();
1647
1648    if let Ok(refs) = repo.references() {
1649        for reference in refs.flatten() {
1650            // Resolve to the underlying commit Oid (peeling through tags).
1651            let Ok(target) = reference.peel_to_commit() else {
1652                continue;
1653            };
1654            let oid = target.id();
1655
1656            let Ok(full_name) = reference.name() else {
1657                continue;
1658            };
1659
1660            let label = if let Some(branch) = full_name.strip_prefix("refs/heads/") {
1661                branch.to_string()
1662            } else if let Some(tag) = full_name.strip_prefix("refs/tags/") {
1663                format!("tag:{}", tag)
1664            } else if let Some(remote) = full_name.strip_prefix("refs/remotes/") {
1665                // Skip the symbolic HEAD pointer each remote keeps (e.g. origin/HEAD).
1666                if remote.ends_with("/HEAD") {
1667                    continue;
1668                }
1669                format!("remote:{}", remote)
1670            } else {
1671                continue;
1672            };
1673
1674            map.entry(oid).or_default().push(label);
1675        }
1676    }
1677    map
1678}
1679
1680#[allow(clippy::type_complexity)]
1681static REF_MAP_CACHE: std::sync::OnceLock<
1682    std::sync::Mutex<
1683        std::collections::HashMap<
1684            String,
1685            (std::collections::HashMap<git2::Oid, Vec<String>>, std::time::Instant),
1686        >,
1687    >,
1688> = std::sync::OnceLock::new();
1689
1690fn get_cached_ref_map(
1691    repo: &Repository,
1692    repo_path: &Path,
1693) -> std::collections::HashMap<git2::Oid, Vec<String>> {
1694    let cache_lock =
1695        REF_MAP_CACHE.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()));
1696    let mut cache = cache_lock.lock().unwrap_or_else(|e| e.into_inner());
1697    let path_key = repo_path.to_string_lossy().to_string();
1698
1699    if let Some((map, loaded_at)) = cache.get(&path_key) {
1700        if loaded_at.elapsed() < std::time::Duration::from_secs(10) {
1701            return map.clone();
1702        }
1703    }
1704
1705    let map = build_ref_map(repo);
1706    cache.insert(path_key, (map.clone(), std::time::Instant::now()));
1707    map
1708}
1709
1710pub fn invalidate_ref_map_cache(repo_path: &Path) {
1711    if let Some(cache_lock) = REF_MAP_CACHE.get() {
1712        if let Ok(mut cache) = cache_lock.lock() {
1713            cache.remove(&repo_path.to_string_lossy().to_string());
1714        }
1715    }
1716}
1717
1718/// Maximum file entries collected per bucket. Prevents pathologically large
1719/// working trees from overwhelming the detail view.
1720const MAX_FILES_PER_SECTION: usize = 100;
1721
1722/// Walk the working-tree status once and collect both summary counts and per-file info.
1723fn populate_summary_and_file_changes(repo: &Repository, info: &mut RepoInfo) {
1724    let mut opts = StatusOptions::new();
1725    opts.include_untracked(true)
1726        .renames_head_to_index(true)
1727        .recurse_untracked_dirs(true)
1728        .show(StatusShow::IndexAndWorkdir);
1729    let Ok(statuses) = repo.statuses(Some(&mut opts)) else {
1730        return;
1731    };
1732    for entry in statuses.iter() {
1733        let path = entry.path().unwrap_or("(unknown)").to_string();
1734        let flags = entry.status();
1735
1736        // 1. Populate summary counters
1737        if flags.is_conflicted() {
1738            info.summary.conflicted += 1;
1739        } else {
1740            if flags.is_wt_new() {
1741                info.summary.untracked += 1;
1742            }
1743            if flags.is_wt_modified()
1744                || flags.is_wt_deleted()
1745                || flags.is_wt_renamed()
1746                || flags.is_wt_typechange()
1747            {
1748                info.summary.modified += 1;
1749            }
1750            if flags.is_index_new()
1751                || flags.is_index_modified()
1752                || flags.is_index_deleted()
1753                || flags.is_index_renamed()
1754                || flags.is_index_typechange()
1755            {
1756                info.summary.staged += 1;
1757            }
1758        }
1759
1760        // 2. Populate file entries
1761        // Skip directories to avoid showing folders in staging panels
1762        let path_buf = repo.workdir().unwrap_or(Path::new("")).join(&path);
1763        if path_buf.is_dir() {
1764            continue;
1765        }
1766
1767        if flags.is_conflicted() {
1768            if info.changes.conflicted.len() < MAX_FILES_PER_SECTION {
1769                info.changes.conflicted.push(FileEntry { path: path.clone(), label: "C" });
1770            }
1771            continue;
1772        }
1773
1774        // Index (staged) changes
1775        if (flags.is_index_new()
1776            || flags.is_index_modified()
1777            || flags.is_index_deleted()
1778            || flags.is_index_renamed()
1779            || flags.is_index_typechange())
1780            && info.changes.staged.len() < MAX_FILES_PER_SECTION
1781        {
1782            let label = if flags.is_index_new() {
1783                "N"
1784            } else if flags.is_index_deleted() {
1785                "D"
1786            } else if flags.is_index_renamed() {
1787                "R"
1788            } else if flags.is_index_typechange() {
1789                "T"
1790            } else {
1791                "M"
1792            };
1793            info.changes.staged.push(FileEntry { path: path.clone(), label });
1794        }
1795
1796        // Working-tree changes
1797        if flags.is_wt_new() {
1798            if info.changes.untracked.len() < MAX_FILES_PER_SECTION {
1799                info.changes.untracked.push(FileEntry { path: path.clone(), label: "?" });
1800            }
1801            if info.changes.unstaged.len() < MAX_FILES_PER_SECTION {
1802                info.changes.unstaged.push(FileEntry { path: path.clone(), label: "N" });
1803            }
1804        } else if (flags.is_wt_modified()
1805            || flags.is_wt_deleted()
1806            || flags.is_wt_renamed()
1807            || flags.is_wt_typechange())
1808            && info.changes.unstaged.len() < MAX_FILES_PER_SECTION
1809        {
1810            let label = if flags.is_wt_deleted() {
1811                "D"
1812            } else if flags.is_wt_renamed() {
1813                "R"
1814            } else if flags.is_wt_typechange() {
1815                "T"
1816            } else {
1817                "M"
1818            };
1819            info.changes.unstaged.push(FileEntry { path: path.clone(), label });
1820        }
1821    }
1822}
1823
1824/// Collect the branch name, worktree counts, and ahead/behind for an opened
1825/// repo. Used by both `inspect_summary` (card) and `collect_info` (detail)
1826/// so the values shown in both places always agree.
1827fn collect_summary(repo: &Repository) -> RepoSummary {
1828    let mut s = RepoSummary::default();
1829    // git2 0.21: head() + shorthand() = Result<&str, Error>.
1830    if let Ok(head) = repo.head() {
1831        s.branch = head.shorthand().ok().map(String::from);
1832        if let Ok(commit) = head.peel_to_commit() {
1833            s.last_commit_time = Some(commit.time().seconds());
1834        }
1835    }
1836    populate_worktree(repo, &mut s);
1837    populate_ahead_behind(repo, &mut s);
1838    s.state = match repo.state() {
1839        git2::RepositoryState::Clean => RepoState::Clean,
1840        git2::RepositoryState::Merge => RepoState::Merge,
1841        git2::RepositoryState::Revert | git2::RepositoryState::RevertSequence => RepoState::Revert,
1842        git2::RepositoryState::CherryPick | git2::RepositoryState::CherryPickSequence => {
1843            RepoState::CherryPick
1844        }
1845        git2::RepositoryState::Bisect => RepoState::Bisect,
1846        git2::RepositoryState::Rebase
1847        | git2::RepositoryState::RebaseInteractive
1848        | git2::RepositoryState::RebaseMerge => RepoState::Rebase,
1849        git2::RepositoryState::ApplyMailbox | git2::RepositoryState::ApplyMailboxOrRebase => {
1850            RepoState::ApplyMailbox
1851        }
1852    };
1853    s
1854}
1855
1856fn populate_worktree(repo: &Repository, s: &mut RepoSummary) {
1857    let mut opts = StatusOptions::new();
1858    opts.include_untracked(true).renames_head_to_index(true).show(StatusShow::IndexAndWorkdir);
1859    let Ok(statuses) = repo.statuses(Some(&mut opts)) else {
1860        return;
1861    };
1862    for entry in statuses.iter() {
1863        let flags = entry.status();
1864        if flags.is_conflicted() {
1865            s.conflicted += 1;
1866            continue;
1867        }
1868        if flags.is_wt_new() {
1869            s.untracked += 1;
1870        }
1871        if flags.is_wt_modified()
1872            || flags.is_wt_deleted()
1873            || flags.is_wt_renamed()
1874            || flags.is_wt_typechange()
1875        {
1876            s.modified += 1;
1877        }
1878        if flags.is_index_new()
1879            || flags.is_index_modified()
1880            || flags.is_index_deleted()
1881            || flags.is_index_renamed()
1882            || flags.is_index_typechange()
1883        {
1884            s.staged += 1;
1885        }
1886    }
1887}
1888
1889/// Compute commits ahead/behind the upstream branch. Silently leaves
1890/// both at 0 if HEAD is detached, the branch has no upstream configured,
1891/// or any libgit2 lookup fails — the card simply shows no ↑/↓ then.
1892fn populate_ahead_behind(repo: &Repository, s: &mut RepoSummary) {
1893    let Ok(head) = repo.head() else { return };
1894    let Some(local_oid) = head.target() else {
1895        return;
1896    };
1897    let Ok(head_name) = head.name() else { return };
1898    let Ok(upstream_buf) = repo.branch_upstream_name(head_name) else {
1899        return;
1900    };
1901    let Ok(upstream_name) = std::str::from_utf8(&upstream_buf) else {
1902        return;
1903    };
1904    let Ok(upstream_ref) = repo.find_reference(upstream_name) else {
1905        return;
1906    };
1907    let Some(upstream_oid) = upstream_ref.target() else {
1908        return;
1909    };
1910    if let Ok((ahead, behind)) = repo.graph_ahead_behind(local_oid, upstream_oid) {
1911        s.ahead = ahead;
1912        s.behind = behind;
1913    }
1914}
1915
1916/// `"origin/main"`-style short name for HEAD's upstream, or `None`.
1917fn upstream_short_name(repo: &Repository, head_name: &str) -> Option<String> {
1918    let buf = repo.branch_upstream_name(head_name).ok()?;
1919    let raw = std::str::from_utf8(&buf).ok()?;
1920    Some(raw.strip_prefix("refs/remotes/").unwrap_or(raw).to_string())
1921}
1922
1923/// Format a unix-epoch timestamp as a relative time string ("3 days ago").
1924pub fn format_relative_time(secs: i64) -> String {
1925    if secs <= 0 {
1926        return "unknown".to_string();
1927    }
1928    let then = UNIX_EPOCH + Duration::from_secs(secs as u64);
1929    let now = SystemTime::now();
1930    let Ok(elapsed) = now.duration_since(then) else {
1931        return "in the future".to_string();
1932    };
1933    let secs = elapsed.as_secs();
1934    let (n, unit) = if secs < 60 {
1935        (secs, "second")
1936    } else if secs < 3600 {
1937        (secs / 60, "minute")
1938    } else if secs < 86_400 {
1939        (secs / 3600, "hour")
1940    } else if secs < 86_400 * 30 {
1941        (secs / 86_400, "day")
1942    } else if secs < 86_400 * 365 {
1943        (secs / (86_400 * 30), "month")
1944    } else {
1945        (secs / (86_400 * 365), "year")
1946    };
1947    let plural = if n == 1 { "" } else { "s" };
1948    format!("{} {}{} ago", n, unit, plural)
1949}
1950
1951/// Format a unix-epoch timestamp as a UTC date string ("YYYY-MM-DD HH:MM:SS UTC").
1952fn format_utc_date(secs: i64) -> String {
1953    if secs <= 0 {
1954        return "unknown".to_string();
1955    }
1956    let seconds_in_day = 86400;
1957    let day_number = secs / seconds_in_day;
1958    let time_of_day = secs % seconds_in_day;
1959
1960    let mut hour = time_of_day / 3600;
1961    let mut minute = (time_of_day % 3600) / 60;
1962    let mut second = time_of_day % 60;
1963    if hour < 0 {
1964        hour += 24;
1965    }
1966    if minute < 0 {
1967        minute += 60;
1968    }
1969    if second < 0 {
1970        second += 60;
1971    }
1972
1973    // Howard Hinnant's civil date from epoch days algorithm
1974    let z = day_number + 719468;
1975    let era = (if z >= 0 { z } else { z - 146096 }) / 146097;
1976    let doe = (z - era * 146097) as u32;
1977    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
1978    let y = (yoe as i32) + (era as i32) * 400;
1979    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1980    let mp = (5 * doy + 2) / 153;
1981    let d = doy - (153 * mp + 2) / 5 + 1;
1982    let m = if mp < 10 { mp + 3 } else { mp - 9 };
1983    let y = y + if m <= 2 { 1 } else { 0 };
1984
1985    format!("{:04}-{:02}-{:02} {:02}:{:02}:{:02} UTC", y, m, d, hour, minute, second)
1986}
1987
1988// ── Per-file diff (private) ────────────────────────────────────────────────
1989
1990fn get_file_diff_inner(
1991    repo_path: &Path,
1992    commit_oid: &str,
1993    file_path: &str,
1994) -> Option<Vec<DiffLine>> {
1995    let repo = Repository::open(repo_path).ok()?;
1996    let oid = git2::Oid::from_str(commit_oid).ok()?;
1997    let commit = repo.find_commit(oid).ok()?;
1998
1999    let commit_tree = commit.tree().ok()?;
2000    // For the initial commit, parent_tree is None; libgit2 treats it as empty.
2001    let parent_tree = commit.parent(0).ok().and_then(|p| p.tree().ok());
2002
2003    let mut opts = git2::DiffOptions::new();
2004    opts.pathspec(file_path);
2005
2006    let diff =
2007        repo.diff_tree_to_tree(parent_tree.as_ref(), Some(&commit_tree), Some(&mut opts)).ok()?;
2008
2009    collect_diff_lines(&diff)
2010}
2011
2012/// Diff a single file in the working tree.
2013///
2014/// `staged = true`:  HEAD-tree → index (what `git diff --cached` shows).
2015/// `staged = false`: index → working directory (what `git diff` shows).
2016fn get_worktree_diff_inner(
2017    repo_path: &Path,
2018    file_path: &str,
2019    staged: bool,
2020) -> Option<Vec<DiffLine>> {
2021    let repo = Repository::open(repo_path).ok()?;
2022    let mut opts = git2::DiffOptions::new();
2023    opts.pathspec(file_path);
2024    opts.include_untracked(true);
2025    opts.recurse_untracked_dirs(true);
2026
2027    let diff = if staged {
2028        // Staged: diff HEAD tree (or empty tree for new repos) → index.
2029        let head_tree = repo.head().ok().and_then(|h| h.peel_to_tree().ok());
2030        repo.diff_tree_to_index(head_tree.as_ref(), None, Some(&mut opts)).ok()?
2031    } else {
2032        // Unstaged: diff index → working directory.
2033        repo.diff_index_to_workdir(None, Some(&mut opts)).ok()?
2034    };
2035
2036    collect_diff_lines(&diff)
2037}
2038
2039/// Walk a libgit2 `Diff` and collect coloured `DiffLine` values.
2040fn collect_diff_lines(diff: &git2::Diff<'_>) -> Option<Vec<DiffLine>> {
2041    let mut lines: Vec<DiffLine> = Vec::new();
2042    diff.print(git2::DiffFormat::Patch, |_delta, _hunk, line| {
2043        let kind = match line.origin() {
2044            '+' => DiffLineKind::Added,
2045            '-' => DiffLineKind::Removed,
2046            'H' => DiffLineKind::Header,
2047            ' ' => DiffLineKind::Context,
2048            _ => return true, // skip file-header meta lines
2049        };
2050        let content = String::from_utf8_lossy(line.content())
2051            .trim_end_matches('\n')
2052            .trim_end_matches('\r')
2053            .to_string();
2054        lines.push(DiffLine { kind, content });
2055        true
2056    })
2057    .ok()?;
2058    Some(lines)
2059}
2060
2061fn parse_graph_line(line: &str) -> GraphLine {
2062    if line.contains("__TWIG_SEP__") {
2063        let parts: Vec<&str> = line.split("__TWIG_SEP__").collect();
2064        if parts.len() >= 5 {
2065            let graph_and_hash = parts[0];
2066            let decoration = parts[1].trim().to_string();
2067            let summary = parts[2].trim().to_string();
2068            let author = parts[3].trim().to_string();
2069            let date = parts[4].trim().to_string();
2070            let signature_status =
2071                if parts.len() >= 6 { parts[5].trim().to_string() } else { "N".to_string() };
2072
2073            let char_count = graph_and_hash.chars().count();
2074            if char_count >= 40 {
2075                let graph: String = graph_and_hash.chars().take(char_count - 40).collect();
2076                let oid: String = graph_and_hash.chars().skip(char_count - 40).collect();
2077                GraphLine {
2078                    graph,
2079                    commit: Some(GraphCommit {
2080                        oid,
2081                        decoration,
2082                        summary,
2083                        author,
2084                        date,
2085                        signature_status,
2086                    }),
2087                }
2088            } else {
2089                GraphLine { graph: graph_and_hash.to_string(), commit: None }
2090            }
2091        } else {
2092            GraphLine { graph: line.to_string(), commit: None }
2093        }
2094    } else {
2095        GraphLine { graph: line.to_string(), commit: None }
2096    }
2097}
2098
2099#[allow(dead_code)]
2100fn collect_graph_lines(repo_path: &Path, graph_max_commits: usize) -> Vec<GraphLine> {
2101    let mut graph_lines = Vec::new();
2102    let format_str = "%H__TWIG_SEP__%d__TWIG_SEP__%s__TWIG_SEP__%an__TWIG_SEP__%ad__TWIG_SEP__%G?";
2103
2104    let mut args = vec![
2105        "log".to_string(),
2106        "--graph".to_string(),
2107        "--all".to_string(),
2108        "--date=relative".to_string(),
2109    ];
2110    if graph_max_commits > 0 {
2111        args.push(format!("--max-count={}", graph_max_commits));
2112    }
2113    args.push(format!("--pretty=format:{}", format_str));
2114    args.push("--color=never".to_string());
2115
2116    let output = std::process::Command::new("git")
2117        .env("GIT_TERMINAL_PROMPT", "0")
2118        .env("GIT_SSH_COMMAND", ssh_command_val())
2119        .args(&args)
2120        .current_dir(repo_path)
2121        .output();
2122
2123    if let Ok(out) = output {
2124        if out.status.success() {
2125            let stdout_str = String::from_utf8_lossy(&out.stdout);
2126            for line in stdout_str.lines() {
2127                graph_lines.push(parse_graph_line(line));
2128            }
2129        }
2130    }
2131    graph_lines
2132}
2133
2134pub fn checkout_local_branch(repo_path: &Path, branch_name: &str) -> Result<(), git2::Error> {
2135    let output = std::process::Command::new("git")
2136        .env("GIT_TERMINAL_PROMPT", "0")
2137        .env("GIT_SSH_COMMAND", ssh_command_val())
2138        .arg("checkout")
2139        .arg(branch_name)
2140        .current_dir(repo_path)
2141        .output()
2142        .map_err(|e| git2::Error::from_str(&e.to_string()))?;
2143
2144    if !output.status.success() {
2145        let err = String::from_utf8_lossy(&output.stderr).trim().to_string();
2146        return Err(git2::Error::from_str(&err));
2147    }
2148    Ok(())
2149}
2150
2151pub fn checkout_remote_branch(
2152    repo_path: &Path,
2153    remote_branch_name: &str,
2154) -> Result<String, git2::Error> {
2155    let parts: Vec<&str> = remote_branch_name.splitn(2, '/').collect();
2156    if parts.len() < 2 {
2157        return Err(git2::Error::from_str("Invalid remote branch name"));
2158    }
2159    let local_name = parts[1];
2160
2161    let output = std::process::Command::new("git")
2162        .env("GIT_TERMINAL_PROMPT", "0")
2163        .env("GIT_SSH_COMMAND", ssh_command_val())
2164        .arg("checkout")
2165        .arg(local_name)
2166        .current_dir(repo_path)
2167        .output()
2168        .map_err(|e| git2::Error::from_str(&e.to_string()))?;
2169
2170    if output.status.success() {
2171        return Ok(format!("Switched to existing branch '{}'", local_name));
2172    }
2173
2174    let output = std::process::Command::new("git")
2175        .env("GIT_TERMINAL_PROMPT", "0")
2176        .env("GIT_SSH_COMMAND", ssh_command_val())
2177        .arg("checkout")
2178        .arg("--track")
2179        .arg(remote_branch_name)
2180        .current_dir(repo_path)
2181        .output()
2182        .map_err(|e| git2::Error::from_str(&e.to_string()))?;
2183
2184    if !output.status.success() {
2185        let err = String::from_utf8_lossy(&output.stderr).trim().to_string();
2186        return Err(git2::Error::from_str(&err));
2187    }
2188
2189    Ok(format!("Created and switched to branch '{}' tracking '{}'", local_name, remote_branch_name))
2190}
2191
2192/// Creates a new local branch pointing at HEAD.
2193pub fn create_branch(repo_path: &Path, branch_name: &str) -> Result<(), git2::Error> {
2194    let repo = Repository::open(repo_path)?;
2195    let head = repo.head()?;
2196    let target_commit = head.peel_to_commit()?;
2197    repo.branch(branch_name, &target_commit, false)?;
2198    Ok(())
2199}
2200
2201/// Deletes a local branch.
2202pub fn delete_local_branch(repo_path: &Path, branch_name: &str) -> Result<(), git2::Error> {
2203    let repo = Repository::open(repo_path)?;
2204    let mut branch = repo.find_branch(branch_name, git2::BranchType::Local)?;
2205    branch.delete()?;
2206    Ok(())
2207}
2208
2209/// Deletes a remote-tracking branch locally.
2210pub fn delete_remote_branch(repo_path: &Path, branch_name: &str) -> Result<(), git2::Error> {
2211    let repo = Repository::open(repo_path)?;
2212    let mut branch = repo.find_branch(branch_name, git2::BranchType::Remote)?;
2213    branch.delete()?;
2214    Ok(())
2215}
2216
2217/// Creates a new lightweight tag pointing at the specified commit OID.
2218pub fn create_tag(
2219    repo_path: &Path,
2220    tag_name: &str,
2221    commit_oid_str: &str,
2222) -> Result<(), git2::Error> {
2223    let repo = Repository::open(repo_path)?;
2224    let oid = git2::Oid::from_str(commit_oid_str)?;
2225    let target_object = repo.find_object(oid, Some(git2::ObjectType::Commit))?;
2226    repo.tag_lightweight(tag_name, &target_object, false)?;
2227    Ok(())
2228}
2229
2230/// Deletes a local tag.
2231pub fn delete_tag(repo_path: &Path, tag_name: &str) -> Result<(), git2::Error> {
2232    let repo = Repository::open(repo_path)?;
2233    repo.tag_delete(tag_name)?;
2234    Ok(())
2235}
2236
2237/// Deletes a tag on the remote.
2238pub fn delete_remote_tag(
2239    repo_path: &Path,
2240    remote_name: &str,
2241    tag_name: &str,
2242) -> Result<(), Box<dyn std::error::Error>> {
2243    let safe_remote = safe_ref(remote_name)?;
2244    let safe_tag = safe_ref(tag_name)?;
2245    let output = git_command()
2246        .arg("push")
2247        .arg(safe_remote)
2248        .arg("--delete")
2249        .arg(safe_tag)
2250        .current_dir(repo_path)
2251        .output()?;
2252    if !output.status.success() {
2253        let err = String::from_utf8_lossy(&output.stderr).trim().to_string();
2254        return Err(err.into());
2255    }
2256    Ok(())
2257}
2258
2259pub fn checkout_tag(repo_path: &Path, tag_name: &str) -> Result<(), git2::Error> {
2260    let safe_tag = safe_ref(tag_name).map_err(|e| git2::Error::from_str(&e))?;
2261    let output = git_command()
2262        .arg("checkout")
2263        .arg(safe_tag)
2264        .current_dir(repo_path)
2265        .output()
2266        .map_err(|e| git2::Error::from_str(&e.to_string()))?;
2267
2268    if !output.status.success() {
2269        let err = String::from_utf8_lossy(&output.stderr).trim().to_string();
2270        return Err(git2::Error::from_str(&err));
2271    }
2272    Ok(())
2273}
2274
2275/// Helper to run `git ls-remote --tags` and return parsed tag information.
2276pub fn get_remote_tags(
2277    repo_path: &Path,
2278    remote_name: &str,
2279) -> Result<Vec<BranchInfo>, Box<dyn std::error::Error>> {
2280    let safe_remote = safe_ref(remote_name)?;
2281    let output = git_command()
2282        .arg("ls-remote")
2283        .arg("--tags")
2284        .arg(safe_remote)
2285        .current_dir(repo_path)
2286        .output()?;
2287
2288    if !output.status.success() {
2289        let err = String::from_utf8_lossy(&output.stderr).trim().to_string();
2290        return Err(err.into());
2291    }
2292
2293    let stdout = String::from_utf8_lossy(&output.stdout);
2294    let repo = git2::Repository::open(repo_path)?;
2295    let mut tags_map = std::collections::HashMap::new();
2296
2297    for line in stdout.lines() {
2298        let parts: Vec<&str> = line.split_whitespace().collect();
2299        if parts.len() >= 2 {
2300            let sha = parts[0];
2301            let ref_name = parts[1];
2302            if ref_name.starts_with("refs/tags/") {
2303                let is_peeled = ref_name.ends_with("^{}");
2304                let clean_ref = if is_peeled {
2305                    safe_sha_slice(ref_name, ref_name.len().saturating_sub(3))
2306                } else {
2307                    ref_name
2308                };
2309                let tag_name = clean_ref.strip_prefix("refs/tags/").unwrap_or(clean_ref);
2310                let short_sha = safe_sha_slice(sha, 7);
2311
2312                // Try to resolve the summary locally
2313                let mut short_message = String::new();
2314                if let Ok(oid) = git2::Oid::from_str(sha) {
2315                    if let Ok(commit) = repo.find_commit(oid) {
2316                        if let Ok(Some(summary)) = commit.summary() {
2317                            short_message = summary.to_string();
2318                        }
2319                    }
2320                }
2321                if short_message.is_empty() {
2322                    short_message = "(not fetched)".to_string();
2323                }
2324
2325                let sanitized_tag = sanitize_text(tag_name);
2326                let sanitized_msg = sanitize_text(&short_message);
2327
2328                if is_peeled {
2329                    tags_map.insert(sanitized_tag, (short_sha.to_string(), sanitized_msg));
2330                } else {
2331                    tags_map
2332                        .entry(sanitized_tag)
2333                        .or_insert_with(|| (short_sha.to_string(), sanitized_msg));
2334                }
2335            }
2336        }
2337    }
2338
2339    let mut tags = Vec::new();
2340    for (name, (short_sha, short_message)) in tags_map {
2341        tags.push(BranchInfo { name, is_head: false, short_sha, short_message });
2342    }
2343    tags.sort_by(|a, b| b.name.cmp(&a.name));
2344    Ok(tags)
2345}
2346
2347pub fn serialize_tags(tags: &[BranchInfo]) -> String {
2348    let mut s = String::new();
2349    for tag in tags {
2350        s.push_str(&format!("{}|{}|{}\n", tag.name, tag.short_sha, tag.short_message));
2351    }
2352    s
2353}
2354
2355pub fn deserialize_tags(s: &str) -> Vec<BranchInfo> {
2356    let mut tags = Vec::new();
2357    for line in s.lines() {
2358        let parts: Vec<&str> = line.split('|').collect();
2359        if parts.len() >= 3 {
2360            tags.push(BranchInfo {
2361                name: parts[0].to_string(),
2362                is_head: false,
2363                short_sha: parts[1].to_string(),
2364                short_message: parts[2].to_string(),
2365            });
2366        }
2367    }
2368    tags
2369}
2370
2371pub fn delete_stash(repo_path: &Path, index: usize) -> Result<(), git2::Error> {
2372    let mut repo = Repository::open(repo_path)?;
2373    repo.stash_drop(index)?;
2374    Ok(())
2375}
2376
2377pub fn apply_stash(repo_path: &Path, index: usize) -> Result<(), String> {
2378    let stash_ref = format!("stash@{{{}}}", index);
2379    let output = std::process::Command::new("git")
2380        .env("GIT_TERMINAL_PROMPT", "0")
2381        .env("GIT_SSH_COMMAND", ssh_command_val())
2382        .arg("stash")
2383        .arg("apply")
2384        .arg(&stash_ref)
2385        .current_dir(repo_path)
2386        .output()
2387        .map_err(|e| e.to_string())?;
2388
2389    if !output.status.success() {
2390        let err_msg = String::from_utf8_lossy(&output.stderr).trim().to_string();
2391        return Err(err_msg);
2392    }
2393    Ok(())
2394}
2395
2396pub fn save_stash(
2397    repo_path: &Path,
2398    message: &str,
2399    include_untracked: bool,
2400    keep_index: bool,
2401) -> Result<(), String> {
2402    let mut cmd = std::process::Command::new("git");
2403    cmd.env("GIT_TERMINAL_PROMPT", "0")
2404        .env("GIT_SSH_COMMAND", ssh_command_val())
2405        .arg("stash")
2406        .arg("push");
2407
2408    if include_untracked {
2409        cmd.arg("--include-untracked");
2410    }
2411    if keep_index {
2412        cmd.arg("--keep-index");
2413    }
2414
2415    if !message.is_empty() {
2416        cmd.arg("-m").arg(message);
2417    }
2418
2419    let output = cmd.current_dir(repo_path).output().map_err(|e| e.to_string())?;
2420
2421    if !output.status.success() {
2422        let err_msg = String::from_utf8_lossy(&output.stderr).trim().to_string();
2423        return Err(err_msg);
2424    }
2425    Ok(())
2426}
2427
2428pub fn get_latest_change_time(item: &str) -> u64 {
2429    let path = expand_tilde(item);
2430    if !path.exists() {
2431        return 0;
2432    }
2433
2434    if path.join(".git").exists() {
2435        if let Ok(repo) = Repository::open(&path) {
2436            if let Ok(head) = repo.head() {
2437                if let Ok(commit) = head.peel_to_commit() {
2438                    return commit.time().seconds() as u64;
2439                }
2440            }
2441        }
2442    }
2443
2444    if let Ok(meta) = std::fs::metadata(&path) {
2445        if let Ok(modified) = meta.modified() {
2446            if let Ok(duration) = modified.duration_since(std::time::UNIX_EPOCH) {
2447                return duration.as_secs();
2448            }
2449        }
2450    }
2451    0
2452}
2453
2454pub fn get_last_commit_message(repo_path: &Path) -> Option<String> {
2455    if let Ok(repo) = Repository::open(repo_path) {
2456        if let Ok(head) = repo.head() {
2457            if let Ok(commit) = head.peel_to_commit() {
2458                if let Ok(msg) = commit.message() {
2459                    return Some(msg.to_string());
2460                }
2461            }
2462        }
2463    }
2464    None
2465}
2466
2467pub fn commit_amend(repo_path: &Path, message: &str) -> Result<(), String> {
2468    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
2469    let head = repo.head().map_err(|e| format!("No HEAD commit to amend: {}", e))?;
2470    let head_commit = head.peel_to_commit().map_err(|e| e.to_string())?;
2471
2472    let mut index = repo.index().map_err(|e| e.to_string())?;
2473    let tree_id = index.write_tree().map_err(|e| e.to_string())?;
2474    let tree = repo.find_tree(tree_id).map_err(|e| e.to_string())?;
2475
2476    let signature = repo
2477        .signature()
2478        .map_err(|e| format!("Failed to get signature. Check user.name/email config: {}", e))?;
2479
2480    head_commit
2481        .amend(Some("HEAD"), None, Some(&signature), None, Some(message), Some(&tree))
2482        .map_err(|e| e.to_string())?;
2483
2484    Ok(())
2485}
2486
2487// ── Merge Conflict Helpers ──────────────────────────────────────────────────
2488
2489/// Returns `true` when `.git/MERGE_HEAD` exists — i.e. a merge is in progress.
2490/// Cheap file-existence check, no libgit2 required.
2491pub fn is_merging(repo_path: &Path) -> bool {
2492    repo_path.join(".git/MERGE_HEAD").exists()
2493}
2494
2495/// Returns the conflict-marker diff for a conflicted file by parsing the file on disk.
2496/// Colorizes conflict blocks using DiffLineKind variants.
2497pub fn get_conflict_markers_diff(repo_path: &Path, file_path: &str) -> Vec<DiffLine> {
2498    let full_path = repo_path.join(file_path);
2499    let content = match std::fs::read_to_string(&full_path) {
2500        Ok(s) => s,
2501        Err(_) => return Vec::new(),
2502    };
2503
2504    let mut lines = Vec::new();
2505    let mut in_ours = false;
2506    let mut in_theirs = false;
2507
2508    for line in content.lines() {
2509        if line.starts_with("<<<<<<<") {
2510            in_ours = true;
2511            in_theirs = false;
2512            lines.push(DiffLine {
2513                kind: DiffLineKind::ConflictSeparator,
2514                content: line.to_string(),
2515            });
2516        } else if line.starts_with("=======") {
2517            in_ours = false;
2518            in_theirs = true;
2519            lines.push(DiffLine {
2520                kind: DiffLineKind::ConflictSeparator,
2521                content: line.to_string(),
2522            });
2523        } else if line.starts_with(">>>>>>>") {
2524            in_ours = false;
2525            in_theirs = false;
2526            lines.push(DiffLine {
2527                kind: DiffLineKind::ConflictSeparator,
2528                content: line.to_string(),
2529            });
2530        } else if in_ours {
2531            lines.push(DiffLine { kind: DiffLineKind::ConflictOurs, content: line.to_string() });
2532        } else if in_theirs {
2533            lines.push(DiffLine { kind: DiffLineKind::ConflictTheirs, content: line.to_string() });
2534        } else {
2535            lines.push(DiffLine { kind: DiffLineKind::Context, content: line.to_string() });
2536        }
2537    }
2538    lines
2539}
2540
2541/// Accept the OURS (HEAD) version of a conflicted file.
2542/// Equivalent to: git checkout --ours <file> && git add <file>
2543pub fn resolve_ours(repo_path: &Path, file_path: &str) -> Result<(), String> {
2544    let output1 = std::process::Command::new("git")
2545        .env("GIT_TERMINAL_PROMPT", "0")
2546        .env("GIT_SSH_COMMAND", ssh_command_val())
2547        .args(["checkout", "--ours", file_path])
2548        .current_dir(repo_path)
2549        .output()
2550        .map_err(|e| e.to_string())?;
2551    if !output1.status.success() {
2552        return Err(String::from_utf8_lossy(&output1.stderr).to_string());
2553    }
2554    stage_file(repo_path, file_path)?;
2555    Ok(())
2556}
2557
2558/// Accept the THEIRS (incoming) version of a conflicted file.
2559/// Equivalent to: git checkout --theirs <file> && git add <file>
2560pub fn resolve_theirs(repo_path: &Path, file_path: &str) -> Result<(), String> {
2561    let output1 = std::process::Command::new("git")
2562        .env("GIT_TERMINAL_PROMPT", "0")
2563        .env("GIT_SSH_COMMAND", ssh_command_val())
2564        .args(["checkout", "--theirs", file_path])
2565        .current_dir(repo_path)
2566        .output()
2567        .map_err(|e| e.to_string())?;
2568    if !output1.status.success() {
2569        return Err(String::from_utf8_lossy(&output1.stderr).to_string());
2570    }
2571    stage_file(repo_path, file_path)?;
2572    Ok(())
2573}
2574
2575/// Mark the file as resolved (stage it) after manual edits.
2576pub fn mark_resolved(repo_path: &Path, file_path: &str) -> Result<(), String> {
2577    stage_file(repo_path, file_path)
2578}
2579
2580/// Resolve a specific conflict hunk inside a file (Ours vs Theirs).
2581/// Replaces the hunk at index `hunk_idx` in the file on disk.
2582/// If no more conflicts remain in the file, it automatically stages the file.
2583pub fn resolve_conflict_hunk(
2584    repo_path: &Path,
2585    file_path: &str,
2586    hunk_idx: usize,
2587    accept_ours: bool,
2588) -> Result<(), String> {
2589    let full_path = repo_path.join(file_path);
2590    let content = std::fs::read_to_string(&full_path).map_err(|e| e.to_string())?;
2591
2592    let mut new_lines = Vec::new();
2593    let mut lines_iter = content.lines().peekable();
2594    let mut current_hunk_idx = 0;
2595
2596    while let Some(line) = lines_iter.next() {
2597        if line.starts_with("<<<<<<<") {
2598            let mut ours_block = Vec::new();
2599            let mut theirs_block = Vec::new();
2600
2601            // Read ours block (until =======)
2602            let mut found_separator = false;
2603            while let Some(&next_line) = lines_iter.peek() {
2604                if next_line.starts_with("=======") {
2605                    lines_iter.next(); // consume =======
2606                    found_separator = true;
2607                    break;
2608                }
2609                if let Some(line) = lines_iter.next() {
2610                    ours_block.push(line.to_string());
2611                }
2612            }
2613
2614            // Read theirs block (until >>>>>>>)
2615            let mut found_end = false;
2616            let mut end_line_marker = ">>>>>>>".to_string();
2617            while let Some(&next_line) = lines_iter.peek() {
2618                if next_line.starts_with(">>>>>>>") {
2619                    if let Some(marker) = lines_iter.next() {
2620                        end_line_marker = marker.to_string(); // consume >>>>>>>
2621                    }
2622                    found_end = true;
2623                    break;
2624                }
2625                if let Some(line) = lines_iter.next() {
2626                    theirs_block.push(line.to_string());
2627                }
2628            }
2629
2630            if current_hunk_idx == hunk_idx {
2631                if accept_ours {
2632                    new_lines.extend(ours_block);
2633                } else {
2634                    new_lines.extend(theirs_block);
2635                }
2636            } else {
2637                new_lines.push(line.to_string());
2638                new_lines.extend(ours_block);
2639                if found_separator {
2640                    new_lines.push("=======".to_string());
2641                }
2642                new_lines.extend(theirs_block);
2643                if found_end {
2644                    new_lines.push(end_line_marker);
2645                }
2646            }
2647
2648            current_hunk_idx += 1;
2649        } else {
2650            new_lines.push(line.to_string());
2651        }
2652    }
2653
2654    let mut new_content = new_lines.join("\n");
2655    if content.ends_with('\n') && !new_content.ends_with('\n') {
2656        new_content.push('\n');
2657    }
2658    std::fs::write(&full_path, new_content).map_err(|e| e.to_string())?;
2659
2660    // Check if any conflict markers remain in the file
2661    let updated_content = std::fs::read_to_string(&full_path).map_err(|e| e.to_string())?;
2662    let has_conflict_markers = updated_content
2663        .lines()
2664        .any(|l| l.starts_with("<<<<<<<") || l.starts_with("=======") || l.starts_with(">>>>>>>"));
2665
2666    if !has_conflict_markers {
2667        stage_file(repo_path, file_path)?;
2668    }
2669
2670    Ok(())
2671}
2672
2673/// Abort the in-progress merge.
2674pub fn abort_merge(repo_path: &Path) -> Result<(), String> {
2675    let output = std::process::Command::new("git")
2676        .env("GIT_TERMINAL_PROMPT", "0")
2677        .env("GIT_SSH_COMMAND", ssh_command_val())
2678        .args(["merge", "--abort"])
2679        .current_dir(repo_path)
2680        .output()
2681        .map_err(|e| e.to_string())?;
2682    if !output.status.success() {
2683        return Err(String::from_utf8_lossy(&output.stderr).to_string());
2684    }
2685    Ok(())
2686}
2687
2688/// Continue the merge after conflicts are resolved.
2689pub fn continue_merge(repo_path: &Path) -> Result<(), String> {
2690    let output = std::process::Command::new("git")
2691        .env("GIT_TERMINAL_PROMPT", "0")
2692        .env("GIT_SSH_COMMAND", ssh_command_val())
2693        .args(["merge", "--continue"])
2694        .env("GIT_EDITOR", "true")
2695        .current_dir(repo_path)
2696        .output()
2697        .map_err(|e| e.to_string())?;
2698    if !output.status.success() {
2699        return Err(String::from_utf8_lossy(&output.stderr).to_string());
2700    }
2701    Ok(())
2702}
2703
2704/// Returns the upstream tracking remote name for a branch, if configured.
2705pub fn get_branch_upstream_remote(repo_path: &Path, branch_name: &str) -> Option<String> {
2706    let repo = Repository::open(repo_path).ok()?;
2707    let branch = repo.find_branch(branch_name, git2::BranchType::Local).ok()?;
2708    let upstream = branch.upstream().ok()?;
2709    let upstream_ref = upstream.get().name().ok()?;
2710    let remote_buf = repo.branch_upstream_remote(upstream_ref).ok()?;
2711    remote_buf.as_str().ok().map(|s| s.to_string())
2712}
2713
2714/// Returns whether the specified branch has a configured upstream tracking branch.
2715pub fn has_upstream_remote(repo_path: &Path, branch_name: &str) -> bool {
2716    get_branch_upstream_remote(repo_path, branch_name).is_some()
2717}
2718
2719/// Finds the remote target for pushing a branch. Returns `(remote_name, set_upstream)`.
2720pub fn get_branch_push_target(repo_path: &Path, branch_name: &str) -> Option<(String, bool)> {
2721    let repo = Repository::open(repo_path).ok()?;
2722    let branch = repo.find_branch(branch_name, git2::BranchType::Local).ok()?;
2723    if let Ok(upstream) = branch.upstream() {
2724        if let Ok(upstream_ref) = upstream.get().name() {
2725            if let Ok(remote_buf) = repo.branch_upstream_remote(upstream_ref) {
2726                if let Ok(name) = remote_buf.as_str() {
2727                    return Some((name.to_string(), false));
2728                }
2729            }
2730        }
2731    }
2732    let remotes = repo.remotes().ok()?;
2733    let first_remote = remotes.iter().next()?.ok()??.to_string();
2734    Some((first_remote, true))
2735}
2736
2737/// Returns whether the specified commit OID has no parents (i.e. it is the root commit).
2738pub fn is_root_commit(repo_path: &Path, commit_oid: &str) -> bool {
2739    if let Ok(repo) = Repository::open(repo_path) {
2740        if let Ok(oid) = git2::Oid::from_str(commit_oid) {
2741            if let Ok(commit) = repo.find_commit(oid) {
2742                return commit.parent_count() == 0;
2743            }
2744        }
2745    }
2746    false
2747}
2748
2749pub fn load_tab_worktrees(repo_path: &Path) -> Result<Vec<WorktreeInfo>, String> {
2750    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
2751    let mut worktrees_list = Vec::new();
2752    if let Ok(worktree_names) = repo.worktrees() {
2753        for name in worktree_names.iter() {
2754            let Ok(Some(wt_name)) = name else { continue };
2755            if let Ok(wt) = repo.find_worktree(wt_name) {
2756                let path = wt.path().to_path_buf();
2757                let mut branch = None;
2758                if let Ok(wt_repo) = Repository::open(&path) {
2759                    if let Ok(head) = wt_repo.head() {
2760                        branch = head.shorthand().map(String::from).ok();
2761                    }
2762                }
2763
2764                let mut is_locked = false;
2765                let mut lock_reason = None;
2766                if let Ok(git2::WorktreeLockStatus::Locked(reason_opt)) = wt.is_locked() {
2767                    is_locked = true;
2768                    if let Some(reason) = reason_opt {
2769                        if !reason.is_empty() {
2770                            lock_reason = Some(reason);
2771                        }
2772                    }
2773                }
2774
2775                worktrees_list.push(WorktreeInfo {
2776                    name: wt_name.to_string(),
2777                    path,
2778                    branch,
2779                    is_locked,
2780                    lock_reason,
2781                });
2782            }
2783        }
2784    }
2785    Ok(worktrees_list)
2786}
2787
2788pub fn worktree_add(repo_path: &Path, branch: &str, wt_path: &Path) -> Result<(), String> {
2789    let output = std::process::Command::new("git")
2790        .arg("worktree")
2791        .arg("add")
2792        .arg(wt_path)
2793        .arg(branch)
2794        .current_dir(repo_path)
2795        .output()
2796        .map_err(|e| e.to_string())?;
2797
2798    if !output.status.success() {
2799        return Err(String::from_utf8_lossy(&output.stderr).to_string());
2800    }
2801    Ok(())
2802}
2803
2804pub fn worktree_lock(repo_path: &Path, name: &str, reason: &str) -> Result<(), String> {
2805    let output = std::process::Command::new("git")
2806        .arg("worktree")
2807        .arg("lock")
2808        .arg("--reason")
2809        .arg(reason)
2810        .arg(name)
2811        .current_dir(repo_path)
2812        .output()
2813        .map_err(|e| e.to_string())?;
2814
2815    if !output.status.success() {
2816        return Err(String::from_utf8_lossy(&output.stderr).to_string());
2817    }
2818    Ok(())
2819}
2820
2821pub fn worktree_unlock(repo_path: &Path, name: &str) -> Result<(), String> {
2822    let output = std::process::Command::new("git")
2823        .arg("worktree")
2824        .arg("unlock")
2825        .arg(name)
2826        .current_dir(repo_path)
2827        .output()
2828        .map_err(|e| e.to_string())?;
2829
2830    if !output.status.success() {
2831        return Err(String::from_utf8_lossy(&output.stderr).to_string());
2832    }
2833    Ok(())
2834}
2835
2836pub fn worktree_remove(repo_path: &Path, name: &str, force: bool) -> Result<(), String> {
2837    let mut cmd = std::process::Command::new("git");
2838    cmd.arg("worktree").arg("remove");
2839    if force {
2840        cmd.arg("--force");
2841    }
2842    let output = cmd.arg(name).current_dir(repo_path).output().map_err(|e| e.to_string())?;
2843
2844    if !output.status.success() {
2845        return Err(String::from_utf8_lossy(&output.stderr).to_string());
2846    }
2847    Ok(())
2848}
2849
2850pub fn worktree_prune(repo_path: &Path) -> Result<(), String> {
2851    let output = std::process::Command::new("git")
2852        .arg("worktree")
2853        .arg("prune")
2854        .current_dir(repo_path)
2855        .output()
2856        .map_err(|e| e.to_string())?;
2857
2858    if !output.status.success() {
2859        return Err(String::from_utf8_lossy(&output.stderr).to_string());
2860    }
2861    Ok(())
2862}
2863
2864#[cfg(test)]
2865#[allow(clippy::unwrap_used, clippy::panic)]
2866mod tests {
2867    use super::*;
2868    use std::fs::File;
2869    use std::io::Write;
2870
2871    #[test]
2872    fn test_commit_amend() {
2873        let mut temp_path = std::env::temp_dir();
2874        temp_path.push(format!(
2875            "twig_test_{}",
2876            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
2877        ));
2878        std::fs::create_dir_all(&temp_path).unwrap();
2879
2880        // Init repo
2881        let repo = Repository::init(&temp_path).unwrap();
2882
2883        // Configure author
2884        let mut config = repo.config().unwrap();
2885        config.set_str("user.name", "Test User").unwrap();
2886        config.set_str("user.email", "test@example.com").unwrap();
2887
2888        // Create initial file
2889        let file_path = temp_path.join("test.txt");
2890        let mut file = File::create(&file_path).unwrap();
2891        writeln!(file, "initial content").unwrap();
2892
2893        // Stage and commit initial
2894        stage_file(&temp_path, "test.txt").unwrap();
2895        commit_changes(&temp_path, "initial commit").unwrap();
2896
2897        // Verify message
2898        let msg = get_last_commit_message(&temp_path).unwrap();
2899        assert_eq!(msg, "initial commit");
2900
2901        // Amend the commit message
2902        commit_amend(&temp_path, "amended commit").unwrap();
2903
2904        // Verify amended message
2905        let amended_msg = get_last_commit_message(&temp_path).unwrap();
2906        assert_eq!(amended_msg, "amended commit");
2907
2908        // Clean up
2909        let _ = std::fs::remove_dir_all(&temp_path);
2910    }
2911
2912    #[test]
2913    fn test_commit_signatures_collection() {
2914        let mut temp_path = std::env::temp_dir();
2915        temp_path.push(format!(
2916            "twig_test_sig_{}",
2917            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
2918        ));
2919        std::fs::create_dir_all(&temp_path).unwrap();
2920
2921        // Init repo
2922        let repo = Repository::init(&temp_path).unwrap();
2923
2924        // Configure author
2925        let mut config = repo.config().unwrap();
2926        config.set_str("user.name", "Test User").unwrap();
2927        config.set_str("user.email", "test@example.com").unwrap();
2928
2929        // Create initial file
2930        let file_path = temp_path.join("test.txt");
2931        let mut file = File::create(&file_path).unwrap();
2932        writeln!(file, "initial content").unwrap();
2933
2934        // Stage and commit initial
2935        stage_file(&temp_path, "test.txt").unwrap();
2936        commit_changes(&temp_path, "initial commit").unwrap();
2937
2938        // 1. Test collect_signatures
2939        let sigs = collect_signatures(&temp_path, 0);
2940        assert_eq!(sigs.len(), 1);
2941        let head_oid = repo.head().unwrap().target().unwrap().to_string();
2942        let sig_status = sigs.get(&head_oid).unwrap();
2943        assert_eq!(sig_status, "N");
2944
2945        // 2. Test collect_commits (files should be empty by default)
2946        let commits = collect_commits(&repo, 0, &temp_path, true).unwrap();
2947        assert_eq!(commits.len(), 1);
2948        assert_eq!(commits[0].signature_status, "N");
2949        assert!(commits[0].files.is_empty());
2950
2951        // Test get_commit_files (lazy loading)
2952        let files = get_commit_files(&temp_path, &commits[0].oid).unwrap();
2953        assert_eq!(files.len(), 1);
2954        assert_eq!(files[0].path, "test.txt");
2955        assert_eq!(files[0].label, "N");
2956
2957        // 3. Test collect_graph_lines
2958        let graph = collect_graph_lines(&temp_path, 1000);
2959        assert_eq!(graph.len(), 1);
2960        assert!(graph[0].commit.is_some());
2961        assert_eq!(graph[0].commit.as_ref().unwrap().signature_status, "N");
2962
2963        // Clean up
2964        let _ = std::fs::remove_dir_all(&temp_path);
2965    }
2966
2967    #[test]
2968    fn test_ref_map_cache_behavior() {
2969        let temp_dir = std::env::temp_dir();
2970        let repo_path = temp_dir.join("test_ref_map_repo");
2971        let _ = std::fs::remove_dir_all(&repo_path);
2972        std::fs::create_dir_all(&repo_path).unwrap();
2973
2974        let repo = Repository::init(&repo_path).unwrap();
2975
2976        // 1. First fetch (rebuilds and caches)
2977        let map1 = get_cached_ref_map(&repo, &repo_path);
2978
2979        // 2. Second fetch (returns cached map)
2980        let map2 = get_cached_ref_map(&repo, &repo_path);
2981        assert_eq!(map1.len(), map2.len());
2982
2983        // 3. Invalidate cache
2984        invalidate_ref_map_cache(&repo_path);
2985
2986        // Clean up
2987        let _ = std::fs::remove_dir_all(&repo_path);
2988    }
2989
2990    #[test]
2991    fn test_get_latest_change_time() {
2992        let mut temp_path = std::env::temp_dir();
2993        temp_path.push(format!(
2994            "twig_test_{}",
2995            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
2996        ));
2997        std::fs::create_dir_all(&temp_path).unwrap();
2998
2999        let change_time = get_latest_change_time(temp_path.to_str().unwrap());
3000        assert!(change_time > 0);
3001
3002        let _ = std::fs::remove_dir_all(&temp_path);
3003    }
3004
3005    #[test]
3006    fn test_committer_stats() {
3007        let mut temp_path = std::env::temp_dir();
3008        temp_path.push(format!(
3009            "twig_test_{}",
3010            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
3011        ));
3012        std::fs::create_dir_all(&temp_path).unwrap();
3013
3014        // Init repo
3015        let repo = Repository::init(&temp_path).unwrap();
3016
3017        // Configure author
3018        let mut config = repo.config().unwrap();
3019        config.set_str("user.name", "Test User").unwrap();
3020        config.set_str("user.email", "test@example.com").unwrap();
3021
3022        // Create initial file
3023        let file_path = temp_path.join("test.txt");
3024        let mut file = File::create(&file_path).unwrap();
3025        writeln!(file, "initial content").unwrap();
3026
3027        // Stage and commit initial
3028        stage_file(&temp_path, "test.txt").unwrap();
3029        commit_changes(&temp_path, "initial commit").unwrap();
3030
3031        // Collect stats
3032        let (stats, limit_reached) = collect_committer_stats(&repo, 10).unwrap();
3033        assert_eq!(stats.len(), 1);
3034        assert_eq!(stats[0].name, "Test User");
3035        assert_eq!(stats[0].email, "test@example.com");
3036        assert_eq!(stats[0].count, 1);
3037        assert!(!limit_reached);
3038
3039        // Clean up
3040        let _ = std::fs::remove_dir_all(&temp_path);
3041    }
3042
3043    #[test]
3044    fn test_untracked_files_in_unstaged() {
3045        let mut temp_path = std::env::temp_dir();
3046        temp_path.push(format!(
3047            "twig_test_{}",
3048            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
3049        ));
3050        std::fs::create_dir_all(&temp_path).unwrap();
3051
3052        // Init repo
3053        let _repo = Repository::init(&temp_path).unwrap();
3054
3055        // Create an untracked file
3056        let file_path = temp_path.join("untracked.txt");
3057        let mut file = File::create(&file_path).unwrap();
3058        writeln!(file, "hello untracked").unwrap();
3059
3060        // Create an untracked directory and a file inside it
3061        let untracked_dir = temp_path.join("untracked_dir");
3062        std::fs::create_dir_all(&untracked_dir).unwrap();
3063        let nested_file_path = untracked_dir.join("nested.txt");
3064        std::fs::write(&nested_file_path, "nested untracked file").unwrap();
3065
3066        // Inspect detail
3067        let detail = inspect_detail(temp_path.to_str().unwrap(), 0, 1000, false);
3068        match detail {
3069            ItemDetail::Repo { info, .. } => {
3070                // Verify no folders are in the unstaged/untracked list
3071                let unstaged_paths: Vec<String> =
3072                    info.changes.unstaged.iter().map(|f| f.path.clone()).collect();
3073                let untracked_paths: Vec<String> =
3074                    info.changes.untracked.iter().map(|f| f.path.clone()).collect();
3075
3076                // Folder itself should NOT be listed
3077                assert!(!unstaged_paths.contains(&"untracked_dir".to_string()));
3078                assert!(!unstaged_paths.contains(&"untracked_dir/".to_string()));
3079                assert!(!untracked_paths.contains(&"untracked_dir".to_string()));
3080                assert!(!untracked_paths.contains(&"untracked_dir/".to_string()));
3081
3082                // Untracked files (both root and nested) should be listed
3083                assert!(unstaged_paths.contains(&"untracked.txt".to_string()));
3084                assert!(unstaged_paths.contains(&"untracked_dir/nested.txt".to_string()));
3085                assert!(untracked_paths.contains(&"untracked.txt".to_string()));
3086                assert!(untracked_paths.contains(&"untracked_dir/nested.txt".to_string()));
3087            }
3088            _ => panic!("Expected ItemDetail::Repo"),
3089        }
3090
3091        // Clean up
3092        let _ = std::fs::remove_dir_all(&temp_path);
3093    }
3094
3095    #[test]
3096    fn test_stage_new_and_deleted_files() {
3097        let mut temp_path = std::env::temp_dir();
3098        temp_path.push(format!(
3099            "twig_test_{}",
3100            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
3101        ));
3102        std::fs::create_dir_all(&temp_path).unwrap();
3103
3104        // Init repo
3105        let repo = Repository::init(&temp_path).unwrap();
3106
3107        // Configure author
3108        let mut config = repo.config().unwrap();
3109        config.set_str("user.name", "Test User").unwrap();
3110        config.set_str("user.email", "test@example.com").unwrap();
3111
3112        // Create initial file & commit
3113        let init_file = temp_path.join("init.txt");
3114        std::fs::write(&init_file, "initial").unwrap();
3115        stage_file(&temp_path, "init.txt").unwrap();
3116        commit_changes(&temp_path, "initial commit").unwrap();
3117
3118        // 1. Create a new file (untracked)
3119        let untracked_file = temp_path.join("untracked.txt");
3120        std::fs::write(&untracked_file, "new file content").unwrap();
3121
3122        // Try staging untracked file
3123        stage_file(&temp_path, "untracked.txt").unwrap();
3124
3125        // 2. Delete the initial file
3126        std::fs::remove_file(&init_file).unwrap();
3127
3128        // Try staging deleted file
3129        stage_file(&temp_path, "init.txt").unwrap();
3130
3131        // Check status of repo
3132        let detail = inspect_detail(temp_path.to_str().unwrap(), 0, 1000, false);
3133        match detail {
3134            ItemDetail::Repo { info, .. } => {
3135                // Both should be in staged changes
3136                assert_eq!(info.changes.staged.len(), 2);
3137                let paths: Vec<String> =
3138                    info.changes.staged.iter().map(|f| f.path.clone()).collect();
3139                assert!(paths.contains(&"untracked.txt".to_string()));
3140                assert!(paths.contains(&"init.txt".to_string()));
3141            }
3142            _ => panic!("Expected ItemDetail::Repo"),
3143        }
3144
3145        // Clean up
3146        let _ = std::fs::remove_dir_all(&temp_path);
3147    }
3148
3149    #[test]
3150    fn test_discard_file_changes_all_cases() {
3151        let mut temp_path = std::env::temp_dir();
3152        temp_path.push(format!(
3153            "twig_test_{}",
3154            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
3155        ));
3156        std::fs::create_dir_all(&temp_path).unwrap();
3157
3158        // Init repo
3159        let repo = Repository::init(&temp_path).unwrap();
3160
3161        // Configure author
3162        let mut config = repo.config().unwrap();
3163        config.set_str("user.name", "Test User").unwrap();
3164        config.set_str("user.email", "test@example.com").unwrap();
3165
3166        // Create and commit initial files
3167        let file_tracked = temp_path.join("tracked.txt");
3168        std::fs::write(&file_tracked, "original content\n").unwrap();
3169        stage_file(&temp_path, "tracked.txt").unwrap();
3170        commit_changes(&temp_path, "initial commit").unwrap();
3171
3172        // Case 1: Untracked file
3173        let file_untracked = temp_path.join("untracked.txt");
3174        std::fs::write(&file_untracked, "new untracked file\n").unwrap();
3175        assert!(file_untracked.exists());
3176        discard_file_changes(&temp_path, "untracked.txt", false).unwrap();
3177        assert!(!file_untracked.exists());
3178
3179        // Case 2: Tracked file with unstaged modification
3180        std::fs::write(&file_tracked, "unstaged modifications\n").unwrap();
3181        discard_file_changes(&temp_path, "tracked.txt", false).unwrap();
3182        assert_eq!(std::fs::read_to_string(&file_tracked).unwrap(), "original content\n");
3183
3184        // Case 3: Tracked file with staged modification
3185        std::fs::write(&file_tracked, "staged modifications\n").unwrap();
3186        stage_file(&temp_path, "tracked.txt").unwrap();
3187        // verify it's staged
3188        let detail = inspect_detail(temp_path.to_str().unwrap(), 0, 1000, false);
3189        match detail {
3190            ItemDetail::Repo { info, .. } => {
3191                assert!(!info.changes.staged.is_empty());
3192            }
3193            _ => panic!("Expected ItemDetail::Repo"),
3194        }
3195        discard_file_changes(&temp_path, "tracked.txt", true).unwrap();
3196        assert_eq!(std::fs::read_to_string(&file_tracked).unwrap(), "original content\n");
3197        // verify it's no longer staged/unstaged (it's clean)
3198        let detail = inspect_detail(temp_path.to_str().unwrap(), 0, 1000, false);
3199        match detail {
3200            ItemDetail::Repo { info, .. } => {
3201                assert!(info.changes.staged.is_empty());
3202                assert!(info.changes.unstaged.is_empty());
3203            }
3204            _ => panic!("Expected ItemDetail::Repo"),
3205        }
3206
3207        // Case 4: Tracked deleted file
3208        std::fs::remove_file(&file_tracked).unwrap();
3209        assert!(!file_tracked.exists());
3210        discard_file_changes(&temp_path, "tracked.txt", false).unwrap();
3211        assert!(file_tracked.exists());
3212        assert_eq!(std::fs::read_to_string(&file_tracked).unwrap(), "original content\n");
3213
3214        // Clean up
3215        let _ = std::fs::remove_dir_all(&temp_path);
3216    }
3217
3218    #[test]
3219    #[cfg_attr(target_os = "windows", ignore = "CRLF patch issues on Windows")]
3220    fn test_stage_unstage_by_hunk() {
3221        let mut temp_path = std::env::temp_dir();
3222        temp_path.push(format!(
3223            "twig_test_{}",
3224            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
3225        ));
3226        std::fs::create_dir_all(&temp_path).unwrap();
3227
3228        // Init repo
3229        let repo = Repository::init(&temp_path).unwrap();
3230
3231        // Configure author
3232        let mut config = repo.config().unwrap();
3233        config.set_str("user.name", "Test User").unwrap();
3234        config.set_str("user.email", "test@example.com").unwrap();
3235
3236        // Create initial file with multiple lines
3237        let file_path = temp_path.join("multihunk.txt");
3238        let mut file = File::create(&file_path).unwrap();
3239        for i in 1..=20 {
3240            writeln!(file, "Line {}", i).unwrap();
3241        }
3242        drop(file);
3243
3244        // Stage and commit initial
3245        stage_file(&temp_path, "multihunk.txt").unwrap();
3246        commit_changes(&temp_path, "initial commit").unwrap();
3247
3248        // Now modify lines 2 and 18 to create two distinct hunks
3249        let mut file = File::create(&file_path).unwrap();
3250        for i in 1..=20 {
3251            if i == 2 || i == 18 {
3252                writeln!(file, "Line {} modified", i).unwrap();
3253            } else {
3254                writeln!(file, "Line {}", i).unwrap();
3255            }
3256        }
3257        drop(file);
3258
3259        // Get the unstaged diff lines
3260        let diff_lines = get_worktree_file_diff(&temp_path, "multihunk.txt", false);
3261        // Identify hunk ranges. A hunk header starts with "@@"
3262        let mut hunk_ranges = Vec::new();
3263        let mut current_start = None;
3264        for (i, line) in diff_lines.iter().enumerate() {
3265            if line.kind == DiffLineKind::Header {
3266                if let Some(start) = current_start {
3267                    hunk_ranges.push(start..i);
3268                }
3269                current_start = Some(i);
3270            }
3271        }
3272        if let Some(start) = current_start {
3273            hunk_ranges.push(start..diff_lines.len());
3274        }
3275
3276        // We expect exactly 2 hunks
3277        assert_eq!(hunk_ranges.len(), 2);
3278
3279        // Stage the second hunk
3280        let hunk2 = &diff_lines[hunk_ranges[1].clone()];
3281        stage_hunk(&temp_path, "multihunk.txt", hunk2).unwrap();
3282
3283        // Now check staged diff for the file: it should contain the second modification
3284        let staged_diff = get_worktree_file_diff(&temp_path, "multihunk.txt", true);
3285        let staged_content: String =
3286            staged_diff.iter().map(|l| l.content.as_str()).collect::<Vec<_>>().join("\n");
3287        assert!(staged_content.contains("Line 18 modified"));
3288        assert!(!staged_content.contains("Line 2 modified"));
3289
3290        // Check unstaged diff for the file: it should contain the first modification
3291        let unstaged_diff = get_worktree_file_diff(&temp_path, "multihunk.txt", false);
3292        let unstaged_content: String =
3293            unstaged_diff.iter().map(|l| l.content.as_str()).collect::<Vec<_>>().join("\n");
3294        assert!(unstaged_content.contains("Line 2 modified"));
3295        assert!(!unstaged_content.contains("Line 18 modified"));
3296
3297        // Unstage the staged hunk
3298        let staged_hunk_ranges = {
3299            let mut ranges = Vec::new();
3300            let mut current_start = None;
3301            for (i, line) in staged_diff.iter().enumerate() {
3302                if line.kind == DiffLineKind::Header {
3303                    if let Some(start) = current_start {
3304                        ranges.push(start..i);
3305                    }
3306                    current_start = Some(i);
3307                }
3308            }
3309            if let Some(start) = current_start {
3310                ranges.push(start..staged_diff.len());
3311            }
3312            ranges
3313        };
3314        assert_eq!(staged_hunk_ranges.len(), 1);
3315        let staged_hunk = &staged_diff[staged_hunk_ranges[0].clone()];
3316        unstage_hunk(&temp_path, "multihunk.txt", staged_hunk).unwrap();
3317
3318        // Staged diff should now be empty
3319        let staged_diff_after = get_worktree_file_diff(&temp_path, "multihunk.txt", true);
3320        assert!(staged_diff_after.is_empty());
3321
3322        // Clean up
3323        let _ = std::fs::remove_dir_all(&temp_path);
3324    }
3325
3326    #[test]
3327    #[cfg_attr(target_os = "windows", ignore = "CRLF patch issues on Windows")]
3328    fn test_discard_hunk() {
3329        let mut temp_path = std::env::temp_dir();
3330        temp_path.push(format!(
3331            "twig_test_{}",
3332            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
3333        ));
3334        std::fs::create_dir_all(&temp_path).unwrap();
3335
3336        // Init repo
3337        let repo = Repository::init(&temp_path).unwrap();
3338
3339        // Configure author
3340        let mut config = repo.config().unwrap();
3341        config.set_str("user.name", "Test User").unwrap();
3342        config.set_str("user.email", "test@example.com").unwrap();
3343
3344        // Create initial file with multiple lines
3345        let file_path = temp_path.join("discardhunk.txt");
3346        let mut file = File::create(&file_path).unwrap();
3347        for i in 1..=20 {
3348            writeln!(file, "Line {}", i).unwrap();
3349        }
3350        drop(file);
3351
3352        // Stage and commit initial
3353        stage_file(&temp_path, "discardhunk.txt").unwrap();
3354        commit_changes(&temp_path, "initial commit").unwrap();
3355
3356        // Now modify lines 2 and 18 to create two distinct hunks
3357        let mut file = File::create(&file_path).unwrap();
3358        for i in 1..=20 {
3359            if i == 2 || i == 18 {
3360                writeln!(file, "Line {} modified", i).unwrap();
3361            } else {
3362                writeln!(file, "Line {}", i).unwrap();
3363            }
3364        }
3365        drop(file);
3366
3367        // Get the unstaged diff lines
3368        let diff_lines = get_worktree_file_diff(&temp_path, "discardhunk.txt", false);
3369        // Identify hunk ranges
3370        let mut hunk_ranges = Vec::new();
3371        let mut current_start = None;
3372        for (i, line) in diff_lines.iter().enumerate() {
3373            if line.kind == DiffLineKind::Header {
3374                if let Some(start) = current_start {
3375                    hunk_ranges.push(start..i);
3376                }
3377                current_start = Some(i);
3378            }
3379        }
3380        if let Some(start) = current_start {
3381            hunk_ranges.push(start..diff_lines.len());
3382        }
3383
3384        // We expect exactly 2 hunks
3385        assert_eq!(hunk_ranges.len(), 2);
3386
3387        // Discard the second hunk (Line 18 modified)
3388        let hunk2 = &diff_lines[hunk_ranges[1].clone()];
3389        discard_hunk(&temp_path, "discardhunk.txt", hunk2).unwrap();
3390
3391        // Now check file contents: line 18 should be reverted to "Line 18", while line 2 should remain "Line 2 modified"
3392        let contents = std::fs::read_to_string(&file_path).unwrap();
3393        assert!(contents.contains("Line 2 modified"));
3394        assert!(contents.contains("Line 18\n"));
3395        assert!(!contents.contains("Line 18 modified"));
3396
3397        // Clean up
3398        let _ = std::fs::remove_dir_all(&temp_path);
3399    }
3400
3401    #[test]
3402    #[cfg_attr(target_os = "windows", ignore = "CRLF patch issues on Windows")]
3403    fn test_stage_unstage_discard_line() {
3404        let mut temp_path = std::env::temp_dir();
3405        temp_path.push(format!(
3406            "twig_test_{}",
3407            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
3408        ));
3409        std::fs::create_dir_all(&temp_path).unwrap();
3410
3411        let repo = Repository::init(&temp_path).unwrap();
3412        let mut config = repo.config().unwrap();
3413        config.set_str("user.name", "Test User").unwrap();
3414        config.set_str("user.email", "test@example.com").unwrap();
3415
3416        // 1. Create initial file
3417        let file_path = temp_path.join("line_test.txt");
3418        let mut file = File::create(&file_path).unwrap();
3419        writeln!(file, "line A").unwrap();
3420        writeln!(file, "line B").unwrap();
3421        writeln!(file, "line C").unwrap();
3422        drop(file);
3423
3424        stage_file(&temp_path, "line_test.txt").unwrap();
3425        commit_changes(&temp_path, "initial").unwrap();
3426
3427        // 2. Modify to introduce two distinct changes in one hunk
3428        let mut file = File::create(&file_path).unwrap();
3429        writeln!(file, "line A modified").unwrap();
3430        writeln!(file, "line B").unwrap();
3431        writeln!(file, "line C modified").unwrap();
3432        drop(file);
3433
3434        let diff_lines = get_worktree_file_diff(&temp_path, "line_test.txt", false);
3435        let mut hunk_ranges = Vec::new();
3436        let mut current_start = None;
3437        for (i, line) in diff_lines.iter().enumerate() {
3438            if line.kind == DiffLineKind::Header {
3439                if let Some(start) = current_start {
3440                    hunk_ranges.push(start..i);
3441                }
3442                current_start = Some(i);
3443            }
3444        }
3445        if let Some(start) = current_start {
3446            hunk_ranges.push(start..diff_lines.len());
3447        }
3448
3449        assert_eq!(hunk_ranges.len(), 1);
3450        let hunk0 = &diff_lines[hunk_ranges[0].clone()];
3451
3452        assert_eq!(hunk0[2].content, "line A modified");
3453        assert_eq!(hunk0[5].content, "line C modified");
3454
3455        // A) Stage line A modified (relative index 2)
3456        stage_line(&temp_path, "line_test.txt", hunk0, 2).unwrap();
3457
3458        // Check staged diff
3459        let staged_diff = get_worktree_file_diff(&temp_path, "line_test.txt", true);
3460        assert!(
3461            staged_diff
3462                .iter()
3463                .any(|l| l.kind == DiffLineKind::Added && l.content == "line A modified")
3464        );
3465        assert!(
3466            !staged_diff
3467                .iter()
3468                .any(|l| l.kind == DiffLineKind::Added && l.content == "line C modified")
3469        );
3470
3471        // Check unstaged diff
3472        let unstaged_diff = get_worktree_file_diff(&temp_path, "line_test.txt", false);
3473        assert!(
3474            !unstaged_diff
3475                .iter()
3476                .any(|l| l.kind == DiffLineKind::Added && l.content == "line A modified")
3477        );
3478        assert!(
3479            unstaged_diff
3480                .iter()
3481                .any(|l| l.kind == DiffLineKind::Added && l.content == "line C modified")
3482        );
3483
3484        // B) Unstage line A modified
3485        assert_eq!(staged_diff[2].content, "line A modified");
3486        unstage_line(&temp_path, "line_test.txt", &staged_diff, 2).unwrap();
3487
3488        // Staged diff should now be empty
3489        assert!(get_worktree_file_diff(&temp_path, "line_test.txt", true).is_empty());
3490
3491        // C) Discard line C modified (index 5) in unstaged diff
3492        let unstaged_diff2 = get_worktree_file_diff(&temp_path, "line_test.txt", false);
3493        assert_eq!(unstaged_diff2[5].content, "line C modified");
3494        discard_line(&temp_path, "line_test.txt", &unstaged_diff2, 5).unwrap();
3495
3496        let unstaged_diff3 = get_worktree_file_diff(&temp_path, "line_test.txt", false);
3497        let remove_idx = unstaged_diff3
3498            .iter()
3499            .position(|l| l.kind == DiffLineKind::Removed && l.content == "line C")
3500            .unwrap();
3501        discard_line(&temp_path, "line_test.txt", &unstaged_diff3, remove_idx).unwrap();
3502
3503        // File contents check
3504        let contents = std::fs::read_to_string(&file_path).unwrap();
3505        assert!(contents.contains("line A modified"));
3506        assert!(contents.contains("line B"));
3507        assert!(contents.contains("line C\n"));
3508        assert!(!contents.contains("line C modified"));
3509
3510        // Clean up
3511        let _ = std::fs::remove_dir_all(&temp_path);
3512    }
3513
3514    #[test]
3515    #[cfg_attr(target_os = "windows", ignore = "CRLF patch issues on Windows")]
3516    fn test_stage_unstage_discard_all_changes() {
3517        let mut temp_path = std::env::temp_dir();
3518        temp_path.push(format!(
3519            "twig_test_all_{}",
3520            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
3521        ));
3522        std::fs::create_dir_all(&temp_path).unwrap();
3523
3524        // Init repo
3525        let repo = Repository::init(&temp_path).unwrap();
3526
3527        // Configure author
3528        let mut config = repo.config().unwrap();
3529        config.set_str("user.name", "Test User").unwrap();
3530        config.set_str("user.email", "test@example.com").unwrap();
3531
3532        // Create initial file & commit it
3533        let file_path = temp_path.join("tracked.txt");
3534        std::fs::write(&file_path, "original content\n").unwrap();
3535        stage_file(&temp_path, "tracked.txt").unwrap();
3536        commit_changes(&temp_path, "initial").unwrap();
3537
3538        // 1. Make a modification and create a new untracked file
3539        std::fs::write(&file_path, "modified content\n").unwrap();
3540        let untracked_path = temp_path.join("untracked.txt");
3541        std::fs::write(&untracked_path, "untracked content\n").unwrap();
3542
3543        // Verify status has unstaged changes
3544        let status = repo.statuses(None).unwrap();
3545        assert_eq!(status.len(), 2);
3546
3547        // Stage all changes
3548        stage_all_changes(&temp_path).unwrap();
3549
3550        // Verify all changes are staged
3551        let status = repo.statuses(None).unwrap();
3552        for entry in status.iter() {
3553            assert!(
3554                entry.status().intersects(git2::Status::INDEX_MODIFIED | git2::Status::INDEX_NEW)
3555            );
3556        }
3557
3558        // Unstage all changes
3559        unstage_all_changes(&temp_path).unwrap();
3560
3561        // Verify all changes are unstaged again
3562        let status = repo.statuses(None).unwrap();
3563        for entry in status.iter() {
3564            assert!(entry.status().intersects(git2::Status::WT_MODIFIED | git2::Status::WT_NEW));
3565        }
3566
3567        // Discard all changes
3568        discard_all_changes(&temp_path).unwrap();
3569
3570        // Verify repo is completely clean
3571        let status = repo.statuses(None).unwrap();
3572        assert_eq!(status.len(), 0);
3573
3574        // Verify tracked file is reset and untracked file is removed
3575        let contents = std::fs::read_to_string(&file_path).unwrap();
3576        assert_eq!(contents, "original content\n");
3577        assert!(!untracked_path.exists());
3578
3579        // Clean up
3580        let _ = std::fs::remove_dir_all(&temp_path);
3581    }
3582
3583    #[test]
3584    fn test_merge_conflicts_flow() {
3585        let mut temp_path = std::env::temp_dir();
3586        temp_path.push(format!(
3587            "twig_test_conflict_{}",
3588            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
3589        ));
3590        std::fs::create_dir_all(&temp_path).unwrap();
3591
3592        // Init repo
3593        let repo = Repository::init(&temp_path).unwrap();
3594
3595        // Configure author
3596        let mut config = repo.config().unwrap();
3597        config.set_str("user.name", "Test User").unwrap();
3598        config.set_str("user.email", "test@example.com").unwrap();
3599
3600        // 1. Initial commit on main
3601        let file_path = temp_path.join("conflict.txt");
3602        std::fs::write(&file_path, "line 1\nline 2\nline 3\n").unwrap();
3603        stage_file(&temp_path, "conflict.txt").unwrap();
3604        commit_changes(&temp_path, "initial commit").unwrap();
3605
3606        // Get the main branch name first
3607        let output = std::process::Command::new("git")
3608            .env("GIT_TERMINAL_PROMPT", "0")
3609            .env("GIT_SSH_COMMAND", ssh_command_val())
3610            .args(["symbolic-ref", "--short", "HEAD"])
3611            .current_dir(&temp_path)
3612            .output()
3613            .unwrap();
3614        let main_branch = String::from_utf8_lossy(&output.stdout).trim().to_string();
3615
3616        // 2. Create feature branch and edit
3617        std::process::Command::new("git")
3618            .env("GIT_TERMINAL_PROMPT", "0")
3619            .env("GIT_SSH_COMMAND", ssh_command_val())
3620            .args(["checkout", "-b", "feature"])
3621            .current_dir(&temp_path)
3622            .output()
3623            .unwrap();
3624
3625        std::fs::write(&file_path, "line 1\nline 2 on feature\nline 3\n").unwrap();
3626        stage_file(&temp_path, "conflict.txt").unwrap();
3627        commit_changes(&temp_path, "feature commit").unwrap();
3628
3629        // 3. Checkout main/master and edit differently
3630        std::process::Command::new("git")
3631            .env("GIT_TERMINAL_PROMPT", "0")
3632            .env("GIT_SSH_COMMAND", ssh_command_val())
3633            .args(["checkout", &main_branch])
3634            .current_dir(&temp_path)
3635            .output()
3636            .unwrap();
3637
3638        std::fs::write(&file_path, "line 1\nline 2 on main\nline 3\n").unwrap();
3639        stage_file(&temp_path, "conflict.txt").unwrap();
3640        commit_changes(&temp_path, "main commit").unwrap();
3641
3642        // 4. Merge feature into main -> conflict
3643        assert!(!is_merging(&temp_path));
3644        let merge_output = std::process::Command::new("git")
3645            .env("GIT_TERMINAL_PROMPT", "0")
3646            .env("GIT_SSH_COMMAND", ssh_command_val())
3647            .args(["merge", "feature"])
3648            .current_dir(&temp_path)
3649            .output()
3650            .unwrap();
3651
3652        assert!(!merge_output.status.success());
3653        assert!(is_merging(&temp_path));
3654
3655        // 5. Check conflict markers diff
3656        let diff = get_conflict_markers_diff(&temp_path, "conflict.txt");
3657        assert!(!diff.is_empty());
3658        let has_separator = diff.iter().any(|l| matches!(l.kind, DiffLineKind::ConflictSeparator));
3659        let has_ours = diff.iter().any(|l| matches!(l.kind, DiffLineKind::ConflictOurs));
3660        let has_theirs = diff.iter().any(|l| matches!(l.kind, DiffLineKind::ConflictTheirs));
3661        assert!(has_separator);
3662        assert!(has_ours);
3663        assert!(has_theirs);
3664
3665        // 6. Abort merge and verify
3666        abort_merge(&temp_path).unwrap();
3667        assert!(!is_merging(&temp_path));
3668
3669        // 7. Conflict again to test resolve_ours/resolve_theirs
3670        std::process::Command::new("git")
3671            .env("GIT_TERMINAL_PROMPT", "0")
3672            .env("GIT_SSH_COMMAND", ssh_command_val())
3673            .args(["merge", "feature"])
3674            .current_dir(&temp_path)
3675            .output()
3676            .unwrap();
3677        assert!(is_merging(&temp_path));
3678
3679        // Test resolve_ours
3680        resolve_ours(&temp_path, "conflict.txt").unwrap();
3681        let contents = std::fs::read_to_string(&file_path).unwrap();
3682        assert!(contents.contains("line 2 on main"));
3683        assert!(!contents.contains("<<<<<<<"));
3684
3685        // Since it's resolved, we can continue merge
3686        continue_merge(&temp_path).unwrap();
3687        assert!(!is_merging(&temp_path));
3688
3689        // 8. Test resolve_theirs by resetting main to before the merge
3690        std::process::Command::new("git")
3691            .env("GIT_TERMINAL_PROMPT", "0")
3692            .env("GIT_SSH_COMMAND", ssh_command_val())
3693            .args(["reset", "--hard", "HEAD~1"])
3694            .current_dir(&temp_path)
3695            .output()
3696            .unwrap();
3697
3698        std::process::Command::new("git")
3699            .env("GIT_TERMINAL_PROMPT", "0")
3700            .env("GIT_SSH_COMMAND", ssh_command_val())
3701            .args(["merge", "feature"])
3702            .current_dir(&temp_path)
3703            .output()
3704            .unwrap();
3705        assert!(is_merging(&temp_path));
3706
3707        resolve_theirs(&temp_path, "conflict.txt").unwrap();
3708        let contents_theirs = std::fs::read_to_string(&file_path).unwrap();
3709        assert!(contents_theirs.contains("line 2 on feature"));
3710        assert!(!contents_theirs.contains("<<<<<<<"));
3711
3712        continue_merge(&temp_path).unwrap();
3713        assert!(!is_merging(&temp_path));
3714
3715        // Clean up
3716        let _ = std::fs::remove_dir_all(&temp_path);
3717    }
3718
3719    #[test]
3720    fn test_resolve_conflict_hunk() {
3721        let mut temp_path = std::env::temp_dir();
3722        temp_path.push(format!(
3723            "twig_test_hunk_conflict_{}",
3724            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
3725        ));
3726        std::fs::create_dir_all(&temp_path).unwrap();
3727
3728        // Init repo
3729        let repo = Repository::init(&temp_path).unwrap();
3730
3731        // Configure author
3732        let mut config = repo.config().unwrap();
3733        config.set_str("user.name", "Test User").unwrap();
3734        config.set_str("user.email", "test@example.com").unwrap();
3735
3736        // 1. Initial commit on main
3737        let file_path = temp_path.join("conflict.txt");
3738        let initial_lines = "line 1\nline 2\nline 3\nline 4\nline 5\nline 6\nline 7\nline 8\nline 9\nline 10\nline 11\nline 12\n";
3739        std::fs::write(&file_path, initial_lines).unwrap();
3740        stage_file(&temp_path, "conflict.txt").unwrap();
3741        commit_changes(&temp_path, "initial commit").unwrap();
3742
3743        // Get the main branch name first
3744        let output = std::process::Command::new("git")
3745            .env("GIT_TERMINAL_PROMPT", "0")
3746            .env("GIT_SSH_COMMAND", ssh_command_val())
3747            .args(["symbolic-ref", "--short", "HEAD"])
3748            .current_dir(&temp_path)
3749            .output()
3750            .unwrap();
3751        let main_branch = String::from_utf8_lossy(&output.stdout).trim().to_string();
3752
3753        // 2. Create feature branch and edit line 2 and line 11
3754        std::process::Command::new("git")
3755            .env("GIT_TERMINAL_PROMPT", "0")
3756            .env("GIT_SSH_COMMAND", ssh_command_val())
3757            .args(["checkout", "-b", "feature"])
3758            .current_dir(&temp_path)
3759            .output()
3760            .unwrap();
3761        let feature_lines = "line 1\nline 2 on feature\nline 3\nline 4\nline 5\nline 6\nline 7\nline 8\nline 9\nline 10\nline 11 on feature\nline 12\n";
3762        std::fs::write(&file_path, feature_lines).unwrap();
3763        stage_file(&temp_path, "conflict.txt").unwrap();
3764        commit_changes(&temp_path, "feature commit").unwrap();
3765
3766        // 3. Checkout main/master and edit line 2 and line 11 differently
3767        std::process::Command::new("git")
3768            .env("GIT_TERMINAL_PROMPT", "0")
3769            .env("GIT_SSH_COMMAND", ssh_command_val())
3770            .args(["checkout", &main_branch])
3771            .current_dir(&temp_path)
3772            .output()
3773            .unwrap();
3774        let main_lines = "line 1\nline 2 on main\nline 3\nline 4\nline 5\nline 6\nline 7\nline 8\nline 9\nline 10\nline 11 on main\nline 12\n";
3775        std::fs::write(&file_path, main_lines).unwrap();
3776        stage_file(&temp_path, "conflict.txt").unwrap();
3777        commit_changes(&temp_path, "main commit").unwrap();
3778
3779        // 4. Merge feature into main -> conflict
3780        let merge_output = std::process::Command::new("git")
3781            .env("GIT_TERMINAL_PROMPT", "0")
3782            .env("GIT_SSH_COMMAND", ssh_command_val())
3783            .args(["merge", "feature"])
3784            .current_dir(&temp_path)
3785            .output()
3786            .unwrap();
3787        assert!(!merge_output.status.success());
3788        assert!(is_merging(&temp_path));
3789
3790        // 5. Resolve first hunk as Ours
3791        resolve_conflict_hunk(&temp_path, "conflict.txt", 0, true).unwrap();
3792        let contents_after_first = std::fs::read_to_string(&file_path).unwrap();
3793        // Line 2 should be resolved to main
3794        assert!(contents_after_first.contains("line 2 on main"));
3795        assert!(!contents_after_first.contains("line 2 on feature"));
3796        // Line 11 should still have conflict markers
3797        assert!(contents_after_first.contains("<<<<<<<"));
3798        assert!(contents_after_first.contains("line 11 on main"));
3799        assert!(contents_after_first.contains("line 11 on feature"));
3800
3801        // Repo should still be in a merging state because 1 conflict hunk remains
3802        assert!(is_merging(&temp_path));
3803
3804        // 6. Resolve second hunk (which is now hunk 0, since hunk 0 was resolved and removed)
3805        // Wait, did the hunk count change? Yes, the first conflict block was removed,
3806        // so the remaining conflict block at line 11 becomes the 0th hunk in the file!
3807        // Let's call resolve_conflict_hunk with hunk_idx 0!
3808        resolve_conflict_hunk(&temp_path, "conflict.txt", 0, false).unwrap();
3809        let contents_after_second = std::fs::read_to_string(&file_path).unwrap();
3810        // Both lines should be resolved, no conflict markers left
3811        assert!(contents_after_second.contains("line 2 on main"));
3812        assert!(contents_after_second.contains("line 11 on feature"));
3813        assert!(!contents_after_second.contains("<<<<<<<"));
3814
3815        // File is fully resolved so it should have been automatically staged
3816        let status = repo.statuses(None).unwrap();
3817        assert_eq!(status.len(), 1);
3818        assert!(status.get(0).unwrap().status().contains(git2::Status::INDEX_MODIFIED));
3819
3820        // Continue and finalize the merge
3821        continue_merge(&temp_path).unwrap();
3822        assert!(!is_merging(&temp_path));
3823
3824        // Clean up
3825        let _ = std::fs::remove_dir_all(&temp_path);
3826    }
3827
3828    #[test]
3829    fn test_branch_and_commit_helpers() {
3830        let mut temp_path = std::env::temp_dir();
3831        temp_path.push(format!(
3832            "twig_test_helpers_{}",
3833            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
3834        ));
3835        let _ = std::fs::remove_dir_all(&temp_path);
3836        std::fs::create_dir_all(&temp_path).unwrap();
3837
3838        // 1. Initialize repository
3839        let repo = Repository::init(&temp_path).unwrap();
3840
3841        // Configure author
3842        let mut config = repo.config().unwrap();
3843        config.set_str("user.name", "Test User").unwrap();
3844        config.set_str("user.email", "test@example.com").unwrap();
3845
3846        // 2. Create initial commit (root commit)
3847        let file_path = temp_path.join("test.txt");
3848        std::fs::write(&file_path, "root content").unwrap();
3849        stage_file(&temp_path, "test.txt").unwrap();
3850        commit_changes(&temp_path, "root commit").unwrap();
3851
3852        let head_oid = repo.head().unwrap().target().unwrap().to_string();
3853        assert!(is_root_commit(&temp_path, &head_oid));
3854
3855        // 3. Create second commit (non-root commit)
3856        std::fs::write(&file_path, "second content").unwrap();
3857        stage_file(&temp_path, "test.txt").unwrap();
3858        commit_changes(&temp_path, "second commit").unwrap();
3859
3860        let new_head_oid = repo.head().unwrap().target().unwrap().to_string();
3861        assert!(!is_root_commit(&temp_path, &new_head_oid));
3862
3863        // 4. Test push target with first remote config
3864        // Currently there are no remotes, so it should return None or fallback.
3865        // Wait, get_branch_push_target returns None if no remotes are found and no upstream config.
3866        // Let's add a remote.
3867        remote_add(&temp_path, "origin", "https://github.com/example/repo.git").unwrap();
3868        let target = get_branch_push_target(&temp_path, "master")
3869            .or_else(|| get_branch_push_target(&temp_path, "main"));
3870        assert!(target.is_some());
3871        let (remote_name, set_upstream) = target.unwrap();
3872        assert_eq!(remote_name, "origin");
3873        assert!(set_upstream);
3874
3875        // Clean up
3876        let _ = std::fs::remove_dir_all(&temp_path);
3877    }
3878}