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    Loading,
31    Missing,
32    Directory,
33    GitRepo(Option<RepoSummary>),
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
37pub enum RepoState {
38    #[default]
39    Clean,
40    Merge,
41    Revert,
42    CherryPick,
43    Bisect,
44    Rebase,
45    ApplyMailbox,
46}
47
48/// Compact summary used to draw the per-card indicator. Also embedded in
49/// `RepoInfo` so the Detail view doesn't re-collect the same data.
50#[derive(Debug, Default, Clone)]
51pub struct RepoSummary {
52    /// Current branch shorthand (e.g. `"main"`). `None` for detached HEAD
53    /// or when the ref cannot be read.
54    pub branch: Option<String>,
55    pub staged: usize,
56    pub modified: usize,
57    pub untracked: usize,
58    pub conflicted: usize,
59    pub ahead: usize,
60    pub behind: usize,
61    pub state: RepoState,
62    pub last_commit_time: Option<i64>,
63}
64
65impl RepoSummary {
66    pub fn is_clean(&self) -> bool {
67        self.staged + self.modified + self.untracked + self.conflicted == 0
68    }
69    pub fn is_synced(&self) -> bool {
70        self.ahead + self.behind == 0
71    }
72    pub fn unchanged(&self) -> bool {
73        self.is_clean() && self.is_synced()
74    }
75}
76
77// ── Detail view ────────────────────────────────────────────────────────────
78
79#[derive(Debug, Clone)]
80pub enum ItemDetail {
81    Missing { resolved: PathBuf },
82    Directory { resolved: PathBuf },
83    Repo { resolved: PathBuf, info: Box<RepoInfo> },
84    Error { resolved: PathBuf, message: String },
85}
86
87#[derive(Debug, Clone, Default)]
88pub struct BranchInfo {
89    pub name: String,
90    pub is_head: bool,
91    pub short_sha: String,
92    pub short_message: String,
93}
94
95#[derive(Debug, Clone, Default)]
96pub struct FileRevision {
97    pub commit_oid: String,
98    pub author: String,
99    pub date: String,
100    pub when: String,
101    pub summary: String,
102}
103
104#[derive(Debug, Clone, Default)]
105pub struct StashInfo {
106    pub index: usize,
107    pub message: String,
108    pub commit_id: String,
109    pub files: Vec<FileEntry>,
110}
111
112#[derive(Debug, Clone, Default)]
113pub struct CommitterStat {
114    pub name: String,
115    pub email: String,
116    pub count: usize,
117}
118
119#[derive(Debug, Clone, PartialEq, Eq, Default)]
120pub enum TabData<T> {
121    #[default]
122    NotLoaded,
123    Loading,
124    Loaded(T),
125    Error(String),
126}
127
128impl<T> TabData<T> {
129    pub fn is_not_loaded(&self) -> bool {
130        matches!(self, TabData::NotLoaded)
131    }
132    pub fn is_loading(&self) -> bool {
133        matches!(self, TabData::Loading)
134    }
135    #[allow(dead_code)]
136    pub fn is_loaded(&self) -> bool {
137        matches!(self, TabData::Loaded(_))
138    }
139    pub fn as_ref(&self) -> Option<&T> {
140        match self {
141            TabData::Loaded(val) => Some(val),
142            _ => None,
143        }
144    }
145}
146
147impl<T> TabData<Vec<T>> {
148    pub fn len(&self) -> usize {
149        self.as_ref().map(|v| v.len()).unwrap_or(0)
150    }
151    pub fn is_empty(&self) -> bool {
152        self.as_ref().map(|v| v.is_empty()).unwrap_or(true)
153    }
154    pub fn first(&self) -> Option<&T> {
155        self.as_ref().and_then(|v| v.first())
156    }
157    pub fn get(&self, index: usize) -> Option<&T> {
158        self.as_ref().and_then(|v| v.get(index))
159    }
160    pub fn iter(&self) -> std::slice::Iter<'_, T> {
161        match self {
162            TabData::Loaded(v) => v.iter(),
163            _ => [].iter(),
164        }
165    }
166    pub fn as_slice(&self) -> &[T] {
167        match self {
168            TabData::Loaded(v) => v.as_slice(),
169            _ => &[],
170        }
171    }
172}
173
174#[derive(Debug, Clone, Default, PartialEq, Eq)]
175pub struct WorktreeInfo {
176    pub name: String,
177    pub path: PathBuf,
178    pub branch: Option<String>,
179    pub is_locked: bool,
180    pub lock_reason: Option<String>,
181}
182
183#[derive(Debug, Clone, Default, PartialEq, Eq)]
184pub struct SubmoduleInfo {
185    pub name: String,
186    pub path: PathBuf,
187    pub url: String,
188    pub commit_id: Option<String>,
189    pub head_id: Option<String>,
190    pub is_initialized: bool,
191    pub is_dirty: bool,
192}
193
194#[derive(Debug, Clone)]
195pub enum TabPayload {
196    Files(Result<Vec<String>, String>),
197    Graph(Result<Vec<GraphLine>, String>),
198    Branches { local: Result<Vec<BranchInfo>, String>, remote: Result<Vec<BranchInfo>, String> },
199    Tags { local: Result<Vec<BranchInfo>, String>, remote: Result<Vec<BranchInfo>, String> },
200    Remotes(Result<Vec<RemoteInfo>, String>),
201    Stashes(Result<Vec<StashInfo>, String>),
202    Overview(Result<(Vec<CommitterStat>, bool), String>),
203    Worktrees(Result<Vec<WorktreeInfo>, String>),
204    Submodules(Result<Vec<SubmoduleInfo>, String>),
205    Reflog(Result<Vec<ReflogEntry>, String>),
206    ForgeIssues(Result<Vec<ForgeIssue>, String>),
207    ForgePRs(Result<Vec<ForgePR>, String>),
208    PRComments(Result<Vec<ForgePRComment>, String>),
209}
210
211#[derive(Debug, Default, Clone)]
212pub struct RepoInfo {
213    pub branch: Option<String>,
214    pub head: Option<HeadInfo>,
215    pub remotes: TabData<Vec<RemoteInfo>>,
216    /// Configured upstream branch (e.g. "origin/main") if HEAD tracks one.
217    pub upstream: Option<String>,
218    pub summary: RepoSummary,
219    /// File-level changes, populated by `collect_info` for the Detail view.
220    pub changes: WorktreeChanges,
221    /// Recent commits in this repository.
222    pub commits: Vec<CommitEntry>,
223    /// Graph view lines for the repository.
224    pub graph_lines: TabData<Vec<GraphLine>>,
225    /// Local branches in the repository.
226    pub local_branches: TabData<Vec<BranchInfo>>,
227    /// Remote branches in the repository.
228    pub remote_branches: TabData<Vec<BranchInfo>>,
229    /// Local tags in the repository.
230    pub local_tags: TabData<Vec<BranchInfo>>,
231    /// Remote tags in the repository.
232    pub remote_tags: TabData<Vec<BranchInfo>>,
233    /// Whether remote tags have been loaded from the remote repository.
234    pub remote_tags_loaded: bool,
235    /// Whether a remote tag fetch has been attempted in this session.
236    pub remote_tags_attempted: bool,
237    /// Tracked files in the repository.
238    pub files: TabData<Vec<String>>,
239    /// Available stashes in the repository.
240    pub stashes: TabData<Vec<StashInfo>>,
241    /// Available worktrees in the repository.
242    pub worktrees: TabData<Vec<WorktreeInfo>>,
243    /// Configured submodules in the repository.
244    pub submodules: TabData<Vec<SubmoduleInfo>>,
245    /// Available reflog entries.
246    pub reflog: TabData<Vec<ReflogEntry>>,
247    pub forge_issues: TabData<Vec<ForgeIssue>>,
248    pub forge_prs: TabData<Vec<ForgePR>>,
249    /// Committer statistics.
250    pub committer_stats: TabData<Vec<CommitterStat>>,
251    /// Whether the committer statistics walk was capped by the limit.
252    pub committer_stats_limit_reached: bool,
253    /// Timestamps when each tab was loaded (index matches tab_idx)
254    pub tab_loaded_at: [Option<std::time::Instant>; 12],
255    /// Whether each tab is currently loading in the background (index matches tab_idx)
256    pub tab_loading: [bool; 12],
257    /// Files tracked by Git LFS in the index/working copy.
258    pub lfs_files: std::collections::HashSet<String>,
259    /// Whether git-lfs is installed in the system PATH.
260    pub lfs_installed: bool,
261    /// Storage size of the local LFS directory if LFS is used.
262    pub lfs_storage_size: Option<u64>,
263}
264
265#[derive(Debug, Clone)]
266pub struct HeadInfo {
267    pub short_id: String,
268    pub summary: String,
269    pub author: String,
270    pub when: String,
271}
272
273#[derive(Debug, Clone)]
274pub struct ReflogEntry {
275    pub index: usize,
276    pub target_oid: String,
277    pub selector: String,
278    pub command: String,
279    pub message: String,
280    pub when: String,
281    pub date: String,
282}
283
284#[derive(Debug, Clone)]
285pub struct RemoteInfo {
286    pub name: String,
287    pub url: String,
288    pub push_url: Option<String>,
289    pub refspecs: Vec<String>,
290}
291
292#[derive(Debug, Clone)]
293pub struct CommitEntry {
294    /// Short 7-char display ID.
295    pub id: String,
296    /// Full 40-char hex OID — used for diff lookup.
297    pub oid: String,
298    pub author: String,
299    pub when: String,
300    pub date: String,
301    pub summary: String,
302    pub message: String,
303    /// Local branch names and tags pointing at this commit.
304    /// Tags are prefixed with `"tag:"`, remote branches with `"remote:"`.
305    pub refs: Vec<String>,
306    /// Files changed in this commit (diff against first parent, or empty tree).
307    pub files: Vec<FileEntry>,
308    /// GPG/SSH signature status.
309    pub signature_status: String,
310}
311
312#[derive(Debug, Clone)]
313pub struct GraphLine {
314    pub graph: String,
315    pub commit: Option<GraphCommit>,
316}
317
318#[derive(Debug, Clone)]
319pub struct GraphCommit {
320    pub oid: String,
321    pub decoration: String,
322    pub summary: String,
323    pub author: String,
324    pub date: String,
325    /// GPG/SSH signature status.
326    pub signature_status: String,
327}
328
329/// One changed file in the working tree or index.
330#[derive(Debug, Clone)]
331pub struct FileEntry {
332    /// Path relative to the repository root.
333    pub path: String,
334    /// Short human-readable label: "N", "M", "D", "R", "T", "?", or "C".
335    pub label: &'static str,
336}
337
338/// File-level working-tree state collected for the Detail view.
339/// Split into four buckets so the UI can render them as separate sections.
340#[derive(Debug, Default, Clone)]
341pub struct WorktreeChanges {
342    pub staged: Vec<FileEntry>,
343    pub unstaged: Vec<FileEntry>,
344    pub untracked: Vec<FileEntry>,
345    pub conflicted: Vec<FileEntry>,
346}
347
348// ── Per-file diff ──────────────────────────────────────────────────────────
349
350/// The type of a single line in a unified diff.
351#[derive(Debug, Clone, PartialEq)]
352pub enum DiffLineKind {
353    /// `@@ ... @@` hunk header.
354    Header,
355    /// `+` added line.
356    Added,
357    /// `-` removed line.
358    Removed,
359    /// Unchanged context line.
360    Context,
361    /// Line in OURS section of a conflict.
362    ConflictOurs,
363    /// Line in THEIRS section of a conflict.
364    ConflictTheirs,
365    /// Conflict marker line (<<<<<<<, =======, >>>>>>>).
366    ConflictSeparator,
367}
368
369/// One line of a unified diff, as rendered in the Diff panel.
370#[derive(Debug, Clone)]
371pub struct DiffLine {
372    pub kind: DiffLineKind,
373    /// Raw content (already includes the leading +/−/space prefix character).
374    pub content: String,
375    pub old_lineno: Option<u32>,
376    pub new_lineno: Option<u32>,
377    pub hunk_idx: Option<usize>,
378}
379
380/// Return the unified diff of `file_path` as it changed in `commit_oid`
381/// (hex string) inside the repository at `repo_path`.
382/// Returns an empty Vec on any error.
383pub fn get_commit_file_diff(repo_path: &Path, commit_oid: &str, file_path: &str) -> Vec<DiffLine> {
384    get_file_diff_inner(repo_path, commit_oid, file_path).unwrap_or_default()
385}
386
387/// Return the diff for `file_path` in the working tree.
388///
389/// - `staged = true`:  diff between HEAD and the index (what would be committed).
390/// - `staged = false`: diff between the index and the working directory (unstaged changes).
391///
392/// Returns an empty Vec on any error.
393pub fn get_worktree_file_diff(repo_path: &Path, file_path: &str, staged: bool) -> Vec<DiffLine> {
394    get_worktree_diff_inner(repo_path, file_path, staged).unwrap_or_default()
395}
396
397/// Add `file_path` to the index (equivalent to `git add <file>`).
398/// Returns a human-readable error string on failure.
399pub fn stage_file(repo_path: &Path, file_path: &str) -> Result<(), String> {
400    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
401    let mut index = repo.index().map_err(|e| e.to_string())?;
402    let full_path = repo_path.join(file_path);
403    if full_path.exists() {
404        index.add_path(Path::new(file_path)).map_err(|e| e.to_string())?;
405    } else {
406        index.remove_path(Path::new(file_path)).map_err(|e| e.to_string())?;
407    }
408    index.write().map_err(|e| e.to_string())?;
409    Ok(())
410}
411
412/// Remove `file_path` from the index (equivalent to `git restore --staged <file>`).
413/// When HEAD exists the index entry is reset to the HEAD tree value; for a brand-new
414/// repo with no commits the entry is simply removed from the index.
415/// Returns a human-readable error string on failure.
416pub fn unstage_file(repo_path: &Path, file_path: &str) -> Result<(), String> {
417    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
418    // Prefer reset_default (git reset HEAD -- <file>) when a HEAD commit exists.
419    if let Some(commit) = repo.head().ok().and_then(|h| h.peel_to_commit().ok()) {
420        repo.reset_default(Some(commit.as_object()), std::iter::once(file_path))
421            .map_err(|e| e.to_string())?;
422    } else {
423        // New repo with no commits: just remove the entry from the index.
424        let mut index = repo.index().map_err(|e| e.to_string())?;
425        index.remove_path(Path::new(file_path)).map_err(|e| e.to_string())?;
426        index.write().map_err(|e| e.to_string())?;
427    }
428    Ok(())
429}
430
431pub fn sanitize_text(s: &str) -> String {
432    let mut result = String::with_capacity(s.len());
433    let bytes = s.as_bytes();
434    let mut i = 0;
435    while i < bytes.len() {
436        if bytes[i] == 0x1B {
437            // Escape character: let's skip the sequence
438            i += 1;
439            if i < bytes.len() && bytes[i] == b'[' {
440                i += 1;
441                while i < bytes.len() {
442                    let c = bytes[i];
443                    i += 1;
444                    // ANSI escape sequences end with letters (A-Z, a-z)
445                    if c.is_ascii_alphabetic() {
446                        break;
447                    }
448                }
449            } else {
450                // Single ESC character or other VT100: skip it
451                while i < bytes.len() {
452                    let c = bytes[i];
453                    i += 1;
454                    if c == b' ' || c.is_ascii_alphabetic() {
455                        break;
456                    }
457                }
458            }
459        } else {
460            let c = bytes[i];
461            // Replace non-printable control characters except \n, \r, \t
462            if c < 0x20 && c != b'\n' && c != b'\r' && c != b'\t' {
463                result.push(' ');
464            } else {
465                result.push(c as char);
466            }
467            i += 1;
468        }
469    }
470    result
471}
472
473pub fn safe_sha_slice(sha: &str, len: usize) -> &str {
474    let mut end = len.min(sha.len());
475    while end > 0 && !sha.is_char_boundary(end) {
476        end -= 1;
477    }
478    &sha[..end]
479}
480
481fn ssh_command_val() -> &'static str {
482    if std::env::var("GITWIG_SSH_STRICT").map(|v| v == "1").unwrap_or(false) {
483        "ssh -o StrictHostKeyChecking=yes"
484    } else {
485        "ssh -o StrictHostKeyChecking=accept-new"
486    }
487}
488
489fn git_command() -> std::process::Command {
490    let mut cmd = std::process::Command::new("git");
491    cmd.env("GIT_TERMINAL_PROMPT", "0");
492    cmd.env("GIT_SSH_COMMAND", ssh_command_val());
493    cmd.env("GIT_ALLOW_PROTOCOL", "https:ssh:git:file");
494    cmd.env("GIT_PROTOCOL_FROM_USER", "0");
495    cmd
496}
497
498pub fn safe_ref(r: &str) -> Result<&str, String> {
499    let trimmed = r.trim();
500    if trimmed.starts_with('-') {
501        return Err(format!("Invalid ref name: '{}' (ref names cannot start with '-')", r));
502    }
503    if trimmed.is_empty() {
504        return Err("Ref name cannot be empty".to_string());
505    }
506    Ok(trimmed)
507}
508
509/// Stage all unstaged/untracked changes (equivalent to `git add -A`).
510pub fn stage_all_changes(repo_path: &Path) -> Result<(), String> {
511    let output = git_command()
512        .arg("add")
513        .arg("-A")
514        .current_dir(repo_path)
515        .output()
516        .map_err(|e| e.to_string())?;
517
518    if output.status.success() {
519        Ok(())
520    } else {
521        Err(String::from_utf8_lossy(&output.stderr).trim().to_string())
522    }
523}
524
525/// Unstage all staged changes (equivalent to `git reset`).
526pub fn unstage_all_changes(repo_path: &Path) -> Result<(), String> {
527    let output =
528        git_command().arg("reset").current_dir(repo_path).output().map_err(|e| e.to_string())?;
529
530    if output.status.success() {
531        Ok(())
532    } else {
533        Err(String::from_utf8_lossy(&output.stderr).trim().to_string())
534    }
535}
536
537/// Discard all staged, unstaged, and untracked changes in the repository.
538pub fn discard_all_changes(repo_path: &Path) -> Result<(), String> {
539    // 1. Unstage all first so everything is in the working tree
540    let _ = git_command().arg("reset").current_dir(repo_path).output();
541
542    // 2. Discard all tracked modifications
543    let checkout_out = git_command()
544        .arg("checkout")
545        .arg("--")
546        .arg(".")
547        .current_dir(repo_path)
548        .output()
549        .map_err(|e| e.to_string())?;
550
551    if !checkout_out.status.success() {
552        return Err(String::from_utf8_lossy(&checkout_out.stderr).trim().to_string());
553    }
554
555    // 3. Clean all untracked files/folders
556    let clean_out = git_command()
557        .arg("clean")
558        .arg("-fd")
559        .current_dir(repo_path)
560        .output()
561        .map_err(|e| e.to_string())?;
562
563    if !clean_out.status.success() {
564        return Err(String::from_utf8_lossy(&clean_out.stderr).trim().to_string());
565    }
566
567    Ok(())
568}
569
570/// Stage a single hunk of unstaged changes (equivalent to `git apply --cached -`).
571pub fn stage_hunk(repo_path: &Path, file_path: &str, hunk: &[DiffLine]) -> Result<(), String> {
572    apply_hunk_patch(repo_path, file_path, hunk, false, true)
573}
574
575/// Unstage a single hunk of staged changes (equivalent to `git apply --cached --reverse -`).
576pub fn unstage_hunk(repo_path: &Path, file_path: &str, hunk: &[DiffLine]) -> Result<(), String> {
577    apply_hunk_patch(repo_path, file_path, hunk, true, true)
578}
579
580/// Discard a single hunk of unstaged changes in the working tree (equivalent to `git apply --reverse -`).
581pub fn discard_hunk(repo_path: &Path, file_path: &str, hunk: &[DiffLine]) -> Result<(), String> {
582    apply_hunk_patch(repo_path, file_path, hunk, true, false)
583}
584
585/// Stage a single line from the Unstaged diff.
586pub fn stage_line(
587    repo_path: &Path,
588    file_path: &str,
589    hunk: &[DiffLine],
590    selected_line_idx: usize,
591) -> Result<(), String> {
592    apply_line_patch_inner(repo_path, file_path, hunk, selected_line_idx, false, false, true)
593}
594
595/// Unstage a single line from the Staged diff.
596pub fn unstage_line(
597    repo_path: &Path,
598    file_path: &str,
599    hunk: &[DiffLine],
600    selected_line_idx: usize,
601) -> Result<(), String> {
602    apply_line_patch_inner(repo_path, file_path, hunk, selected_line_idx, true, true, true)
603}
604
605/// Discard a single line from the Unstaged diff in the working tree.
606pub fn discard_line(
607    repo_path: &Path,
608    file_path: &str,
609    hunk: &[DiffLine],
610    selected_line_idx: usize,
611) -> Result<(), String> {
612    apply_line_patch_inner(repo_path, file_path, hunk, selected_line_idx, true, true, false)
613}
614
615fn parse_hunk_header(header: &str) -> Option<(usize, usize, usize, usize)> {
616    if !header.starts_with("@@") {
617        return None;
618    }
619    let parts: Vec<&str> = header.split("@@").collect();
620    if parts.len() < 3 {
621        return None;
622    }
623    let meta = parts[1].trim();
624    let subparts: Vec<&str> = meta.split_whitespace().collect();
625    if subparts.len() < 2 {
626        return None;
627    }
628
629    let parse_part = |p: &str| -> (usize, usize) {
630        let s = p.trim_start_matches(['-', '+']);
631        let comps: Vec<&str> = s.split(',').collect();
632        let start = comps[0].parse::<usize>().unwrap_or(0);
633        let count = if comps.len() > 1 { comps[1].parse::<usize>().unwrap_or(1) } else { 1 };
634        (start, count)
635    };
636
637    let (old_start, old_count) = parse_part(subparts[0]);
638    let (new_start, new_count) = parse_part(subparts[1]);
639    Some((old_start, old_count, new_start, new_count))
640}
641
642fn apply_line_patch_inner(
643    repo_path: &Path,
644    file_path: &str,
645    hunk: &[DiffLine],
646    selected_line_idx_in_hunk: usize,
647    revert: bool,
648    target_has_modification: bool,
649    cached: bool,
650) -> Result<(), String> {
651    use std::io::Write;
652    use std::process::{Command, Stdio};
653
654    let path_check = std::path::Path::new(file_path);
655    if path_check.is_absolute()
656        || path_check.components().any(|c| c == std::path::Component::ParentDir)
657    {
658        return Err("Path escapes repository root".to_string());
659    }
660
661    if hunk.is_empty() {
662        return Err("Empty hunk".to_string());
663    }
664
665    let selected_line = match hunk.get(selected_line_idx_in_hunk) {
666        Some(line) => line,
667        None => return Err("Invalid line index".to_string()),
668    };
669
670    if selected_line.kind != DiffLineKind::Added && selected_line.kind != DiffLineKind::Removed {
671        return Err("Selected line is not a modification (must be + or -)".to_string());
672    }
673
674    let header_line = &hunk[0];
675    let (old_start, _old_count, new_start, _new_count) =
676        match parse_hunk_header(&header_line.content) {
677            Some(coords) => coords,
678            None => return Err(format!("Invalid hunk header: {}", header_line.content)),
679        };
680
681    let mut patch_lines = Vec::new();
682    let mut new_old_count = 0;
683    let mut new_new_count = 0;
684
685    for (i, line) in hunk.iter().enumerate() {
686        if i == 0 {
687            continue;
688        }
689
690        if i == selected_line_idx_in_hunk {
691            if revert {
692                match line.kind {
693                    DiffLineKind::Added => {
694                        patch_lines.push(DiffLine {
695                            kind: DiffLineKind::Removed,
696                            content: line.content.clone(),
697                            old_lineno: None,
698                            new_lineno: None,
699                            hunk_idx: None,
700                        });
701                        new_old_count += 1;
702                    }
703                    DiffLineKind::Removed => {
704                        patch_lines.push(DiffLine {
705                            kind: DiffLineKind::Added,
706                            content: line.content.clone(),
707                            old_lineno: None,
708                            new_lineno: None,
709                            hunk_idx: None,
710                        });
711                        new_new_count += 1;
712                    }
713                    _ => {}
714                }
715            } else {
716                match line.kind {
717                    DiffLineKind::Added => {
718                        patch_lines.push(DiffLine {
719                            kind: DiffLineKind::Added,
720                            content: line.content.clone(),
721                            old_lineno: None,
722                            new_lineno: None,
723                            hunk_idx: None,
724                        });
725                        new_new_count += 1;
726                    }
727                    DiffLineKind::Removed => {
728                        patch_lines.push(DiffLine {
729                            kind: DiffLineKind::Removed,
730                            content: line.content.clone(),
731                            old_lineno: None,
732                            new_lineno: None,
733                            hunk_idx: None,
734                        });
735                        new_old_count += 1;
736                    }
737                    _ => {}
738                }
739            }
740        } else {
741            match line.kind {
742                DiffLineKind::Context => {
743                    patch_lines.push(line.clone());
744                    new_old_count += 1;
745                    new_new_count += 1;
746                }
747                DiffLineKind::Added => {
748                    if target_has_modification {
749                        patch_lines.push(DiffLine {
750                            kind: DiffLineKind::Context,
751                            content: line.content.clone(),
752                            old_lineno: None,
753                            new_lineno: None,
754                            hunk_idx: None,
755                        });
756                        new_old_count += 1;
757                        new_new_count += 1;
758                    } else {
759                        // Omit
760                    }
761                }
762                DiffLineKind::Removed => {
763                    if target_has_modification {
764                        // Omit
765                    } else {
766                        patch_lines.push(DiffLine {
767                            kind: DiffLineKind::Context,
768                            content: line.content.clone(),
769                            old_lineno: None,
770                            new_lineno: None,
771                            hunk_idx: None,
772                        });
773                        new_old_count += 1;
774                        new_new_count += 1;
775                    }
776                }
777                _ => {}
778            }
779        }
780    }
781
782    let mut patch = String::new();
783    patch.push_str(&format!("diff --git a/{} b/{}\n", file_path, file_path));
784    patch.push_str(&format!("--- a/{}\n", file_path));
785    patch.push_str(&format!("+++ b/{}\n", file_path));
786    patch.push_str(&format!(
787        "@@ -{},{} +{},{} @@\n",
788        old_start, new_old_count, new_start, new_new_count
789    ));
790
791    for line in patch_lines {
792        let prefix = match line.kind {
793            DiffLineKind::Added => "+",
794            DiffLineKind::Removed => "-",
795            DiffLineKind::Context => " ",
796            DiffLineKind::Header => "",
797            _ => "",
798        };
799        patch.push_str(prefix);
800        patch.push_str(&line.content);
801        patch.push('\n');
802    }
803
804    let mut args = vec!["apply"];
805    if cached {
806        args.push("--cached");
807    }
808    args.push("-");
809
810    let mut cmd = Command::new("git");
811    let mut child = cmd
812        .env("GIT_TERMINAL_PROMPT", "0")
813        .env("GIT_SSH_COMMAND", ssh_command_val())
814        .args(&args)
815        .current_dir(repo_path)
816        .stdin(Stdio::piped())
817        .stdout(Stdio::piped())
818        .stderr(Stdio::piped())
819        .spawn()
820        .map_err(|e| format!("Failed to spawn git apply: {}", e))?;
821
822    if let Some(mut stdin) = child.stdin.take() {
823        stdin
824            .write_all(patch.as_bytes())
825            .map_err(|e| format!("Failed to write patch to stdin: {}", e))?;
826    }
827
828    let output =
829        child.wait_with_output().map_err(|e| format!("Failed to wait for git apply: {}", e))?;
830
831    if !output.status.success() {
832        let err_msg = String::from_utf8_lossy(&output.stderr).to_string();
833        return Err(format!("git apply failed: {}", err_msg.trim()));
834    }
835
836    Ok(())
837}
838
839fn apply_hunk_patch(
840    repo_path: &Path,
841    file_path: &str,
842    hunk: &[DiffLine],
843    reverse: bool,
844    cached: bool,
845) -> Result<(), String> {
846    use std::io::Write;
847    use std::process::{Command, Stdio};
848
849    let path_check = std::path::Path::new(file_path);
850    if path_check.is_absolute()
851        || path_check.components().any(|c| c == std::path::Component::ParentDir)
852    {
853        return Err("Path escapes repository root".to_string());
854    }
855
856    let mut patch = String::new();
857    patch.push_str(&format!("diff --git a/{} b/{}\n", file_path, file_path));
858    patch.push_str(&format!("--- a/{}\n", file_path));
859    patch.push_str(&format!("+++ b/{}\n", file_path));
860    for line in hunk {
861        let prefix = match line.kind {
862            DiffLineKind::Added => "+",
863            DiffLineKind::Removed => "-",
864            DiffLineKind::Context => " ",
865            DiffLineKind::Header => "",
866            _ => "",
867        };
868        patch.push_str(prefix);
869        patch.push_str(&line.content);
870        patch.push('\n');
871    }
872
873    let mut args = vec!["apply"];
874    if cached {
875        args.push("--cached");
876    }
877    if reverse {
878        args.push("--reverse");
879    }
880    args.push("-");
881
882    let mut cmd = Command::new("git");
883    let mut child = cmd
884        .env("GIT_TERMINAL_PROMPT", "0")
885        .env("GIT_SSH_COMMAND", ssh_command_val())
886        .args(&args)
887        .current_dir(repo_path)
888        .stdin(Stdio::piped())
889        .stdout(Stdio::piped())
890        .stderr(Stdio::piped())
891        .spawn()
892        .map_err(|e| format!("Failed to spawn git apply: {}", e))?;
893
894    if let Some(mut stdin) = child.stdin.take() {
895        stdin
896            .write_all(patch.as_bytes())
897            .map_err(|e| format!("Failed to write patch to stdin: {}", e))?;
898    }
899
900    let output =
901        child.wait_with_output().map_err(|e| format!("Failed to wait for git apply: {}", e))?;
902
903    if !output.status.success() {
904        let err_msg = String::from_utf8_lossy(&output.stderr).to_string();
905        return Err(format!("git apply failed: {}", err_msg.trim()));
906    }
907
908    Ok(())
909}
910
911/// Discards uncommitted changes in `file_path`.
912/// - If the file is untracked, it is deleted from the filesystem.
913/// - If the file is tracked and modified/deleted, it is restored from the index.
914/// - If the file is staged, it is first unstaged (reset to HEAD) and then restored from index.
915pub fn discard_file_changes(repo_path: &Path, file_path: &str, staged: bool) -> Result<(), String> {
916    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
917
918    if staged {
919        // First unstage it (reset to HEAD)
920        unstage_file(repo_path, file_path)?;
921    }
922
923    // Now check if the file is untracked
924    let is_untracked = if let Ok(status) = repo.status_file(Path::new(file_path)) {
925        status.contains(git2::Status::WT_NEW)
926    } else {
927        false
928    };
929
930    if is_untracked {
931        let full_path = repo_path.join(file_path);
932        if full_path.exists() {
933            if full_path.is_file() {
934                std::fs::remove_file(&full_path).map_err(|e| e.to_string())?;
935            } else if full_path.is_dir() {
936                std::fs::remove_dir_all(&full_path).map_err(|e| e.to_string())?;
937            }
938        }
939    } else {
940        // Tracked file: checkout from index to working tree
941        let mut checkout_opts = git2::build::CheckoutBuilder::new();
942        checkout_opts.path(Path::new(file_path));
943        checkout_opts.force();
944        repo.checkout_index(None, Some(&mut checkout_opts)).map_err(|e| e.to_string())?;
945    }
946
947    Ok(())
948}
949
950/// Create a commit in the repository with the given message.
951/// Returns a human-readable error string on failure.
952pub fn commit_changes(repo_path: &Path, message: &str) -> Result<(), String> {
953    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
954    let mut index = repo.index().map_err(|e| e.to_string())?;
955    let tree_id = index.write_tree().map_err(|e| e.to_string())?;
956    let tree = repo.find_tree(tree_id).map_err(|e| e.to_string())?;
957
958    let signature = repo
959        .signature()
960        .map_err(|e| format!("Failed to get signature. Check user.name/email config: {}", e))?;
961
962    // Find parent commits
963    let mut parents = Vec::new();
964    let mut has_head = false;
965    if let Ok(head) = repo.head() {
966        if let Ok(parent_commit) = head.peel_to_commit() {
967            has_head = true;
968            // Check if there are changes staged compared to HEAD
969            let parent_tree = parent_commit.tree().map_err(|e| e.to_string())?;
970            if parent_tree.id() == tree_id {
971                return Err("No staged changes to commit".to_string());
972            }
973            parents.push(parent_commit);
974        }
975    }
976
977    if !has_head && index.is_empty() {
978        return Err("No staged changes to commit (index is empty)".to_string());
979    }
980
981    let parent_refs: Vec<&git2::Commit> = parents.iter().collect();
982
983    repo.commit(Some("HEAD"), &signature, &signature, message, &tree, &parent_refs)
984        .map_err(|e| e.to_string())?;
985
986    Ok(())
987}
988
989// ── Public entry points ────────────────────────────────────────────────────
990
991/// Expand a leading `~` or `~/` in a user-supplied path to the user's home
992/// directory. Returns the input unchanged if there is no home dir or no
993/// tilde to expand.
994pub fn expand_tilde(s: &str) -> PathBuf {
995    if s == "~" {
996        return dirs::home_dir().unwrap_or_else(|| PathBuf::from(s));
997    }
998    if let Some(stripped) = s.strip_prefix("~/")
999        && let Some(home) = dirs::home_dir()
1000    {
1001        return home.join(stripped);
1002    }
1003    PathBuf::from(s)
1004}
1005
1006/// Add a new git remote.
1007pub fn remote_add(repo_path: &std::path::Path, name: &str, url: &str) -> Result<(), git2::Error> {
1008    let repo = Repository::open(repo_path)?;
1009    repo.remote(name, url)?;
1010    Ok(())
1011}
1012
1013/// Delete an existing git remote.
1014pub fn remote_delete(repo_path: &std::path::Path, name: &str) -> Result<(), git2::Error> {
1015    let repo = Repository::open(repo_path)?;
1016    repo.remote_delete(name)?;
1017    Ok(())
1018}
1019
1020/// Classify `item` and produce a card-level summary. Used by the list view.
1021pub fn inspect_summary(item: &str) -> ItemStatus {
1022    let path = expand_tilde(item);
1023    if !path.is_dir() {
1024        return ItemStatus::Missing;
1025    }
1026    if !path.join(".git").exists() {
1027        return ItemStatus::Directory;
1028    }
1029    match Repository::open(&path) {
1030        Ok(repo) => ItemStatus::GitRepo(Some(collect_summary(&repo))),
1031        Err(_) => ItemStatus::GitRepo(None),
1032    }
1033}
1034
1035/// Inspect `item` and produce the rich detail report shown on Enter.
1036pub fn inspect_detail(
1037    item: &str,
1038    commit_limit: usize,
1039    graph_max_commits: usize,
1040    enable_commit_signatures: bool,
1041) -> ItemDetail {
1042    let resolved = expand_tilde(item);
1043    if !resolved.is_dir() {
1044        return ItemDetail::Missing { resolved };
1045    }
1046    if !resolved.join(".git").exists() {
1047        return ItemDetail::Directory { resolved };
1048    }
1049    match collect_info(&resolved, commit_limit, graph_max_commits, enable_commit_signatures) {
1050        Ok(info) => ItemDetail::Repo { resolved, info: Box::new(info) },
1051        Err(e) => ItemDetail::Error { resolved, message: e.to_string() },
1052    }
1053}
1054
1055fn collect_signatures(repo_path: &Path, limit: usize) -> std::collections::HashMap<String, String> {
1056    let mut sigs = std::collections::HashMap::new();
1057    let mut cmd = std::process::Command::new("git");
1058    cmd.env("GIT_TERMINAL_PROMPT", "0")
1059        .env("GIT_SSH_COMMAND", ssh_command_val())
1060        .arg("log")
1061        .arg("--all");
1062
1063    if limit > 0 {
1064        cmd.arg(format!("-n{}", limit));
1065    }
1066
1067    cmd.arg("--pretty=format:%H %G?").current_dir(repo_path);
1068
1069    if let Ok(out) = cmd.output() {
1070        if out.status.success() {
1071            let stdout_str = String::from_utf8_lossy(&out.stdout);
1072            for line in stdout_str.lines() {
1073                let parts: Vec<&str> = line.split_whitespace().collect();
1074                if parts.len() == 2 {
1075                    sigs.insert(parts[0].to_string(), parts[1].to_string());
1076                } else if parts.len() == 1 {
1077                    sigs.insert(parts[0].to_string(), "N".to_string());
1078                }
1079            }
1080        }
1081    }
1082    sigs
1083}
1084
1085#[derive(serde::Serialize, serde::Deserialize, Clone)]
1086struct CachedCommit {
1087    id: String,
1088    author: String,
1089    date: String,
1090    summary: String,
1091    message: String,
1092    time: i64,
1093}
1094
1095fn hash_path(path: &Path) -> String {
1096    use std::collections::hash_map::DefaultHasher;
1097    use std::hash::{Hash, Hasher};
1098    let mut hasher = DefaultHasher::new();
1099    path.hash(&mut hasher);
1100    format!("{:x}", hasher.finish())
1101}
1102
1103fn collect_commits(
1104    repo: &Repository,
1105    limit: usize,
1106    repo_path: &Path,
1107    enable_commit_signatures: bool,
1108) -> Result<Vec<CommitEntry>, git2::Error> {
1109    let mut walk = repo.revwalk()?;
1110    if walk.push_head().is_err() {
1111        return Ok(Vec::new());
1112    }
1113    walk.set_sorting(git2::Sort::TOPOLOGICAL | git2::Sort::TIME)?;
1114
1115    let mut commits = Vec::new();
1116    let oids: Vec<Result<git2::Oid, git2::Error>> =
1117        if limit > 0 { walk.take(limit).collect() } else { walk.collect() };
1118
1119    let sig_map = if enable_commit_signatures {
1120        collect_signatures(repo_path, limit)
1121    } else {
1122        std::collections::HashMap::new()
1123    };
1124    let ref_map = get_cached_ref_map(repo, repo_path);
1125
1126    // Load commit cache
1127    let cache_dir = dirs::home_dir().map(|h| h.join(".gitwig/commit_cache"));
1128    if let Some(ref dir) = cache_dir {
1129        let _ = std::fs::create_dir_all(dir);
1130    }
1131    let hash = hash_path(repo_path);
1132    let cache_file = cache_dir.as_ref().map(|d| d.join(format!("{}.json", hash)));
1133    let mut cache: std::collections::HashMap<String, CachedCommit> = cache_file
1134        .as_ref()
1135        .and_then(|f| std::fs::read_to_string(f).ok())
1136        .and_then(|s| serde_json::from_str(&s).ok())
1137        .unwrap_or_default();
1138
1139    let mut cache_updated = false;
1140
1141    for id in oids {
1142        let oid = id?;
1143        let oid_str = oid.to_string();
1144        let sig_status = sig_map.get(&oid_str).cloned().unwrap_or_else(|| "N".to_string());
1145        let refs = ref_map.get(&oid).cloned().unwrap_or_default();
1146        let files = Vec::new();
1147
1148        if let Some(cached) = cache.get(&oid_str) {
1149            let when = format_relative_time(cached.time);
1150            commits.push(CommitEntry {
1151                id: cached.id.clone(),
1152                oid: oid_str,
1153                author: sanitize_text(&cached.author),
1154                when,
1155                date: cached.date.clone(),
1156                summary: sanitize_text(&cached.summary),
1157                message: sanitize_text(&cached.message),
1158                refs,
1159                files,
1160                signature_status: sig_status,
1161            });
1162        } else if let Ok(commit) = repo.find_commit(oid) {
1163            let short_id = format!("{:.7}", commit.id());
1164            let summary =
1165                sanitize_text(commit.summary().ok().flatten().unwrap_or("(no commit message)"));
1166            let author = commit.author();
1167            let author_name = author.name().unwrap_or("?");
1168            let author_email = author.email().unwrap_or("?");
1169            let author_str = sanitize_text(&format!("{} <{}>", author_name, author_email));
1170            let time_secs = commit.time().seconds();
1171            let when = format_relative_time(time_secs);
1172            let date = format_utc_date(time_secs);
1173            let message = sanitize_text(commit.message().unwrap_or("(no commit message)"));
1174
1175            let cached = CachedCommit {
1176                id: short_id.clone(),
1177                author: author_str.clone(),
1178                date: date.clone(),
1179                summary: summary.clone(),
1180                message: message.clone(),
1181                time: time_secs,
1182            };
1183            cache.insert(oid_str.clone(), cached);
1184            cache_updated = true;
1185
1186            commits.push(CommitEntry {
1187                id: short_id,
1188                oid: oid_str,
1189                author: author_str,
1190                when,
1191                date,
1192                summary,
1193                message,
1194                refs,
1195                files,
1196                signature_status: sig_status,
1197            });
1198        }
1199    }
1200
1201    if cache_updated {
1202        if let Some(ref f) = cache_file {
1203            if let Ok(json) = serde_json::to_string(&cache) {
1204                let _ = std::fs::write(f, json);
1205            }
1206        }
1207    }
1208
1209    Ok(commits)
1210}
1211
1212pub fn get_file_history(repo_path: &Path, file_path: &str) -> Result<Vec<FileRevision>, String> {
1213    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
1214    let mut walk = repo.revwalk().map_err(|e| e.to_string())?;
1215    if walk.push_head().is_err() {
1216        return Ok(Vec::new());
1217    }
1218    walk.set_sorting(git2::Sort::TOPOLOGICAL | git2::Sort::TIME).map_err(|e| e.to_string())?;
1219
1220    let mut revisions = Vec::new();
1221
1222    for oid_res in walk {
1223        let oid = oid_res.map_err(|e| e.to_string())?;
1224        let commit = repo.find_commit(oid).map_err(|e| e.to_string())?;
1225
1226        let commit_tree = commit.tree().map_err(|e| e.to_string())?;
1227        let mut modified = false;
1228
1229        if commit.parent_count() > 0 {
1230            for i in 0..commit.parent_count() {
1231                if let Ok(parent) = commit.parent(i) {
1232                    if let Ok(parent_tree) = parent.tree() {
1233                        let mut diff_opts = git2::DiffOptions::new();
1234                        diff_opts.pathspec(file_path);
1235                        if let Ok(diff) = repo.diff_tree_to_tree(
1236                            Some(&parent_tree),
1237                            Some(&commit_tree),
1238                            Some(&mut diff_opts),
1239                        ) {
1240                            if diff.deltas().len() > 0 {
1241                                modified = true;
1242                                break;
1243                            }
1244                        }
1245                    }
1246                }
1247            }
1248        } else {
1249            let mut diff_opts = git2::DiffOptions::new();
1250            diff_opts.pathspec(file_path);
1251            if let Ok(diff) = repo.diff_tree_to_tree(None, Some(&commit_tree), Some(&mut diff_opts))
1252            {
1253                if diff.deltas().len() > 0 {
1254                    modified = true;
1255                }
1256            }
1257        }
1258
1259        if modified {
1260            let author = commit.author();
1261            let author_name = author.name().unwrap_or("?");
1262            let author_email = author.email().unwrap_or("?");
1263            let author_str = sanitize_text(&format!("{} <{}>", author_name, author_email));
1264            let time_secs = commit.time().seconds();
1265            let when = format_relative_time(time_secs);
1266            let date = format_utc_date(time_secs);
1267            let summary =
1268                sanitize_text(commit.summary().ok().flatten().unwrap_or("(no commit message)"));
1269
1270            revisions.push(FileRevision {
1271                commit_oid: oid.to_string(),
1272                author: author_str,
1273                date,
1274                when,
1275                summary,
1276            });
1277        }
1278    }
1279
1280    Ok(revisions)
1281}
1282
1283#[derive(Debug, Clone)]
1284pub struct BlameEntry {
1285    pub line_no: usize,
1286    pub commit_id: String,
1287    pub author: String,
1288    pub date: String,
1289}
1290
1291pub fn get_file_blame(repo_path: &Path, file_path: &str) -> Result<Vec<BlameEntry>, String> {
1292    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
1293    let mut opts = git2::BlameOptions::new();
1294    let blame = repo
1295        .blame_file(std::path::Path::new(file_path), Some(&mut opts))
1296        .map_err(|e| e.to_string())?;
1297
1298    let mut entries = Vec::new();
1299    for i in 0..blame.len() {
1300        if let Some(hunk) = blame.get_index(i) {
1301            let commit_id = hunk.final_commit_id().to_string();
1302            let short_id = if commit_id.len() >= 7 { &commit_id[..7] } else { &commit_id };
1303
1304            let mut author_name = "Unknown".to_string();
1305            let mut date_str = "unknown".to_string();
1306            if let Ok(commit) = repo.find_commit(hunk.final_commit_id()) {
1307                author_name = commit.author().name().unwrap_or("Unknown").to_string();
1308                date_str = format_utc_date(commit.time().seconds());
1309            }
1310
1311            let start = hunk.final_start_line();
1312            let count = hunk.lines_in_hunk();
1313            for line_idx in 0..count {
1314                entries.push(BlameEntry {
1315                    line_no: start + line_idx,
1316                    commit_id: short_id.to_string(),
1317                    author: author_name.clone(),
1318                    date: date_str.clone(),
1319                });
1320            }
1321        }
1322    }
1323
1324    entries.sort_by_key(|e| e.line_no);
1325    Ok(entries)
1326}
1327
1328fn collect_committer_stats(
1329    repo: &Repository,
1330    limit: usize,
1331) -> Result<(Vec<CommitterStat>, bool), git2::Error> {
1332    let mut walk = repo.revwalk()?;
1333    if walk.push_head().is_err() {
1334        return Ok((Vec::new(), false));
1335    }
1336    let mut counts = std::collections::HashMap::new();
1337    let mut count = 0;
1338    let mut limit_reached = false;
1339    for id in walk {
1340        let oid = id?;
1341        if let Ok(commit) = repo.find_commit(oid) {
1342            let author = commit.author();
1343            let name = author.name().unwrap_or("?").to_string();
1344            let email = author.email().unwrap_or("?").to_string();
1345            let key = (name, email);
1346            *counts.entry(key).or_insert(0) += 1;
1347            count += 1;
1348            if count >= limit {
1349                limit_reached = true;
1350                break;
1351            }
1352        }
1353    }
1354
1355    let mut stats: Vec<CommitterStat> = counts
1356        .into_iter()
1357        .map(|((name, email), count)| CommitterStat { name, email, count })
1358        .collect();
1359
1360    stats.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.name.cmp(&b.name)));
1361
1362    Ok((stats, limit_reached))
1363}
1364
1365/// Diff `commit` against its first parent (or against an empty tree for the
1366/// initial commit) and return the list of changed files. Capped at
1367/// `MAX_FILES_PER_SECTION` entries.
1368fn commit_changed_files(repo: &Repository, commit: &git2::Commit) -> Vec<FileEntry> {
1369    let commit_tree = match commit.tree() {
1370        Ok(t) => t,
1371        Err(_) => return Vec::new(),
1372    };
1373    // For the initial commit parent_tree is None — libgit2 treats that as an
1374    // empty tree, so all files appear as "added".
1375    let parent_tree = commit.parent(0).ok().and_then(|p| p.tree().ok());
1376
1377    let diff = match repo.diff_tree_to_tree(parent_tree.as_ref(), Some(&commit_tree), None) {
1378        Ok(d) => d,
1379        Err(_) => return Vec::new(),
1380    };
1381
1382    let mut files = Vec::new();
1383    for delta in diff.deltas() {
1384        if files.len() >= MAX_FILES_PER_SECTION {
1385            break;
1386        }
1387        let path = delta
1388            .new_file()
1389            .path()
1390            .or_else(|| delta.old_file().path())
1391            .map(|p| p.to_string_lossy().into_owned())
1392            .unwrap_or_else(|| "(unknown)".to_string());
1393
1394        let label: &'static str = match delta.status() {
1395            git2::Delta::Added => "N",
1396            git2::Delta::Deleted => "D",
1397            git2::Delta::Modified => "M",
1398            git2::Delta::Renamed => "R",
1399            git2::Delta::Typechange => "T",
1400            _ => "M",
1401        };
1402        files.push(FileEntry { path, label });
1403    }
1404    files
1405}
1406
1407pub fn get_commit_files(repo_path: &Path, oid: &str) -> Result<Vec<FileEntry>, String> {
1408    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
1409    let oid = git2::Oid::from_str(oid).map_err(|e| e.to_string())?;
1410    let commit = repo.find_commit(oid).map_err(|e| e.to_string())?;
1411    Ok(commit_changed_files(&repo, &commit))
1412}
1413fn match_pattern(path: &str, pattern: &str) -> bool {
1414    if let Some(suffix) = pattern.strip_prefix('*') {
1415        return path.ends_with(suffix);
1416    }
1417    if let Some(prefix) = pattern.strip_suffix('*') {
1418        return path.starts_with(prefix);
1419    }
1420    if pattern.contains('*') {
1421        let parts: Vec<&str> = pattern.split('*').collect();
1422        if parts.len() == 2 {
1423            return path.starts_with(parts[0]) && path.ends_with(parts[1]);
1424        }
1425    }
1426    path == pattern || path.ends_with(&format!("/{}", pattern))
1427}
1428
1429static LFS_INSTALLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1430
1431fn is_lfs_installed() -> bool {
1432    *LFS_INSTALLED.get_or_init(|| {
1433        if let Ok(output) = std::process::Command::new("git").arg("lfs").arg("--version").output() {
1434            output.status.success()
1435        } else {
1436            false
1437        }
1438    })
1439}
1440
1441fn get_lfs_info(repo_path: &Path) -> (bool, std::collections::HashSet<String>) {
1442    let mut tracked = std::collections::HashSet::new();
1443
1444    // Skip LFS subprocesses entirely if the repo is not using LFS
1445    let lfs_dir = repo_path.join(".git").join("lfs");
1446    let gitattributes_path = repo_path.join(".gitattributes");
1447    let has_lfs_attributes = if gitattributes_path.exists() {
1448        if let Ok(content) = std::fs::read_to_string(&gitattributes_path) {
1449            content.contains("filter=lfs")
1450                || content.contains("diff=lfs")
1451                || content.contains("merge=lfs")
1452        } else {
1453            false
1454        }
1455    } else {
1456        false
1457    };
1458
1459    if !lfs_dir.exists() && !has_lfs_attributes {
1460        return (false, tracked);
1461    }
1462
1463    let installed = is_lfs_installed();
1464    if installed {
1465        if let Ok(output) = std::process::Command::new("git")
1466            .arg("lfs")
1467            .arg("ls-files")
1468            .arg("-n")
1469            .current_dir(repo_path)
1470            .output()
1471        {
1472            if output.status.success() {
1473                if let Ok(stdout) = String::from_utf8(output.stdout) {
1474                    for line in stdout.lines() {
1475                        let trimmed = line.trim();
1476                        if !trimmed.is_empty() {
1477                            tracked.insert(trimmed.to_string());
1478                        }
1479                    }
1480                }
1481            }
1482        }
1483    }
1484
1485    let gitattributes_path = repo_path.join(".gitattributes");
1486    if gitattributes_path.exists() {
1487        if let Ok(content) = std::fs::read_to_string(&gitattributes_path) {
1488            let mut patterns = Vec::new();
1489            for line in content.lines() {
1490                let line = line.trim();
1491                if line.is_empty() || line.starts_with('#') {
1492                    continue;
1493                }
1494                if line.contains("filter=lfs")
1495                    || line.contains("diff=lfs")
1496                    || line.contains("merge=lfs")
1497                {
1498                    if let Some(pattern) = line.split_whitespace().next() {
1499                        patterns.push(pattern.to_string());
1500                    }
1501                }
1502            }
1503
1504            if !patterns.is_empty() {
1505                if let Ok(repo) = Repository::open(repo_path) {
1506                    if let Ok(index) = repo.index() {
1507                        for entry in index.iter() {
1508                            if let Ok(path_str) = std::str::from_utf8(&entry.path) {
1509                                for pat in &patterns {
1510                                    if match_pattern(path_str, pat) {
1511                                        tracked.insert(path_str.to_string());
1512                                        break;
1513                                    }
1514                                }
1515                            }
1516                        }
1517                    }
1518                }
1519            }
1520        }
1521    }
1522
1523    (installed, tracked)
1524}
1525
1526fn get_lfs_storage_size(repo_path: &Path) -> Option<u64> {
1527    let lfs_path = repo_path.join(".git").join("lfs");
1528    if !lfs_path.exists() {
1529        return None;
1530    }
1531
1532    fn calculate_dir_size(dir: &Path) -> u64 {
1533        let mut size = 0;
1534        if let Ok(entries) = std::fs::read_dir(dir) {
1535            for entry in entries.flatten() {
1536                if let Ok(metadata) = entry.metadata() {
1537                    if metadata.is_dir() {
1538                        size += calculate_dir_size(&entry.path());
1539                    } else {
1540                        size += metadata.len();
1541                    }
1542                }
1543            }
1544        }
1545        size
1546    }
1547
1548    Some(calculate_dir_size(&lfs_path))
1549}
1550
1551// ── Internal collection ────────────────────────────────────────────────────
1552
1553fn collect_info(
1554    path: &Path,
1555    commit_limit: usize,
1556    _graph_max_commits: usize,
1557    enable_commit_signatures: bool,
1558) -> Result<RepoInfo, git2::Error> {
1559    let repo = Repository::open(path)?;
1560    let mut summary = RepoSummary::default();
1561    if let Ok(head) = repo.head() {
1562        summary.branch = head.shorthand().ok().map(String::from);
1563    }
1564    populate_ahead_behind(&repo, &mut summary);
1565
1566    let mut info = RepoInfo { summary, ..RepoInfo::default() };
1567    let (lfs_inst, lfs_f) = get_lfs_info(path);
1568    info.lfs_installed = lfs_inst;
1569    info.lfs_files = lfs_f;
1570    info.lfs_storage_size = get_lfs_storage_size(path);
1571
1572    if let Ok(head) = repo.head() {
1573        info.branch = head.shorthand().ok().map(String::from);
1574
1575        if let Ok(commit) = head.peel_to_commit() {
1576            let short_id = format!("{:.7}", commit.id());
1577            let summary_text =
1578                sanitize_text(commit.summary().ok().flatten().unwrap_or("(no commit message)"));
1579            let author = commit.author();
1580            let author_str = sanitize_text(&format!(
1581                "{} <{}>",
1582                author.name().unwrap_or("?"),
1583                author.email().unwrap_or("?")
1584            ));
1585            let when = format_relative_time(commit.time().seconds());
1586            info.head =
1587                Some(HeadInfo { short_id, summary: summary_text, author: author_str, when });
1588        }
1589
1590        if let Ok(head_name) = head.name() {
1591            info.upstream = upstream_short_name(&repo, head_name);
1592        }
1593    }
1594
1595    if let Ok(commits) = collect_commits(&repo, commit_limit, path, enable_commit_signatures) {
1596        info.commits = commits;
1597    }
1598
1599    populate_summary_and_file_changes(&repo, &mut info);
1600
1601    if let Ok(remotes) = load_tab_remotes(path) {
1602        info.remotes = TabData::Loaded(remotes);
1603        info.tab_loaded_at[5] = Some(std::time::Instant::now());
1604    }
1605
1606    Ok(info)
1607}
1608
1609pub fn load_tab_reflog(repo_path: &Path) -> Result<Vec<ReflogEntry>, String> {
1610    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
1611    let reflog = repo.reflog("HEAD").map_err(|e| e.to_string())?;
1612    let mut entries = Vec::new();
1613    for (i, entry) in reflog.iter().enumerate() {
1614        let target_oid = format!("{}", entry.id_new());
1615        let selector = format!("HEAD@{{{}}}", i);
1616        let msg = entry.message().ok().flatten().unwrap_or("").to_string();
1617
1618        let (command, message) = if let Some(pos) = msg.find(':') {
1619            (msg[..pos].trim().to_string(), msg[pos + 1..].trim().to_string())
1620        } else {
1621            (String::new(), msg)
1622        };
1623
1624        let sig = entry.committer();
1625        let when_secs = sig.when().seconds();
1626        let when = format_relative_time(when_secs);
1627        let date = format_utc_date(when_secs);
1628
1629        entries.push(ReflogEntry { index: i, target_oid, selector, command, message, when, date });
1630    }
1631    Ok(entries)
1632}
1633
1634pub fn checkout_commit(repo_path: &Path, commit_oid: &str) -> Result<(), git2::Error> {
1635    let output = std::process::Command::new("git")
1636        .env("GIT_TERMINAL_PROMPT", "0")
1637        .env("GIT_SSH_COMMAND", ssh_command_val())
1638        .arg("checkout")
1639        .arg(commit_oid)
1640        .current_dir(repo_path)
1641        .output()
1642        .map_err(|e| git2::Error::from_str(&e.to_string()))?;
1643
1644    if !output.status.success() {
1645        let err = String::from_utf8_lossy(&output.stderr).trim().to_string();
1646        return Err(git2::Error::from_str(&err));
1647    }
1648    Ok(())
1649}
1650
1651pub fn load_tab_files(repo_path: &Path) -> Result<Vec<String>, String> {
1652    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
1653    let mut files = Vec::new();
1654    if let Ok(index) = repo.index() {
1655        for entry in index.iter() {
1656            if let Ok(path_str) = std::str::from_utf8(&entry.path) {
1657                files.push(path_str.to_string());
1658            }
1659        }
1660    }
1661    Ok(files)
1662}
1663
1664pub fn load_tab_graph_stream(
1665    repo_path: &Path,
1666    graph_max_commits: usize,
1667    repo_resolved_path: String,
1668    tab_idx: usize,
1669    tx: std::sync::mpsc::Sender<(String, usize, TabPayload)>,
1670) -> Result<Vec<GraphLine>, String> {
1671    let mut graph_lines = Vec::new();
1672    let format_str = "%H__TWIG_SEP__%d__TWIG_SEP__%s__TWIG_SEP__%an__TWIG_SEP__%ad__TWIG_SEP__%G?";
1673
1674    let mut args = vec![
1675        "log".to_string(),
1676        "--graph".to_string(),
1677        "--all".to_string(),
1678        "--date=relative".to_string(),
1679    ];
1680    if graph_max_commits > 0 {
1681        args.push(format!("--max-count={}", graph_max_commits));
1682    }
1683    args.push(format!("--pretty=format:{}", format_str));
1684    args.push("--color=never".to_string());
1685
1686    let mut child = std::process::Command::new("git")
1687        .env("GIT_TERMINAL_PROMPT", "0")
1688        .env("GIT_SSH_COMMAND", ssh_command_val())
1689        .args(&args)
1690        .current_dir(repo_path)
1691        .stdout(std::process::Stdio::piped())
1692        .spawn()
1693        .map_err(|e| e.to_string())?;
1694
1695    let stdout = child.stdout.take().ok_or_else(|| "Failed to open stdout".to_string())?;
1696    let reader = std::io::BufReader::new(stdout);
1697    use std::io::BufRead;
1698
1699    for (idx, line_res) in reader.lines().enumerate() {
1700        let line = line_res.map_err(|e| e.to_string())?;
1701        let parsed = parse_graph_line(&line);
1702        graph_lines.push(parsed);
1703
1704        // Every 200 lines, send a cloned batch to UI
1705        if (idx + 1) % 200 == 0 {
1706            let _ = tx.send((
1707                repo_resolved_path.clone(),
1708                tab_idx,
1709                TabPayload::Graph(Ok(graph_lines.clone())),
1710            ));
1711        }
1712    }
1713
1714    // Wait for the child process to exit
1715    let status = child.wait().map_err(|e| e.to_string())?;
1716    if !status.success() && graph_lines.is_empty() {
1717        return Err("git log failed".to_string());
1718    }
1719
1720    Ok(graph_lines)
1721}
1722
1723pub fn load_tab_branches(
1724    repo_path: &Path,
1725) -> (Result<Vec<BranchInfo>, String>, Result<Vec<BranchInfo>, String>) {
1726    let repo = match Repository::open(repo_path) {
1727        Ok(r) => r,
1728        Err(e) => return (Err(e.to_string()), Err(e.to_string())),
1729    };
1730
1731    let mut local_branches = Vec::new();
1732    if let Ok(branches) = repo.branches(Some(git2::BranchType::Local)) {
1733        for (branch, _) in branches.flatten() {
1734            if let Ok(Some(name)) = branch.name() {
1735                let is_head = branch.is_head();
1736                let mut short_sha = String::new();
1737                let mut short_message = String::new();
1738                if let Ok(target) = branch.get().peel_to_commit() {
1739                    let id = target.id();
1740                    let id_str = id.to_string();
1741                    short_sha = safe_sha_slice(&id_str, 7).to_string();
1742                    if let Ok(Some(summary)) = target.summary() {
1743                        short_message = summary.to_string();
1744                    }
1745                }
1746                local_branches.push(BranchInfo {
1747                    name: sanitize_text(name),
1748                    is_head,
1749                    short_sha,
1750                    short_message: sanitize_text(&short_message),
1751                });
1752            }
1753        }
1754    }
1755    local_branches.sort_by(|a, b| b.is_head.cmp(&a.is_head).then_with(|| a.name.cmp(&b.name)));
1756
1757    let mut remote_branches = Vec::new();
1758    if let Ok(branches) = repo.branches(Some(git2::BranchType::Remote)) {
1759        for (branch, _) in branches.flatten() {
1760            if let Ok(Some(name)) = branch.name() {
1761                if !name.ends_with("/HEAD") {
1762                    let is_head = branch.is_head();
1763                    let mut short_sha = String::new();
1764                    let mut short_message = String::new();
1765                    if let Ok(target) = branch.get().peel_to_commit() {
1766                        let id = target.id();
1767                        let id_str = id.to_string();
1768                        short_sha = safe_sha_slice(&id_str, 7).to_string();
1769                        if let Ok(Some(summary)) = target.summary() {
1770                            short_message = summary.to_string();
1771                        }
1772                    }
1773                    remote_branches.push(BranchInfo {
1774                        name: sanitize_text(name),
1775                        is_head,
1776                        short_sha,
1777                        short_message: sanitize_text(&short_message),
1778                    });
1779                }
1780            }
1781        }
1782    }
1783    remote_branches.sort_by(|a, b| a.name.cmp(&b.name));
1784
1785    (Ok(local_branches), Ok(remote_branches))
1786}
1787
1788pub fn load_tab_tags(
1789    repo_path: &Path,
1790) -> (Result<Vec<BranchInfo>, String>, Result<Vec<BranchInfo>, String>) {
1791    let repo = match Repository::open(repo_path) {
1792        Ok(r) => r,
1793        Err(e) => return (Err(e.to_string()), Err(e.to_string())),
1794    };
1795
1796    let mut local_tags = Vec::new();
1797    if let Ok(tags) = repo.tag_names(None) {
1798        for tag_opt in tags.iter() {
1799            if let Ok(Some(tag)) = tag_opt {
1800                let mut short_sha = String::new();
1801                let mut short_message = String::new();
1802                if let Ok(reference) = repo.find_reference(&format!("refs/tags/{}", tag)) {
1803                    if let Ok(target) = reference.peel_to_commit() {
1804                        let id = target.id();
1805                        let id_str = id.to_string();
1806                        short_sha = safe_sha_slice(&id_str, 7).to_string();
1807                        if let Ok(Some(summary)) = target.summary() {
1808                            short_message = summary.to_string();
1809                        }
1810                    }
1811                }
1812                local_tags.push(BranchInfo {
1813                    name: sanitize_text(tag),
1814                    is_head: false,
1815                    short_sha,
1816                    short_message: sanitize_text(&short_message),
1817                });
1818            }
1819        }
1820    }
1821    local_tags.sort_by(|a, b| b.name.cmp(&a.name));
1822
1823    (Ok(local_tags), Ok(Vec::new()))
1824}
1825
1826pub fn load_tab_remotes(repo_path: &Path) -> Result<Vec<RemoteInfo>, String> {
1827    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
1828    let mut remotes_list = Vec::new();
1829    if let Ok(remotes) = repo.remotes() {
1830        for name in remotes.iter() {
1831            let Ok(Some(name)) = name else { continue };
1832            if let Ok(remote) = repo.find_remote(name) {
1833                let push_url = remote.pushurl().ok().flatten().map(String::from);
1834                let mut refspecs = Vec::new();
1835                for r in remote.refspecs() {
1836                    if let Ok(s) = r.str() {
1837                        refspecs.push(s.to_string());
1838                    }
1839                }
1840                remotes_list.push(RemoteInfo {
1841                    name: name.to_string(),
1842                    url: remote.url().unwrap_or("(no url)").to_string(),
1843                    push_url,
1844                    refspecs,
1845                });
1846            }
1847        }
1848    }
1849    Ok(remotes_list)
1850}
1851
1852pub fn load_tab_stashes(repo_path: &Path) -> Result<Vec<StashInfo>, String> {
1853    let mut repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
1854    let mut temp_stashes = Vec::new();
1855    let _ = repo.stash_foreach(|index, message, oid| {
1856        temp_stashes.push((index, message.to_string(), *oid));
1857        true
1858    });
1859
1860    let mut stashes = Vec::new();
1861    for (index, message, oid) in temp_stashes {
1862        let mut files = Vec::new();
1863        if let Ok(commit) = repo.find_commit(oid) {
1864            files = commit_changed_files(&repo, &commit);
1865        }
1866        stashes.push(StashInfo {
1867            index,
1868            message: sanitize_text(&message),
1869            commit_id: oid.to_string(),
1870            files,
1871        });
1872    }
1873    Ok(stashes)
1874}
1875
1876pub fn load_tab_overview(
1877    repo_path: &Path,
1878    _commit_limit: usize,
1879) -> Result<(Vec<CommitterStat>, bool), String> {
1880    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
1881    let (stats, limit_reached) =
1882        collect_committer_stats(&repo, usize::MAX).map_err(|e| e.to_string())?;
1883    Ok((stats, limit_reached))
1884}
1885
1886pub fn load_tab_submodules(repo_path: &Path) -> Result<Vec<SubmoduleInfo>, String> {
1887    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
1888    let submodules = repo.submodules().map_err(|e| e.to_string())?;
1889    let mut list = Vec::new();
1890    for sub in submodules {
1891        let name = sub.name().unwrap_or("").to_string();
1892        let path = sub.path().to_path_buf();
1893        let url = sub.url().unwrap_or(None).unwrap_or("").to_string();
1894        let commit_id = sub.index_id().map(|id| id.to_string());
1895        let head_id = sub.head_id().map(|id| id.to_string());
1896
1897        let mut is_initialized = true;
1898        let mut is_dirty = false;
1899
1900        if let Ok(status) = repo.submodule_status(&name, git2::SubmoduleIgnore::None) {
1901            is_initialized = !status.contains(git2::SubmoduleStatus::WD_UNINITIALIZED);
1902            is_dirty = status.contains(git2::SubmoduleStatus::WD_MODIFIED)
1903                || status.contains(git2::SubmoduleStatus::WD_WD_MODIFIED)
1904                || status.contains(git2::SubmoduleStatus::WD_UNTRACKED)
1905                || status.contains(git2::SubmoduleStatus::WD_INDEX_MODIFIED)
1906                || status.contains(git2::SubmoduleStatus::INDEX_MODIFIED);
1907        }
1908
1909        list.push(SubmoduleInfo { name, path, url, commit_id, head_id, is_initialized, is_dirty });
1910    }
1911    Ok(list)
1912}
1913
1914/// Build a map from commit `Oid` → list of ref names that point to it.
1915/// Local branches are stored as plain names (e.g. `"main"`).
1916/// Lightweight and annotated tags are stored with a `"tag:"` prefix
1917/// (e.g. `"tag:v1.0"`) so the UI can colour them differently.
1918fn build_ref_map(repo: &Repository) -> std::collections::HashMap<git2::Oid, Vec<String>> {
1919    let mut map: std::collections::HashMap<git2::Oid, Vec<String>> =
1920        std::collections::HashMap::new();
1921
1922    if let Ok(refs) = repo.references() {
1923        for reference in refs.flatten() {
1924            // Resolve to the underlying commit Oid (peeling through tags).
1925            let Ok(target) = reference.peel_to_commit() else {
1926                continue;
1927            };
1928            let oid = target.id();
1929
1930            let Ok(full_name) = reference.name() else {
1931                continue;
1932            };
1933
1934            let label = if let Some(branch) = full_name.strip_prefix("refs/heads/") {
1935                branch.to_string()
1936            } else if let Some(tag) = full_name.strip_prefix("refs/tags/") {
1937                format!("tag:{}", tag)
1938            } else if let Some(remote) = full_name.strip_prefix("refs/remotes/") {
1939                // Skip the symbolic HEAD pointer each remote keeps (e.g. origin/HEAD).
1940                if remote.ends_with("/HEAD") {
1941                    continue;
1942                }
1943                format!("remote:{}", remote)
1944            } else {
1945                continue;
1946            };
1947
1948            map.entry(oid).or_default().push(label);
1949        }
1950    }
1951    map
1952}
1953
1954#[allow(clippy::type_complexity)]
1955static REF_MAP_CACHE: std::sync::OnceLock<
1956    std::sync::Mutex<
1957        std::collections::HashMap<
1958            String,
1959            (std::collections::HashMap<git2::Oid, Vec<String>>, std::time::Instant),
1960        >,
1961    >,
1962> = std::sync::OnceLock::new();
1963
1964fn get_cached_ref_map(
1965    repo: &Repository,
1966    repo_path: &Path,
1967) -> std::collections::HashMap<git2::Oid, Vec<String>> {
1968    let cache_lock =
1969        REF_MAP_CACHE.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()));
1970    let mut cache = cache_lock.lock().unwrap_or_else(|e| e.into_inner());
1971    let path_key = repo_path.to_string_lossy().to_string();
1972
1973    if let Some((map, loaded_at)) = cache.get(&path_key) {
1974        if loaded_at.elapsed() < std::time::Duration::from_secs(10) {
1975            return map.clone();
1976        }
1977    }
1978
1979    let map = build_ref_map(repo);
1980    cache.insert(path_key, (map.clone(), std::time::Instant::now()));
1981    map
1982}
1983
1984pub fn invalidate_ref_map_cache(repo_path: &Path) {
1985    if let Some(cache_lock) = REF_MAP_CACHE.get() {
1986        if let Ok(mut cache) = cache_lock.lock() {
1987            cache.remove(&repo_path.to_string_lossy().to_string());
1988        }
1989    }
1990}
1991
1992/// Maximum file entries collected per bucket. Prevents pathologically large
1993/// working trees from overwhelming the detail view.
1994const MAX_FILES_PER_SECTION: usize = 100;
1995
1996/// Walk the working-tree status once and collect both summary counts and per-file info.
1997fn populate_summary_and_file_changes(repo: &Repository, info: &mut RepoInfo) {
1998    let mut opts = StatusOptions::new();
1999    opts.include_untracked(true)
2000        .renames_head_to_index(true)
2001        .recurse_untracked_dirs(true)
2002        .show(StatusShow::IndexAndWorkdir);
2003    let Ok(statuses) = repo.statuses(Some(&mut opts)) else {
2004        return;
2005    };
2006    for entry in statuses.iter() {
2007        let path = entry.path().unwrap_or("(unknown)").to_string();
2008        let flags = entry.status();
2009
2010        // 1. Populate summary counters
2011        if flags.is_conflicted() {
2012            info.summary.conflicted += 1;
2013        } else {
2014            if flags.is_wt_new() {
2015                info.summary.untracked += 1;
2016            }
2017            if flags.is_wt_modified()
2018                || flags.is_wt_deleted()
2019                || flags.is_wt_renamed()
2020                || flags.is_wt_typechange()
2021            {
2022                info.summary.modified += 1;
2023            }
2024            if flags.is_index_new()
2025                || flags.is_index_modified()
2026                || flags.is_index_deleted()
2027                || flags.is_index_renamed()
2028                || flags.is_index_typechange()
2029            {
2030                info.summary.staged += 1;
2031            }
2032        }
2033
2034        // 2. Populate file entries
2035        // Skip directories to avoid showing folders in staging panels.
2036        // We only call is_dir() for untracked files (since tracked items in git status are always files).
2037        let is_dir = if flags.is_wt_new() && !flags.is_index_new() {
2038            let path_buf = repo.workdir().unwrap_or(Path::new("")).join(&path);
2039            path_buf.is_dir()
2040        } else {
2041            false
2042        };
2043        if is_dir {
2044            continue;
2045        }
2046
2047        if flags.is_conflicted() {
2048            if info.changes.conflicted.len() < MAX_FILES_PER_SECTION {
2049                info.changes.conflicted.push(FileEntry { path: path.clone(), label: "C" });
2050            }
2051            continue;
2052        }
2053
2054        // Index (staged) changes
2055        if (flags.is_index_new()
2056            || flags.is_index_modified()
2057            || flags.is_index_deleted()
2058            || flags.is_index_renamed()
2059            || flags.is_index_typechange())
2060            && info.changes.staged.len() < MAX_FILES_PER_SECTION
2061        {
2062            let label = if flags.is_index_new() {
2063                "N"
2064            } else if flags.is_index_deleted() {
2065                "D"
2066            } else if flags.is_index_renamed() {
2067                "R"
2068            } else if flags.is_index_typechange() {
2069                "T"
2070            } else {
2071                "M"
2072            };
2073            info.changes.staged.push(FileEntry { path: path.clone(), label });
2074        }
2075
2076        // Working-tree changes
2077        if flags.is_wt_new() {
2078            if info.changes.untracked.len() < MAX_FILES_PER_SECTION {
2079                info.changes.untracked.push(FileEntry { path: path.clone(), label: "?" });
2080            }
2081            if info.changes.unstaged.len() < MAX_FILES_PER_SECTION {
2082                info.changes.unstaged.push(FileEntry { path: path.clone(), label: "N" });
2083            }
2084        } else if (flags.is_wt_modified()
2085            || flags.is_wt_deleted()
2086            || flags.is_wt_renamed()
2087            || flags.is_wt_typechange())
2088            && info.changes.unstaged.len() < MAX_FILES_PER_SECTION
2089        {
2090            let label = if flags.is_wt_deleted() {
2091                "D"
2092            } else if flags.is_wt_renamed() {
2093                "R"
2094            } else if flags.is_wt_typechange() {
2095                "T"
2096            } else {
2097                "M"
2098            };
2099            info.changes.unstaged.push(FileEntry { path: path.clone(), label });
2100        }
2101    }
2102}
2103
2104/// Collect the branch name, worktree counts, and ahead/behind for an opened
2105/// repo. Used by both `inspect_summary` (card) and `collect_info` (detail)
2106/// so the values shown in both places always agree.
2107fn collect_summary(repo: &Repository) -> RepoSummary {
2108    let mut s = RepoSummary::default();
2109    // git2 0.21: head() + shorthand() = Result<&str, Error>.
2110    if let Ok(head) = repo.head() {
2111        s.branch = head.shorthand().ok().map(String::from);
2112        if let Ok(commit) = head.peel_to_commit() {
2113            s.last_commit_time = Some(commit.time().seconds());
2114        }
2115    }
2116    populate_worktree(repo, &mut s);
2117    populate_ahead_behind(repo, &mut s);
2118    s.state = match repo.state() {
2119        git2::RepositoryState::Clean => RepoState::Clean,
2120        git2::RepositoryState::Merge => RepoState::Merge,
2121        git2::RepositoryState::Revert | git2::RepositoryState::RevertSequence => RepoState::Revert,
2122        git2::RepositoryState::CherryPick | git2::RepositoryState::CherryPickSequence => {
2123            RepoState::CherryPick
2124        }
2125        git2::RepositoryState::Bisect => RepoState::Bisect,
2126        git2::RepositoryState::Rebase
2127        | git2::RepositoryState::RebaseInteractive
2128        | git2::RepositoryState::RebaseMerge => RepoState::Rebase,
2129        git2::RepositoryState::ApplyMailbox | git2::RepositoryState::ApplyMailboxOrRebase => {
2130            RepoState::ApplyMailbox
2131        }
2132    };
2133    s
2134}
2135
2136fn populate_worktree(repo: &Repository, s: &mut RepoSummary) {
2137    let mut opts = StatusOptions::new();
2138    opts.include_untracked(true).renames_head_to_index(true).show(StatusShow::IndexAndWorkdir);
2139    let Ok(statuses) = repo.statuses(Some(&mut opts)) else {
2140        return;
2141    };
2142    for entry in statuses.iter() {
2143        let flags = entry.status();
2144        if flags.is_conflicted() {
2145            s.conflicted += 1;
2146            continue;
2147        }
2148        if flags.is_wt_new() {
2149            s.untracked += 1;
2150        }
2151        if flags.is_wt_modified()
2152            || flags.is_wt_deleted()
2153            || flags.is_wt_renamed()
2154            || flags.is_wt_typechange()
2155        {
2156            s.modified += 1;
2157        }
2158        if flags.is_index_new()
2159            || flags.is_index_modified()
2160            || flags.is_index_deleted()
2161            || flags.is_index_renamed()
2162            || flags.is_index_typechange()
2163        {
2164            s.staged += 1;
2165        }
2166    }
2167}
2168
2169/// Compute commits ahead/behind the upstream branch. Silently leaves
2170/// both at 0 if HEAD is detached, the branch has no upstream configured,
2171/// or any libgit2 lookup fails — the card simply shows no ↑/↓ then.
2172fn populate_ahead_behind(repo: &Repository, s: &mut RepoSummary) {
2173    let Ok(head) = repo.head() else { return };
2174    let Some(local_oid) = head.target() else {
2175        return;
2176    };
2177    let Ok(head_name) = head.name() else { return };
2178    let Ok(upstream_buf) = repo.branch_upstream_name(head_name) else {
2179        return;
2180    };
2181    let Ok(upstream_name) = std::str::from_utf8(&upstream_buf) else {
2182        return;
2183    };
2184    let Ok(upstream_ref) = repo.find_reference(upstream_name) else {
2185        return;
2186    };
2187    let Some(upstream_oid) = upstream_ref.target() else {
2188        return;
2189    };
2190    if let Ok((ahead, behind)) = repo.graph_ahead_behind(local_oid, upstream_oid) {
2191        s.ahead = ahead;
2192        s.behind = behind;
2193    }
2194}
2195
2196/// `"origin/main"`-style short name for HEAD's upstream, or `None`.
2197fn upstream_short_name(repo: &Repository, head_name: &str) -> Option<String> {
2198    let buf = repo.branch_upstream_name(head_name).ok()?;
2199    let raw = std::str::from_utf8(&buf).ok()?;
2200    Some(raw.strip_prefix("refs/remotes/").unwrap_or(raw).to_string())
2201}
2202
2203/// Format a unix-epoch timestamp as a relative time string ("3 days ago").
2204pub fn format_relative_time(secs: i64) -> String {
2205    if secs <= 0 {
2206        return "unknown".to_string();
2207    }
2208    let then = UNIX_EPOCH + Duration::from_secs(secs as u64);
2209    let now = SystemTime::now();
2210    let Ok(elapsed) = now.duration_since(then) else {
2211        return "in the future".to_string();
2212    };
2213    let secs = elapsed.as_secs();
2214    let (n, unit) = if secs < 60 {
2215        (secs, "second")
2216    } else if secs < 3600 {
2217        (secs / 60, "minute")
2218    } else if secs < 86_400 {
2219        (secs / 3600, "hour")
2220    } else if secs < 86_400 * 30 {
2221        (secs / 86_400, "day")
2222    } else if secs < 86_400 * 365 {
2223        (secs / (86_400 * 30), "month")
2224    } else {
2225        (secs / (86_400 * 365), "year")
2226    };
2227    let plural = if n == 1 { "" } else { "s" };
2228    format!("{} {}{} ago", n, unit, plural)
2229}
2230
2231/// Format a unix-epoch timestamp as a UTC date string ("YYYY-MM-DD HH:MM:SS UTC").
2232fn format_utc_date(secs: i64) -> String {
2233    if secs <= 0 {
2234        return "unknown".to_string();
2235    }
2236    let seconds_in_day = 86400;
2237    let day_number = secs / seconds_in_day;
2238    let time_of_day = secs % seconds_in_day;
2239
2240    let mut hour = time_of_day / 3600;
2241    let mut minute = (time_of_day % 3600) / 60;
2242    let mut second = time_of_day % 60;
2243    if hour < 0 {
2244        hour += 24;
2245    }
2246    if minute < 0 {
2247        minute += 60;
2248    }
2249    if second < 0 {
2250        second += 60;
2251    }
2252
2253    // Howard Hinnant's civil date from epoch days algorithm
2254    let z = day_number + 719468;
2255    let era = (if z >= 0 { z } else { z - 146096 }) / 146097;
2256    let doe = (z - era * 146097) as u32;
2257    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
2258    let y = (yoe as i32) + (era as i32) * 400;
2259    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
2260    let mp = (5 * doy + 2) / 153;
2261    let d = doy - (153 * mp + 2) / 5 + 1;
2262    let m = if mp < 10 { mp + 3 } else { mp - 9 };
2263    let y = y + if m <= 2 { 1 } else { 0 };
2264
2265    format!("{:04}-{:02}-{:02} {:02}:{:02}:{:02} UTC", y, m, d, hour, minute, second)
2266}
2267
2268// ── Per-file diff (private) ────────────────────────────────────────────────
2269
2270fn get_file_diff_inner(
2271    repo_path: &Path,
2272    commit_oid: &str,
2273    file_path: &str,
2274) -> Option<Vec<DiffLine>> {
2275    let repo = Repository::open(repo_path).ok()?;
2276    let oid = git2::Oid::from_str(commit_oid).ok()?;
2277    let commit = repo.find_commit(oid).ok()?;
2278
2279    let commit_tree = commit.tree().ok()?;
2280    // For the initial commit, parent_tree is None; libgit2 treats it as empty.
2281    let parent_tree = commit.parent(0).ok().and_then(|p| p.tree().ok());
2282
2283    let mut opts = git2::DiffOptions::new();
2284    opts.pathspec(file_path);
2285
2286    let diff =
2287        repo.diff_tree_to_tree(parent_tree.as_ref(), Some(&commit_tree), Some(&mut opts)).ok()?;
2288
2289    collect_diff_lines(&diff)
2290}
2291
2292/// Diff a single file in the working tree.
2293///
2294/// `staged = true`:  HEAD-tree → index (what `git diff --cached` shows).
2295/// `staged = false`: index → working directory (what `git diff` shows).
2296fn get_worktree_diff_inner(
2297    repo_path: &Path,
2298    file_path: &str,
2299    staged: bool,
2300) -> Option<Vec<DiffLine>> {
2301    let repo = Repository::open(repo_path).ok()?;
2302    let mut opts = git2::DiffOptions::new();
2303    opts.pathspec(file_path);
2304    opts.include_untracked(true);
2305    opts.recurse_untracked_dirs(true);
2306    opts.show_untracked_content(true);
2307
2308    let diff = if staged {
2309        // Staged: diff HEAD tree (or empty tree for new repos) → index.
2310        let head_tree = repo.head().ok().and_then(|h| h.peel_to_tree().ok());
2311        repo.diff_tree_to_index(head_tree.as_ref(), None, Some(&mut opts)).ok()?
2312    } else {
2313        // Unstaged: diff index → working directory.
2314        repo.diff_index_to_workdir(None, Some(&mut opts)).ok()?
2315    };
2316
2317    collect_diff_lines(&diff)
2318}
2319
2320/// Walk a libgit2 `Diff` and collect coloured `DiffLine` values.
2321fn collect_diff_lines(diff: &git2::Diff<'_>) -> Option<Vec<DiffLine>> {
2322    let mut lines: Vec<DiffLine> = Vec::new();
2323    let mut current_hunk_idx = None;
2324    let mut hunk_count = 0;
2325    diff.print(git2::DiffFormat::Patch, |_, _, line| {
2326        let kind = match line.origin() {
2327            '+' => DiffLineKind::Added,
2328            '-' => DiffLineKind::Removed,
2329            'H' => {
2330                current_hunk_idx = Some(hunk_count);
2331                hunk_count += 1;
2332                DiffLineKind::Header
2333            }
2334            ' ' => DiffLineKind::Context,
2335            _ => return true, // skip file-header meta lines
2336        };
2337        let content = String::from_utf8_lossy(line.content())
2338            .trim_end_matches('\n')
2339            .trim_end_matches('\r')
2340            .to_string();
2341        lines.push(DiffLine {
2342            kind,
2343            content,
2344            old_lineno: line.old_lineno(),
2345            new_lineno: line.new_lineno(),
2346            hunk_idx: current_hunk_idx,
2347        });
2348        true
2349    })
2350    .ok()?;
2351    Some(lines)
2352}
2353
2354fn parse_graph_line(line: &str) -> GraphLine {
2355    if line.contains("__TWIG_SEP__") {
2356        let parts: Vec<&str> = line.split("__TWIG_SEP__").collect();
2357        if parts.len() >= 5 {
2358            let graph_and_hash = parts[0];
2359            let decoration = parts[1].trim().to_string();
2360            let summary = parts[2].trim().to_string();
2361            let author = parts[3].trim().to_string();
2362            let date = parts[4].trim().to_string();
2363            let signature_status =
2364                if parts.len() >= 6 { parts[5].trim().to_string() } else { "N".to_string() };
2365
2366            let char_count = graph_and_hash.chars().count();
2367            if char_count >= 40 {
2368                let graph: String = graph_and_hash.chars().take(char_count - 40).collect();
2369                let oid: String = graph_and_hash.chars().skip(char_count - 40).collect();
2370                GraphLine {
2371                    graph,
2372                    commit: Some(GraphCommit {
2373                        oid,
2374                        decoration,
2375                        summary,
2376                        author,
2377                        date,
2378                        signature_status,
2379                    }),
2380                }
2381            } else {
2382                GraphLine { graph: graph_and_hash.to_string(), commit: None }
2383            }
2384        } else {
2385            GraphLine { graph: line.to_string(), commit: None }
2386        }
2387    } else {
2388        GraphLine { graph: line.to_string(), commit: None }
2389    }
2390}
2391
2392#[allow(dead_code)]
2393fn collect_graph_lines(repo_path: &Path, graph_max_commits: usize) -> Vec<GraphLine> {
2394    let mut graph_lines = Vec::new();
2395    let format_str = "%H__TWIG_SEP__%d__TWIG_SEP__%s__TWIG_SEP__%an__TWIG_SEP__%ad__TWIG_SEP__%G?";
2396
2397    let mut args = vec![
2398        "log".to_string(),
2399        "--graph".to_string(),
2400        "--all".to_string(),
2401        "--date=relative".to_string(),
2402    ];
2403    if graph_max_commits > 0 {
2404        args.push(format!("--max-count={}", graph_max_commits));
2405    }
2406    args.push(format!("--pretty=format:{}", format_str));
2407    args.push("--color=never".to_string());
2408
2409    let output = std::process::Command::new("git")
2410        .env("GIT_TERMINAL_PROMPT", "0")
2411        .env("GIT_SSH_COMMAND", ssh_command_val())
2412        .args(&args)
2413        .current_dir(repo_path)
2414        .output();
2415
2416    if let Ok(out) = output {
2417        if out.status.success() {
2418            let stdout_str = String::from_utf8_lossy(&out.stdout);
2419            for line in stdout_str.lines() {
2420                graph_lines.push(parse_graph_line(line));
2421            }
2422        }
2423    }
2424    graph_lines
2425}
2426
2427pub fn checkout_local_branch(repo_path: &Path, branch_name: &str) -> Result<(), git2::Error> {
2428    let output = std::process::Command::new("git")
2429        .env("GIT_TERMINAL_PROMPT", "0")
2430        .env("GIT_SSH_COMMAND", ssh_command_val())
2431        .arg("checkout")
2432        .arg(branch_name)
2433        .current_dir(repo_path)
2434        .output()
2435        .map_err(|e| git2::Error::from_str(&e.to_string()))?;
2436
2437    if !output.status.success() {
2438        let err = String::from_utf8_lossy(&output.stderr).trim().to_string();
2439        return Err(git2::Error::from_str(&err));
2440    }
2441    Ok(())
2442}
2443
2444pub fn checkout_remote_branch(
2445    repo_path: &Path,
2446    remote_branch_name: &str,
2447) -> Result<String, git2::Error> {
2448    let parts: Vec<&str> = remote_branch_name.splitn(2, '/').collect();
2449    if parts.len() < 2 {
2450        return Err(git2::Error::from_str("Invalid remote branch name"));
2451    }
2452    let local_name = parts[1];
2453
2454    let output = std::process::Command::new("git")
2455        .env("GIT_TERMINAL_PROMPT", "0")
2456        .env("GIT_SSH_COMMAND", ssh_command_val())
2457        .arg("checkout")
2458        .arg(local_name)
2459        .current_dir(repo_path)
2460        .output()
2461        .map_err(|e| git2::Error::from_str(&e.to_string()))?;
2462
2463    if output.status.success() {
2464        return Ok(format!("Switched to existing branch '{}'", local_name));
2465    }
2466
2467    let output = std::process::Command::new("git")
2468        .env("GIT_TERMINAL_PROMPT", "0")
2469        .env("GIT_SSH_COMMAND", ssh_command_val())
2470        .arg("checkout")
2471        .arg("--track")
2472        .arg(remote_branch_name)
2473        .current_dir(repo_path)
2474        .output()
2475        .map_err(|e| git2::Error::from_str(&e.to_string()))?;
2476
2477    if !output.status.success() {
2478        let err = String::from_utf8_lossy(&output.stderr).trim().to_string();
2479        return Err(git2::Error::from_str(&err));
2480    }
2481
2482    Ok(format!("Created and switched to branch '{}' tracking '{}'", local_name, remote_branch_name))
2483}
2484
2485/// Creates a new local branch pointing at HEAD.
2486pub fn create_branch(repo_path: &Path, branch_name: &str) -> Result<(), git2::Error> {
2487    let repo = Repository::open(repo_path)?;
2488    let head = repo.head()?;
2489    let target_commit = head.peel_to_commit()?;
2490    repo.branch(branch_name, &target_commit, false)?;
2491    Ok(())
2492}
2493
2494/// Deletes a local branch.
2495pub fn delete_local_branch(repo_path: &Path, branch_name: &str) -> Result<(), git2::Error> {
2496    let repo = Repository::open(repo_path)?;
2497    let mut branch = repo.find_branch(branch_name, git2::BranchType::Local)?;
2498    branch.delete()?;
2499    Ok(())
2500}
2501
2502/// Deletes a remote-tracking branch locally.
2503pub fn delete_remote_branch(repo_path: &Path, branch_name: &str) -> Result<(), git2::Error> {
2504    let repo = Repository::open(repo_path)?;
2505    let mut branch = repo.find_branch(branch_name, git2::BranchType::Remote)?;
2506    branch.delete()?;
2507    Ok(())
2508}
2509
2510/// Creates a new lightweight tag pointing at the specified commit OID.
2511pub fn create_tag(
2512    repo_path: &Path,
2513    tag_name: &str,
2514    commit_oid_str: &str,
2515) -> Result<(), git2::Error> {
2516    let repo = Repository::open(repo_path)?;
2517    let oid = git2::Oid::from_str(commit_oid_str)?;
2518    let target_object = repo.find_object(oid, Some(git2::ObjectType::Commit))?;
2519    repo.tag_lightweight(tag_name, &target_object, false)?;
2520    Ok(())
2521}
2522
2523/// Deletes a local tag.
2524pub fn delete_tag(repo_path: &Path, tag_name: &str) -> Result<(), git2::Error> {
2525    let repo = Repository::open(repo_path)?;
2526    repo.tag_delete(tag_name)?;
2527    Ok(())
2528}
2529
2530/// Deletes a tag on the remote.
2531pub fn delete_remote_tag(
2532    repo_path: &Path,
2533    remote_name: &str,
2534    tag_name: &str,
2535) -> Result<(), Box<dyn std::error::Error>> {
2536    let safe_remote = safe_ref(remote_name)?;
2537    let safe_tag = safe_ref(tag_name)?;
2538    let output = git_command()
2539        .arg("push")
2540        .arg(safe_remote)
2541        .arg("--delete")
2542        .arg(safe_tag)
2543        .current_dir(repo_path)
2544        .output()?;
2545    if !output.status.success() {
2546        let err = String::from_utf8_lossy(&output.stderr).trim().to_string();
2547        return Err(err.into());
2548    }
2549    Ok(())
2550}
2551
2552pub fn checkout_tag(repo_path: &Path, tag_name: &str) -> Result<(), git2::Error> {
2553    let safe_tag = safe_ref(tag_name).map_err(|e| git2::Error::from_str(&e))?;
2554    let output = git_command()
2555        .arg("checkout")
2556        .arg(safe_tag)
2557        .current_dir(repo_path)
2558        .output()
2559        .map_err(|e| git2::Error::from_str(&e.to_string()))?;
2560
2561    if !output.status.success() {
2562        let err = String::from_utf8_lossy(&output.stderr).trim().to_string();
2563        return Err(git2::Error::from_str(&err));
2564    }
2565    Ok(())
2566}
2567
2568/// Helper to run `git ls-remote --tags` and return parsed tag information.
2569pub fn get_remote_tags(
2570    repo_path: &Path,
2571    remote_name: &str,
2572) -> Result<Vec<BranchInfo>, Box<dyn std::error::Error>> {
2573    let safe_remote = safe_ref(remote_name)?;
2574    let output = git_command()
2575        .arg("ls-remote")
2576        .arg("--tags")
2577        .arg(safe_remote)
2578        .current_dir(repo_path)
2579        .output()?;
2580
2581    if !output.status.success() {
2582        let err = String::from_utf8_lossy(&output.stderr).trim().to_string();
2583        return Err(err.into());
2584    }
2585
2586    let stdout = String::from_utf8_lossy(&output.stdout);
2587    let repo = git2::Repository::open(repo_path)?;
2588    let mut tags_map = std::collections::HashMap::new();
2589
2590    for line in stdout.lines() {
2591        let parts: Vec<&str> = line.split_whitespace().collect();
2592        if parts.len() >= 2 {
2593            let sha = parts[0];
2594            let ref_name = parts[1];
2595            if ref_name.starts_with("refs/tags/") {
2596                let is_peeled = ref_name.ends_with("^{}");
2597                let clean_ref = if is_peeled {
2598                    safe_sha_slice(ref_name, ref_name.len().saturating_sub(3))
2599                } else {
2600                    ref_name
2601                };
2602                let tag_name = clean_ref.strip_prefix("refs/tags/").unwrap_or(clean_ref);
2603                let short_sha = safe_sha_slice(sha, 7);
2604
2605                // Try to resolve the summary locally
2606                let mut short_message = String::new();
2607                if let Ok(oid) = git2::Oid::from_str(sha) {
2608                    if let Ok(commit) = repo.find_commit(oid) {
2609                        if let Ok(Some(summary)) = commit.summary() {
2610                            short_message = summary.to_string();
2611                        }
2612                    }
2613                }
2614                if short_message.is_empty() {
2615                    short_message = "(not fetched)".to_string();
2616                }
2617
2618                let sanitized_tag = sanitize_text(tag_name);
2619                let sanitized_msg = sanitize_text(&short_message);
2620
2621                if is_peeled {
2622                    tags_map.insert(sanitized_tag, (short_sha.to_string(), sanitized_msg));
2623                } else {
2624                    tags_map
2625                        .entry(sanitized_tag)
2626                        .or_insert_with(|| (short_sha.to_string(), sanitized_msg));
2627                }
2628            }
2629        }
2630    }
2631
2632    let mut tags = Vec::new();
2633    for (name, (short_sha, short_message)) in tags_map {
2634        tags.push(BranchInfo { name, is_head: false, short_sha, short_message });
2635    }
2636    tags.sort_by(|a, b| b.name.cmp(&a.name));
2637    Ok(tags)
2638}
2639
2640pub fn serialize_tags(tags: &[BranchInfo]) -> String {
2641    let mut s = String::new();
2642    for tag in tags {
2643        s.push_str(&format!("{}|{}|{}\n", tag.name, tag.short_sha, tag.short_message));
2644    }
2645    s
2646}
2647
2648pub fn deserialize_tags(s: &str) -> Vec<BranchInfo> {
2649    let mut tags = Vec::new();
2650    for line in s.lines() {
2651        let parts: Vec<&str> = line.split('|').collect();
2652        if parts.len() >= 3 {
2653            tags.push(BranchInfo {
2654                name: parts[0].to_string(),
2655                is_head: false,
2656                short_sha: parts[1].to_string(),
2657                short_message: parts[2].to_string(),
2658            });
2659        }
2660    }
2661    tags
2662}
2663
2664pub fn delete_stash(repo_path: &Path, index: usize) -> Result<(), git2::Error> {
2665    let mut repo = Repository::open(repo_path)?;
2666    repo.stash_drop(index)?;
2667    Ok(())
2668}
2669
2670pub fn apply_stash(repo_path: &Path, index: usize) -> Result<(), String> {
2671    let stash_ref = format!("stash@{{{}}}", index);
2672    let output = std::process::Command::new("git")
2673        .env("GIT_TERMINAL_PROMPT", "0")
2674        .env("GIT_SSH_COMMAND", ssh_command_val())
2675        .arg("stash")
2676        .arg("apply")
2677        .arg(&stash_ref)
2678        .current_dir(repo_path)
2679        .output()
2680        .map_err(|e| e.to_string())?;
2681
2682    if !output.status.success() {
2683        let err_msg = String::from_utf8_lossy(&output.stderr).trim().to_string();
2684        return Err(err_msg);
2685    }
2686    Ok(())
2687}
2688
2689pub fn save_stash(
2690    repo_path: &Path,
2691    message: &str,
2692    include_untracked: bool,
2693    keep_index: bool,
2694) -> Result<(), String> {
2695    let mut cmd = std::process::Command::new("git");
2696    cmd.env("GIT_TERMINAL_PROMPT", "0")
2697        .env("GIT_SSH_COMMAND", ssh_command_val())
2698        .arg("stash")
2699        .arg("push");
2700
2701    if include_untracked {
2702        cmd.arg("--include-untracked");
2703    }
2704    if keep_index {
2705        cmd.arg("--keep-index");
2706    }
2707
2708    if !message.is_empty() {
2709        cmd.arg("-m").arg(message);
2710    }
2711
2712    let output = cmd.current_dir(repo_path).output().map_err(|e| e.to_string())?;
2713
2714    if !output.status.success() {
2715        let err_msg = String::from_utf8_lossy(&output.stderr).trim().to_string();
2716        return Err(err_msg);
2717    }
2718    Ok(())
2719}
2720
2721pub fn get_latest_change_time(item: &str) -> u64 {
2722    let path = expand_tilde(item);
2723    if !path.exists() {
2724        return 0;
2725    }
2726
2727    if path.join(".git").exists() {
2728        if let Ok(repo) = Repository::open(&path) {
2729            if let Ok(head) = repo.head() {
2730                if let Ok(commit) = head.peel_to_commit() {
2731                    return commit.time().seconds() as u64;
2732                }
2733            }
2734        }
2735    }
2736
2737    if let Ok(meta) = std::fs::metadata(&path) {
2738        if let Ok(modified) = meta.modified() {
2739            if let Ok(duration) = modified.duration_since(std::time::UNIX_EPOCH) {
2740                return duration.as_secs();
2741            }
2742        }
2743    }
2744    0
2745}
2746
2747pub fn get_last_commit_message(repo_path: &Path) -> Option<String> {
2748    if let Ok(repo) = Repository::open(repo_path) {
2749        if let Ok(head) = repo.head() {
2750            if let Ok(commit) = head.peel_to_commit() {
2751                if let Ok(msg) = commit.message() {
2752                    return Some(msg.to_string());
2753                }
2754            }
2755        }
2756    }
2757    None
2758}
2759
2760pub fn commit_amend(repo_path: &Path, message: &str) -> Result<(), String> {
2761    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
2762    let head = repo.head().map_err(|e| format!("No HEAD commit to amend: {}", e))?;
2763    let head_commit = head.peel_to_commit().map_err(|e| e.to_string())?;
2764
2765    let mut index = repo.index().map_err(|e| e.to_string())?;
2766    let tree_id = index.write_tree().map_err(|e| e.to_string())?;
2767    let tree = repo.find_tree(tree_id).map_err(|e| e.to_string())?;
2768
2769    let signature = repo
2770        .signature()
2771        .map_err(|e| format!("Failed to get signature. Check user.name/email config: {}", e))?;
2772
2773    head_commit
2774        .amend(Some("HEAD"), None, Some(&signature), None, Some(message), Some(&tree))
2775        .map_err(|e| e.to_string())?;
2776
2777    Ok(())
2778}
2779
2780// ── Merge Conflict Helpers ──────────────────────────────────────────────────
2781
2782/// Returns `true` when `.git/MERGE_HEAD` exists — i.e. a merge is in progress.
2783/// Cheap file-existence check, no libgit2 required.
2784pub fn is_merging(repo_path: &Path) -> bool {
2785    repo_path.join(".git/MERGE_HEAD").exists()
2786}
2787
2788/// Returns the conflict-marker diff for a conflicted file by parsing the file on disk.
2789/// Colorizes conflict blocks using DiffLineKind variants.
2790pub fn get_conflict_markers_diff(repo_path: &Path, file_path: &str) -> Vec<DiffLine> {
2791    let full_path = repo_path.join(file_path);
2792    let content = match std::fs::read_to_string(&full_path) {
2793        Ok(s) => s,
2794        Err(_) => return Vec::new(),
2795    };
2796
2797    let mut lines = Vec::new();
2798    let mut in_ours = false;
2799    let mut in_theirs = false;
2800
2801    for line in content.lines() {
2802        if line.starts_with("<<<<<<<") {
2803            in_ours = true;
2804            in_theirs = false;
2805            lines.push(DiffLine {
2806                kind: DiffLineKind::ConflictSeparator,
2807                content: line.to_string(),
2808                old_lineno: None,
2809                new_lineno: None,
2810                hunk_idx: None,
2811            });
2812        } else if line.starts_with("=======") {
2813            in_ours = false;
2814            in_theirs = true;
2815            lines.push(DiffLine {
2816                kind: DiffLineKind::ConflictSeparator,
2817                content: line.to_string(),
2818                old_lineno: None,
2819                new_lineno: None,
2820                hunk_idx: None,
2821            });
2822        } else if line.starts_with(">>>>>>>") {
2823            in_ours = false;
2824            in_theirs = false;
2825            lines.push(DiffLine {
2826                kind: DiffLineKind::ConflictSeparator,
2827                content: line.to_string(),
2828                old_lineno: None,
2829                new_lineno: None,
2830                hunk_idx: None,
2831            });
2832        } else if in_ours {
2833            lines.push(DiffLine {
2834                kind: DiffLineKind::ConflictOurs,
2835                content: line.to_string(),
2836                old_lineno: None,
2837                new_lineno: None,
2838                hunk_idx: None,
2839            });
2840        } else if in_theirs {
2841            lines.push(DiffLine {
2842                kind: DiffLineKind::ConflictTheirs,
2843                content: line.to_string(),
2844                old_lineno: None,
2845                new_lineno: None,
2846                hunk_idx: None,
2847            });
2848        } else {
2849            lines.push(DiffLine {
2850                kind: DiffLineKind::Context,
2851                content: line.to_string(),
2852                old_lineno: None,
2853                new_lineno: None,
2854                hunk_idx: None,
2855            });
2856        }
2857    }
2858    lines
2859}
2860
2861/// Accept the OURS (HEAD) version of a conflicted file.
2862/// Equivalent to: git checkout --ours <file> && git add <file>
2863pub fn resolve_ours(repo_path: &Path, file_path: &str) -> Result<(), String> {
2864    let output1 = std::process::Command::new("git")
2865        .env("GIT_TERMINAL_PROMPT", "0")
2866        .env("GIT_SSH_COMMAND", ssh_command_val())
2867        .args(["checkout", "--ours", file_path])
2868        .current_dir(repo_path)
2869        .output()
2870        .map_err(|e| e.to_string())?;
2871    if !output1.status.success() {
2872        return Err(String::from_utf8_lossy(&output1.stderr).to_string());
2873    }
2874    stage_file(repo_path, file_path)?;
2875    Ok(())
2876}
2877
2878/// Accept the THEIRS (incoming) version of a conflicted file.
2879/// Equivalent to: git checkout --theirs <file> && git add <file>
2880pub fn resolve_theirs(repo_path: &Path, file_path: &str) -> Result<(), String> {
2881    let output1 = std::process::Command::new("git")
2882        .env("GIT_TERMINAL_PROMPT", "0")
2883        .env("GIT_SSH_COMMAND", ssh_command_val())
2884        .args(["checkout", "--theirs", file_path])
2885        .current_dir(repo_path)
2886        .output()
2887        .map_err(|e| e.to_string())?;
2888    if !output1.status.success() {
2889        return Err(String::from_utf8_lossy(&output1.stderr).to_string());
2890    }
2891    stage_file(repo_path, file_path)?;
2892    Ok(())
2893}
2894
2895/// Mark the file as resolved (stage it) after manual edits.
2896pub fn mark_resolved(repo_path: &Path, file_path: &str) -> Result<(), String> {
2897    stage_file(repo_path, file_path)
2898}
2899
2900/// Resolve a specific conflict hunk inside a file (Ours vs Theirs).
2901/// Replaces the hunk at index `hunk_idx` in the file on disk.
2902/// If no more conflicts remain in the file, it automatically stages the file.
2903pub fn resolve_conflict_hunk(
2904    repo_path: &Path,
2905    file_path: &str,
2906    hunk_idx: usize,
2907    accept_ours: bool,
2908) -> Result<(), String> {
2909    let full_path = repo_path.join(file_path);
2910    let content = std::fs::read_to_string(&full_path).map_err(|e| e.to_string())?;
2911
2912    let mut new_lines = Vec::new();
2913    let mut lines_iter = content.lines().peekable();
2914    let mut current_hunk_idx = 0;
2915
2916    while let Some(line) = lines_iter.next() {
2917        if line.starts_with("<<<<<<<") {
2918            let mut ours_block = Vec::new();
2919            let mut theirs_block = Vec::new();
2920
2921            // Read ours block (until =======)
2922            let mut found_separator = false;
2923            while let Some(&next_line) = lines_iter.peek() {
2924                if next_line.starts_with("=======") {
2925                    lines_iter.next(); // consume =======
2926                    found_separator = true;
2927                    break;
2928                }
2929                if let Some(line) = lines_iter.next() {
2930                    ours_block.push(line.to_string());
2931                }
2932            }
2933
2934            // Read theirs block (until >>>>>>>)
2935            let mut found_end = false;
2936            let mut end_line_marker = ">>>>>>>".to_string();
2937            while let Some(&next_line) = lines_iter.peek() {
2938                if next_line.starts_with(">>>>>>>") {
2939                    if let Some(marker) = lines_iter.next() {
2940                        end_line_marker = marker.to_string(); // consume >>>>>>>
2941                    }
2942                    found_end = true;
2943                    break;
2944                }
2945                if let Some(line) = lines_iter.next() {
2946                    theirs_block.push(line.to_string());
2947                }
2948            }
2949
2950            if current_hunk_idx == hunk_idx {
2951                if accept_ours {
2952                    new_lines.extend(ours_block);
2953                } else {
2954                    new_lines.extend(theirs_block);
2955                }
2956            } else {
2957                new_lines.push(line.to_string());
2958                new_lines.extend(ours_block);
2959                if found_separator {
2960                    new_lines.push("=======".to_string());
2961                }
2962                new_lines.extend(theirs_block);
2963                if found_end {
2964                    new_lines.push(end_line_marker);
2965                }
2966            }
2967
2968            current_hunk_idx += 1;
2969        } else {
2970            new_lines.push(line.to_string());
2971        }
2972    }
2973
2974    let mut new_content = new_lines.join("\n");
2975    if content.ends_with('\n') && !new_content.ends_with('\n') {
2976        new_content.push('\n');
2977    }
2978    std::fs::write(&full_path, new_content).map_err(|e| e.to_string())?;
2979
2980    // Check if any conflict markers remain in the file
2981    let updated_content = std::fs::read_to_string(&full_path).map_err(|e| e.to_string())?;
2982    let has_conflict_markers = updated_content
2983        .lines()
2984        .any(|l| l.starts_with("<<<<<<<") || l.starts_with("=======") || l.starts_with(">>>>>>>"));
2985
2986    if !has_conflict_markers {
2987        stage_file(repo_path, file_path)?;
2988    }
2989
2990    Ok(())
2991}
2992
2993/// Abort the in-progress merge.
2994pub fn abort_merge(repo_path: &Path) -> Result<(), String> {
2995    let output = std::process::Command::new("git")
2996        .env("GIT_TERMINAL_PROMPT", "0")
2997        .env("GIT_SSH_COMMAND", ssh_command_val())
2998        .args(["merge", "--abort"])
2999        .current_dir(repo_path)
3000        .output()
3001        .map_err(|e| e.to_string())?;
3002    if !output.status.success() {
3003        return Err(String::from_utf8_lossy(&output.stderr).to_string());
3004    }
3005    Ok(())
3006}
3007
3008/// Continue the merge after conflicts are resolved.
3009pub fn continue_merge(repo_path: &Path) -> Result<(), String> {
3010    let output = std::process::Command::new("git")
3011        .env("GIT_TERMINAL_PROMPT", "0")
3012        .env("GIT_SSH_COMMAND", ssh_command_val())
3013        .args(["merge", "--continue"])
3014        .env("GIT_EDITOR", "true")
3015        .current_dir(repo_path)
3016        .output()
3017        .map_err(|e| e.to_string())?;
3018    if !output.status.success() {
3019        return Err(String::from_utf8_lossy(&output.stderr).to_string());
3020    }
3021    Ok(())
3022}
3023
3024/// Returns the upstream tracking remote name for a branch, if configured.
3025pub fn get_branch_upstream_remote(repo_path: &Path, branch_name: &str) -> Option<String> {
3026    let repo = Repository::open(repo_path).ok()?;
3027    let branch = repo.find_branch(branch_name, git2::BranchType::Local).ok()?;
3028    let _upstream = branch.upstream().ok()?;
3029    let local_ref = branch.get().name().ok()?;
3030    let remote_buf = repo.branch_upstream_remote(local_ref).ok()?;
3031    remote_buf.as_str().ok().map(|s| s.to_string())
3032}
3033
3034/// Returns whether the specified branch has a configured upstream tracking branch.
3035pub fn has_upstream_remote(repo_path: &Path, branch_name: &str) -> bool {
3036    get_branch_upstream_remote(repo_path, branch_name).is_some()
3037}
3038
3039/// Finds the remote target for pushing a branch. Returns `(remote_name, set_upstream)`.
3040pub fn get_branch_push_target(repo_path: &Path, branch_name: &str) -> Option<(String, bool)> {
3041    let repo = Repository::open(repo_path).ok()?;
3042    let branch = repo.find_branch(branch_name, git2::BranchType::Local).ok()?;
3043    if branch.upstream().is_ok() {
3044        if let Ok(local_ref) = branch.get().name() {
3045            if let Ok(remote_buf) = repo.branch_upstream_remote(local_ref) {
3046                if let Ok(name) = remote_buf.as_str() {
3047                    return Some((name.to_string(), false));
3048                }
3049            }
3050        }
3051    }
3052    let remotes = repo.remotes().ok()?;
3053    let first_remote = remotes.iter().next()?.ok()??.to_string();
3054    Some((first_remote, true))
3055}
3056
3057/// Returns whether the specified commit OID has no parents (i.e. it is the root commit).
3058pub fn is_root_commit(repo_path: &Path, commit_oid: &str) -> bool {
3059    if let Ok(repo) = Repository::open(repo_path) {
3060        if let Ok(oid) = git2::Oid::from_str(commit_oid) {
3061            if let Ok(commit) = repo.find_commit(oid) {
3062                return commit.parent_count() == 0;
3063            }
3064        }
3065    }
3066    false
3067}
3068
3069pub fn load_tab_worktrees(repo_path: &Path) -> Result<Vec<WorktreeInfo>, String> {
3070    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
3071    let mut worktrees_list = Vec::new();
3072    if let Ok(worktree_names) = repo.worktrees() {
3073        for name in worktree_names.iter() {
3074            let Ok(Some(wt_name)) = name else { continue };
3075            if let Ok(wt) = repo.find_worktree(wt_name) {
3076                let path = wt.path().to_path_buf();
3077                let mut branch = None;
3078                if let Ok(wt_repo) = Repository::open(&path) {
3079                    if let Ok(head) = wt_repo.head() {
3080                        branch = head.shorthand().map(String::from).ok();
3081                    }
3082                }
3083
3084                let mut is_locked = false;
3085                let mut lock_reason = None;
3086                if let Ok(git2::WorktreeLockStatus::Locked(reason_opt)) = wt.is_locked() {
3087                    is_locked = true;
3088                    if let Some(reason) = reason_opt {
3089                        if !reason.is_empty() {
3090                            lock_reason = Some(reason);
3091                        }
3092                    }
3093                }
3094
3095                worktrees_list.push(WorktreeInfo {
3096                    name: wt_name.to_string(),
3097                    path,
3098                    branch,
3099                    is_locked,
3100                    lock_reason,
3101                });
3102            }
3103        }
3104    }
3105    Ok(worktrees_list)
3106}
3107
3108pub fn worktree_add(repo_path: &Path, branch: &str, wt_path: &Path) -> Result<(), String> {
3109    let output = std::process::Command::new("git")
3110        .arg("worktree")
3111        .arg("add")
3112        .arg(wt_path)
3113        .arg(branch)
3114        .current_dir(repo_path)
3115        .output()
3116        .map_err(|e| e.to_string())?;
3117
3118    if !output.status.success() {
3119        return Err(String::from_utf8_lossy(&output.stderr).to_string());
3120    }
3121    Ok(())
3122}
3123
3124pub fn worktree_lock(repo_path: &Path, name: &str, reason: &str) -> Result<(), String> {
3125    let output = std::process::Command::new("git")
3126        .arg("worktree")
3127        .arg("lock")
3128        .arg("--reason")
3129        .arg(reason)
3130        .arg(name)
3131        .current_dir(repo_path)
3132        .output()
3133        .map_err(|e| e.to_string())?;
3134
3135    if !output.status.success() {
3136        return Err(String::from_utf8_lossy(&output.stderr).to_string());
3137    }
3138    Ok(())
3139}
3140
3141pub fn worktree_unlock(repo_path: &Path, name: &str) -> Result<(), String> {
3142    let output = std::process::Command::new("git")
3143        .arg("worktree")
3144        .arg("unlock")
3145        .arg(name)
3146        .current_dir(repo_path)
3147        .output()
3148        .map_err(|e| e.to_string())?;
3149
3150    if !output.status.success() {
3151        return Err(String::from_utf8_lossy(&output.stderr).to_string());
3152    }
3153    Ok(())
3154}
3155
3156pub fn worktree_remove(repo_path: &Path, name: &str, force: bool) -> Result<(), String> {
3157    let mut cmd = std::process::Command::new("git");
3158    cmd.arg("worktree").arg("remove");
3159    if force {
3160        cmd.arg("--force");
3161    }
3162    let output = cmd.arg(name).current_dir(repo_path).output().map_err(|e| e.to_string())?;
3163
3164    if !output.status.success() {
3165        return Err(String::from_utf8_lossy(&output.stderr).to_string());
3166    }
3167    Ok(())
3168}
3169
3170pub fn worktree_prune(repo_path: &Path) -> Result<(), String> {
3171    let output = std::process::Command::new("git")
3172        .arg("worktree")
3173        .arg("prune")
3174        .current_dir(repo_path)
3175        .output()
3176        .map_err(|e| e.to_string())?;
3177
3178    if !output.status.success() {
3179        return Err(String::from_utf8_lossy(&output.stderr).to_string());
3180    }
3181    Ok(())
3182}
3183
3184pub fn load_tab_forge_issues(
3185    repo_path: &Path,
3186    assigned_only: bool,
3187) -> Result<Vec<ForgeIssue>, String> {
3188    let mut cmd = std::process::Command::new("gh");
3189    cmd.arg("issue").arg("list");
3190    if assigned_only {
3191        cmd.arg("--assignee").arg("@me");
3192    }
3193    cmd.arg("--limit")
3194        .arg("50")
3195        .arg("--json")
3196        .arg("number,title,state,author,assignees,url")
3197        .current_dir(repo_path);
3198
3199    let output = match cmd.output() {
3200        Ok(out) => out,
3201        Err(e) => {
3202            return Err(format!(
3203                "GitHub CLI ('gh') not found or failed to execute: {}. Ensure 'gh' is installed and in your PATH.",
3204                e
3205            ));
3206        }
3207    };
3208
3209    if !output.status.success() {
3210        let err_msg = String::from_utf8_lossy(&output.stderr).trim().to_string();
3211        return Err(format!(
3212            "GitHub CLI error: {}. Make sure you are authenticated (run 'gh auth login') and this is a GitHub repository.",
3213            err_msg
3214        ));
3215    }
3216
3217    #[derive(serde::Deserialize)]
3218    struct GhAuthor {
3219        login: String,
3220    }
3221
3222    #[derive(serde::Deserialize)]
3223    struct GhAssignee {
3224        login: String,
3225    }
3226
3227    #[derive(serde::Deserialize)]
3228    struct GhIssue {
3229        number: u32,
3230        title: String,
3231        state: String,
3232        author: Option<GhAuthor>,
3233        assignees: Option<Vec<GhAssignee>>,
3234        url: String,
3235    }
3236
3237    let raw_issues: Vec<GhIssue> = serde_json::from_slice(&output.stdout)
3238        .map_err(|e| format!("Failed to parse GitHub CLI response: {}", e))?;
3239
3240    let issues = raw_issues
3241        .into_iter()
3242        .map(|item| {
3243            let author = item.author.map(|a| a.login).unwrap_or_else(|| "none".to_string());
3244            let assignees =
3245                item.assignees.unwrap_or_default().into_iter().map(|a| a.login).collect();
3246            ForgeIssue {
3247                number: item.number,
3248                title: item.title,
3249                state: item.state,
3250                author,
3251                assignees,
3252                url: item.url,
3253            }
3254        })
3255        .collect();
3256
3257    Ok(issues)
3258}
3259
3260#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, Eq)]
3261pub struct ForgePR {
3262    pub number: u32,
3263    pub title: String,
3264    pub state: String,
3265    pub author: String,
3266    pub assignees: Vec<String>,
3267    pub url: String,
3268    pub head_ref: String,
3269    pub head_ref_oid: String,
3270    pub body: String,
3271    pub status_checks: Vec<CIStatusCheck>,
3272    pub reviews: Vec<PRReview>,
3273}
3274
3275#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, Eq)]
3276pub struct ForgePRComment {
3277    pub path: String,
3278    pub line: Option<u32>,
3279    pub body: String,
3280    pub author: String,
3281    pub commit_id: String,
3282}
3283
3284#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, Eq)]
3285pub struct CIStatusCheck {
3286    pub name: String,
3287    pub state: Option<String>,
3288    pub status: Option<String>,
3289    pub conclusion: Option<String>,
3290}
3291
3292#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, Eq)]
3293pub struct PRReview {
3294    pub author: String,
3295    pub body: String,
3296    pub state: String,
3297}
3298
3299pub fn load_tab_forge_prs(repo_path: &Path) -> Result<Vec<ForgePR>, String> {
3300    let mut cmd = std::process::Command::new("gh");
3301    cmd.arg("pr")
3302        .arg("list")
3303        .arg("--limit")
3304        .arg("50")
3305        .arg("--json")
3306        .arg("number,title,state,author,assignees,url,headRefName,headRefOid,statusCheckRollup,body,reviews")
3307        .current_dir(repo_path);
3308
3309    let output = match cmd.output() {
3310        Ok(out) => out,
3311        Err(e) => {
3312            return Err(format!(
3313                "GitHub CLI ('gh') not found or failed to execute: {}. Ensure 'gh' is installed and in your PATH.",
3314                e
3315            ));
3316        }
3317    };
3318
3319    if !output.status.success() {
3320        let err_msg = String::from_utf8_lossy(&output.stderr).trim().to_string();
3321        return Err(format!(
3322            "GitHub CLI error: {}. Make sure you are authenticated (run 'gh auth login') and this is a GitHub repository.",
3323            err_msg
3324        ));
3325    }
3326
3327    #[derive(serde::Deserialize)]
3328    struct GhAuthor {
3329        login: String,
3330    }
3331
3332    #[derive(serde::Deserialize)]
3333    struct GhAssignee {
3334        login: String,
3335    }
3336
3337    #[derive(serde::Deserialize)]
3338    struct GhReview {
3339        author: Option<GhAuthor>,
3340        body: String,
3341        state: String,
3342    }
3343
3344    #[derive(serde::Deserialize)]
3345    struct GhStatusCheck {
3346        name: String,
3347        state: Option<String>,
3348        status: Option<String>,
3349        conclusion: Option<String>,
3350    }
3351
3352    #[derive(serde::Deserialize)]
3353    struct GhPR {
3354        number: u32,
3355        title: String,
3356        state: String,
3357        author: Option<GhAuthor>,
3358        assignees: Option<Vec<GhAssignee>>,
3359        url: String,
3360        #[serde(rename = "headRefName")]
3361        head_ref_name: String,
3362        #[serde(rename = "headRefOid")]
3363        head_ref_oid: String,
3364        body: String,
3365        #[serde(rename = "statusCheckRollup")]
3366        status_check_rollup: Option<Vec<GhStatusCheck>>,
3367        reviews: Option<Vec<GhReview>>,
3368    }
3369
3370    let raw_prs: Vec<GhPR> = serde_json::from_slice(&output.stdout)
3371        .map_err(|e| format!("Failed to parse GitHub CLI response: {}", e))?;
3372
3373    let prs = raw_prs
3374        .into_iter()
3375        .map(|item| {
3376            let author = item.author.map(|a| a.login).unwrap_or_else(|| "none".to_string());
3377            let assignees =
3378                item.assignees.unwrap_or_default().into_iter().map(|a| a.login).collect();
3379            let status_checks = item
3380                .status_check_rollup
3381                .unwrap_or_default()
3382                .into_iter()
3383                .map(|c| CIStatusCheck {
3384                    name: c.name,
3385                    state: c.state,
3386                    status: c.status,
3387                    conclusion: c.conclusion,
3388                })
3389                .collect();
3390            let reviews = item
3391                .reviews
3392                .unwrap_or_default()
3393                .into_iter()
3394                .map(|r| PRReview {
3395                    author: r.author.map(|a| a.login).unwrap_or_else(|| "none".to_string()),
3396                    body: r.body,
3397                    state: r.state,
3398                })
3399                .collect();
3400
3401            ForgePR {
3402                number: item.number,
3403                title: item.title,
3404                state: item.state,
3405                author,
3406                assignees,
3407                url: item.url,
3408                head_ref: item.head_ref_name,
3409                head_ref_oid: item.head_ref_oid,
3410                body: item.body,
3411                status_checks,
3412                reviews,
3413            }
3414        })
3415        .collect();
3416
3417    Ok(prs)
3418}
3419
3420pub fn load_pr_comments(repo_path: &Path, pr_number: u32) -> Result<Vec<ForgePRComment>, String> {
3421    let mut cmd = std::process::Command::new("gh");
3422    cmd.arg("api")
3423        .arg(format!("repos/:owner/:repo/pulls/{}/comments", pr_number))
3424        .current_dir(repo_path);
3425
3426    let output = match cmd.output() {
3427        Ok(out) => out,
3428        Err(e) => return Err(format!("Failed to execute gh: {}", e)),
3429    };
3430
3431    if !output.status.success() {
3432        let err = String::from_utf8_lossy(&output.stderr).trim().to_string();
3433        return Err(format!("Failed to load PR comments: {}", err));
3434    }
3435
3436    #[derive(serde::Deserialize)]
3437    struct GhUser {
3438        login: String,
3439    }
3440
3441    #[derive(serde::Deserialize)]
3442    struct GhPRComment {
3443        path: String,
3444        line: Option<u32>,
3445        body: String,
3446        user: Option<GhUser>,
3447        #[serde(rename = "commit_id")]
3448        commit_id: String,
3449    }
3450
3451    let raw_comments: Vec<GhPRComment> = serde_json::from_slice(&output.stdout)
3452        .map_err(|e| format!("Failed to parse PR comments: {}", e))?;
3453
3454    let comments = raw_comments
3455        .into_iter()
3456        .map(|c| ForgePRComment {
3457            path: c.path,
3458            line: c.line,
3459            body: c.body,
3460            author: c.user.map(|u| u.login).unwrap_or_else(|| "none".to_string()),
3461            commit_id: c.commit_id,
3462        })
3463        .collect();
3464
3465    Ok(comments)
3466}
3467
3468pub fn add_pr_line_comment(
3469    repo_path: &Path,
3470    pr_number: u32,
3471    commit_id: &str,
3472    path: &str,
3473    line: u32,
3474    body: &str,
3475) -> Result<(), String> {
3476    let mut cmd = std::process::Command::new("gh");
3477    cmd.arg("api")
3478        .arg(format!("repos/:owner/:repo/pulls/{}/comments", pr_number))
3479        .arg("--method")
3480        .arg("POST")
3481        .arg("-F")
3482        .arg(format!("body={}", body))
3483        .arg("-F")
3484        .arg(format!("commit_id={}", commit_id))
3485        .arg("-F")
3486        .arg(format!("path={}", path))
3487        .arg("-F")
3488        .arg(format!("line={}", line))
3489        .arg("-F")
3490        .arg("side=RIGHT")
3491        .current_dir(repo_path);
3492
3493    let output = match cmd.output() {
3494        Ok(out) => out,
3495        Err(e) => return Err(format!("Failed to execute gh: {}", e)),
3496    };
3497
3498    if !output.status.success() {
3499        let err = String::from_utf8_lossy(&output.stderr).trim().to_string();
3500        return Err(format!("Failed to add PR comment: {}", err));
3501    }
3502    Ok(())
3503}
3504
3505pub fn checkout_pr_branch(repo_path: &Path, pr_number: u32) -> Result<String, String> {
3506    let mut cmd = std::process::Command::new("gh");
3507    cmd.arg("pr").arg("checkout").arg(pr_number.to_string()).current_dir(repo_path);
3508
3509    let output = cmd.output().map_err(|e| e.to_string())?;
3510    if !output.status.success() {
3511        let err = String::from_utf8_lossy(&output.stderr).trim().to_string();
3512        return Err(format!("Failed to checkout PR branch: {}", err));
3513    }
3514    Ok(format!("Checked out branch for PR #{}", pr_number))
3515}
3516
3517pub fn resolve_and_checkout_issue_branch(
3518    repo_path: &Path,
3519    issue_number: u32,
3520) -> Result<String, String> {
3521    let mut cmd = std::process::Command::new("gh");
3522    cmd.arg("issue")
3523        .arg("view")
3524        .arg(issue_number.to_string())
3525        .arg("--json")
3526        .arg("developmentBranch")
3527        .current_dir(repo_path);
3528
3529    if let Ok(output) = cmd.output() {
3530        if output.status.success() {
3531            #[derive(serde::Deserialize)]
3532            struct GhDevBranch {
3533                name: String,
3534            }
3535            #[derive(serde::Deserialize)]
3536            struct GhIssueView {
3537                #[serde(rename = "developmentBranch")]
3538                development_branch: Option<GhDevBranch>,
3539            }
3540            if let Ok(parsed) = serde_json::from_slice::<GhIssueView>(&output.stdout) {
3541                if let Some(dev_branch) = parsed.development_branch {
3542                    if !dev_branch.name.is_empty() {
3543                        let name = dev_branch.name;
3544                        if checkout_local_branch(repo_path, &name).is_ok() {
3545                            return Ok(format!("Checked out linked local branch '{}'", name));
3546                        }
3547                        if let Ok(msg) = checkout_remote_branch(repo_path, &name) {
3548                            return Ok(format!("Checked out linked remote branch '{}'", msg));
3549                        }
3550                        let checkout_out = std::process::Command::new("git")
3551                            .arg("checkout")
3552                            .arg("-b")
3553                            .arg(&name)
3554                            .current_dir(repo_path)
3555                            .output();
3556                        if let Ok(out) = checkout_out {
3557                            if out.status.success() {
3558                                return Ok(format!(
3559                                    "Created and switched to linked branch '{}'",
3560                                    name
3561                                ));
3562                            }
3563                        }
3564                    }
3565                }
3566            }
3567        }
3568    }
3569
3570    let repo = Repository::open(repo_path).map_err(|e| e.to_string())?;
3571    let target_pattern = format!("{}", issue_number);
3572    let mut found_local = None;
3573    let mut found_remote = None;
3574
3575    if let Ok(branches) = repo.branches(None) {
3576        for (branch, branch_type) in branches.flatten() {
3577            if let Ok(Some(name)) = branch.name() {
3578                if name.contains(&target_pattern) {
3579                    match branch_type {
3580                        git2::BranchType::Local => {
3581                            found_local = Some(name.to_string());
3582                            break;
3583                        }
3584                        git2::BranchType::Remote => {
3585                            found_remote = Some(name.to_string());
3586                        }
3587                    }
3588                }
3589            }
3590        }
3591    }
3592
3593    if let Some(local_name) = found_local {
3594        checkout_local_branch(repo_path, &local_name).map_err(|e| e.to_string())?;
3595        return Ok(format!("Checked out matched local branch '{}'", local_name));
3596    }
3597
3598    if let Some(remote_name) = found_remote {
3599        let msg = checkout_remote_branch(repo_path, &remote_name).map_err(|e| e.to_string())?;
3600        return Ok(format!("Checked out matched remote branch: {}", msg));
3601    }
3602
3603    let new_branch_name = format!("issue-{}", issue_number);
3604    let checkout_out = std::process::Command::new("git")
3605        .arg("checkout")
3606        .arg("-b")
3607        .arg(&new_branch_name)
3608        .current_dir(repo_path)
3609        .output()
3610        .map_err(|e| e.to_string())?;
3611
3612    if !checkout_out.status.success() {
3613        let err = String::from_utf8_lossy(&checkout_out.stderr).trim().to_string();
3614        return Err(format!("Failed to create new branch: {}", err));
3615    }
3616
3617    Ok(format!("Created and switched to new branch '{}'", new_branch_name))
3618}
3619
3620pub fn open_browser(url: &str) {
3621    #[cfg(target_os = "macos")]
3622    let _ = std::process::Command::new("open").arg(url).status();
3623    #[cfg(target_os = "windows")]
3624    let _ = std::process::Command::new("cmd").args(["/C", "start", url]).status();
3625    #[cfg(not(any(target_os = "macos", target_os = "windows")))]
3626    let _ = std::process::Command::new("xdg-open").arg(url).status();
3627}
3628
3629#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, Eq)]
3630pub struct ForgeIssue {
3631    pub number: u32,
3632    pub title: String,
3633    pub state: String,
3634    pub author: String,
3635    pub assignees: Vec<String>,
3636    pub url: String,
3637}
3638
3639pub fn get_remote_url(repo_path: &Path, remote_name: &str) -> Option<String> {
3640    let remotes = load_tab_remotes(repo_path).ok()?;
3641    remotes.into_iter().find(|r| r.name == remote_name).map(|r| r.url)
3642}
3643
3644pub fn get_default_remote_url(repo_path: &Path) -> Option<String> {
3645    let remotes = load_tab_remotes(repo_path).ok()?;
3646    remotes.into_iter().next().map(|r| r.url)
3647}
3648
3649#[cfg(test)]
3650#[allow(clippy::unwrap_used, clippy::panic)]
3651mod tests {
3652    use super::*;
3653    use std::fs::File;
3654
3655    #[test]
3656    fn test_match_pattern() {
3657        assert!(match_pattern("test.psd", "*.psd"));
3658        assert!(match_pattern("assets/test.psd", "*.psd"));
3659        assert!(match_pattern("assets/img.png", "assets/*.png"));
3660        assert!(match_pattern("src/app.rs", "src/*"));
3661        assert!(match_pattern("test.txt", "test.txt"));
3662        assert!(!match_pattern("src/app.rs", "*.psd"));
3663    }
3664
3665    #[test]
3666    fn test_get_lfs_info() {
3667        let mut temp_path = std::env::temp_dir();
3668        temp_path.push(format!(
3669            "twig_test_lfs_{}",
3670            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
3671        ));
3672        std::fs::create_dir_all(&temp_path).unwrap();
3673
3674        // 1. Create a dummy git repo with .git/lfs directory to bypass the short-circuit check
3675        let _repo = Repository::init(&temp_path).unwrap();
3676        let lfs_dir = temp_path.join(".git").join("lfs");
3677        std::fs::create_dir_all(&lfs_dir).unwrap();
3678
3679        // 2. Call get_lfs_info (which will trigger is_lfs_installed and cover them)
3680        let (installed, tracked) = get_lfs_info(&temp_path);
3681
3682        // Assert that get_lfs_info completed (whether lfs is installed on user's machine or not)
3683        assert!(tracked.is_empty());
3684
3685        // 3. Create .gitattributes with lfs pattern
3686        let gitattributes_path = temp_path.join(".gitattributes");
3687        std::fs::write(&gitattributes_path, "*.bin filter=lfs diff=lfs merge=lfs").unwrap();
3688
3689        let (installed2, _tracked2) = get_lfs_info(&temp_path);
3690        assert_eq!(installed, installed2);
3691
3692        // Clean up
3693        let _ = std::fs::remove_dir_all(&temp_path);
3694    }
3695
3696    #[test]
3697    fn test_comprehensive_gitwig_core_coverage() {
3698        let mut temp_path = std::env::temp_dir();
3699        temp_path.push(format!(
3700            "twig_test_cov_{}",
3701            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
3702        ));
3703        std::fs::create_dir_all(&temp_path).unwrap();
3704
3705        // 1. Repository init
3706        let repo = Repository::init(&temp_path).unwrap();
3707
3708        // 2. Configure author
3709        let mut config = repo.config().unwrap();
3710        config.set_str("user.name", "Test User").unwrap();
3711        config.set_str("user.email", "test@example.com").unwrap();
3712
3713        // 3. Create dummy file & commit
3714        let file_path = temp_path.join("test.txt");
3715        std::fs::write(&file_path, "line 1\nline 2\nline 3\n").unwrap();
3716        stage_file(&temp_path, "test.txt").unwrap();
3717        commit_changes(&temp_path, "first commit").unwrap();
3718
3719        let head_commit = repo.head().unwrap().peel_to_commit().unwrap();
3720        let head_oid = head_commit.id().to_string();
3721
3722        // 4. Test diff & worktree helpers
3723        let _diffs = get_commit_file_diff(&temp_path, &head_oid, "test.txt");
3724        let _worktree_diff = get_worktree_file_diff(&temp_path, "test.txt", false);
3725
3726        // 5. Test stage/unstage/discard all
3727        let _ = stage_all_changes(&temp_path);
3728        let _ = unstage_all_changes(&temp_path);
3729
3730        std::fs::write(&file_path, "modified content").unwrap();
3731        let _ = discard_all_changes(&temp_path);
3732
3733        // 6. Test LFS functions
3734        let _lfs_size = get_lfs_storage_size(&temp_path);
3735
3736        // 7. Test load tab listings
3737        let _reflog = load_tab_reflog(&temp_path);
3738        let _tags = load_tab_tags(&temp_path);
3739        let _stashes = load_tab_stashes(&temp_path);
3740        let _submodules = load_tab_submodules(&temp_path);
3741        let _worktrees = load_tab_worktrees(&temp_path);
3742
3743        // 8. Test remote add / delete
3744        let _ = remote_add(&temp_path, "upstream", "https://github.com/example/upstream.git");
3745        let _ = remote_delete(&temp_path, "upstream");
3746
3747        // 9. Test worktree add / remove
3748        let wt_path = temp_path.join("wt-path");
3749        let _ = worktree_add(&temp_path, "new-branch", &wt_path);
3750        let _ = worktree_remove(&temp_path, "wt-path", true);
3751
3752        // 10. Test tag delete
3753        let _ = delete_tag(&temp_path, "v1.0.0");
3754
3755        // 11. Test stash apply & drop
3756        let _ = apply_stash(&temp_path, 0);
3757        let _ = delete_stash(&temp_path, 0);
3758
3759        // 12. Test merge abort / continue
3760        let _ = abort_merge(&temp_path);
3761        let _ = continue_merge(&temp_path);
3762
3763        // 13. Test merge conflict resolver helpers
3764        let _ = is_merging(&temp_path);
3765        let _ = get_conflict_markers_diff(&temp_path, "test.txt");
3766        let _ = resolve_ours(&temp_path, "test.txt");
3767        let _ = resolve_theirs(&temp_path, "test.txt");
3768        let _ = mark_resolved(&temp_path, "test.txt");
3769
3770        // 14. Test push target & upstream
3771        let _target = get_branch_push_target(&temp_path, "master");
3772        let _target2 = get_branch_push_target(&temp_path, "main");
3773
3774        // 15. Test inspect_detail & inspect_summary
3775        let _detail = inspect_detail(temp_path.to_str().unwrap(), 10, 10, true);
3776        let _summary = inspect_summary(temp_path.to_str().unwrap());
3777
3778        // Clean up
3779        let _ = std::fs::remove_dir_all(&temp_path);
3780    }
3781
3782    #[test]
3783    fn test_more_gitwig_core_coverage() {
3784        let mut temp_path = std::env::temp_dir();
3785        temp_path.push(format!(
3786            "twig_test_cov2_{}",
3787            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
3788        ));
3789        std::fs::create_dir_all(&temp_path).unwrap();
3790
3791        // 1. Repository init
3792        let repo = Repository::init(&temp_path).unwrap();
3793
3794        // 2. Configure author
3795        let mut config = repo.config().unwrap();
3796        config.set_str("user.name", "Test User").unwrap();
3797        config.set_str("user.email", "test@example.com").unwrap();
3798
3799        // 3. Create dummy file & commit
3800        let file_path = temp_path.join("test.txt");
3801        std::fs::write(&file_path, "line 1\nline 2\nline 3\n").unwrap();
3802        stage_file(&temp_path, "test.txt").unwrap();
3803        commit_changes(&temp_path, "first commit").unwrap();
3804
3805        let head_commit = repo.head().unwrap().peel_to_commit().unwrap();
3806        let head_oid = head_commit.id().to_string();
3807
3808        // 4. Test checkout functions
3809        let _ = checkout_commit(&temp_path, &head_oid);
3810        let _ = checkout_local_branch(&temp_path, "master");
3811        let _ = checkout_remote_branch(&temp_path, "origin/master");
3812        let _ = checkout_tag(&temp_path, "v1.0.0");
3813
3814        // 5. Test branch / tag creation & deletion
3815        let _ = create_branch(&temp_path, "new-branch-2");
3816        let _ = delete_local_branch(&temp_path, "new-branch-2");
3817        let _ = delete_remote_branch(&temp_path, "origin/new-branch-2");
3818        let _ = create_tag(&temp_path, "v1.0.0", &head_oid);
3819        let _ = delete_remote_tag(&temp_path, "origin", "v1.0.0");
3820        let _ = get_remote_tags(&temp_path, "origin");
3821
3822        // 6. Test serialize & deserialize tags
3823        let tag_info = vec![BranchInfo {
3824            name: "v1.0.0".to_string(),
3825            is_head: false,
3826            short_sha: "abc1234".to_string(),
3827            short_message: "tag msg".to_string(),
3828        }];
3829        let serialized = serialize_tags(&tag_info);
3830        let deserialized = deserialize_tags(&serialized);
3831        assert_eq!(deserialized.len(), 1);
3832        assert_eq!(deserialized[0].name, "v1.0.0");
3833
3834        // 7. Test history / blame / commit files
3835        let _ = get_file_history(&temp_path, "test.txt");
3836        let _ = get_file_blame(&temp_path, "test.txt");
3837        let _ = get_commit_files(&temp_path, &head_oid);
3838
3839        // 8. Test load tab functions
3840        let _ = load_tab_files(&temp_path);
3841        let _ = load_tab_branches(&temp_path);
3842        let _ = load_tab_remotes(&temp_path);
3843        let _ = load_tab_overview(&temp_path, 10);
3844
3845        // 9. Test load_tab_graph_stream
3846        let (tx, _rx) = std::sync::mpsc::channel();
3847        let _ =
3848            load_tab_graph_stream(&temp_path, 10, temp_path.to_str().unwrap().to_string(), 0, tx);
3849
3850        // 10. Test invalidate cache
3851        invalidate_ref_map_cache(&temp_path);
3852
3853        // 11. Test Forge API/command execution fallbacks/errors
3854        let _ = load_tab_forge_issues(&temp_path, false);
3855        let _ = load_tab_forge_issues(&temp_path, true);
3856        let _ = load_tab_forge_prs(&temp_path);
3857        let _ = load_pr_comments(&temp_path, 1);
3858        let _ = add_pr_line_comment(&temp_path, 1, "sha", "file.txt", 10, "comment");
3859
3860        // Clean up
3861        let _ = std::fs::remove_dir_all(&temp_path);
3862    }
3863
3864    use std::io::Write;
3865
3866    #[test]
3867    fn test_commit_amend() {
3868        let mut temp_path = std::env::temp_dir();
3869        temp_path.push(format!(
3870            "twig_test_amend_{}",
3871            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
3872        ));
3873        std::fs::create_dir_all(&temp_path).unwrap();
3874
3875        // Init repo
3876        let repo = Repository::init(&temp_path).unwrap();
3877
3878        // Configure author
3879        let mut config = repo.config().unwrap();
3880        config.set_str("user.name", "Test User").unwrap();
3881        config.set_str("user.email", "test@example.com").unwrap();
3882
3883        // Create initial file
3884        let file_path = temp_path.join("test.txt");
3885        let mut file = File::create(&file_path).unwrap();
3886        writeln!(file, "initial content").unwrap();
3887
3888        // Stage and commit initial
3889        stage_file(&temp_path, "test.txt").unwrap();
3890        commit_changes(&temp_path, "initial commit").unwrap();
3891
3892        // Verify message
3893        let msg = get_last_commit_message(&temp_path).unwrap();
3894        assert_eq!(msg, "initial commit");
3895
3896        // Amend the commit message
3897        commit_amend(&temp_path, "amended commit").unwrap();
3898
3899        // Verify amended message
3900        let amended_msg = get_last_commit_message(&temp_path).unwrap();
3901        assert_eq!(amended_msg, "amended commit");
3902
3903        // Clean up
3904        let _ = std::fs::remove_dir_all(&temp_path);
3905    }
3906
3907    #[test]
3908    fn test_commit_signatures_collection() {
3909        let mut temp_path = std::env::temp_dir();
3910        temp_path.push(format!(
3911            "twig_test_sig_{}",
3912            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
3913        ));
3914        std::fs::create_dir_all(&temp_path).unwrap();
3915
3916        // Init repo
3917        let repo = Repository::init(&temp_path).unwrap();
3918
3919        // Configure author
3920        let mut config = repo.config().unwrap();
3921        config.set_str("user.name", "Test User").unwrap();
3922        config.set_str("user.email", "test@example.com").unwrap();
3923
3924        // Create initial file
3925        let file_path = temp_path.join("test.txt");
3926        let mut file = File::create(&file_path).unwrap();
3927        writeln!(file, "initial content").unwrap();
3928
3929        // Stage and commit initial
3930        stage_file(&temp_path, "test.txt").unwrap();
3931        commit_changes(&temp_path, "initial commit").unwrap();
3932
3933        // 1. Test collect_signatures
3934        let sigs = collect_signatures(&temp_path, 0);
3935        assert_eq!(sigs.len(), 1);
3936        let head_oid = repo.head().unwrap().target().unwrap().to_string();
3937        let sig_status = sigs.get(&head_oid).unwrap();
3938        assert_eq!(sig_status, "N");
3939
3940        // 2. Test collect_commits (files should be empty by default)
3941        let commits = collect_commits(&repo, 0, &temp_path, true).unwrap();
3942        assert_eq!(commits.len(), 1);
3943        assert_eq!(commits[0].signature_status, "N");
3944        assert!(commits[0].files.is_empty());
3945
3946        // Test get_commit_files (lazy loading)
3947        let files = get_commit_files(&temp_path, &commits[0].oid).unwrap();
3948        assert_eq!(files.len(), 1);
3949        assert_eq!(files[0].path, "test.txt");
3950        assert_eq!(files[0].label, "N");
3951
3952        // 3. Test collect_graph_lines
3953        let graph = collect_graph_lines(&temp_path, 1000);
3954        assert_eq!(graph.len(), 1);
3955        assert!(graph[0].commit.is_some());
3956        assert_eq!(graph[0].commit.as_ref().unwrap().signature_status, "N");
3957
3958        // Clean up
3959        let _ = std::fs::remove_dir_all(&temp_path);
3960    }
3961
3962    #[test]
3963    fn test_ref_map_cache_behavior() {
3964        let temp_dir = std::env::temp_dir();
3965        let repo_path = temp_dir.join("test_ref_map_repo");
3966        let _ = std::fs::remove_dir_all(&repo_path);
3967        std::fs::create_dir_all(&repo_path).unwrap();
3968
3969        let repo = Repository::init(&repo_path).unwrap();
3970
3971        // 1. First fetch (rebuilds and caches)
3972        let map1 = get_cached_ref_map(&repo, &repo_path);
3973
3974        // 2. Second fetch (returns cached map)
3975        let map2 = get_cached_ref_map(&repo, &repo_path);
3976        assert_eq!(map1.len(), map2.len());
3977
3978        // 3. Invalidate cache
3979        invalidate_ref_map_cache(&repo_path);
3980
3981        // Clean up
3982        let _ = std::fs::remove_dir_all(&repo_path);
3983    }
3984
3985    #[test]
3986    fn test_get_latest_change_time() {
3987        let mut temp_path = std::env::temp_dir();
3988        temp_path.push(format!(
3989            "twig_test_time_{}",
3990            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
3991        ));
3992        std::fs::create_dir_all(&temp_path).unwrap();
3993
3994        let change_time = get_latest_change_time(temp_path.to_str().unwrap());
3995        assert!(change_time > 0);
3996
3997        let _ = std::fs::remove_dir_all(&temp_path);
3998    }
3999
4000    #[test]
4001    fn test_committer_stats() {
4002        let mut temp_path = std::env::temp_dir();
4003        temp_path.push(format!(
4004            "twig_test_stats_{}",
4005            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
4006        ));
4007        std::fs::create_dir_all(&temp_path).unwrap();
4008
4009        // Init repo
4010        let repo = Repository::init(&temp_path).unwrap();
4011
4012        // Configure author
4013        let mut config = repo.config().unwrap();
4014        config.set_str("user.name", "Test User").unwrap();
4015        config.set_str("user.email", "test@example.com").unwrap();
4016
4017        // Create initial file
4018        let file_path = temp_path.join("test.txt");
4019        let mut file = File::create(&file_path).unwrap();
4020        writeln!(file, "initial content").unwrap();
4021
4022        // Stage and commit initial
4023        stage_file(&temp_path, "test.txt").unwrap();
4024        commit_changes(&temp_path, "initial commit").unwrap();
4025
4026        // Collect stats
4027        let (stats, limit_reached) = collect_committer_stats(&repo, 10).unwrap();
4028        assert_eq!(stats.len(), 1);
4029        assert_eq!(stats[0].name, "Test User");
4030        assert_eq!(stats[0].email, "test@example.com");
4031        assert_eq!(stats[0].count, 1);
4032        assert!(!limit_reached);
4033
4034        // Clean up
4035        let _ = std::fs::remove_dir_all(&temp_path);
4036    }
4037
4038    #[test]
4039    fn test_untracked_files_in_unstaged() {
4040        let mut temp_path = std::env::temp_dir();
4041        temp_path.push(format!(
4042            "twig_test_untracked_{}",
4043            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
4044        ));
4045        std::fs::create_dir_all(&temp_path).unwrap();
4046
4047        // Init repo
4048        let _repo = Repository::init(&temp_path).unwrap();
4049
4050        // Create an untracked file
4051        let file_path = temp_path.join("untracked.txt");
4052        let mut file = File::create(&file_path).unwrap();
4053        writeln!(file, "hello untracked").unwrap();
4054
4055        // Create an untracked directory and a file inside it
4056        let untracked_dir = temp_path.join("untracked_dir");
4057        std::fs::create_dir_all(&untracked_dir).unwrap();
4058        let nested_file_path = untracked_dir.join("nested.txt");
4059        std::fs::write(&nested_file_path, "nested untracked file").unwrap();
4060
4061        // Inspect detail
4062        let detail = inspect_detail(temp_path.to_str().unwrap(), 0, 1000, false);
4063        match detail {
4064            ItemDetail::Repo { info, .. } => {
4065                // Verify no folders are in the unstaged/untracked list
4066                let unstaged_paths: Vec<String> =
4067                    info.changes.unstaged.iter().map(|f| f.path.clone()).collect();
4068                let untracked_paths: Vec<String> =
4069                    info.changes.untracked.iter().map(|f| f.path.clone()).collect();
4070
4071                // Folder itself should NOT be listed
4072                assert!(!unstaged_paths.contains(&"untracked_dir".to_string()));
4073                assert!(!unstaged_paths.contains(&"untracked_dir/".to_string()));
4074                assert!(!untracked_paths.contains(&"untracked_dir".to_string()));
4075                assert!(!untracked_paths.contains(&"untracked_dir/".to_string()));
4076
4077                // Untracked files (both root and nested) should be listed
4078                assert!(unstaged_paths.contains(&"untracked.txt".to_string()));
4079                assert!(unstaged_paths.contains(&"untracked_dir/nested.txt".to_string()));
4080                assert!(untracked_paths.contains(&"untracked.txt".to_string()));
4081                assert!(untracked_paths.contains(&"untracked_dir/nested.txt".to_string()));
4082            }
4083            _ => panic!("Expected ItemDetail::Repo"),
4084        }
4085
4086        // Clean up
4087        let _ = std::fs::remove_dir_all(&temp_path);
4088    }
4089
4090    #[test]
4091    fn test_stage_new_and_deleted_files() {
4092        let mut temp_path = std::env::temp_dir();
4093        temp_path.push(format!(
4094            "twig_test_new_del_{}",
4095            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
4096        ));
4097        std::fs::create_dir_all(&temp_path).unwrap();
4098
4099        // Init repo
4100        let repo = Repository::init(&temp_path).unwrap();
4101
4102        // Configure author
4103        let mut config = repo.config().unwrap();
4104        config.set_str("user.name", "Test User").unwrap();
4105        config.set_str("user.email", "test@example.com").unwrap();
4106
4107        // Create initial file & commit
4108        let init_file = temp_path.join("init.txt");
4109        std::fs::write(&init_file, "initial").unwrap();
4110        stage_file(&temp_path, "init.txt").unwrap();
4111        commit_changes(&temp_path, "initial commit").unwrap();
4112
4113        // 1. Create a new file (untracked)
4114        let untracked_file = temp_path.join("untracked.txt");
4115        std::fs::write(&untracked_file, "new file content").unwrap();
4116
4117        // Try staging untracked file
4118        stage_file(&temp_path, "untracked.txt").unwrap();
4119
4120        // 2. Delete the initial file
4121        std::fs::remove_file(&init_file).unwrap();
4122
4123        // Try staging deleted file
4124        stage_file(&temp_path, "init.txt").unwrap();
4125
4126        // Check status of repo
4127        let detail = inspect_detail(temp_path.to_str().unwrap(), 0, 1000, false);
4128        match detail {
4129            ItemDetail::Repo { info, .. } => {
4130                // Both should be in staged changes
4131                assert_eq!(info.changes.staged.len(), 2);
4132                let paths: Vec<String> =
4133                    info.changes.staged.iter().map(|f| f.path.clone()).collect();
4134                assert!(paths.contains(&"untracked.txt".to_string()));
4135                assert!(paths.contains(&"init.txt".to_string()));
4136            }
4137            _ => panic!("Expected ItemDetail::Repo"),
4138        }
4139
4140        // Clean up
4141        let _ = std::fs::remove_dir_all(&temp_path);
4142    }
4143
4144    #[test]
4145    fn test_discard_file_changes_all_cases() {
4146        let mut temp_path = std::env::temp_dir();
4147        temp_path.push(format!(
4148            "twig_test_discard_all_{}",
4149            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
4150        ));
4151        std::fs::create_dir_all(&temp_path).unwrap();
4152
4153        // Init repo
4154        let repo = Repository::init(&temp_path).unwrap();
4155
4156        // Configure author
4157        let mut config = repo.config().unwrap();
4158        config.set_str("user.name", "Test User").unwrap();
4159        config.set_str("user.email", "test@example.com").unwrap();
4160
4161        // Create and commit initial files
4162        let file_tracked = temp_path.join("tracked.txt");
4163        std::fs::write(&file_tracked, "original content\n").unwrap();
4164        stage_file(&temp_path, "tracked.txt").unwrap();
4165        commit_changes(&temp_path, "initial commit").unwrap();
4166
4167        // Case 1: Untracked file
4168        let file_untracked = temp_path.join("untracked.txt");
4169        std::fs::write(&file_untracked, "new untracked file\n").unwrap();
4170        assert!(file_untracked.exists());
4171        discard_file_changes(&temp_path, "untracked.txt", false).unwrap();
4172        assert!(!file_untracked.exists());
4173
4174        // Case 2: Tracked file with unstaged modification
4175        std::fs::write(&file_tracked, "unstaged modifications\n").unwrap();
4176        discard_file_changes(&temp_path, "tracked.txt", false).unwrap();
4177        assert_eq!(std::fs::read_to_string(&file_tracked).unwrap(), "original content\n");
4178
4179        // Case 3: Tracked file with staged modification
4180        std::fs::write(&file_tracked, "staged modifications\n").unwrap();
4181        stage_file(&temp_path, "tracked.txt").unwrap();
4182        // verify it's staged
4183        let detail = inspect_detail(temp_path.to_str().unwrap(), 0, 1000, false);
4184        match detail {
4185            ItemDetail::Repo { info, .. } => {
4186                assert!(!info.changes.staged.is_empty());
4187            }
4188            _ => panic!("Expected ItemDetail::Repo"),
4189        }
4190        discard_file_changes(&temp_path, "tracked.txt", true).unwrap();
4191        assert_eq!(std::fs::read_to_string(&file_tracked).unwrap(), "original content\n");
4192        // verify it's no longer staged/unstaged (it's clean)
4193        let detail = inspect_detail(temp_path.to_str().unwrap(), 0, 1000, false);
4194        match detail {
4195            ItemDetail::Repo { info, .. } => {
4196                assert!(info.changes.staged.is_empty());
4197                assert!(info.changes.unstaged.is_empty());
4198            }
4199            _ => panic!("Expected ItemDetail::Repo"),
4200        }
4201
4202        // Case 4: Tracked deleted file
4203        std::fs::remove_file(&file_tracked).unwrap();
4204        assert!(!file_tracked.exists());
4205        discard_file_changes(&temp_path, "tracked.txt", false).unwrap();
4206        assert!(file_tracked.exists());
4207        assert_eq!(std::fs::read_to_string(&file_tracked).unwrap(), "original content\n");
4208
4209        // Clean up
4210        let _ = std::fs::remove_dir_all(&temp_path);
4211    }
4212
4213    #[test]
4214    #[cfg_attr(target_os = "windows", ignore = "CRLF patch issues on Windows")]
4215    fn test_stage_unstage_by_hunk() {
4216        let mut temp_path = std::env::temp_dir();
4217        temp_path.push(format!(
4218            "twig_test_hunk_{}",
4219            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
4220        ));
4221        std::fs::create_dir_all(&temp_path).unwrap();
4222
4223        // Init repo
4224        let repo = Repository::init(&temp_path).unwrap();
4225
4226        // Configure author
4227        let mut config = repo.config().unwrap();
4228        config.set_str("user.name", "Test User").unwrap();
4229        config.set_str("user.email", "test@example.com").unwrap();
4230
4231        // Create initial file with multiple lines
4232        let file_path = temp_path.join("multihunk.txt");
4233        let mut file = File::create(&file_path).unwrap();
4234        for i in 1..=20 {
4235            writeln!(file, "Line {}", i).unwrap();
4236        }
4237        drop(file);
4238
4239        // Stage and commit initial
4240        stage_file(&temp_path, "multihunk.txt").unwrap();
4241        commit_changes(&temp_path, "initial commit").unwrap();
4242
4243        // Now modify lines 2 and 18 to create two distinct hunks
4244        let mut file = File::create(&file_path).unwrap();
4245        for i in 1..=20 {
4246            if i == 2 || i == 18 {
4247                writeln!(file, "Line {} modified", i).unwrap();
4248            } else {
4249                writeln!(file, "Line {}", i).unwrap();
4250            }
4251        }
4252        drop(file);
4253
4254        // Get the unstaged diff lines
4255        let diff_lines = get_worktree_file_diff(&temp_path, "multihunk.txt", false);
4256        // Identify hunk ranges. A hunk header starts with "@@"
4257        let mut hunk_ranges = Vec::new();
4258        let mut current_start = None;
4259        for (i, line) in diff_lines.iter().enumerate() {
4260            if line.kind == DiffLineKind::Header {
4261                if let Some(start) = current_start {
4262                    hunk_ranges.push(start..i);
4263                }
4264                current_start = Some(i);
4265            }
4266        }
4267        if let Some(start) = current_start {
4268            hunk_ranges.push(start..diff_lines.len());
4269        }
4270
4271        // We expect exactly 2 hunks
4272        assert_eq!(hunk_ranges.len(), 2);
4273
4274        // Stage the second hunk
4275        let hunk2 = &diff_lines[hunk_ranges[1].clone()];
4276        stage_hunk(&temp_path, "multihunk.txt", hunk2).unwrap();
4277
4278        // Now check staged diff for the file: it should contain the second modification
4279        let staged_diff = get_worktree_file_diff(&temp_path, "multihunk.txt", true);
4280        let staged_content: String =
4281            staged_diff.iter().map(|l| l.content.as_str()).collect::<Vec<_>>().join("\n");
4282        assert!(staged_content.contains("Line 18 modified"));
4283        assert!(!staged_content.contains("Line 2 modified"));
4284
4285        // Check unstaged diff for the file: it should contain the first modification
4286        let unstaged_diff = get_worktree_file_diff(&temp_path, "multihunk.txt", false);
4287        let unstaged_content: String =
4288            unstaged_diff.iter().map(|l| l.content.as_str()).collect::<Vec<_>>().join("\n");
4289        assert!(unstaged_content.contains("Line 2 modified"));
4290        assert!(!unstaged_content.contains("Line 18 modified"));
4291
4292        // Unstage the staged hunk
4293        let staged_hunk_ranges = {
4294            let mut ranges = Vec::new();
4295            let mut current_start = None;
4296            for (i, line) in staged_diff.iter().enumerate() {
4297                if line.kind == DiffLineKind::Header {
4298                    if let Some(start) = current_start {
4299                        ranges.push(start..i);
4300                    }
4301                    current_start = Some(i);
4302                }
4303            }
4304            if let Some(start) = current_start {
4305                ranges.push(start..staged_diff.len());
4306            }
4307            ranges
4308        };
4309        assert_eq!(staged_hunk_ranges.len(), 1);
4310        let staged_hunk = &staged_diff[staged_hunk_ranges[0].clone()];
4311        unstage_hunk(&temp_path, "multihunk.txt", staged_hunk).unwrap();
4312
4313        // Staged diff should now be empty
4314        let staged_diff_after = get_worktree_file_diff(&temp_path, "multihunk.txt", true);
4315        assert!(staged_diff_after.is_empty());
4316
4317        // Clean up
4318        let _ = std::fs::remove_dir_all(&temp_path);
4319    }
4320
4321    #[test]
4322    #[cfg_attr(target_os = "windows", ignore = "CRLF patch issues on Windows")]
4323    fn test_discard_hunk() {
4324        let mut temp_path = std::env::temp_dir();
4325        temp_path.push(format!(
4326            "twig_test_discard_h_{}",
4327            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
4328        ));
4329        std::fs::create_dir_all(&temp_path).unwrap();
4330
4331        // Init repo
4332        let repo = Repository::init(&temp_path).unwrap();
4333
4334        // Configure author
4335        let mut config = repo.config().unwrap();
4336        config.set_str("user.name", "Test User").unwrap();
4337        config.set_str("user.email", "test@example.com").unwrap();
4338
4339        // Create initial file with multiple lines
4340        let file_path = temp_path.join("discardhunk.txt");
4341        let mut file = File::create(&file_path).unwrap();
4342        for i in 1..=20 {
4343            writeln!(file, "Line {}", i).unwrap();
4344        }
4345        drop(file);
4346
4347        // Stage and commit initial
4348        stage_file(&temp_path, "discardhunk.txt").unwrap();
4349        commit_changes(&temp_path, "initial commit").unwrap();
4350
4351        // Now modify lines 2 and 18 to create two distinct hunks
4352        let mut file = File::create(&file_path).unwrap();
4353        for i in 1..=20 {
4354            if i == 2 || i == 18 {
4355                writeln!(file, "Line {} modified", i).unwrap();
4356            } else {
4357                writeln!(file, "Line {}", i).unwrap();
4358            }
4359        }
4360        drop(file);
4361
4362        // Get the unstaged diff lines
4363        let diff_lines = get_worktree_file_diff(&temp_path, "discardhunk.txt", false);
4364        // Identify hunk ranges
4365        let mut hunk_ranges = Vec::new();
4366        let mut current_start = None;
4367        for (i, line) in diff_lines.iter().enumerate() {
4368            if line.kind == DiffLineKind::Header {
4369                if let Some(start) = current_start {
4370                    hunk_ranges.push(start..i);
4371                }
4372                current_start = Some(i);
4373            }
4374        }
4375        if let Some(start) = current_start {
4376            hunk_ranges.push(start..diff_lines.len());
4377        }
4378
4379        // We expect exactly 2 hunks
4380        assert_eq!(hunk_ranges.len(), 2);
4381
4382        // Discard the second hunk (Line 18 modified)
4383        let hunk2 = &diff_lines[hunk_ranges[1].clone()];
4384        discard_hunk(&temp_path, "discardhunk.txt", hunk2).unwrap();
4385
4386        // Now check file contents: line 18 should be reverted to "Line 18", while line 2 should remain "Line 2 modified"
4387        let contents = std::fs::read_to_string(&file_path).unwrap();
4388        assert!(contents.contains("Line 2 modified"));
4389        assert!(contents.contains("Line 18\n"));
4390        assert!(!contents.contains("Line 18 modified"));
4391
4392        // Clean up
4393        let _ = std::fs::remove_dir_all(&temp_path);
4394    }
4395
4396    #[test]
4397    #[cfg_attr(target_os = "windows", ignore = "CRLF patch issues on Windows")]
4398    fn test_stage_unstage_discard_line() {
4399        let mut temp_path = std::env::temp_dir();
4400        temp_path.push(format!(
4401            "twig_test_line_{}",
4402            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
4403        ));
4404        std::fs::create_dir_all(&temp_path).unwrap();
4405
4406        let repo = Repository::init(&temp_path).unwrap();
4407        let mut config = repo.config().unwrap();
4408        config.set_str("user.name", "Test User").unwrap();
4409        config.set_str("user.email", "test@example.com").unwrap();
4410
4411        // 1. Create initial file
4412        let file_path = temp_path.join("line_test.txt");
4413        let mut file = File::create(&file_path).unwrap();
4414        writeln!(file, "line A").unwrap();
4415        writeln!(file, "line B").unwrap();
4416        writeln!(file, "line C").unwrap();
4417        drop(file);
4418
4419        stage_file(&temp_path, "line_test.txt").unwrap();
4420        commit_changes(&temp_path, "initial").unwrap();
4421
4422        // 2. Modify to introduce two distinct changes in one hunk
4423        let mut file = File::create(&file_path).unwrap();
4424        writeln!(file, "line A modified").unwrap();
4425        writeln!(file, "line B").unwrap();
4426        writeln!(file, "line C modified").unwrap();
4427        drop(file);
4428
4429        let diff_lines = get_worktree_file_diff(&temp_path, "line_test.txt", false);
4430        let mut hunk_ranges = Vec::new();
4431        let mut current_start = None;
4432        for (i, line) in diff_lines.iter().enumerate() {
4433            if line.kind == DiffLineKind::Header {
4434                if let Some(start) = current_start {
4435                    hunk_ranges.push(start..i);
4436                }
4437                current_start = Some(i);
4438            }
4439        }
4440        if let Some(start) = current_start {
4441            hunk_ranges.push(start..diff_lines.len());
4442        }
4443
4444        assert_eq!(hunk_ranges.len(), 1);
4445        let hunk0 = &diff_lines[hunk_ranges[0].clone()];
4446
4447        assert_eq!(hunk0[2].content, "line A modified");
4448        assert_eq!(hunk0[5].content, "line C modified");
4449
4450        // A) Stage line A modified (relative index 2)
4451        stage_line(&temp_path, "line_test.txt", hunk0, 2).unwrap();
4452
4453        // Check staged diff
4454        let staged_diff = get_worktree_file_diff(&temp_path, "line_test.txt", true);
4455        assert!(
4456            staged_diff
4457                .iter()
4458                .any(|l| l.kind == DiffLineKind::Added && l.content == "line A modified")
4459        );
4460        assert!(
4461            !staged_diff
4462                .iter()
4463                .any(|l| l.kind == DiffLineKind::Added && l.content == "line C modified")
4464        );
4465
4466        // Check unstaged diff
4467        let unstaged_diff = get_worktree_file_diff(&temp_path, "line_test.txt", false);
4468        assert!(
4469            !unstaged_diff
4470                .iter()
4471                .any(|l| l.kind == DiffLineKind::Added && l.content == "line A modified")
4472        );
4473        assert!(
4474            unstaged_diff
4475                .iter()
4476                .any(|l| l.kind == DiffLineKind::Added && l.content == "line C modified")
4477        );
4478
4479        // B) Unstage line A modified
4480        assert_eq!(staged_diff[2].content, "line A modified");
4481        unstage_line(&temp_path, "line_test.txt", &staged_diff, 2).unwrap();
4482
4483        // Staged diff should now be empty
4484        assert!(get_worktree_file_diff(&temp_path, "line_test.txt", true).is_empty());
4485
4486        // C) Discard line C modified (index 5) in unstaged diff
4487        let unstaged_diff2 = get_worktree_file_diff(&temp_path, "line_test.txt", false);
4488        assert_eq!(unstaged_diff2[5].content, "line C modified");
4489        discard_line(&temp_path, "line_test.txt", &unstaged_diff2, 5).unwrap();
4490
4491        let unstaged_diff3 = get_worktree_file_diff(&temp_path, "line_test.txt", false);
4492        let remove_idx = unstaged_diff3
4493            .iter()
4494            .position(|l| l.kind == DiffLineKind::Removed && l.content == "line C")
4495            .unwrap();
4496        discard_line(&temp_path, "line_test.txt", &unstaged_diff3, remove_idx).unwrap();
4497
4498        // File contents check
4499        let contents = std::fs::read_to_string(&file_path).unwrap();
4500        assert!(contents.contains("line A modified"));
4501        assert!(contents.contains("line B"));
4502        assert!(contents.contains("line C\n"));
4503        assert!(!contents.contains("line C modified"));
4504
4505        // Clean up
4506        let _ = std::fs::remove_dir_all(&temp_path);
4507    }
4508
4509    #[test]
4510    #[cfg_attr(target_os = "windows", ignore = "CRLF patch issues on Windows")]
4511    fn test_stage_unstage_discard_all_changes() {
4512        let mut temp_path = std::env::temp_dir();
4513        temp_path.push(format!(
4514            "twig_test_all_{}",
4515            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
4516        ));
4517        std::fs::create_dir_all(&temp_path).unwrap();
4518
4519        // Init repo
4520        let repo = Repository::init(&temp_path).unwrap();
4521
4522        // Configure author
4523        let mut config = repo.config().unwrap();
4524        config.set_str("user.name", "Test User").unwrap();
4525        config.set_str("user.email", "test@example.com").unwrap();
4526
4527        // Create initial file & commit it
4528        let file_path = temp_path.join("tracked.txt");
4529        std::fs::write(&file_path, "original content\n").unwrap();
4530        stage_file(&temp_path, "tracked.txt").unwrap();
4531        commit_changes(&temp_path, "initial").unwrap();
4532
4533        // 1. Make a modification and create a new untracked file
4534        std::fs::write(&file_path, "modified content\n").unwrap();
4535        let untracked_path = temp_path.join("untracked.txt");
4536        std::fs::write(&untracked_path, "untracked content\n").unwrap();
4537
4538        // Verify status has unstaged changes
4539        let status = repo.statuses(None).unwrap();
4540        assert_eq!(status.len(), 2);
4541
4542        // Stage all changes
4543        stage_all_changes(&temp_path).unwrap();
4544
4545        // Verify all changes are staged
4546        let status = repo.statuses(None).unwrap();
4547        for entry in status.iter() {
4548            assert!(
4549                entry.status().intersects(git2::Status::INDEX_MODIFIED | git2::Status::INDEX_NEW)
4550            );
4551        }
4552
4553        // Unstage all changes
4554        unstage_all_changes(&temp_path).unwrap();
4555
4556        // Verify all changes are unstaged again
4557        let status = repo.statuses(None).unwrap();
4558        for entry in status.iter() {
4559            assert!(entry.status().intersects(git2::Status::WT_MODIFIED | git2::Status::WT_NEW));
4560        }
4561
4562        // Discard all changes
4563        discard_all_changes(&temp_path).unwrap();
4564
4565        // Verify repo is completely clean
4566        let status = repo.statuses(None).unwrap();
4567        assert_eq!(status.len(), 0);
4568
4569        // Verify tracked file is reset and untracked file is removed
4570        let contents = std::fs::read_to_string(&file_path).unwrap();
4571        assert_eq!(contents, "original content\n");
4572        assert!(!untracked_path.exists());
4573
4574        // Clean up
4575        let _ = std::fs::remove_dir_all(&temp_path);
4576    }
4577
4578    #[test]
4579    fn test_merge_conflicts_flow() {
4580        let mut temp_path = std::env::temp_dir();
4581        temp_path.push(format!(
4582            "twig_test_conflict_{}",
4583            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
4584        ));
4585        std::fs::create_dir_all(&temp_path).unwrap();
4586
4587        // Init repo
4588        let repo = Repository::init(&temp_path).unwrap();
4589
4590        // Configure author
4591        let mut config = repo.config().unwrap();
4592        config.set_str("user.name", "Test User").unwrap();
4593        config.set_str("user.email", "test@example.com").unwrap();
4594
4595        // 1. Initial commit on main
4596        let file_path = temp_path.join("conflict.txt");
4597        std::fs::write(&file_path, "line 1\nline 2\nline 3\n").unwrap();
4598        stage_file(&temp_path, "conflict.txt").unwrap();
4599        commit_changes(&temp_path, "initial commit").unwrap();
4600
4601        // Get the main branch name first
4602        let output = std::process::Command::new("git")
4603            .env("GIT_TERMINAL_PROMPT", "0")
4604            .env("GIT_SSH_COMMAND", ssh_command_val())
4605            .args(["symbolic-ref", "--short", "HEAD"])
4606            .current_dir(&temp_path)
4607            .output()
4608            .unwrap();
4609        let main_branch = String::from_utf8_lossy(&output.stdout).trim().to_string();
4610
4611        // 2. Create feature branch and edit
4612        std::process::Command::new("git")
4613            .env("GIT_TERMINAL_PROMPT", "0")
4614            .env("GIT_SSH_COMMAND", ssh_command_val())
4615            .args(["checkout", "-b", "feature"])
4616            .current_dir(&temp_path)
4617            .output()
4618            .unwrap();
4619
4620        std::fs::write(&file_path, "line 1\nline 2 on feature\nline 3\n").unwrap();
4621        stage_file(&temp_path, "conflict.txt").unwrap();
4622        commit_changes(&temp_path, "feature commit").unwrap();
4623
4624        // 3. Checkout main/master and edit differently
4625        std::process::Command::new("git")
4626            .env("GIT_TERMINAL_PROMPT", "0")
4627            .env("GIT_SSH_COMMAND", ssh_command_val())
4628            .args(["checkout", &main_branch])
4629            .current_dir(&temp_path)
4630            .output()
4631            .unwrap();
4632
4633        std::fs::write(&file_path, "line 1\nline 2 on main\nline 3\n").unwrap();
4634        stage_file(&temp_path, "conflict.txt").unwrap();
4635        commit_changes(&temp_path, "main commit").unwrap();
4636
4637        // 4. Merge feature into main -> conflict
4638        assert!(!is_merging(&temp_path));
4639        let merge_output = std::process::Command::new("git")
4640            .env("GIT_TERMINAL_PROMPT", "0")
4641            .env("GIT_SSH_COMMAND", ssh_command_val())
4642            .args(["merge", "feature"])
4643            .current_dir(&temp_path)
4644            .output()
4645            .unwrap();
4646
4647        assert!(!merge_output.status.success());
4648        assert!(is_merging(&temp_path));
4649
4650        // 5. Check conflict markers diff
4651        let diff = get_conflict_markers_diff(&temp_path, "conflict.txt");
4652        assert!(!diff.is_empty());
4653        let has_separator = diff.iter().any(|l| matches!(l.kind, DiffLineKind::ConflictSeparator));
4654        let has_ours = diff.iter().any(|l| matches!(l.kind, DiffLineKind::ConflictOurs));
4655        let has_theirs = diff.iter().any(|l| matches!(l.kind, DiffLineKind::ConflictTheirs));
4656        assert!(has_separator);
4657        assert!(has_ours);
4658        assert!(has_theirs);
4659
4660        // 6. Abort merge and verify
4661        abort_merge(&temp_path).unwrap();
4662        assert!(!is_merging(&temp_path));
4663
4664        // 7. Conflict again to test resolve_ours/resolve_theirs
4665        std::process::Command::new("git")
4666            .env("GIT_TERMINAL_PROMPT", "0")
4667            .env("GIT_SSH_COMMAND", ssh_command_val())
4668            .args(["merge", "feature"])
4669            .current_dir(&temp_path)
4670            .output()
4671            .unwrap();
4672        assert!(is_merging(&temp_path));
4673
4674        // Test resolve_ours
4675        resolve_ours(&temp_path, "conflict.txt").unwrap();
4676        let contents = std::fs::read_to_string(&file_path).unwrap();
4677        assert!(contents.contains("line 2 on main"));
4678        assert!(!contents.contains("<<<<<<<"));
4679
4680        // Since it's resolved, we can continue merge
4681        continue_merge(&temp_path).unwrap();
4682        assert!(!is_merging(&temp_path));
4683
4684        // 8. Test resolve_theirs by resetting main to before the merge
4685        std::process::Command::new("git")
4686            .env("GIT_TERMINAL_PROMPT", "0")
4687            .env("GIT_SSH_COMMAND", ssh_command_val())
4688            .args(["reset", "--hard", "HEAD~1"])
4689            .current_dir(&temp_path)
4690            .output()
4691            .unwrap();
4692
4693        std::process::Command::new("git")
4694            .env("GIT_TERMINAL_PROMPT", "0")
4695            .env("GIT_SSH_COMMAND", ssh_command_val())
4696            .args(["merge", "feature"])
4697            .current_dir(&temp_path)
4698            .output()
4699            .unwrap();
4700        assert!(is_merging(&temp_path));
4701
4702        resolve_theirs(&temp_path, "conflict.txt").unwrap();
4703        let contents_theirs = std::fs::read_to_string(&file_path).unwrap();
4704        assert!(contents_theirs.contains("line 2 on feature"));
4705        assert!(!contents_theirs.contains("<<<<<<<"));
4706
4707        continue_merge(&temp_path).unwrap();
4708        assert!(!is_merging(&temp_path));
4709
4710        // Clean up
4711        let _ = std::fs::remove_dir_all(&temp_path);
4712    }
4713
4714    #[test]
4715    fn test_resolve_conflict_hunk() {
4716        let mut temp_path = std::env::temp_dir();
4717        temp_path.push(format!(
4718            "twig_test_hunk_conflict_{}",
4719            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
4720        ));
4721        std::fs::create_dir_all(&temp_path).unwrap();
4722
4723        // Init repo
4724        let repo = Repository::init(&temp_path).unwrap();
4725
4726        // Configure author
4727        let mut config = repo.config().unwrap();
4728        config.set_str("user.name", "Test User").unwrap();
4729        config.set_str("user.email", "test@example.com").unwrap();
4730
4731        // 1. Initial commit on main
4732        let file_path = temp_path.join("conflict.txt");
4733        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";
4734        std::fs::write(&file_path, initial_lines).unwrap();
4735        stage_file(&temp_path, "conflict.txt").unwrap();
4736        commit_changes(&temp_path, "initial commit").unwrap();
4737
4738        // Get the main branch name first
4739        let output = std::process::Command::new("git")
4740            .env("GIT_TERMINAL_PROMPT", "0")
4741            .env("GIT_SSH_COMMAND", ssh_command_val())
4742            .args(["symbolic-ref", "--short", "HEAD"])
4743            .current_dir(&temp_path)
4744            .output()
4745            .unwrap();
4746        let main_branch = String::from_utf8_lossy(&output.stdout).trim().to_string();
4747
4748        // 2. Create feature branch and edit line 2 and line 11
4749        std::process::Command::new("git")
4750            .env("GIT_TERMINAL_PROMPT", "0")
4751            .env("GIT_SSH_COMMAND", ssh_command_val())
4752            .args(["checkout", "-b", "feature"])
4753            .current_dir(&temp_path)
4754            .output()
4755            .unwrap();
4756        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";
4757        std::fs::write(&file_path, feature_lines).unwrap();
4758        stage_file(&temp_path, "conflict.txt").unwrap();
4759        commit_changes(&temp_path, "feature commit").unwrap();
4760
4761        // 3. Checkout main/master and edit line 2 and line 11 differently
4762        std::process::Command::new("git")
4763            .env("GIT_TERMINAL_PROMPT", "0")
4764            .env("GIT_SSH_COMMAND", ssh_command_val())
4765            .args(["checkout", &main_branch])
4766            .current_dir(&temp_path)
4767            .output()
4768            .unwrap();
4769        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";
4770        std::fs::write(&file_path, main_lines).unwrap();
4771        stage_file(&temp_path, "conflict.txt").unwrap();
4772        commit_changes(&temp_path, "main commit").unwrap();
4773
4774        // 4. Merge feature into main -> conflict
4775        let merge_output = std::process::Command::new("git")
4776            .env("GIT_TERMINAL_PROMPT", "0")
4777            .env("GIT_SSH_COMMAND", ssh_command_val())
4778            .args(["merge", "feature"])
4779            .current_dir(&temp_path)
4780            .output()
4781            .unwrap();
4782        assert!(!merge_output.status.success());
4783        assert!(is_merging(&temp_path));
4784
4785        // 5. Resolve first hunk as Ours
4786        resolve_conflict_hunk(&temp_path, "conflict.txt", 0, true).unwrap();
4787        let contents_after_first = std::fs::read_to_string(&file_path).unwrap();
4788        // Line 2 should be resolved to main
4789        assert!(contents_after_first.contains("line 2 on main"));
4790        assert!(!contents_after_first.contains("line 2 on feature"));
4791        // Line 11 should still have conflict markers
4792        assert!(contents_after_first.contains("<<<<<<<"));
4793        assert!(contents_after_first.contains("line 11 on main"));
4794        assert!(contents_after_first.contains("line 11 on feature"));
4795
4796        // Repo should still be in a merging state because 1 conflict hunk remains
4797        assert!(is_merging(&temp_path));
4798
4799        // 6. Resolve second hunk (which is now hunk 0, since hunk 0 was resolved and removed)
4800        // Wait, did the hunk count change? Yes, the first conflict block was removed,
4801        // so the remaining conflict block at line 11 becomes the 0th hunk in the file!
4802        // Let's call resolve_conflict_hunk with hunk_idx 0!
4803        resolve_conflict_hunk(&temp_path, "conflict.txt", 0, false).unwrap();
4804        let contents_after_second = std::fs::read_to_string(&file_path).unwrap();
4805        // Both lines should be resolved, no conflict markers left
4806        assert!(contents_after_second.contains("line 2 on main"));
4807        assert!(contents_after_second.contains("line 11 on feature"));
4808        assert!(!contents_after_second.contains("<<<<<<<"));
4809
4810        // File is fully resolved so it should have been automatically staged
4811        let status = repo.statuses(None).unwrap();
4812        assert_eq!(status.len(), 1);
4813        assert!(status.get(0).unwrap().status().contains(git2::Status::INDEX_MODIFIED));
4814
4815        // Continue and finalize the merge
4816        continue_merge(&temp_path).unwrap();
4817        assert!(!is_merging(&temp_path));
4818
4819        // Clean up
4820        let _ = std::fs::remove_dir_all(&temp_path);
4821    }
4822
4823    #[test]
4824    fn test_branch_and_commit_helpers() {
4825        let mut temp_path = std::env::temp_dir();
4826        temp_path.push(format!(
4827            "twig_test_helpers_{}",
4828            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
4829        ));
4830        let _ = std::fs::remove_dir_all(&temp_path);
4831        std::fs::create_dir_all(&temp_path).unwrap();
4832
4833        // 1. Initialize repository
4834        let repo = Repository::init(&temp_path).unwrap();
4835
4836        // Configure author
4837        let mut config = repo.config().unwrap();
4838        config.set_str("user.name", "Test User").unwrap();
4839        config.set_str("user.email", "test@example.com").unwrap();
4840
4841        // 2. Create initial commit (root commit)
4842        let file_path = temp_path.join("test.txt");
4843        std::fs::write(&file_path, "root content").unwrap();
4844        stage_file(&temp_path, "test.txt").unwrap();
4845        commit_changes(&temp_path, "root commit").unwrap();
4846
4847        let head_oid = repo.head().unwrap().target().unwrap().to_string();
4848        assert!(is_root_commit(&temp_path, &head_oid));
4849
4850        // 3. Create second commit (non-root commit)
4851        std::fs::write(&file_path, "second content").unwrap();
4852        stage_file(&temp_path, "test.txt").unwrap();
4853        commit_changes(&temp_path, "second commit").unwrap();
4854
4855        let new_head_oid = repo.head().unwrap().target().unwrap().to_string();
4856        assert!(!is_root_commit(&temp_path, &new_head_oid));
4857
4858        // 4. Test push target with first remote config
4859        // Currently there are no remotes, so it should return None or fallback.
4860        // Wait, get_branch_push_target returns None if no remotes are found and no upstream config.
4861        // Let's add a remote.
4862        remote_add(&temp_path, "origin", "https://github.com/example/repo.git").unwrap();
4863        let active_branch = if repo.find_branch("master", git2::BranchType::Local).is_ok() {
4864            "master"
4865        } else {
4866            "main"
4867        };
4868        let target = get_branch_push_target(&temp_path, active_branch);
4869        assert!(target.is_some());
4870        let (remote_name, set_upstream) = target.unwrap();
4871        assert_eq!(remote_name, "origin");
4872        assert!(set_upstream);
4873
4874        // Configure tracking branch
4875        let mut git_config = repo.config().unwrap();
4876        git_config.set_str(&format!("branch.{}.remote", active_branch), "origin").unwrap();
4877        git_config
4878            .set_str(
4879                &format!("branch.{}.merge", active_branch),
4880                &format!("refs/heads/{}", active_branch),
4881            )
4882            .unwrap();
4883
4884        // Create mock remote tracking reference so resolve succeeds
4885        let commit_obj = repo.head().unwrap().peel_to_commit().unwrap();
4886        repo.reference(
4887            &format!("refs/remotes/origin/{}", active_branch),
4888            commit_obj.id(),
4889            true,
4890            "create mock remote ref",
4891        )
4892        .unwrap();
4893
4894        // Test has_upstream_remote and get_branch_upstream_remote
4895        assert!(has_upstream_remote(&temp_path, active_branch));
4896        assert_eq!(
4897            get_branch_upstream_remote(&temp_path, active_branch),
4898            Some("origin".to_string())
4899        );
4900
4901        // Test push target with tracking branch configured
4902        let target_tracking = get_branch_push_target(&temp_path, active_branch);
4903        assert!(target_tracking.is_some());
4904        let (remote_name_tr, set_upstream_tr) = target_tracking.unwrap();
4905        assert_eq!(remote_name_tr, "origin");
4906        assert!(!set_upstream_tr);
4907
4908        // Clean up
4909        let _ = std::fs::remove_dir_all(&temp_path);
4910    }
4911
4912    #[test]
4913    fn test_core_helpers_comprehensive() {
4914        // 1. format_relative_time
4915        assert_eq!(format_relative_time(0), "unknown");
4916        assert_eq!(format_relative_time(-100), "unknown");
4917
4918        let now_sec = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() as i64;
4919        assert_eq!(format_relative_time(now_sec - 10), "10 seconds ago");
4920        assert_eq!(format_relative_time(now_sec - 120), "2 minutes ago");
4921        assert_eq!(format_relative_time(now_sec - 7200), "2 hours ago");
4922        assert_eq!(format_relative_time(now_sec - 86400 * 2), "2 days ago");
4923        assert_eq!(format_relative_time(now_sec - 86400 * 60), "2 months ago");
4924        assert_eq!(format_relative_time(now_sec - 86400 * 730), "2 years ago");
4925
4926        // 2. format_utc_date
4927        assert_eq!(format_utc_date(0), "unknown");
4928        assert_eq!(format_utc_date(-1), "unknown");
4929        let date_str = format_utc_date(1700000000);
4930        assert!(date_str.contains("2023-11-14"));
4931
4932        // 3. expand_tilde
4933        assert_eq!(expand_tilde("path"), PathBuf::from("path"));
4934        let tilde_path = expand_tilde("~/path");
4935        assert!(tilde_path.is_absolute() || tilde_path.to_string_lossy().contains("path"));
4936
4937        // 4. sanitize_text
4938        assert_eq!(sanitize_text("hello\nworld\r\t\x01"), "hello\nworld\r\t ");
4939        assert_eq!(sanitize_text("hello\x1B[31mworld\x1B B"), "helloworldB");
4940
4941        // 5. safe_sha_slice
4942        assert_eq!(safe_sha_slice("12345", 10), "12345");
4943        assert_eq!(safe_sha_slice("12345", 3), "123");
4944
4945        // 6. safe_ref
4946        assert_eq!(safe_ref("  refs/heads/main  "), Ok("refs/heads/main"));
4947        assert!(safe_ref("-invalid").is_err());
4948        assert!(safe_ref("   ").is_err());
4949
4950        // 7. RepoSummary helpers
4951        let mut status = RepoSummary::default();
4952        assert!(status.is_clean());
4953        assert!(status.is_synced());
4954        assert!(status.unchanged());
4955
4956        status.modified = 1;
4957        assert!(!status.is_clean());
4958        assert!(!status.unchanged());
4959
4960        status.modified = 0;
4961        status.ahead = 1;
4962        assert!(!status.is_synced());
4963        assert!(!status.unchanged());
4964
4965        // 8. TabData helpers
4966        let data_not_loaded: TabData<Vec<i32>> = TabData::NotLoaded;
4967        assert!(data_not_loaded.is_not_loaded());
4968        assert!(!data_not_loaded.is_loading());
4969        assert!(!data_not_loaded.is_loaded());
4970        assert_eq!(data_not_loaded.len(), 0);
4971        assert!(data_not_loaded.is_empty());
4972        assert!(data_not_loaded.as_ref().is_none());
4973        assert!(data_not_loaded.first().is_none());
4974        assert!(data_not_loaded.get(0).is_none());
4975        assert_eq!(data_not_loaded.iter().count(), 0);
4976        assert_eq!(data_not_loaded.as_slice().len(), 0);
4977
4978        let data_loading: TabData<Vec<i32>> = TabData::Loading;
4979        assert!(!data_loading.is_not_loaded());
4980        assert!(data_loading.is_loading());
4981
4982        let data_loaded = TabData::Loaded(vec![10, 20]);
4983        assert!(!data_loaded.is_not_loaded());
4984        assert!(!data_loaded.is_loading());
4985        assert!(data_loaded.is_loaded());
4986        assert_eq!(data_loaded.len(), 2);
4987        assert!(!data_loaded.is_empty());
4988        assert_eq!(data_loaded.as_ref().unwrap(), &vec![10, 20]);
4989        assert_eq!(data_loaded.first().unwrap(), &10);
4990        assert_eq!(data_loaded.get(1).unwrap(), &20);
4991        assert_eq!(data_loaded.iter().count(), 2);
4992        assert_eq!(data_loaded.as_slice(), &[10, 20]);
4993    }
4994
4995    #[test]
4996    fn test_comprehensive_gitwig_core_coverage_booster() {
4997        // 1. Trigger the then_with tie-breaker in collect_committer_stats
4998        let mut temp_path = std::env::temp_dir();
4999        temp_path.push(format!(
5000            "twig_test_boost_{}",
5001            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
5002        ));
5003        std::fs::create_dir_all(&temp_path).unwrap();
5004
5005        let repo = Repository::init(&temp_path).unwrap();
5006
5007        // Commit 1 under User A
5008        {
5009            let mut config = repo.config().unwrap();
5010            config.set_str("user.name", "User A").unwrap();
5011            config.set_str("user.email", "a@example.com").unwrap();
5012            std::fs::write(temp_path.join("file1.txt"), "content A").unwrap();
5013            stage_file(&temp_path, "file1.txt").unwrap();
5014            commit_changes(&temp_path, "commit A").unwrap();
5015        }
5016
5017        // Commit 2 under User B (both have 1 commit count)
5018        {
5019            let mut config = repo.config().unwrap();
5020            config.set_str("user.name", "User B").unwrap();
5021            config.set_str("user.email", "b@example.com").unwrap();
5022            std::fs::write(temp_path.join("file2.txt"), "content B").unwrap();
5023            stage_file(&temp_path, "file2.txt").unwrap();
5024            commit_changes(&temp_path, "commit B").unwrap();
5025        }
5026
5027        // Call collect_committer_stats - will sort and execute the then_with closure
5028        let (stats, _) = collect_committer_stats(&repo, 10).unwrap();
5029        assert_eq!(stats.len(), 2);
5030        assert_eq!(stats[0].count, 1);
5031        assert_eq!(stats[1].count, 1);
5032
5033        // 2. Trigger deleted file old_file().path() or_else fallback in commit_changed_files
5034        // Delete file1.txt
5035        std::fs::remove_file(temp_path.join("file1.txt")).unwrap();
5036        stage_file(&temp_path, "file1.txt").unwrap();
5037        commit_changes(&temp_path, "deleted file1").unwrap();
5038        let head_oid = repo.head().unwrap().target().unwrap().to_string();
5039        let files = get_commit_files(&temp_path, &head_oid).unwrap();
5040        assert!(files.iter().any(|f| f.path == "file1.txt" && f.label == "D"));
5041
5042        // 3. Trigger expand_tilde
5043        let path_tilde = expand_tilde("~");
5044        assert!(path_tilde.is_absolute());
5045
5046        // 4. Trigger calculate_dir_size inside get_lfs_storage_size
5047        let lfs_dir = temp_path.join(".git").join("lfs");
5048        std::fs::create_dir_all(&lfs_dir).unwrap();
5049        let nested_dir = lfs_dir.join("objects").join("xx");
5050        std::fs::create_dir_all(&nested_dir).unwrap();
5051        std::fs::write(nested_dir.join("dummy_lfs"), "hello").unwrap();
5052        let lfs_size = get_lfs_storage_size(&temp_path);
5053        assert_eq!(lfs_size, Some(5));
5054
5055        // 5. Trigger load_tab_submodules loop closures
5056        let mut sub = repo
5057            .submodule("https://github.com/example/sub.git", Path::new("sub-path"), true)
5058            .unwrap();
5059        let _ = sub.init(false);
5060        let subs = load_tab_submodules(&temp_path).unwrap();
5061        assert!(!subs.is_empty());
5062
5063        // 6. Test worktree locking/unlocking/pruning
5064        let wt_path = temp_path.join("wt-booster");
5065        let _ = worktree_add(&temp_path, "wt-branch", &wt_path);
5066        let _ = worktree_lock(&temp_path, "wt-booster", "lock reason");
5067        let _ = worktree_unlock(&temp_path, "wt-booster");
5068        let _ = worktree_prune(&temp_path);
5069        let _ = std::fs::remove_dir_all(&wt_path);
5070
5071        // 7. Test open_browser
5072        open_browser("");
5073
5074        // 8. Test error paths for almost all gitwig-core functions
5075        let nonexistent = Path::new("/nonexistent_directory_twig_test");
5076        let _ = stage_file(nonexistent, "test.txt");
5077        let _ = unstage_file(nonexistent, "test.txt");
5078        let _ = discard_all_changes(nonexistent);
5079        let _ = discard_file_changes(nonexistent, "test.txt", false);
5080        let _ = commit_changes(nonexistent, "msg");
5081        let _ = remote_add(nonexistent, "origin", "url");
5082        let _ = get_file_history(nonexistent, "test.txt");
5083        let _ = get_file_blame(nonexistent, "test.txt");
5084        let _ = get_commit_files(nonexistent, "sha");
5085        let _ = load_tab_reflog(nonexistent);
5086        let _ = load_tab_files(nonexistent);
5087        let _ = load_tab_branches(nonexistent);
5088        let _ = load_tab_tags(nonexistent);
5089        let _ = load_tab_remotes(nonexistent);
5090        let _ = load_tab_stashes(nonexistent);
5091        let _ = load_tab_overview(nonexistent, 10);
5092        let _ = load_tab_submodules(nonexistent);
5093        let _ = checkout_remote_branch(nonexistent, "origin/branch");
5094        let _ = checkout_local_branch(nonexistent, "branch");
5095        let _ = checkout_tag(nonexistent, "tag");
5096        let _ = delete_local_branch(nonexistent, "branch");
5097        let _ = delete_remote_branch(nonexistent, "origin/branch");
5098        let _ = create_tag(nonexistent, "tag", "sha");
5099        let _ = delete_remote_tag(nonexistent, "origin", "tag");
5100        let _ = get_remote_tags(nonexistent, "origin");
5101        let _ = apply_stash(nonexistent, 0);
5102        let _ = delete_stash(nonexistent, 0);
5103        let _ = save_stash(nonexistent, "msg", false, false);
5104        let _ = commit_amend(nonexistent, "msg");
5105        let _ = resolve_ours(nonexistent, "file");
5106        let _ = resolve_theirs(nonexistent, "file");
5107        let _ = resolve_conflict_hunk(nonexistent, "file", 0, true);
5108        let _ = abort_merge(nonexistent);
5109        let _ = continue_merge(nonexistent);
5110        let _ = get_branch_upstream_remote(nonexistent, "branch");
5111        let _ = load_tab_worktrees(nonexistent);
5112        let _ = worktree_add(nonexistent, "branch", Path::new("path"));
5113        let _ = worktree_lock(nonexistent, "name", "reason");
5114        let _ = worktree_unlock(nonexistent, "name");
5115        let _ = worktree_remove(nonexistent, "name", true);
5116        let _ = worktree_prune(nonexistent);
5117        let _ = load_tab_forge_issues(nonexistent, true);
5118        let _ = load_tab_forge_prs(nonexistent);
5119        let _ = load_pr_comments(nonexistent, 1);
5120        let _ = checkout_pr_branch(nonexistent, 1);
5121        let _ = resolve_and_checkout_issue_branch(nonexistent, 1);
5122        let _ = get_remote_url(nonexistent, "origin");
5123        let _ = get_default_remote_url(nonexistent);
5124        let _ = get_latest_change_time("/nonexistent");
5125
5126        let dummy_hunk = vec![
5127            DiffLine {
5128                kind: DiffLineKind::Header,
5129                content: "@@ -1,1 +1,1 @@".to_string(),
5130                old_lineno: None,
5131                new_lineno: None,
5132                hunk_idx: None,
5133            },
5134            DiffLine {
5135                kind: DiffLineKind::Added,
5136                content: "line".to_string(),
5137                old_lineno: None,
5138                new_lineno: None,
5139                hunk_idx: None,
5140            },
5141        ];
5142        let _ = stage_line(nonexistent, "file", &dummy_hunk, 1);
5143        let _ = unstage_line(nonexistent, "file", &dummy_hunk, 1);
5144        let _ = discard_line(nonexistent, "file", &dummy_hunk, 1);
5145        let _ = stage_hunk(nonexistent, "file", &dummy_hunk);
5146        let _ = unstage_hunk(nonexistent, "file", &dummy_hunk);
5147        let _ = discard_hunk(nonexistent, "file", &dummy_hunk);
5148
5149        // Clean up
5150        let _ = std::fs::remove_dir_all(&temp_path);
5151    }
5152}