git-custom-cli 2.4.0

Fast, keyboard-driven terminal UI for dated Git commits
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
//! Ignore mode: edit the repo-root .gitignore, add templates, stop tracking files, explain
//! why a path is ignored, and a plain-English git glossary.

use crate::git::{self, Opts};
use crate::policy::{self, Op};
use crate::{explain, model::Config, screen, ui};
use anyhow::{bail, Context, Result};
use std::path::PathBuf;

// ---------------------------------------------------------------- pure functions

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PatternKind {
    Exact,
    Extension,
    Folder,
}

/// Builds a .gitignore pattern for `path` (backslashes become `/`).
/// Exact: `/path`, Extension: `*.ext`, Folder: `dir/`. A trailing `/` on `path` marks a folder.
/// Kinds that do not apply (no extension, no parent folder) fall back to a sensible neighbour.
pub fn pattern_for(path: &str, kind: PatternKind) -> String {
    let mut p = path.trim().replace('\\', "/");
    while let Some(rest) = p.strip_prefix("./") {
        p = rest.to_string();
    }
    let p = p.trim_start_matches('/');
    let is_dir = p.ends_with('/');
    let p = p.trim_end_matches('/');
    let exact = || format!("/{p}{}", if is_dir { "/" } else { "" });
    let name = p.rsplit('/').next().unwrap_or(p);
    match kind {
        PatternKind::Exact => exact(),
        PatternKind::Extension => match name.rfind('.') {
            Some(dot) if dot > 0 && dot + 1 < name.len() && !is_dir => {
                format!("*{}", &name[dot..])
            }
            _ if is_dir => format!("{p}/"),
            _ => exact(),
        },
        PatternKind::Folder => {
            if is_dir {
                format!("{p}/")
            } else {
                match p.rfind('/') {
                    Some(slash) => format!("{}/", &p[..slash]),
                    None => exact(),
                }
            }
        }
    }
}

fn is_pattern(line: &str) -> bool {
    let t = line.trim();
    !t.is_empty() && !t.starts_with('#')
}

/// Appends `new` lines to `existing`, skipping patterns already present. Keeps the file's EOL
/// style (CRLF or LF), ends with a newline, and separates a leading `#` comment of the new
/// block from the old content with a blank line. Returns the text unchanged (plus a trailing
/// newline) when nothing new would be added.
pub fn merge_gitignore(existing: &str, new: &[String]) -> String {
    let eol = if existing.contains("\r\n") {
        "\r\n"
    } else {
        "\n"
    };
    let mut seen: Vec<&str> = existing
        .lines()
        .filter(|l| is_pattern(l))
        .map(str::trim)
        .collect();
    let mut kept: Vec<&str> = Vec::new();
    for line in new {
        let line = line.trim_end_matches(['\r', '\n']);
        if is_pattern(line) {
            if seen.contains(&line.trim()) {
                continue;
            }
            seen.push(line.trim());
        }
        kept.push(line);
    }
    while kept.last().is_some_and(|l| l.trim().is_empty()) {
        kept.pop();
    }
    while kept.first().is_some_and(|l| l.trim().is_empty()) {
        kept.remove(0);
    }
    let mut out = existing.to_string();
    if !out.is_empty() && !out.ends_with('\n') {
        out.push_str(eol);
    }
    if !kept.iter().any(|l| is_pattern(l)) {
        return out;
    }
    let last_blank = out.lines().last().is_none_or(|l| l.trim().is_empty());
    if !last_blank
        && kept
            .first()
            .is_some_and(|l| l.trim_start().starts_with('#'))
    {
        out.push_str(eol);
    }
    for line in kept {
        out.push_str(line);
        out.push_str(eol);
    }
    out
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IgnoreMatch {
    pub source: String,
    pub line: u32,
    pub pattern: String,
    pub path: String,
}

/// Parses `git check-ignore -v -- <path>` output (`source:line:pattern<TAB>path`).
pub fn parse_check_ignore(output: &str) -> Option<IgnoreMatch> {
    let first = output.lines().find(|l| !l.trim().is_empty())?;
    let (left, path) = first.split_once('\t')?;
    let bytes = left.as_bytes();
    // First ":<digits>:" (a Windows drive colon is never followed by digits).
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b':' {
            let digits = bytes[i + 1..]
                .iter()
                .take_while(|b| b.is_ascii_digit())
                .count();
            if digits > 0 && bytes.get(i + 1 + digits) == Some(&b':') {
                let line = left[i + 1..i + 1 + digits].parse().ok()?;
                return Some(IgnoreMatch {
                    source: left[..i].to_string(),
                    line,
                    pattern: left[i + 2 + digits..].to_string(),
                    path: path.trim_end_matches('\r').to_string(),
                });
            }
        }
        i += 1;
    }
    None
}

const RUST: &str = "/target/\n**/*.rs.bk\n";
const NODE: &str = "node_modules/\nnpm-debug.log*\nyarn-error.log*\n.npm/\ndist/\n.next/\ncoverage/\n*.tsbuildinfo\n";
const PYTHON: &str = "__pycache__/\n*.py[cod]\n.venv/\nvenv/\n*.egg-info/\n.pytest_cache/\n.mypy_cache/\nbuild/\ndist/\n";
const VSCODE: &str = ".vscode/*\n!.vscode/settings.json\n!.vscode/tasks.json\n!.vscode/launch.json\n!.vscode/extensions.json\n*.code-workspace\n";
const VISUALSTUDIO: &str =
    ".vs/\nbin/\nobj/\n*.user\n*.suo\n*.userprefs\n*.rsuser\n[Dd]ebug/\n[Rr]elease/\n";
const JETBRAINS: &str = ".idea/\n*.iml\n*.iws\ncmake-build-*/\n";
const MACOS: &str = ".DS_Store\n.AppleDouble\n.LSOverride\n._*\n.Trashes\n";
const WINDOWS: &str = "Thumbs.db\nehthumbs.db\nDesktop.ini\n$RECYCLE.BIN/\n*.lnk\n";
const SECRETS: &str = ".env\n.env.*\n!.env.example\n*.pem\n*.key\nsecrets.*\ncredentials.json\n";

const TEMPLATES: &[(&str, &str)] = &[
    ("Rust", RUST),
    ("Node", NODE),
    ("Python", PYTHON),
    ("VSCode", VSCODE),
    ("VisualStudio", VISUALSTUDIO),
    ("JetBrains", JETBRAINS),
    ("macOS", MACOS),
    ("Windows", WINDOWS),
    ("Secrets (.env)", SECRETS),
];

/// Names of the built-in templates, in menu order.
pub fn template_names() -> Vec<&'static str> {
    TEMPLATES.iter().map(|(name, _)| *name).collect()
}

/// The built-in template body (newline-terminated). Case-insensitive; `.env` and `secrets` work too.
pub fn template(name: &str) -> Option<&'static str> {
    let name = name.trim();
    let name = if name.eq_ignore_ascii_case(".env") || name.eq_ignore_ascii_case("secrets") {
        "Secrets (.env)"
    } else {
        name
    };
    TEMPLATES
        .iter()
        .find(|(n, _)| n.eq_ignore_ascii_case(name))
        .map(|(_, body)| *body)
}

/// Untracked paths (entries starting `?? `) from `git status --porcelain=v1 -z` output.
fn parse_untracked(raw: &[u8]) -> Vec<String> {
    raw.split(|b| *b == 0)
        .filter_map(|entry| entry.strip_prefix(b"?? "))
        .map(|p| String::from_utf8_lossy(p).into_owned())
        .collect()
}

fn wrap(text: &str, width: usize) -> Vec<String> {
    let mut lines = Vec::new();
    let mut cur = String::new();
    for word in text.split_whitespace() {
        if !cur.is_empty() && cur.chars().count() + 1 + word.chars().count() > width {
            lines.push(std::mem::take(&mut cur));
        }
        if !cur.is_empty() {
            cur.push(' ');
        }
        cur.push_str(word);
    }
    if !cur.is_empty() {
        lines.push(cur);
    }
    lines
}

// ---------------------------------------------------------------- executors

const LITERAL: &[(&str, &str)] = &[("GIT_LITERAL_PATHSPECS", "1")];

fn repo_root() -> Result<String> {
    Ok(
        git::git_ok(&["rev-parse", "--show-toplevel"], &Opts::default())?
            .trim()
            .to_string(),
    )
}

/// Runs `git -C <repo root> <args>`. Every path in this mode is root-relative (patterns go into
/// the root .gitignore), so git must not resolve them against a subfolder.
fn in_root(args: &[&str], literal: bool) -> Result<git::Out> {
    let root = repo_root()?;
    let mut full = vec!["-C", root.as_str()];
    full.extend_from_slice(args);
    git::git_raw(
        &full,
        &Opts {
            env: if literal { LITERAL } else { &[] },
            ..Opts::default()
        },
    )
}

fn gitignore_path() -> Result<PathBuf> {
    Ok(PathBuf::from(repo_root()?).join(".gitignore"))
}

fn read_gitignore() -> Result<(PathBuf, String)> {
    let path = gitignore_path()?;
    let text = match std::fs::read(&path) {
        Ok(bytes) => {
            String::from_utf8(bytes).context(".gitignore is not valid UTF-8; edit it by hand")?
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(e) => return Err(e).context("could not read .gitignore"),
    };
    Ok((path, text))
}

/// Merges `lines` into the repo-root .gitignore (created if missing). Returns the patterns
/// that were actually added (already-present ones are skipped).
pub fn add_lines(lines: &[String]) -> Result<Vec<String>> {
    let (path, existing) = read_gitignore()?;
    let merged = merge_gitignore(&existing, lines);
    let before: Vec<&str> = existing.lines().collect();
    let added: Vec<String> = merged
        .lines()
        .skip(before.len())
        .filter(|l| is_pattern(l))
        .map(str::to_string)
        .collect();
    if merged != existing {
        std::fs::write(&path, merged).context("could not write .gitignore")?;
    }
    Ok(added)
}

/// Ignores exactly `path`. Returns the pattern when it was added, `None` if already ignored there.
pub fn ignore_exact(path: &str) -> Result<Option<String>> {
    let pattern = pattern_for(path, PatternKind::Exact);
    Ok(add_lines(std::slice::from_ref(&pattern))?.pop())
}

/// Stops tracking `path` (file stays on disk) and adds it to .gitignore.
pub fn untrack(path: &str) -> Result<Option<String>> {
    if path.starts_with('-') {
        bail!("path cannot start with '-'");
    }
    let out = in_root(&["rm", "--cached", "-q", "--", path], true)?;
    if !out.ok() {
        bail!("{}", out.stderr.trim());
    }
    ignore_exact(path)
}

fn tracked_files() -> Result<Vec<String>> {
    let out = in_root(&["ls-files", "-z"], false)?;
    Ok(out
        .stdout
        .split(|b| *b == 0)
        .filter(|p| !p.is_empty())
        .map(|p| String::from_utf8_lossy(p).into_owned())
        .collect())
}

fn untracked_files() -> Result<Vec<String>> {
    let out = in_root(&["status", "--porcelain=v1", "-z", "-unormal"], false)?;
    Ok(parse_untracked(&out.stdout))
}

fn check_ignored(path: &str) -> Result<Option<IgnoreMatch>> {
    if path.starts_with('-') {
        bail!("path cannot start with '-'");
    }
    let out = in_root(&["check-ignore", "-v", "--", path], false)?;
    Ok(parse_check_ignore(&out.text()).filter(|m| !m.pattern.starts_with('!')))
}

// ---------------------------------------------------------------- UI

/// Entry point called by the mode router (`modes::run_mode`) inside an active terminal UI.
pub fn run(config: &mut Config) -> Result<()> {
    let options = [
        "Ignore untracked files",
        "Add a template (Rust, Node, Python, ...)",
        "Stop tracking a committed file",
        "Why is this file ignored?",
        "View .gitignore",
        "Git glossary (what do these words mean?)",
    ];
    let context = vec![screen::muted("Tell git which files to leave alone")];
    while let Some(choice) = ui::choose("Ignore", &context, &options)? {
        match choice {
            0 => ignore_untracked(config)?,
            1 => add_template(config)?,
            2 => untrack_flow(config)?,
            3 => why_ignored(config)?,
            4 => view_gitignore()?,
            _ => glossary()?,
        }
    }
    Ok(())
}

/// Adds `path` to .gitignore (cross-mode entry point).
pub fn ignore_path(cfg: &mut Config, path: &str) -> Result<()> {
    let mut lines = match ignore_exact(path)? {
        Some(p) => vec![format!("Added to .gitignore: {p}")],
        None => vec!["That path is already in .gitignore.".to_string()],
    };
    lines.push(
        "Files git already tracks stay tracked: use 'Stop tracking a committed file'.".into(),
    );
    lines.extend(ui::explain(
        cfg,
        &["A .gitignore line tells git to leave matching files alone."],
    ));
    ui::notice("Ignore", &lines)
}

fn ignore_untracked(cfg: &Config) -> Result<()> {
    let files = untracked_files()?;
    if files.is_empty() {
        return ui::notice(
            "Ignore",
            &["No untracked files. Nothing to ignore right now.".into()],
        );
    }
    let mut checked = vec![false; files.len()];
    if !ui::check_list(
        "Untracked files to ignore (Space ticks, Enter confirms)",
        &files,
        &mut checked,
    )? {
        return Ok(());
    }
    let mut patterns = Vec::new();
    for file in files
        .iter()
        .zip(&checked)
        .filter(|(_, c)| **c)
        .map(|(f, _)| f)
    {
        let ctx = vec![format!("Ignore: {file}")];
        let kinds = [
            PatternKind::Exact,
            PatternKind::Extension,
            PatternKind::Folder,
        ];
        let labels: Vec<String> = kinds
            .iter()
            .map(|k| {
                let p = pattern_for(file, *k);
                match k {
                    PatternKind::Exact => format!("Exactly this file ({p})"),
                    PatternKind::Extension => format!("All files with this extension ({p})"),
                    PatternKind::Folder => format!("The whole folder ({p})"),
                }
            })
            .collect();
        let refs: Vec<&str> = labels.iter().map(String::as_str).collect();
        if let Some(i) = ui::choose("Ignore how?", &ctx, &refs)? {
            patterns.push(pattern_for(file, kinds[i]));
        }
    }
    if patterns.is_empty() {
        return Ok(());
    }
    let added = add_lines(&patterns)?;
    let mut lines = if added.is_empty() {
        vec!["Those patterns were already in .gitignore.".to_string()]
    } else {
        added.iter().map(|p| format!("Added: {p}")).collect()
    };
    lines.extend(ui::explain(
        cfg,
        &["Ignored files no longer show up as untracked."],
    ));
    ui::notice("Ignore", &lines)
}

fn add_template(cfg: &Config) -> Result<()> {
    let names = template_names();
    let items: Vec<String> = names.iter().map(|n| n.to_string()).collect();
    let mut index = 0;
    let Some(i) = ui::pick_list("Add a .gitignore template", &items, &mut index, "")? else {
        return Ok(());
    };
    let Some(body) = template(names[i]) else {
        return Ok(());
    };
    let mut lines = vec![String::new(), format!("# {} (added by gct)", names[i])];
    lines.extend(body.lines().map(str::to_string));
    let added = add_lines(&lines)?;
    let mut out = if added.is_empty() {
        vec![format!(
            "The {} template was already fully in .gitignore.",
            names[i]
        )]
    } else {
        vec![format!(
            "Added {} line(s) from the {} template.",
            added.len(),
            names[i]
        )]
    };
    out.extend(ui::explain(
        cfg,
        &["Existing lines are never duplicated or removed."],
    ));
    ui::notice("Ignore", &out)
}

fn untrack_flow(cfg: &Config) -> Result<()> {
    let files = tracked_files()?;
    if files.is_empty() {
        return ui::notice("Ignore", &["No tracked files in this repository.".into()]);
    }
    let filter = ui::ask("Filter files (empty = all)", "")?
        .unwrap_or_default()
        .to_lowercase();
    let shown: Vec<String> = files
        .into_iter()
        .filter(|f| f.to_lowercase().contains(&filter))
        .collect();
    if shown.is_empty() {
        return ui::notice("Ignore", &["No tracked file matches that filter.".into()]);
    }
    let mut index = 0;
    let Some(i) = ui::pick_list("Stop tracking which file?", &shown, &mut index, "")? else {
        return Ok(());
    };
    let path = &shown[i];
    let command = format!("git rm --cached -- {path}");
    let what = format!(
        "Stop tracking {path}? The file stays on your disk but is removed from the repository on your next commit, and teammates lose it when they pull."
    );
    if !ui::gate(
        cfg,
        &policy::check(cfg, &Op::CreatesCommit),
        &what,
        &command,
    )? {
        return Ok(());
    }
    let added = untrack(path)?;
    let mut lines = vec![
        format!("$ {command}"),
        format!("{path} is no longer tracked (still on disk)."),
    ];
    match added {
        Some(p) => lines.push(format!("Added to .gitignore: {p}")),
        None => lines.push("It was already listed in .gitignore.".into()),
    }
    lines.push("Commit the change to finish removing it from the repository.".into());
    lines.extend(ui::explain(
        cfg,
        &["The removal only becomes official once you commit."],
    ));
    ui::notice("Ignore", &lines)
}

fn why_ignored(cfg: &mut Config) -> Result<()> {
    let Some(path) = ui::ask("Path to check (from the repo root)", "")? else {
        return Ok(());
    };
    let path = path.trim().to_string();
    if path.is_empty() {
        return Ok(());
    }
    let lines = match check_ignored(&path)? {
        Some(m) => vec![
            format!("{} is ignored.", m.path),
            format!("Rule: {}", m.pattern),
            format!("From: {} line {}", m.source, m.line),
        ],
        None => {
            let tracked = in_root(&["ls-files", "--", &path], true)?;
            let mut l = vec![format!("{path} is not ignored.")];
            if !tracked.stdout.is_empty() {
                l.push("It is tracked, and ignore rules never apply to tracked files.".into());
                l.push("Use 'Stop tracking a committed file' to change that.".into());
            } else {
                ui::notice("Why is this file ignored?", &l)?;
                let ctx = vec![format!("Add {path} to .gitignore?")];
                return match ui::choose("Ignore it now?", &ctx, &["Yes, ignore this path", "No"])? {
                    Some(0) => ignore_path(cfg, &path),
                    _ => Ok(()),
                };
            }
            l
        }
    };
    ui::notice("Why is this file ignored?", &lines)
}

fn view_gitignore() -> Result<()> {
    let (path, text) = read_gitignore()?;
    if text.is_empty() {
        return ui::notice(
            ".gitignore",
            &[
                format!("{} is empty or missing.", path.display()),
                "Add a template or ignore some files first.".into(),
            ],
        );
    }
    let lines: Vec<String> = text.lines().map(str::to_string).collect();
    ui::pager(".gitignore", &lines, "")
}

fn glossary() -> Result<()> {
    let query = ui::ask("Search the glossary (empty = all)", "")?;
    let Some(query) = query else {
        return Ok(());
    };
    let hits = explain::search(&query);
    if hits.is_empty() {
        return ui::notice(
            "Glossary",
            &[format!("No term matches '{}'.", query.trim())],
        );
    }
    let items: Vec<String> = hits.iter().map(|(t, _)| t.to_string()).collect();
    let mut index = 0;
    while let Some(i) = ui::pick_list("Git glossary", &items, &mut index, "")? {
        let (term, def) = hits[i];
        let mut lines = wrap(def, 70);
        lines.insert(0, String::new());
        ui::notice(term, &lines)?;
    }
    Ok(())
}

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

    #[test]
    fn pattern_table() {
        use PatternKind::*;
        let cases = [
            ("a.txt", Exact, "/a.txt"),
            ("src\\gen\\x.log", Exact, "/src/gen/x.log"),
            ("./a.txt", Exact, "/a.txt"),
            ("build/", Exact, "/build/"),
            ("src/x.log", Extension, "*.log"),
            ("archive.tar.gz", Extension, "*.gz"),
            ("Makefile", Extension, "/Makefile"),
            (".env", Extension, "/.env"),
            ("target/", Extension, "target/"),
            ("src/gen/x.log", Folder, "src/gen/"),
            ("build/", Folder, "build/"),
            ("x.log", Folder, "/x.log"),
            ("dir\\sub\\f.rs", Folder, "dir/sub/"),
        ];
        for (path, kind, want) in cases {
            assert_eq!(pattern_for(path, kind), want, "{path} {kind:?}");
        }
    }

    fn s(v: &[&str]) -> Vec<String> {
        v.iter().map(|x| x.to_string()).collect()
    }

    #[test]
    fn merge_basics() {
        assert_eq!(merge_gitignore("", &s(&["/a"])), "/a\n");
        assert_eq!(merge_gitignore("/a", &s(&["/b"])), "/a\n/b\n");
        assert_eq!(merge_gitignore("/a\n", &s(&["/a", "/b", "/b"])), "/a\n/b\n");
        assert_eq!(merge_gitignore("/a", &s(&["/a"])), "/a\n");
        assert_eq!(merge_gitignore("", &s(&[])), "");
    }

    #[test]
    fn merge_keeps_crlf() {
        assert_eq!(
            merge_gitignore("/a\r\n/b\r\n", &s(&["/c"])),
            "/a\r\n/b\r\n/c\r\n"
        );
        assert_eq!(
            merge_gitignore("/a\r\n/b", &s(&["/c"])),
            "/a\r\n/b\r\n/c\r\n"
        );
    }

    #[test]
    fn merge_section_comment_gets_blank_line() {
        let out = merge_gitignore("/a\n", &s(&["# Rust", "/target/"]));
        assert_eq!(out, "/a\n\n# Rust\n/target/\n");
        // Comment alone is not added when every pattern is a duplicate.
        assert_eq!(
            merge_gitignore("/target/\n", &s(&["# Rust", "/target/"])),
            "/target/\n"
        );
        // Already blank-terminated: no second blank line.
        assert_eq!(
            merge_gitignore("/a\n\n", &s(&["# T", "/b"])),
            "/a\n\n# T\n/b\n"
        );
    }

    #[test]
    fn check_ignore_parsing() {
        let m = parse_check_ignore(".gitignore:3:*.log\tsrc/x.log\n").unwrap();
        assert_eq!(
            (
                m.source.as_str(),
                m.line,
                m.pattern.as_str(),
                m.path.as_str()
            ),
            (".gitignore", 3, "*.log", "src/x.log")
        );
        let m = parse_check_ignore("C:/Users/me/.config/git/ignore:12:/a:b\tz\r\n").unwrap();
        assert_eq!(
            (m.source.as_str(), m.line, m.pattern.as_str()),
            ("C:/Users/me/.config/git/ignore", 12, "/a:b")
        );
        assert_eq!(parse_check_ignore(""), None);
        assert_eq!(parse_check_ignore("garbage"), None);
    }

    #[test]
    fn templates_are_valid() {
        assert!(template_names().len() >= 8);
        for name in template_names() {
            let body = template(name).unwrap();
            assert!(!body.trim().is_empty() && body.ends_with('\n'), "{name}");
        }
        assert!(template("rust").is_some() && template(".env").is_some());
        assert!(template("cobol").is_none());
    }

    #[test]
    fn untracked_parsing() {
        let raw = b"?? new file.txt\0 M a.txt\0?? dir/\0";
        assert_eq!(parse_untracked(raw), ["new file.txt", "dir/"]);
    }

    #[test]
    fn ignore_path_hides_file_from_status() {
        let repo = TempRepo::new(1);
        repo.write("junk.log", "x");
        assert!(repo.git(&["status", "--porcelain"]).contains("junk.log"));
        let added = repo.run(|| ignore_exact("junk.log")).unwrap();
        assert_eq!(added.as_deref(), Some("/junk.log"));
        assert!(!repo.git(&["status", "--porcelain"]).contains("junk.log"));
        assert_eq!(repo.run(|| ignore_exact("junk.log")).unwrap(), None);
        let hit = repo.run(|| check_ignored("junk.log")).unwrap().unwrap();
        assert_eq!(hit.pattern, "/junk.log");
    }

    #[test]
    fn untrack_keeps_disk_file() {
        let repo = TempRepo::new(2);
        let added = repo.run(|| untrack("f1.txt")).unwrap();
        assert_eq!(added.as_deref(), Some("/f1.txt"));
        assert!(repo.path().join("f1.txt").exists());
        assert!(!repo.git(&["ls-files"]).contains("f1.txt"));
        assert!(repo.git(&["ls-files"]).contains("f2.txt"));
        assert!(repo.run(|| untrack("-bad")).is_err());
    }

    #[test]
    fn merge_into_existing_crlf_file() {
        let repo = TempRepo::new(1);
        repo.write(".gitignore", "/old\r\n");
        let lines = s(&["", "# Rust (added by gct)", "/target/"]);
        let added = repo.run(|| add_lines(&lines)).unwrap();
        assert_eq!(added, ["/target/"]);
        let text = std::fs::read_to_string(repo.path().join(".gitignore")).unwrap();
        assert_eq!(text, "/old\r\n\r\n# Rust (added by gct)\r\n/target/\r\n");
        assert!(!text.replace("\r\n", "").contains('\n'));
    }

    #[test]
    fn ignore_and_untrack_from_a_subfolder_use_root_paths() {
        let repo = TempRepo::new(1);
        repo.write("same.log", "root");
        repo.write("sub/same.log", "sub");
        repo.write("sub/keep.txt", "k");
        repo.git(&["add", "f1.txt"]);
        let in_sub = |f: &dyn Fn()| crate::git::with_ctx(&repo.path().join("sub"), repo.env(), f);
        in_sub(&|| {
            assert_eq!(
                ignore_exact("same.log").unwrap().as_deref(),
                Some("/same.log")
            )
        });
        let text = std::fs::read_to_string(repo.path().join(".gitignore")).unwrap();
        assert_eq!(text, "/same.log\n");
        assert!(!repo.path().join("sub/.gitignore").exists());
        let status = repo.git(&["status", "--porcelain", "-uall"]);
        assert!(
            status.contains("sub/same.log") && !status.contains("?? same.log"),
            "{status}"
        );
        in_sub(&|| {
            assert!(untracked_files().unwrap().contains(&"sub/".to_string()));
            assert!(tracked_files().unwrap().contains(&"f1.txt".to_string()));
            assert!(check_ignored("same.log").unwrap().is_some());
            assert!(check_ignored("sub/same.log").unwrap().is_none());
            assert_eq!(untrack("f1.txt").unwrap().as_deref(), Some("/f1.txt"));
        });
        assert!(!repo.git(&["ls-files"]).contains("f1.txt"));
        assert!(repo.path().join("sub/same.log").exists());
    }

    #[test]
    fn wraps_text() {
        assert_eq!(wrap("aa bb cc", 5), ["aa bb", "cc"]);
        assert!(wrap("", 10).is_empty());
    }
}