lds-git 0.12.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
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)
        .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);
    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,
    );
    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,
        )
        .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,
        )
        .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,
        )
        .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,
        )
        .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:?}"
    );
}