aether-wisp 0.4.28

A terminal UI for AI coding agents via the Agent Client Protocol (ACP)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use thiserror::Error;

#[doc = include_str!("docs/git_diff_document.md")]
#[allow(dead_code)]
pub struct GitDiffDocument {
    pub repo_root: PathBuf,
    pub files: Vec<FileDiff>,
}

pub struct FileDiff {
    pub old_path: Option<String>,
    pub path: String,
    pub status: FileStatus,
    pub staged: StageState,
    pub hunks: Vec<Hunk>,
    pub binary: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileStatus {
    Modified,
    Added,
    Deleted,
    Renamed,
    Untracked,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StageState {
    Unstaged,
    Staged,
    PartiallyStaged,
}

#[allow(dead_code)]
pub struct Hunk {
    pub header: String,
    pub old_start: usize,
    pub old_count: usize,
    pub new_start: usize,
    pub new_count: usize,
    pub lines: Vec<PatchLine>,
}

pub struct PatchLine {
    pub kind: PatchLineKind,
    pub text: String,
    pub old_line_no: Option<usize>,
    pub new_line_no: Option<usize>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PatchLineKind {
    HunkHeader,
    Context,
    Added,
    Removed,
    Meta,
}

#[doc = include_str!("docs/git_diff_error.md")]
#[derive(Debug, Error)]
pub enum GitDiffError {
    #[error("Not a git repository")]
    NotARepository,
    #[error("Git command failed: {stderr}")]
    CommandFailed { stderr: String },
    #[error("Failed to parse diff: {0}")]
    ParseError(String),
}

impl FileStatus {
    pub fn marker(self) -> char {
        match self {
            Self::Modified => 'M',
            Self::Added => 'A',
            Self::Deleted => 'D',
            Self::Renamed => 'R',
            Self::Untracked => '?',
        }
    }

    pub fn label(self) -> &'static str {
        match self {
            Self::Modified => "modified",
            Self::Added => "new file",
            Self::Deleted => "deleted",
            Self::Renamed => "renamed",
            Self::Untracked => "untracked",
        }
    }
}

impl FileDiff {
    pub fn additions(&self) -> usize {
        self.hunks.iter().map(Hunk::additions).sum()
    }

    pub fn deletions(&self) -> usize {
        self.hunks.iter().map(Hunk::deletions).sum()
    }

    pub fn max_line_no(&self) -> usize {
        self.hunks
            .iter()
            .flat_map(|hunk| &hunk.lines)
            .flat_map(|line| line.old_line_no.into_iter().chain(line.new_line_no))
            .max()
            .unwrap_or(0)
    }
}

impl Hunk {
    pub fn additions(&self) -> usize {
        self.lines.iter().filter(|line| line.kind == PatchLineKind::Added).count()
    }

    pub fn deletions(&self) -> usize {
        self.lines.iter().filter(|line| line.kind == PatchLineKind::Removed).count()
    }
}

pub(crate) async fn load_git_diff(
    working_dir: &Path,
    cached_repo_root: Option<&Path>,
) -> Result<GitDiffDocument, GitDiffError> {
    let repo_root = match cached_repo_root {
        Some(root) => root.to_path_buf(),
        None => resolve_repo_root(working_dir).await?,
    };
    let diff_output = git(&repo_root, &["diff", "--no-ext-diff", "--find-renames", "HEAD"]).await?;

    let mut files = if diff_output.trim().is_empty() { Vec::new() } else { parse_unified_diff(&diff_output)? };

    let untracked_stdout = git(&repo_root, &["ls-files", "--others", "--exclude-standard"]).await?;
    for path in untracked_stdout.lines().filter(|l| !l.is_empty()).map(String::from) {
        files.push(build_untracked_file_diff(&repo_root, path).await);
    }

    let status_map = load_status_map(&repo_root).await?;
    for file in &mut files {
        file.staged = status_map.get(&file.path).copied().unwrap_or(StageState::Unstaged);
    }

    Ok(GitDiffDocument { repo_root, files })
}

pub(crate) async fn stage_file(repo_root: &Path, path: &str) -> Result<(), GitDiffError> {
    git(repo_root, &["add", "--", path]).await.map(drop)
}

pub(crate) async fn unstage_file(repo_root: &Path, path: &str) -> Result<(), GitDiffError> {
    git(repo_root, &["reset", "--quiet", "--", path]).await.map(drop)
}

pub(crate) async fn stage_all(repo_root: &Path) -> Result<(), GitDiffError> {
    git(repo_root, &["add", "-A"]).await.map(drop)
}

pub(crate) async fn unstage_all(repo_root: &Path) -> Result<(), GitDiffError> {
    git(repo_root, &["reset", "--quiet"]).await.map(drop)
}

pub(crate) async fn discard_file(repo_root: &Path, path: &str, status: FileStatus) -> Result<(), GitDiffError> {
    match status {
        FileStatus::Untracked => git(repo_root, &["clean", "-f", "--", path]).await.map(drop),
        _ => git(repo_root, &["restore", "--source=HEAD", "--staged", "--worktree", "--", path]).await.map(drop),
    }
}

pub(crate) async fn commit(repo_root: &Path, message: &str) -> Result<(), GitDiffError> {
    if message.trim().is_empty() {
        return Err(GitDiffError::CommandFailed { stderr: "empty commit message".to_string() });
    }
    git(repo_root, &["commit", "-m", message]).await.map(drop)
}

async fn load_status_map(repo_root: &Path) -> Result<HashMap<String, StageState>, GitDiffError> {
    let output = git(repo_root, &["status", "--porcelain=v1", "-z"]).await?;
    Ok(parse_porcelain_status(&output))
}

fn parse_porcelain_status(input: &str) -> HashMap<String, StageState> {
    let mut map = HashMap::new();
    let mut tokens = input.split('\0').filter(|token| !token.is_empty());

    while let Some(record) = tokens.next() {
        if record.len() < 3 {
            continue;
        }
        let bytes = record.as_bytes();
        let index = bytes[0] as char;
        let worktree = bytes[1] as char;
        let path = &record[3..];

        if matches!(index, 'R' | 'C') || matches!(worktree, 'R' | 'C') {
            tokens.next();
        }

        let state = match (index, worktree) {
            ('?', '?') | (' ', _) => StageState::Unstaged,
            (_, ' ') => StageState::Staged,
            _ => StageState::PartiallyStaged,
        };
        map.insert(path.to_string(), state);
    }

    map
}

async fn resolve_repo_root(working_dir: &Path) -> Result<PathBuf, GitDiffError> {
    let output = tokio::process::Command::new("git")
        .arg("rev-parse")
        .arg("--show-toplevel")
        .current_dir(working_dir)
        .output()
        .await
        .map_err(|e| GitDiffError::CommandFailed { stderr: e.to_string() })?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        if stderr.contains("not a git repository") {
            return Err(GitDiffError::NotARepository);
        }
        return Err(GitDiffError::CommandFailed { stderr: stderr.into_owned() });
    }

    let root = String::from_utf8_lossy(&output.stdout).trim().to_string();
    Ok(PathBuf::from(root))
}

async fn git(repo_root: &Path, args: &[&str]) -> Result<String, GitDiffError> {
    let output = tokio::process::Command::new("git")
        .args(args)
        .current_dir(repo_root)
        .output()
        .await
        .map_err(|e| GitDiffError::CommandFailed { stderr: e.to_string() })?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(GitDiffError::CommandFailed { stderr: stderr.into_owned() });
    }

    Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}

async fn build_untracked_file_diff(repo_root: &Path, relative_path: String) -> FileDiff {
    let full_path = repo_root.join(&relative_path);
    let Ok(bytes) = tokio::fs::read(&full_path).await else {
        return binary_untracked(relative_path);
    };

    if bytes.iter().take(8192).any(|&b| b == 0) {
        return binary_untracked(relative_path);
    }

    let Ok(content) = String::from_utf8(bytes) else {
        return binary_untracked(relative_path);
    };

    let text_lines: Vec<&str> = content.lines().collect();
    let line_count = text_lines.len();

    let hunk_header = format!("@@ -0,0 +1,{line_count} @@");

    let mut patch_lines = vec![PatchLine {
        kind: PatchLineKind::HunkHeader,
        text: hunk_header.clone(),
        old_line_no: None,
        new_line_no: None,
    }];

    for (i, line) in text_lines.iter().enumerate() {
        patch_lines.push(PatchLine {
            kind: PatchLineKind::Added,
            text: (*line).to_string(),
            old_line_no: None,
            new_line_no: Some(i + 1),
        });
    }

    let hunk = Hunk {
        header: hunk_header,
        old_start: 0,
        old_count: 0,
        new_start: 1,
        new_count: line_count,
        lines: patch_lines,
    };

    FileDiff {
        old_path: None,
        path: relative_path,
        status: FileStatus::Untracked,
        staged: StageState::Unstaged,
        hunks: vec![hunk],
        binary: false,
    }
}

fn binary_untracked(path: String) -> FileDiff {
    FileDiff {
        old_path: None,
        path,
        status: FileStatus::Untracked,
        staged: StageState::Unstaged,
        hunks: Vec::new(),
        binary: true,
    }
}

pub(crate) fn parse_unified_diff(input: &str) -> Result<Vec<FileDiff>, GitDiffError> {
    split_diff_files(input).into_iter().map(parse_file_diff).collect()
}

fn split_diff_files(input: &str) -> Vec<&str> {
    let mut chunks = Vec::new();
    let mut start = None;
    let mut line_start = 0;

    while line_start < input.len() {
        let line_end = input[line_start..].find('\n').map_or(input.len(), |idx| line_start + idx + 1);
        let line = &input[line_start..line_end];

        if line.starts_with("diff --git ") {
            if let Some(s) = start {
                chunks.push(&input[s..line_start]);
            }
            start = Some(line_start);
        }

        line_start = line_end;
    }

    if let Some(s) = start {
        chunks.push(&input[s..]);
    }

    chunks
}

fn parse_file_diff(chunk: &str) -> Result<FileDiff, GitDiffError> {
    let lines: Vec<&str> = chunk.lines().collect();
    if lines.is_empty() {
        return Err(GitDiffError::ParseError("Empty diff chunk".to_string()));
    }

    let (old_path, new_path) = parse_diff_header(lines[0])?;
    let (status, binary, rename_from, hunk_start) = scan_file_metadata(&lines);
    let hunks = if binary { Vec::new() } else { parse_file_hunks(&lines[hunk_start..])? };

    Ok(FileDiff {
        old_path: resolve_old_path(status, rename_from, old_path),
        path: new_path,
        status,
        staged: StageState::Unstaged,
        hunks,
        binary,
    })
}

fn scan_file_metadata(lines: &[&str]) -> (FileStatus, bool, Option<String>, usize) {
    let mut status = FileStatus::Modified;
    let mut binary = false;
    let mut rename_from = None;
    let mut i = 1;

    while i < lines.len() {
        let line = lines[i];
        if line.starts_with("new file mode") {
            status = FileStatus::Added;
        } else if line.starts_with("deleted file mode") {
            status = FileStatus::Deleted;
        } else if let Some(from) = line.strip_prefix("rename from ") {
            status = FileStatus::Renamed;
            rename_from = Some(from.to_string());
        } else if line.starts_with("rename to ") {
            status = FileStatus::Renamed;
        } else if line.starts_with("Binary files ") {
            binary = true;
        } else if line.starts_with("@@") {
            break;
        }
        i += 1;
    }

    (status, binary, rename_from, i)
}

fn parse_file_hunks(lines: &[&str]) -> Result<Vec<Hunk>, GitDiffError> {
    let mut hunks = Vec::new();
    let mut i = 0;

    while i < lines.len() {
        if lines[i].starts_with("@@") {
            let (hunk, consumed) = parse_hunk(&lines[i..])?;
            hunks.push(hunk);
            i += consumed;
        } else {
            i += 1;
        }
    }

    Ok(hunks)
}

fn resolve_old_path(status: FileStatus, rename_from: Option<String>, old_path: String) -> Option<String> {
    if status == FileStatus::Added || status == FileStatus::Untracked {
        None
    } else if status == FileStatus::Renamed {
        rename_from.or(Some(old_path))
    } else {
        Some(old_path)
    }
}

fn parse_diff_header(line: &str) -> Result<(String, String), GitDiffError> {
    let rest = line
        .strip_prefix("diff --git ")
        .ok_or_else(|| GitDiffError::ParseError(format!("Invalid diff header: {line}")))?;

    if let Some((a, b)) = rest.split_once(" b/") {
        let old = a.strip_prefix("a/").unwrap_or(a).to_string();
        let new = b.to_string();
        Ok((old, new))
    } else {
        Err(GitDiffError::ParseError(format!("Cannot parse paths from: {line}")))
    }
}

fn parse_hunk(lines: &[&str]) -> Result<(Hunk, usize), GitDiffError> {
    let header = lines[0];
    let (old_start, old_count, new_start, new_count) = parse_hunk_header(header)?;

    let mut patch_lines = Vec::new();
    patch_lines.push(PatchLine {
        kind: PatchLineKind::HunkHeader,
        text: header.to_string(),
        old_line_no: None,
        new_line_no: None,
    });

    let mut old_line = old_start;
    let mut new_line = new_start;
    let mut i = 1;

    while i < lines.len() {
        let line = lines[i];
        if line.starts_with("@@") {
            break;
        }

        if let Some(text) = line.strip_prefix('+') {
            patch_lines.push(PatchLine {
                kind: PatchLineKind::Added,
                text: text.to_string(),
                old_line_no: None,
                new_line_no: Some(new_line),
            });
            new_line += 1;
        } else if let Some(text) = line.strip_prefix('-') {
            patch_lines.push(PatchLine {
                kind: PatchLineKind::Removed,
                text: text.to_string(),
                old_line_no: Some(old_line),
                new_line_no: None,
            });
            old_line += 1;
        } else if let Some(text) = line.strip_prefix(' ') {
            patch_lines.push(PatchLine {
                kind: PatchLineKind::Context,
                text: text.to_string(),
                old_line_no: Some(old_line),
                new_line_no: Some(new_line),
            });
            old_line += 1;
            new_line += 1;
        } else if line.starts_with('\\') {
            patch_lines.push(PatchLine {
                kind: PatchLineKind::Meta,
                text: line.to_string(),
                old_line_no: None,
                new_line_no: None,
            });
        } else {
            // Treat as context (git sometimes omits the leading space for empty lines)
            patch_lines.push(PatchLine {
                kind: PatchLineKind::Context,
                text: line.to_string(),
                old_line_no: Some(old_line),
                new_line_no: Some(new_line),
            });
            old_line += 1;
            new_line += 1;
        }
        i += 1;
    }

    Ok((Hunk { header: header.to_string(), old_start, old_count, new_start, new_count, lines: patch_lines }, i))
}

fn parse_hunk_header(header: &str) -> Result<(usize, usize, usize, usize), GitDiffError> {
    // Format: @@ -old_start,old_count +new_start,new_count @@
    let err = || GitDiffError::ParseError(format!("Invalid hunk header: {header}"));

    let rest = header.strip_prefix("@@ -").ok_or_else(err)?;
    let at_end = rest.find(" @@").ok_or_else(err)?;
    let range_part = &rest[..at_end];

    let (old_range, new_range) = range_part.split_once(" +").ok_or_else(err)?;

    let (old_start, old_count) = parse_range(old_range).ok_or_else(err)?;
    let (new_start, new_count) = parse_range(new_range).ok_or_else(err)?;

    Ok((old_start, old_count, new_start, new_count))
}

fn parse_range(s: &str) -> Option<(usize, usize)> {
    if let Some((start, count)) = s.split_once(',') {
        Some((start.parse().ok()?, count.parse().ok()?))
    } else {
        let start: usize = s.parse().ok()?;
        Some((start, 1))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_modified_file() {
        let input = "\
diff --git a/src/main.rs b/src/main.rs
index abc1234..def5678 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,3 +1,4 @@
 fn main() {
+    println!(\"hello\");
     let x = 1;
 }
";
        let files = parse_unified_diff(input).unwrap();
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].path, "src/main.rs");
        assert_eq!(files[0].status, FileStatus::Modified);
        assert_eq!(files[0].additions(), 1);
        assert_eq!(files[0].deletions(), 0);
        assert!(!files[0].binary);
        assert_eq!(files[0].hunks.len(), 1);
    }

    #[test]
    fn parse_added_file() {
        let input = "\
diff --git a/new_file.txt b/new_file.txt
new file mode 100644
index 0000000..abc1234
--- /dev/null
+++ b/new_file.txt
@@ -0,0 +1,2 @@
+line one
+line two
";
        let files = parse_unified_diff(input).unwrap();
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].path, "new_file.txt");
        assert_eq!(files[0].status, FileStatus::Added);
        assert!(files[0].old_path.is_none());
        assert_eq!(files[0].additions(), 2);
        assert_eq!(files[0].deletions(), 0);
    }

    #[test]
    fn parse_deleted_file() {
        let input = "\
diff --git a/old_file.txt b/old_file.txt
deleted file mode 100644
index abc1234..0000000
--- a/old_file.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-line one
-line two
";
        let files = parse_unified_diff(input).unwrap();
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].path, "old_file.txt");
        assert_eq!(files[0].status, FileStatus::Deleted);
        assert_eq!(files[0].additions(), 0);
        assert_eq!(files[0].deletions(), 2);
    }

    #[test]
    fn parse_renamed_file() {
        let input = "\
diff --git a/old_name.rs b/new_name.rs
similarity index 95%
rename from old_name.rs
rename to new_name.rs
index abc1234..def5678 100644
--- a/old_name.rs
+++ b/new_name.rs
@@ -1,3 +1,3 @@
 fn main() {
-    old();
+    new();
 }
";
        let files = parse_unified_diff(input).unwrap();
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].path, "new_name.rs");
        assert_eq!(files[0].status, FileStatus::Renamed);
        assert_eq!(files[0].old_path.as_deref(), Some("old_name.rs"));
        assert_eq!(files[0].additions(), 1);
        assert_eq!(files[0].deletions(), 1);
    }

    #[test]
    fn parse_hunk_header_tracking() {
        let input = "\
diff --git a/file.rs b/file.rs
index abc..def 100644
--- a/file.rs
+++ b/file.rs
@@ -10,4 +10,5 @@ fn context_label() {
 context
-removed
+added1
+added2
 context
";
        let files = parse_unified_diff(input).unwrap();
        let hunk = &files[0].hunks[0];
        assert_eq!(hunk.old_start, 10);
        assert_eq!(hunk.old_count, 4);
        assert_eq!(hunk.new_start, 10);
        assert_eq!(hunk.new_count, 5);

        // Check line number tracking
        let lines = &hunk.lines;
        // HunkHeader
        assert_eq!(lines[0].kind, PatchLineKind::HunkHeader);
        // context at old=10, new=10
        assert_eq!(lines[1].kind, PatchLineKind::Context);
        assert_eq!(lines[1].old_line_no, Some(10));
        assert_eq!(lines[1].new_line_no, Some(10));
        // removed at old=11
        assert_eq!(lines[2].kind, PatchLineKind::Removed);
        assert_eq!(lines[2].old_line_no, Some(11));
        assert_eq!(lines[2].new_line_no, None);
        // added at new=11
        assert_eq!(lines[3].kind, PatchLineKind::Added);
        assert_eq!(lines[3].old_line_no, None);
        assert_eq!(lines[3].new_line_no, Some(11));
        // added at new=12
        assert_eq!(lines[4].kind, PatchLineKind::Added);
        assert_eq!(lines[4].old_line_no, None);
        assert_eq!(lines[4].new_line_no, Some(12));
        // context at old=12, new=13
        assert_eq!(lines[5].kind, PatchLineKind::Context);
        assert_eq!(lines[5].old_line_no, Some(12));
        assert_eq!(lines[5].new_line_no, Some(13));
    }

    #[test]
    fn parse_meta_line() {
        let input = "\
diff --git a/file.txt b/file.txt
index abc..def 100644
--- a/file.txt
+++ b/file.txt
@@ -1,1 +1,1 @@
-old
\\ No newline at end of file
+new
";
        let files = parse_unified_diff(input).unwrap();
        let hunk = &files[0].hunks[0];
        let meta = hunk.lines.iter().find(|l| l.kind == PatchLineKind::Meta);
        assert!(meta.is_some());
        assert!(meta.unwrap().text.contains("No newline"));
    }

    #[test]
    fn parse_binary_diff() {
        let input = "\
diff --git a/image.png b/image.png
new file mode 100644
index 0000000..abc1234
Binary files /dev/null and b/image.png differ
";
        let files = parse_unified_diff(input).unwrap();
        assert_eq!(files.len(), 1);
        assert!(files[0].binary);
        assert!(files[0].hunks.is_empty());
    }

    #[test]
    fn parse_empty_diff() {
        let files = parse_unified_diff("").unwrap();
        assert!(files.is_empty());
    }

    #[test]
    fn parse_multiple_files() {
        let input = "\
diff --git a/a.rs b/a.rs
index abc..def 100644
--- a/a.rs
+++ b/a.rs
@@ -1,1 +1,1 @@
-old_a
+new_a
diff --git a/b.rs b/b.rs
new file mode 100644
index 0000000..abc1234
--- /dev/null
+++ b/b.rs
@@ -0,0 +1,1 @@
+new_b
";
        let files = parse_unified_diff(input).unwrap();
        assert_eq!(files.len(), 2);
        assert_eq!(files[0].path, "a.rs");
        assert_eq!(files[0].status, FileStatus::Modified);
        assert_eq!(files[1].path, "b.rs");
        assert_eq!(files[1].status, FileStatus::Added);
    }

    #[test]
    fn parse_diff_marker_inside_hunk_line() {
        let input = "\
diff --git a/file.rs b/file.rs
index abc..def 100644
--- a/file.rs
+++ b/file.rs
@@ -1,1 +1,2 @@
 fn main() {
+cannot parse paths from: diff --git /m)
 }
";
        let files = parse_unified_diff(input).unwrap();
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].path, "file.rs");
        assert_eq!(files[0].status, FileStatus::Modified);
        assert_eq!(files[0].additions(), 1);
    }

    #[test]
    fn parse_multiple_hunks() {
        let input = "\
diff --git a/file.rs b/file.rs
index abc..def 100644
--- a/file.rs
+++ b/file.rs
@@ -1,3 +1,3 @@
 fn a() {
-    old_a();
+    new_a();
 }
@@ -10,3 +10,3 @@
 fn b() {
-    old_b();
+    new_b();
 }
";
        let files = parse_unified_diff(input).unwrap();
        assert_eq!(files[0].hunks.len(), 2);
        assert_eq!(files[0].hunks[0].old_start, 1);
        assert_eq!(files[0].hunks[1].old_start, 10);
    }

    #[test]
    fn parse_hunk_header_without_comma() {
        let (start, count, new_start, new_count) = parse_hunk_header("@@ -1 +1 @@ fn main()").unwrap();
        assert_eq!(start, 1);
        assert_eq!(count, 1);
        assert_eq!(new_start, 1);
        assert_eq!(new_count, 1);
    }

    #[test]
    fn file_status_marker() {
        assert_eq!(FileStatus::Modified.marker(), 'M');
        assert_eq!(FileStatus::Added.marker(), 'A');
        assert_eq!(FileStatus::Deleted.marker(), 'D');
        assert_eq!(FileStatus::Renamed.marker(), 'R');
        assert_eq!(FileStatus::Untracked.marker(), '?');
    }

    #[tokio::test]
    async fn build_untracked_text_file() {
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join("hello.txt");
        std::fs::write(&file_path, "line one\nline two\nline three\n").unwrap();

        let diff = build_untracked_file_diff(dir.path(), "hello.txt".to_string()).await;
        assert_eq!(diff.path, "hello.txt");
        assert!(diff.old_path.is_none());
        assert_eq!(diff.status, FileStatus::Untracked);
        assert!(!diff.binary);
        assert_eq!(diff.hunks.len(), 1);
        assert_eq!(diff.additions(), 3);
        assert_eq!(diff.deletions(), 0);

        let hunk = &diff.hunks[0];
        assert_eq!(hunk.old_start, 0);
        assert_eq!(hunk.old_count, 0);
        assert_eq!(hunk.new_start, 1);
        assert_eq!(hunk.new_count, 3);
        assert_eq!(hunk.lines[1].new_line_no, Some(1));
        assert_eq!(hunk.lines[1].text, "line one");
    }

    #[tokio::test]
    async fn build_untracked_binary_file() {
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join("image.bin");
        std::fs::write(&file_path, b"PNG\x00\x00binary data").unwrap();

        let diff = build_untracked_file_diff(dir.path(), "image.bin".to_string()).await;
        assert_eq!(diff.status, FileStatus::Untracked);
        assert!(diff.binary);
        assert!(diff.hunks.is_empty());
    }

    #[tokio::test]
    async fn build_untracked_missing_file() {
        let dir = tempfile::tempdir().unwrap();
        let diff = build_untracked_file_diff(dir.path(), "does_not_exist.txt".to_string()).await;
        assert!(diff.binary);
        assert!(diff.hunks.is_empty());
    }

    async fn init_repo() -> tempfile::TempDir {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path();
        git(path, &["init", "--quiet"]).await.unwrap();
        git(path, &["config", "user.email", "test@example.com"]).await.unwrap();
        git(path, &["config", "user.name", "Test"]).await.unwrap();
        git(path, &["config", "commit.gpgsign", "false"]).await.unwrap();
        dir
    }

    async fn write_file(dir: &Path, name: &str, content: &str) {
        tokio::fs::write(dir.join(name), content).await.unwrap();
    }

    async fn commit_file(dir: &Path, name: &str, content: &str, message: &str) {
        write_file(dir, name, content).await;
        git(dir, &["add", "-A"]).await.unwrap();
        git(dir, &["commit", "--quiet", "-m", message]).await.unwrap();
    }

    fn staged_of(doc: &GitDiffDocument, path: &str) -> StageState {
        doc.files.iter().find(|file| file.path == path).unwrap_or_else(|| panic!("{path} not in diff")).staged
    }

    #[tokio::test]
    async fn stage_toggles_status() {
        let repo = init_repo().await;
        let dir = repo.path();
        commit_file(dir, "a.txt", "one\n", "init").await;
        write_file(dir, "a.txt", "one\ntwo\n").await;

        let doc = load_git_diff(dir, None).await.unwrap();
        assert_eq!(staged_of(&doc, "a.txt"), StageState::Unstaged);

        stage_file(dir, "a.txt").await.unwrap();
        let doc = load_git_diff(dir, None).await.unwrap();
        assert_eq!(staged_of(&doc, "a.txt"), StageState::Staged);

        unstage_file(dir, "a.txt").await.unwrap();
        let doc = load_git_diff(dir, None).await.unwrap();
        assert_eq!(staged_of(&doc, "a.txt"), StageState::Unstaged);
    }

    #[tokio::test]
    async fn stage_all_marks_all_staged() {
        let repo = init_repo().await;
        let dir = repo.path();
        commit_file(dir, "a.txt", "a1\n", "init").await;
        commit_file(dir, "b.txt", "b1\n", "add b").await;
        write_file(dir, "a.txt", "a2\n").await;
        write_file(dir, "b.txt", "b2\n").await;
        write_file(dir, "c.txt", "c1\n").await;

        stage_all(dir).await.unwrap();
        let doc = load_git_diff(dir, None).await.unwrap();
        assert_eq!(staged_of(&doc, "a.txt"), StageState::Staged);
        assert_eq!(staged_of(&doc, "b.txt"), StageState::Staged);
        assert_eq!(staged_of(&doc, "c.txt"), StageState::Staged);
    }

    #[tokio::test]
    async fn commit_creates_commit_and_clears_staged() {
        let repo = init_repo().await;
        let dir = repo.path();
        commit_file(dir, "a.txt", "one\n", "init").await;
        write_file(dir, "a.txt", "one\ntwo\n").await;
        stage_file(dir, "a.txt").await.unwrap();
        commit(dir, "second commit").await.unwrap();
        let log = git(dir, &["log", "--oneline", "-1"]).await.unwrap();
        assert!(log.contains("second commit"), "log was: {log}");

        let doc = load_git_diff(dir, None).await.unwrap();
        assert!(doc.files.is_empty(), "expected clean tree, got {} files", doc.files.len());
    }

    #[tokio::test]
    async fn discard_reverts_tracked_file() {
        let repo = init_repo().await;
        let dir = repo.path();
        commit_file(dir, "a.txt", "v1\n", "init").await;
        write_file(dir, "a.txt", "v2\n").await;
        discard_file(dir, "a.txt", FileStatus::Modified).await.unwrap();
        let content = tokio::fs::read_to_string(dir.join("a.txt")).await.unwrap();
        assert_eq!(content, "v1\n");
    }

    #[tokio::test]
    async fn discard_removes_untracked_file() {
        let repo = init_repo().await;
        let dir = repo.path();
        commit_file(dir, "a.txt", "a1\n", "init").await;
        write_file(dir, "new.txt", "scratch\n").await;
        discard_file(dir, "new.txt", FileStatus::Untracked).await.unwrap();
        assert!(!dir.join("new.txt").exists());
    }

    #[tokio::test]
    async fn commit_with_empty_message_is_rejected() {
        let repo = init_repo().await;
        assert!(commit(repo.path(), "   ").await.is_err());
    }

    #[tokio::test]
    async fn unstage_on_unborn_branch_untracks_file() {
        let repo = init_repo().await;
        let dir = repo.path();
        write_file(dir, "a.txt", "hi\n").await;
        git(dir, &["add", "a.txt"]).await.unwrap();
        unstage_file(dir, "a.txt").await.unwrap();
        let status = git(dir, &["status", "--porcelain"]).await.unwrap();
        assert!(status.contains("?? a.txt"), "status was: {status}");
    }

    #[test]
    fn parse_porcelain_status_handles_rename() {
        let map = parse_porcelain_status("R  new.txt\0old.txt\0 M other.txt\0");
        assert_eq!(map.get("new.txt"), Some(&StageState::Staged));
        assert_eq!(map.get("old.txt"), None);
        assert_eq!(map.get("other.txt"), Some(&StageState::Unstaged));
    }

    #[test]
    fn parse_porcelain_status_classifies_states() {
        let map = parse_porcelain_status("M  staged.txt\0 M unstaged.txt\0MM partial.txt\0?? untracked.txt\0");
        assert_eq!(map.get("staged.txt"), Some(&StageState::Staged));
        assert_eq!(map.get("unstaged.txt"), Some(&StageState::Unstaged));
        assert_eq!(map.get("partial.txt"), Some(&StageState::PartiallyStaged));
        assert_eq!(map.get("untracked.txt"), Some(&StageState::Unstaged));
    }
}