lds-git 0.13.0

Git module for local-develop-server (lds) — git2-rs backed read/write with session-scoped write safety
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
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
use std::path::Path;
use std::process::Command;
use std::sync::Arc;

use lds_core::{Session, SessionConfig};
use lds_git::{GitModule, LogFilters, OtherStagedMode, ResetMode};

fn init_temp_repo(dir: &Path) {
    let run = |args: &[&str]| {
        Command::new("git")
            .args(args)
            .current_dir(dir)
            .output()
            .unwrap();
    };
    run(&["init", "-b", "main"]);
    run(&["config", "user.email", "test@test.com"]);
    run(&["config", "user.name", "Test"]);
    std::fs::write(dir.join("README.md"), "init\n").unwrap();
    run(&["add", "."]);
    run(&["commit", "-m", "initial"]);
    std::fs::create_dir_all(dir.join(".worktrees")).unwrap();
}

fn make_session(root: &Path) -> Arc<Session> {
    Arc::new(
        Session::new(SessionConfig {
            root: root.to_path_buf(),
            timeout_secs: Some(30),
            ..Default::default()
        })
        .unwrap(),
    )
}

#[test]
fn worktree_lifecycle() {
    let tmp = tempfile::tempdir().unwrap();
    init_temp_repo(tmp.path());
    let session = make_session(tmp.path());
    let mut git = GitModule::new(session);

    // worktree_list: only main worktree, not owned by us yet.
    let list = git.worktree_list().unwrap();
    assert_eq!(list.worktrees.len(), 1);
    assert!(!list.worktrees[0].owned);

    // worktree_add
    let add_result = git
        .worktree_add("test-wt", "feat/test", Some("main"))
        .unwrap();
    assert!(add_result.path.ends_with("test-wt"));
    assert_eq!(add_result.branch, "feat/test");

    // worktree_list: the new worktree is now owned.
    let list = git.worktree_list().unwrap();
    assert!(
        list.worktrees.iter().any(|w| w.owned),
        "expected at least one owned worktree, got: {list:?}"
    );

    // commit in worktree
    let wt_path = tmp.path().join(".worktrees/test-wt");
    std::fs::write(wt_path.join("new_file.txt"), "content\n").unwrap();
    let commit_result = git
        .commit(&wt_path, "test commit", None, OtherStagedMode::Stop, false)
        .unwrap();
    assert_eq!(commit_result.sha.len(), 40, "expected full SHA-1");
    assert_eq!(commit_result.message, "test commit");
    assert_eq!(commit_result.files_changed, 1);

    // merge back to main
    let merge_result = git.merge("feat/test", "main", tmp.path()).unwrap();
    assert_eq!(merge_result.branch, "feat/test");
    assert_eq!(merge_result.into_branch, "main");
    assert_eq!(merge_result.sha.len(), 40);

    // worktree_remove
    let remove_result = git.worktree_remove("test-wt").unwrap();
    assert!(remove_result.path.ends_with("test-wt"));

    // branch_delete
    let delete_result = git.branch_delete("feat/test").unwrap();
    assert_eq!(delete_result.branch, "feat/test");

    // verify merge landed: new_file.txt should exist in main
    assert!(tmp.path().join("new_file.txt").exists());

    // git log should show the merge commit
    let log = git
        .log(LogFilters {
            max_count: 5,
            ..Default::default()
        })
        .unwrap();
    assert!(
        log.commits
            .iter()
            .any(|c| c.summary.contains("Merge branch")),
        "expected a 'Merge branch' commit in log, got: {log:?}"
    );
}

#[test]
fn log_filters_by_author_paths_and_since() {
    let tmp = tempfile::tempdir().unwrap();
    let dir = tmp.path();
    let run = |args: &[&str]| {
        Command::new("git")
            .args(args)
            .current_dir(dir)
            .output()
            .expect("git");
    };
    run(&["init", "-b", "main"]);
    run(&["config", "user.email", "alice@example.com"]);
    run(&["config", "user.name", "Alice"]);

    std::fs::write(dir.join("a.txt"), "1\n").unwrap();
    run(&["add", "."]);
    run(&["commit", "-m", "add a.txt"]);

    // Rewrite the second commit under Bob.
    run(&["config", "user.email", "bob@example.com"]);
    run(&["config", "user.name", "Bob"]);
    std::fs::write(dir.join("b.txt"), "2\n").unwrap();
    run(&["add", "."]);
    run(&["commit", "-m", "add b.txt"]);

    // Third commit — Alice again — touches only a.txt.
    run(&["config", "user.email", "alice@example.com"]);
    run(&["config", "user.name", "Alice"]);
    std::fs::write(dir.join("a.txt"), "1\n2\n").unwrap();
    run(&["add", "."]);
    run(&["commit", "-m", "update a.txt"]);

    std::fs::create_dir_all(dir.join(".worktrees")).unwrap();
    let session = make_session(dir);
    let git = GitModule::new(session);

    // author filter — only Bob's commit survives.
    let bob_only = git
        .log(LogFilters {
            max_count: 10,
            author: Some("Bob".to_string()),
            ..Default::default()
        })
        .unwrap();
    assert_eq!(bob_only.commits.len(), 1);
    assert_eq!(bob_only.commits[0].summary, "add b.txt");
    assert!(bob_only.commits[0].author.contains("bob@example.com"));

    // path filter — commits touching b.txt (only the second).
    let touches_b = git
        .log(LogFilters {
            max_count: 10,
            paths: Some(vec!["b.txt".to_string()]),
            ..Default::default()
        })
        .unwrap();
    assert_eq!(touches_b.commits.len(), 1);
    assert_eq!(touches_b.commits[0].summary, "add b.txt");

    // path filter — commits touching a.txt (first + third).
    let touches_a = git
        .log(LogFilters {
            max_count: 10,
            paths: Some(vec!["a.txt".to_string()]),
            ..Default::default()
        })
        .unwrap();
    assert_eq!(touches_a.commits.len(), 2);

    // since filter — cutoff after the third commit's author time drops all.
    let head_ts = touches_a.commits[0].timestamp;
    let none = git
        .log(LogFilters {
            max_count: 10,
            since: Some(head_ts + 1),
            ..Default::default()
        })
        .unwrap();
    assert_eq!(none.commits.len(), 0);

    // max_count is applied post-filter.
    let capped = git
        .log(LogFilters {
            max_count: 1,
            author: Some("Alice".to_string()),
            ..Default::default()
        })
        .unwrap();
    assert_eq!(capped.commits.len(), 1);

    // grep filter — matches subject substring only.
    let updates = git
        .log(LogFilters {
            max_count: 10,
            grep: Some("update".to_string()),
            ..Default::default()
        })
        .unwrap();
    assert_eq!(updates.commits.len(), 1);
    assert_eq!(updates.commits[0].summary, "update a.txt");

    let no_match = git
        .log(LogFilters {
            max_count: 10,
            grep: Some("does-not-appear".to_string()),
            ..Default::default()
        })
        .unwrap();
    assert_eq!(no_match.commits.len(), 0);

    // metadata fields are populated.
    let head = &touches_a.commits[0];
    assert_eq!(head.sha.len(), 40);
    assert_eq!(head.short_sha.len(), 7);
    assert!(head.author.starts_with("Alice <"));
    assert!(head.timestamp > 0);
}

#[test]
fn ownership_guard_rejects_unowned_worktree() {
    let tmp = tempfile::tempdir().unwrap();
    init_temp_repo(tmp.path());
    let session = make_session(tmp.path());
    let git = GitModule::new(session);

    // create a worktree outside of GitModule (simulating another session)
    Command::new("git")
        .args([
            "worktree",
            "add",
            "-b",
            "other/branch",
            tmp.path().join(".worktrees/foreign").to_str().unwrap(),
            "main",
        ])
        .current_dir(tmp.path())
        .output()
        .unwrap();

    let foreign_path = tmp.path().join(".worktrees/foreign");

    // commit to unowned worktree should fail
    std::fs::write(foreign_path.join("file.txt"), "x").unwrap();
    let err = git.commit(
        &foreign_path,
        "bad commit",
        None,
        OtherStagedMode::Stop,
        false,
    );
    assert!(err.is_err());
    assert!(
        err.unwrap_err()
            .to_string()
            .contains("not owned by this session")
    );

    // branch_delete on unowned branch should fail
    let err = git.branch_delete("other/branch");
    assert!(err.is_err());
    assert!(
        err.unwrap_err()
            .to_string()
            .contains("not owned by this session")
    );
}

#[test]
fn commit_allowed_at_session_root() {
    let tmp = tempfile::tempdir().unwrap();
    init_temp_repo(tmp.path());
    let session = make_session(tmp.path());
    let git = GitModule::new(session);

    std::fs::write(tmp.path().join("root_file.txt"), "content\n").unwrap();
    let result = git.commit(
        tmp.path(),
        "root commit",
        Some(&["root_file.txt".to_string()]),
        OtherStagedMode::Stop,
        false,
    );
    let commit = result.expect("commit at session root");
    assert_eq!(commit.sha.len(), 40);
    assert_eq!(commit.message, "root commit");
}

#[test]
fn status_partitions_staged_unstaged_untracked() {
    let tmp = tempfile::tempdir().unwrap();
    init_temp_repo(tmp.path());
    let session = make_session(tmp.path());
    let git = GitModule::new(session);

    // Clean state right after the initial commit.
    // The `.worktrees/` directory created by init_temp_repo is itself
    // untracked, so the clean predicate examines staged + unstaged only.
    let status = git.status().unwrap();
    assert!(status.staged.is_empty(), "staged was {:?}", status.staged);
    assert!(
        status.unstaged.is_empty(),
        "unstaged was {:?}",
        status.unstaged
    );
    assert_eq!(status.branch.as_deref(), Some("main"));
    assert!(status.head_sha.is_some());

    // Add an untracked file.
    std::fs::write(tmp.path().join("untracked.txt"), "u\n").unwrap();
    let status = git.status().unwrap();
    assert!(
        status
            .untracked
            .iter()
            .any(|p| p.ends_with("untracked.txt")),
        "untracked was {:?}",
        status.untracked
    );

    // Stage it -> staged bucket only.
    Command::new("git")
        .args(["add", "untracked.txt"])
        .current_dir(tmp.path())
        .output()
        .unwrap();
    let status = git.status().unwrap();
    assert!(
        status
            .staged
            .iter()
            .any(|e| e.path.ends_with("untracked.txt")),
        "staged was {:?}",
        status.staged
    );
}

#[test]
fn diff_distinguishes_staged_from_unstaged() {
    let tmp = tempfile::tempdir().unwrap();
    init_temp_repo(tmp.path());
    let session = make_session(tmp.path());
    let git = GitModule::new(session);

    // Modify README and stage it: that change shows in the staged diff only.
    std::fs::write(tmp.path().join("README.md"), "init\nchanged\n").unwrap();
    Command::new("git")
        .args(["add", "README.md"])
        .current_dir(tmp.path())
        .output()
        .unwrap();

    let unstaged = git.diff(false).unwrap();
    assert!(!unstaged.staged);
    assert_eq!(
        unstaged.file_count, 0,
        "expected no unstaged changes, patch was: {:?}",
        unstaged.patch
    );

    let staged = git.diff(true).unwrap();
    assert!(staged.staged);
    assert_eq!(staged.file_count, 1);
    assert!(
        staged.patch.contains("changed"),
        "expected '+changed' line in staged patch, got: {:?}",
        staged.patch
    );

    // Re-modify README without staging: that further change shows in the
    // unstaged diff (worktree-vs-index).
    std::fs::write(tmp.path().join("README.md"), "init\nchanged\nagain\n").unwrap();
    let unstaged = git.diff(false).unwrap();
    assert!(!unstaged.staged);
    assert_eq!(unstaged.file_count, 1);
    assert!(
        unstaged.patch.contains("again"),
        "expected '+again' line in unstaged patch, got: {:?}",
        unstaged.patch
    );
}

#[test]
fn reset_moves_head_back() {
    let tmp = tempfile::tempdir().unwrap();
    init_temp_repo(tmp.path());
    let session = make_session(tmp.path());
    let git = GitModule::new(session);

    // Capture the pre-reset sha.
    let before = Command::new("git")
        .args(["rev-parse", "HEAD"])
        .current_dir(tmp.path())
        .output()
        .unwrap();
    let before_sha = String::from_utf8_lossy(&before.stdout).trim().to_string();

    // Add a second commit on top.
    std::fs::write(tmp.path().join("two.txt"), "two\n").unwrap();
    Command::new("git")
        .args(["add", "two.txt"])
        .current_dir(tmp.path())
        .output()
        .unwrap();
    Command::new("git")
        .args(["commit", "-m", "second"])
        .current_dir(tmp.path())
        .output()
        .unwrap();

    // Reset back to the first commit.
    let result = git
        .reset(tmp.path(), ResetMode::Hard, &before_sha)
        .expect("reset");
    assert!(matches!(result.mode, ResetMode::Hard));
    assert_eq!(result.target, before_sha);
    assert_eq!(result.current_head, before_sha);
    assert_ne!(result.previous_head, result.current_head);
}

#[test]
fn session_release_adopts_orphan_worktree() {
    let tmp = tempfile::tempdir().unwrap();
    init_temp_repo(tmp.path());
    let session = make_session(tmp.path());
    let mut git = GitModule::new(session);

    // Simulate a worktree left over by a previous session: not owned by us.
    Command::new("git")
        .args([
            "worktree",
            "add",
            "-b",
            "left/over",
            tmp.path().join(".worktrees/leftover").to_str().unwrap(),
            "main",
        ])
        .current_dir(tmp.path())
        .output()
        .unwrap();
    let leftover = tmp.path().join(".worktrees/leftover");

    // branch_delete must refuse before we adopt.
    assert!(git.branch_delete("left/over").is_err());

    // Adopt: session_release should pick up `leftover` + branch `left/over`.
    let release = git.session_release().expect("session_release");
    // macOS resolves /var/... to /private/var/..., so compare canonical paths.
    let canonical_leftover = leftover.canonicalize().unwrap_or(leftover.clone());
    assert!(
        release.adopted_worktrees.iter().any(|p| {
            let canon = p.canonicalize().unwrap_or_else(|_| p.clone());
            canon == canonical_leftover
        }),
        "expected leftover to be adopted (canonical: {canonical_leftover:?}), got: {release:?}"
    );
    assert!(
        release.adopted_branches.iter().any(|b| b == "left/over"),
        "expected left/over branch adopted, got: {release:?}"
    );

    // After adoption, branch_delete on `left/over` should succeed once the
    // worktree has been removed (a branch can't be deleted while checked out).
    git.worktree_remove("leftover")
        .expect("worktree_remove after adoption");
    git.branch_delete("left/over")
        .expect("branch_delete after adoption");
}

// ---------------------------------------------------------------------------
// commit(only, other_staged)
// ---------------------------------------------------------------------------

/// `git status --porcelain=v1` line list from `dir`. Test-only helper.
fn porcelain_status(dir: &Path) -> Vec<String> {
    let out = Command::new("git")
        .args(["status", "--porcelain=v1"])
        .current_dir(dir)
        .output()
        .unwrap();
    String::from_utf8_lossy(&out.stdout)
        .lines()
        .map(|l| l.to_string())
        .collect()
}

/// Stage a worktree file so tests can seed "other staged" state.
fn git_add(dir: &Path, path: &str) {
    Command::new("git")
        .args(["add", path])
        .current_dir(dir)
        .output()
        .unwrap();
}

#[test]
fn commit_only_commits_just_those_paths() {
    let tmp = tempfile::tempdir().unwrap();
    init_temp_repo(tmp.path());
    let session = make_session(tmp.path());
    let git = GitModule::new(session);

    // Two new files in the worktree, only one is asked for.
    std::fs::write(tmp.path().join("keep.txt"), "keep\n").unwrap();
    std::fs::write(tmp.path().join("skip.txt"), "skip\n").unwrap();

    let commit = git
        .commit(
            tmp.path(),
            "only keep",
            Some(&["keep.txt".to_string()]),
            OtherStagedMode::Stop,
            false,
        )
        .expect("commit only=keep.txt");

    assert_eq!(commit.files_changed, 1);
    // The committed tree contains keep.txt but not skip.txt.
    let listed = Command::new("git")
        .args(["show", "--name-only", "--pretty=format:", "HEAD"])
        .current_dir(tmp.path())
        .output()
        .unwrap();
    let listed = String::from_utf8_lossy(&listed.stdout);
    assert!(
        listed.contains("keep.txt"),
        "commit should touch keep.txt: {listed}"
    );
    assert!(
        !listed.contains("skip.txt"),
        "commit must not touch skip.txt: {listed}"
    );
    // skip.txt is still on disk, untracked (never staged by us).
    assert!(tmp.path().join("skip.txt").exists());
    let status = porcelain_status(tmp.path());
    assert!(
        status.iter().any(|l| l.ends_with("skip.txt")),
        "skip.txt should still be reported by status, got: {status:?}"
    );
}

#[test]
fn commit_only_stop_refuses_when_index_has_intruders() {
    let tmp = tempfile::tempdir().unwrap();
    init_temp_repo(tmp.path());
    let session = make_session(tmp.path());
    let git = GitModule::new(session);

    // Pre-stage `other.txt` outside of `only`. `stop` mode must abort.
    std::fs::write(tmp.path().join("other.txt"), "other\n").unwrap();
    git_add(tmp.path(), "other.txt");

    std::fs::write(tmp.path().join("only.txt"), "only\n").unwrap();

    let err = git
        .commit(
            tmp.path(),
            "should abort",
            Some(&["only.txt".to_string()]),
            OtherStagedMode::Stop,
            false,
        )
        .expect_err("stop mode must refuse when other paths are staged");
    let msg = err.to_string();
    assert!(
        msg.contains("other_staged=stop"),
        "expected other_staged=stop hint in error: {msg}"
    );
    assert!(
        msg.contains("other.txt"),
        "error should name the intruder: {msg}"
    );

    // State must be untouched: HEAD is still `initial`, other.txt still staged.
    let head_msg = Command::new("git")
        .args(["log", "-1", "--pretty=%s"])
        .current_dir(tmp.path())
        .output()
        .unwrap();
    assert_eq!(
        String::from_utf8_lossy(&head_msg.stdout).trim(),
        "initial",
        "stop mode must not create a commit"
    );
    let status = porcelain_status(tmp.path());
    assert!(
        status.iter().any(|l| l.starts_with("A  other.txt")),
        "other.txt must remain staged, got: {status:?}"
    );
}

#[test]
fn commit_only_restage_survives_round_trip() {
    let tmp = tempfile::tempdir().unwrap();
    init_temp_repo(tmp.path());
    let session = make_session(tmp.path());
    let git = GitModule::new(session);

    // Pre-stage `other.txt`; call commit with only=["target.txt"] + restage.
    std::fs::write(tmp.path().join("other.txt"), "other\n").unwrap();
    git_add(tmp.path(), "other.txt");
    std::fs::write(tmp.path().join("target.txt"), "target\n").unwrap();

    let commit = git
        .commit(
            tmp.path(),
            "only target",
            Some(&["target.txt".to_string()]),
            OtherStagedMode::Restage,
            false,
        )
        .expect("restage mode commits target and re-stages other");

    assert_eq!(commit.files_changed, 1, "commit must only touch target.txt");

    // The new commit contains target.txt, not other.txt.
    let listed = Command::new("git")
        .args(["show", "--name-only", "--pretty=format:", "HEAD"])
        .current_dir(tmp.path())
        .output()
        .unwrap();
    let listed = String::from_utf8_lossy(&listed.stdout);
    assert!(
        listed.contains("target.txt"),
        "commit should touch target.txt: {listed}"
    );
    assert!(
        !listed.contains("other.txt"),
        "commit must not touch other.txt: {listed}"
    );

    // other.txt has been re-staged (still listed as staged-add by porcelain).
    let status = porcelain_status(tmp.path());
    assert!(
        status.iter().any(|l| l.starts_with("A  other.txt")),
        "other.txt must be re-staged after restage round-trip, got: {status:?}"
    );
}

#[test]
fn commit_only_stop_ignores_other_unstaged_changes() {
    // Modified-but-not-staged files are NOT intruders — the mode only cares
    // about the index. This documents that boundary.
    let tmp = tempfile::tempdir().unwrap();
    init_temp_repo(tmp.path());
    let session = make_session(tmp.path());
    let git = GitModule::new(session);

    // Modify README.md but do not stage it.
    std::fs::write(tmp.path().join("README.md"), "init\nunstaged edit\n").unwrap();
    // Add a fresh file that `only` will target.
    std::fs::write(tmp.path().join("target.txt"), "t\n").unwrap();

    let commit = git
        .commit(
            tmp.path(),
            "only target with unstaged noise",
            Some(&["target.txt".to_string()]),
            OtherStagedMode::Stop,
            false,
        )
        .expect("stop mode should still succeed when noise is only unstaged");
    assert_eq!(commit.files_changed, 1);

    // README's unstaged edit is still on disk, unstaged.
    let status = porcelain_status(tmp.path());
    assert!(
        status.iter().any(|l| l.starts_with(" M README.md")),
        "README.md's unstaged edit must survive, got: {status:?}"
    );
}

// ---------------------------------------------------------------------------
// Dotfile / dot-dir safeguard
// ---------------------------------------------------------------------------

#[test]
fn commit_skips_untracked_dotfile_not_in_gitignore() {
    // `.env` newly-dropped without `.gitignore` coverage: the safeguard
    // must drop it from staging AND warn so the caller sees it.
    let tmp = tempfile::tempdir().unwrap();
    init_temp_repo(tmp.path());
    let session = make_session(tmp.path());
    let git = GitModule::new(session);

    std::fs::write(tmp.path().join(".env"), "SECRET=1\n").unwrap();
    std::fs::write(tmp.path().join("safe.txt"), "safe\n").unwrap();

    let commit = git
        .commit(
            tmp.path(),
            "commit with dotfile in tree",
            None,
            OtherStagedMode::Stop,
            false,
        )
        .expect("commit should succeed with safe.txt only");

    assert_eq!(commit.files_changed, 1, "only safe.txt should be committed");
    assert!(
        commit.dotfile_skipped.iter().any(|p| p == ".env"),
        "expected .env in dotfile_skipped, got {:?}",
        commit.dotfile_skipped
    );
    assert!(
        commit
            .dotfile_warnings
            .iter()
            .any(|w| w.path == ".env" && !w.tracked && !w.in_gitignore),
        "expected untracked+not-ignored .env warning, got {:?}",
        commit.dotfile_warnings
    );

    // `.env` is still untracked on disk — never made it into the index.
    let status = porcelain_status(tmp.path());
    assert!(
        status
            .iter()
            .any(|l| l.starts_with("?? ") && l.ends_with(".env")),
        ".env must remain untracked, got: {status:?}"
    );
}

#[test]
fn commit_silently_skips_gitignored_dotfile() {
    // `.env` covered by `.gitignore`: git already hides it from
    // porcelain, so it never even shows up as a candidate. No warning
    // should be emitted for the silent case.
    let tmp = tempfile::tempdir().unwrap();
    init_temp_repo(tmp.path());
    let session = make_session(tmp.path());
    let git = GitModule::new(session);

    std::fs::write(tmp.path().join(".gitignore"), ".env\n").unwrap();
    // Commit .gitignore first so it's tracked and quiet on subsequent runs.
    let _ = git
        .commit(
            tmp.path(),
            "add .gitignore",
            Some(&[".gitignore".to_string()]),
            OtherStagedMode::Stop,
            true, // force_dot: bootstrap the safeguard itself
        )
        .expect("bootstrap .gitignore");

    std::fs::write(tmp.path().join(".env"), "SECRET=1\n").unwrap();
    std::fs::write(tmp.path().join("safe.txt"), "safe\n").unwrap();

    let commit = git
        .commit(
            tmp.path(),
            "commit with ignored .env in tree",
            None,
            OtherStagedMode::Stop,
            false,
        )
        .expect("commit safe.txt only");

    assert_eq!(commit.files_changed, 1);
    assert!(
        commit.dotfile_warnings.is_empty(),
        "ignored .env must not warn, got {:?}",
        commit.dotfile_warnings
    );
    assert!(
        commit.dotfile_skipped.is_empty(),
        "ignored .env is already invisible to porcelain, got {:?}",
        commit.dotfile_skipped
    );
}

#[test]
fn commit_warns_but_includes_tracked_dotfile_change() {
    // Modify a tracked `.gitignore`: safeguard lets the change through
    // (tracked = intentional) but records a warning so pre-publish
    // review can catch unintended edits.
    let tmp = tempfile::tempdir().unwrap();
    init_temp_repo(tmp.path());
    let session = make_session(tmp.path());
    let git = GitModule::new(session);

    std::fs::write(tmp.path().join(".gitignore"), "old\n").unwrap();
    let _ = git
        .commit(
            tmp.path(),
            "add .gitignore",
            Some(&[".gitignore".to_string()]),
            OtherStagedMode::Stop,
            true,
        )
        .expect("bootstrap tracked .gitignore");

    // Now edit it.
    std::fs::write(tmp.path().join(".gitignore"), "old\nnew line\n").unwrap();

    let commit = git
        .commit(
            tmp.path(),
            "update .gitignore",
            None,
            OtherStagedMode::Stop,
            false,
        )
        .expect("commit tracked dotfile change");

    assert_eq!(commit.files_changed, 1, ".gitignore edit must be committed");
    assert!(
        commit
            .dotfile_warnings
            .iter()
            .any(|w| w.path == ".gitignore" && w.tracked),
        "expected tracked .gitignore warning, got {:?}",
        commit.dotfile_warnings
    );
    assert!(
        commit.dotfile_skipped.is_empty(),
        "tracked dotfile must not appear in skipped, got {:?}",
        commit.dotfile_skipped
    );
}

#[test]
fn commit_force_dot_suppresses_safeguard() {
    // `force_dot=true`: `.env` gets staged and committed like any other
    // file, no warning, no skip. This is the manual override path.
    let tmp = tempfile::tempdir().unwrap();
    init_temp_repo(tmp.path());
    let session = make_session(tmp.path());
    let git = GitModule::new(session);

    std::fs::write(tmp.path().join(".env"), "SECRET=1\n").unwrap();

    let commit = git
        .commit(
            tmp.path(),
            "force-commit .env",
            None,
            OtherStagedMode::Stop,
            true,
        )
        .expect("force_dot must let .env through");

    assert_eq!(commit.files_changed, 1);
    assert!(
        commit.dotfile_warnings.is_empty(),
        "force_dot must suppress warnings, got {:?}",
        commit.dotfile_warnings
    );
    assert!(
        commit.dotfile_skipped.is_empty(),
        "force_dot must suppress skip list, got {:?}",
        commit.dotfile_skipped
    );

    // .env is now tracked at HEAD.
    let listed = Command::new("git")
        .args(["show", "--name-only", "--pretty=format:", "HEAD"])
        .current_dir(tmp.path())
        .output()
        .unwrap();
    let listed = String::from_utf8_lossy(&listed.stdout);
    assert!(
        listed.contains(".env"),
        "force_dot commit should include .env: {listed}"
    );
}

#[test]
fn commit_only_drops_dotfile_from_explicit_paths() {
    // `only=[.env, safe.txt]` with safeguard on: `.env` is filtered
    // out of the stage list, `safe.txt` proceeds. HEAD contains only
    // safe.txt afterward.
    let tmp = tempfile::tempdir().unwrap();
    init_temp_repo(tmp.path());
    let session = make_session(tmp.path());
    let git = GitModule::new(session);

    std::fs::write(tmp.path().join(".env"), "SECRET=1\n").unwrap();
    std::fs::write(tmp.path().join("safe.txt"), "safe\n").unwrap();

    let commit = git
        .commit(
            tmp.path(),
            "explicit paths with dotfile filtered",
            Some(&[".env".to_string(), "safe.txt".to_string()]),
            OtherStagedMode::Stop,
            false,
        )
        .expect("commit should proceed with safe.txt only");

    assert_eq!(commit.files_changed, 1);
    assert!(
        commit.dotfile_skipped.iter().any(|p| p == ".env"),
        "expected .env skipped, got {:?}",
        commit.dotfile_skipped
    );

    let listed = Command::new("git")
        .args(["show", "--name-only", "--pretty=format:", "HEAD"])
        .current_dir(tmp.path())
        .output()
        .unwrap();
    let listed = String::from_utf8_lossy(&listed.stdout);
    assert!(listed.contains("safe.txt"));
    assert!(
        !listed.contains(".env"),
        "safeguard-filtered .env must not land in commit: {listed}"
    );
}

#[test]
fn commit_detects_dotfile_under_untracked_nondot_dir() {
    // Regression: previously the safeguard missed `foo/.hidden` because
    // `git status --porcelain` collapsed the untracked `foo/` into a
    // single `?? foo/` record, so the dotfile-classifier only ever saw
    // `foo/` (non-dot) and let git recursively stage everything under it.
    // Fixed by `--untracked-files=all`. Origin: 2026-07-22 jikki smoke
    // that saw `session_start`'s `workspace/.journal.db*` slip through.
    let tmp = tempfile::tempdir().unwrap();
    init_temp_repo(tmp.path());
    let session = make_session(tmp.path());
    let git = GitModule::new(session);

    // Untracked non-dot dir with an untracked nested dotfile.
    std::fs::create_dir_all(tmp.path().join("data")).unwrap();
    std::fs::write(tmp.path().join("data/.hidden"), "secret\n").unwrap();
    std::fs::write(tmp.path().join("data/public.txt"), "ok\n").unwrap();

    let commit = git
        .commit(
            tmp.path(),
            "nested dotfile under untracked non-dot dir",
            None,
            OtherStagedMode::Stop,
            false,
        )
        .expect("commit should proceed with data/public.txt only");

    assert!(
        commit.dotfile_skipped.iter().any(|p| p == "data/.hidden"),
        "expected data/.hidden in dotfile_skipped, got {:?}",
        commit.dotfile_skipped
    );
    assert!(
        commit
            .dotfile_warnings
            .iter()
            .any(|w| w.path == "data/.hidden" && !w.tracked),
        "expected untracked warning for data/.hidden, got {:?}",
        commit.dotfile_warnings
    );

    // HEAD must contain data/public.txt but NOT data/.hidden.
    let listed = Command::new("git")
        .args(["show", "--name-only", "--pretty=format:", "HEAD"])
        .current_dir(tmp.path())
        .output()
        .unwrap();
    let listed = String::from_utf8_lossy(&listed.stdout);
    assert!(
        listed.contains("data/public.txt"),
        "commit should include data/public.txt: {listed}"
    );
    assert!(
        !listed.contains(".hidden"),
        "safeguard-filtered data/.hidden must not land in commit: {listed}"
    );

    // data/.hidden is still on disk, untracked.
    let status = porcelain_status(tmp.path());
    assert!(
        status.iter().any(|l| l.ends_with("data/.hidden")),
        "data/.hidden must remain untracked, got: {status:?}"
    );
}

#[test]
fn commit_detects_nested_dotdir_component() {
    // `.claude/CLAUDE.md`: dot component is not the basename but a
    // path segment. is_dotfile_path must still catch it.
    let tmp = tempfile::tempdir().unwrap();
    init_temp_repo(tmp.path());
    let session = make_session(tmp.path());
    let git = GitModule::new(session);

    std::fs::create_dir_all(tmp.path().join(".claude")).unwrap();
    std::fs::write(tmp.path().join(".claude/CLAUDE.md"), "hi\n").unwrap();
    std::fs::write(tmp.path().join("safe.txt"), "safe\n").unwrap();

    let commit = git
        .commit(
            tmp.path(),
            "nested dot-dir",
            None,
            OtherStagedMode::Stop,
            false,
        )
        .expect("commit safe.txt only");

    assert_eq!(commit.files_changed, 1);
    assert!(
        commit
            .dotfile_skipped
            .iter()
            .any(|p| p.starts_with(".claude/")),
        "expected .claude/... in skipped, got {:?}",
        commit.dotfile_skipped
    );
}