git-loom 0.18.0

A Git CLI tool that weaves together multiple feature branches into integration branches
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
use crate::core::graph;
use crate::core::test_helpers::TestRepo;

/// Wrapper so existing tests don't need to pass patch/theme.
fn run(branch: Option<String>, message: Option<String>, files: Vec<String>) -> anyhow::Result<()> {
    super::run(branch, message, false, files, &graph::Theme::dark())
}

/// Helper: set up a test repo with an empty feature branch at the merge-base.
///
/// Creates:
///   origin/main → (merge-base) ← feature-a (empty, at merge-base)
///                              ← integration (HEAD)
fn setup_with_woven_branch() -> TestRepo {
    let test_repo = TestRepo::new_with_remote();
    let base_oid = test_repo.find_remote_branch_target("origin/main");

    // Create feature-a at merge-base (no merge — it's empty)
    test_repo.create_branch_at("feature-a", &base_oid.to_string());

    test_repo
}

/// Helper: set up a test repo with two woven feature branches, each with a commit.
///
/// Creates:
///   origin/main → A1 (feature-a)
///              ↘              ↘
///               B1 --------→ merge₁ → merge₂ (HEAD on integration)
///               (feature-b)       ↗
fn setup_with_two_branches() -> TestRepo {
    let test_repo = TestRepo::new_with_remote();
    let base_oid = test_repo.find_remote_branch_target("origin/main");

    // Create feature-a at merge-base with one commit
    test_repo.create_branch_at("feature-a", &base_oid.to_string());
    test_repo.switch_branch("feature-a");
    test_repo.commit("A1", "a1.txt");
    test_repo.switch_branch("integration");

    // Create feature-b at merge-base with one commit
    test_repo.create_branch_at("feature-b", &base_oid.to_string());
    test_repo.switch_branch("feature-b");
    test_repo.commit("B1", "b1.txt");
    test_repo.switch_branch("integration");

    // Weave both branches into integration
    test_repo.merge_no_ff("feature-a");
    test_repo.merge_no_ff("feature-b");

    test_repo
}

// ── Staging resolution ───────────────────────────────────────────────────

#[test]
fn commit_stages_specific_file() {
    let test_repo = setup_with_woven_branch();

    test_repo.write_file("new.txt", "content");
    test_repo.write_file("other.txt", "other");

    let result = test_repo.in_dir(|| {
        run(
            Some("feature-a".to_string()),
            Some("Add new file".to_string()),
            vec!["new.txt".to_string()],
        )
    });

    assert!(result.is_ok(), "commit failed: {:?}", result);

    // feature-a should have the commit
    assert_eq!(test_repo.branch_commit_summary("feature-a"), "Add new file");
}

#[test]
fn commit_stages_zz_all_changes() {
    let test_repo = setup_with_woven_branch();

    test_repo.write_file("file1.txt", "content1");
    test_repo.write_file("file2.txt", "content2");

    let result = test_repo.in_dir(|| {
        run(
            Some("feature-a".to_string()),
            Some("Add files".to_string()),
            vec!["zz".to_string()],
        )
    });

    assert!(result.is_ok(), "commit failed: {:?}", result);

    // feature-a should have the commit
    assert_eq!(test_repo.branch_commit_summary("feature-a"), "Add files");
}

#[test]
fn commit_uses_already_staged() {
    let test_repo = setup_with_woven_branch();

    // Stage a file manually
    test_repo.write_file("staged.txt", "content");
    test_repo.stage_files(&["staged.txt"]);

    let result = test_repo.in_dir(|| {
        run(
            Some("feature-a".to_string()),
            Some("Use staged".to_string()),
            vec![], // no file args = use index as-is
        )
    });

    assert!(result.is_ok(), "commit failed: {:?}", result);

    assert_eq!(test_repo.branch_commit_summary("feature-a"), "Use staged");
}

#[test]
fn commit_empty_index_fails() {
    let test_repo = setup_with_woven_branch();

    // No files staged, no file args
    let result = test_repo.in_dir(|| {
        run(
            Some("feature-a".to_string()),
            Some("Message".to_string()),
            vec![],
        )
    });

    assert!(result.is_err());
    assert!(
        result
            .unwrap_err()
            .to_string()
            .contains("Nothing to commit")
    );
}

// ── Branch resolution ────────────────────────────────────────────────────

#[test]
fn commit_to_non_woven_branch_fails() {
    let test_repo = TestRepo::new_with_remote();
    test_repo.commit("A1", "a1.txt");

    // Create a branch that tracks the same upstream as integration.
    // find_branches_in_range excludes such branches, so it won't be "woven".
    test_repo.create_branch_tracking("not-woven", "origin/main");

    test_repo.write_file("file.txt", "content");

    let result = test_repo.in_dir(|| {
        run(
            Some("not-woven".to_string()),
            Some("Message".to_string()),
            vec!["file.txt".to_string()],
        )
    });

    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("not woven"));
}

#[test]
fn commit_to_new_branch_creates_and_weaves() {
    let test_repo = TestRepo::new_with_remote();

    test_repo.write_file("new.txt", "content");

    let result = test_repo.in_dir(|| {
        run(
            Some("feature-new".to_string()),
            Some("Add file".to_string()),
            vec!["new.txt".to_string()],
        )
    });

    assert!(result.is_ok(), "commit failed: {:?}", result);
    assert!(test_repo.branch_exists("feature-new"));

    // Branch should have the commit
    assert_eq!(test_repo.branch_commit_summary("feature-new"), "Add file");

    // Integration HEAD should be a merge commit (proper weave topology)
    let head = test_repo.head_commit();
    assert_eq!(
        head.parent_count(),
        2,
        "HEAD should be a merge commit with 2 parents"
    );

    // The branch commit should be reachable as the second parent of the merge
    let second_parent = head.parent(1).unwrap();
    assert_eq!(second_parent.summary().unwrap(), "Add file");
}

// ── Merge topology ──────────────────────────────────────────────────────

#[test]
fn commit_to_empty_branch_creates_merge_topology() {
    let test_repo = setup_with_woven_branch();

    test_repo.write_file("new.txt", "content");

    let result = test_repo.in_dir(|| {
        run(
            Some("feature-a".to_string()),
            Some("New commit".to_string()),
            vec!["new.txt".to_string()],
        )
    });

    assert!(result.is_ok(), "commit failed: {:?}", result);

    // feature-a should have the commit
    let branch_oid = test_repo.get_branch_target("feature-a");
    let commit = test_repo.find_commit(branch_oid);
    assert_eq!(commit.summary().unwrap(), "New commit");

    // Integration HEAD should be a merge commit (not the same as feature-a)
    let head = test_repo.head_commit();
    assert_eq!(
        head.parent_count(),
        2,
        "HEAD should be a merge commit (branch woven into integration)"
    );

    // feature-a's commit should be the second parent of the merge
    let second_parent = head.parent(1).unwrap();
    assert_eq!(second_parent.id(), branch_oid);
}

/// Helper: set up a test repo with one woven branch (with a commit) and one empty branch.
///
/// Creates:
///   origin/main → (merge-base)
///   feature-a has A1 commit, merged into integration
///   feature-b at merge-base (empty)
///   HEAD = integration = Merge feature-a
fn setup_with_one_woven_one_empty() -> TestRepo {
    let test_repo = TestRepo::new_with_remote();
    let base_oid = test_repo.find_remote_branch_target("origin/main");

    // Create feature-a at merge-base with one commit
    test_repo.create_branch_at("feature-a", &base_oid.to_string());
    test_repo.switch_branch("feature-a");
    test_repo.commit("A1", "a1.txt");
    test_repo.switch_branch("integration");

    // Weave feature-a into integration
    test_repo.merge_no_ff("feature-a");

    // Create feature-b at merge-base (empty, no commits)
    test_repo.create_branch_at("feature-b", &base_oid.to_string());

    test_repo
}

#[test]
fn commit_to_second_empty_branch_creates_parallel_topology() {
    let test_repo = setup_with_one_woven_one_empty();
    let base_oid = test_repo.find_remote_branch_target("origin/main");

    test_repo.write_file("b1.txt", "content");

    let result = test_repo.in_dir(|| {
        run(
            Some("feature-b".to_string()),
            Some("B1".to_string()),
            vec!["b1.txt".to_string()],
        )
    });

    assert!(result.is_ok(), "commit failed: {:?}", result);

    // feature-b should have the commit
    let branch_b_oid = test_repo.get_branch_target("feature-b");
    let commit_b = test_repo.find_commit(branch_b_oid);
    assert_eq!(commit_b.summary().unwrap(), "B1");

    // feature-b's commit should have the merge-base as its parent,
    // NOT the merge commit of feature-a (parallel topology, not stacked)
    let parent = commit_b.parent(0).unwrap();
    assert_eq!(
        parent.id(),
        base_oid,
        "feature-b's commit should fork from merge-base, not from the merge commit"
    );

    // HEAD should be a merge commit (merge of feature-b into integration)
    let head = test_repo.head_commit();
    assert_eq!(head.parent_count(), 2, "HEAD should be a merge commit");

    // The first parent should be the merge of feature-a (the old integration tip)
    let first_parent = head.parent(0).unwrap();
    assert_eq!(
        first_parent.parent_count(),
        2,
        "first parent should also be a merge commit (feature-a merge)"
    );

    // The second parent should be feature-b
    let second_parent = head.parent(1).unwrap();
    assert_eq!(second_parent.id(), branch_b_oid);
}

// ── Move via rebase ──────────────────────────────────────────────────────

#[test]
fn commit_moves_to_correct_branch_in_topology() {
    let test_repo = setup_with_two_branches();

    test_repo.write_file("new.txt", "content");

    let result = test_repo.in_dir(|| {
        run(
            Some("feature-a".to_string()),
            Some("New on A".to_string()),
            vec!["new.txt".to_string()],
        )
    });

    assert!(result.is_ok(), "commit failed: {:?}", result);

    // feature-a tip should be "New on A"
    let branch_oid = test_repo.get_branch_target("feature-a");
    let commit = test_repo.find_commit(branch_oid);
    assert_eq!(commit.summary().unwrap(), "New on A");

    // Its parent should be A1
    let parent = commit.parent(0).unwrap();
    assert_eq!(parent.summary().unwrap(), "A1");

    // feature-b should still be intact
    assert_eq!(test_repo.branch_commit_summary("feature-b"), "B1");
}

/// Bug: committing to a new branch when the file conflicts with an existing
/// woven branch would lose working-tree changes. Now that conflicts pause the
/// operation instead of aborting, the operation is kept alive for `loom continue`
/// or `loom abort`.
#[test]
fn commit_conflict_pauses_operation() {
    let test_repo = TestRepo::new_with_remote();
    let base_oid = test_repo.find_remote_branch_target("origin/main");

    // Create feat1 branch with a commit that adds feature1
    test_repo.create_branch_at("feat1", &base_oid.to_string());
    test_repo.switch_branch("feat1");
    test_repo.write_file("feature1", "feat 1 content");
    test_repo.stage_files(&["feature1"]);
    test_repo.commit_staged("Feature 1");
    test_repo.switch_branch("integration");

    // Weave feat1 into integration
    test_repo.merge_no_ff("feat1");

    // Modify feature1 in the working tree (same file as feat1 commit)
    test_repo.write_file("feature1", "conflicting content");

    let result = test_repo.in_dir(|| {
        run(
            Some("new-line".to_string()),
            Some("New line".to_string()),
            vec!["zz".to_string()],
        )
    });

    // The commit should succeed (operation paused, not aborted)
    assert!(result.is_ok(), "commit should pause on conflict, not fail");

    // The state file should exist indicating a paused operation
    let state_path = test_repo.repo.path().join("loom").join("state.json");
    assert!(
        state_path.exists(),
        "loom state file should exist when paused"
    );

    // The new branch should still exist (kept for potential abort)
    assert!(
        test_repo.branch_exists("new-line"),
        "new-line branch should be kept while operation is paused"
    );
}

#[test]
fn commit_conflict_preserves_existing_empty_branch() {
    let test_repo = TestRepo::new_with_remote();
    let base_oid = test_repo.find_remote_branch_target("origin/main");

    // Create feat1 with a commit (will cause conflict)
    test_repo.create_branch_at("feat1", &base_oid.to_string());
    test_repo.switch_branch("feat1");
    test_repo.write_file("shared.txt", "feat1 content");
    test_repo.stage_files(&["shared.txt"]);
    test_repo.commit_staged("Feature 1");
    test_repo.switch_branch("integration");
    test_repo.merge_no_ff("feat1");

    // Create an empty branch at merge-base (pre-existing, not created by commit)
    test_repo.create_branch_at("empty-branch", &base_oid.to_string());

    // Stage a conflicting change and try to commit to the empty branch
    test_repo.write_file("shared.txt", "conflicting content");

    let result = test_repo.in_dir(|| {
        run(
            Some("empty-branch".to_string()),
            Some("Should conflict".to_string()),
            vec!["zz".to_string()],
        )
    });

    // The commit should pause (not abort) on conflict
    assert!(result.is_ok(), "commit should pause on conflict, not fail");

    // The state file should exist
    let state_path = test_repo.repo.path().join("loom").join("state.json");
    assert!(
        state_path.exists(),
        "loom state file should exist when paused"
    );

    // Critical: the pre-existing empty branch must NOT be deleted while paused
    assert!(
        test_repo.branch_exists("empty-branch"),
        "Pre-existing empty branch should be preserved while operation is paused"
    );
}

// ── Loose commits ────────────────────────────────────────────────────────

#[test]
fn commit_loose_when_no_branch_and_at_remote() {
    // When no -b flag and branch name matches the upstream's local name
    // (e.g. "main" tracking "origin/main"), the commit should land
    // directly on the integration branch (loose).
    let test_repo = TestRepo::new_on_main_with_remote();
    let base_oid = test_repo.find_remote_branch_target("origin/main");

    test_repo.write_file("loose.txt", "content");

    let result = test_repo.in_dir(|| {
        run(
            None, // no -b flag
            Some("Loose commit".to_string()),
            vec!["loose.txt".to_string()],
        )
    });

    assert!(result.is_ok(), "loose commit failed: {:?}", result);

    // HEAD should be a regular (non-merge) commit
    let head = test_repo.head_commit();
    assert_eq!(head.parent_count(), 1, "Loose commit should have 1 parent");
    assert_eq!(head.summary().unwrap(), "Loose commit");

    // Parent should be the merge-base (the remote tip)
    let parent = head.parent(0).unwrap();
    assert_eq!(parent.id(), base_oid);
}

#[test]
fn commit_loose_works_with_existing_local_commits() {
    // Loose commits should work even when local commits already exist
    // on the integration branch (HEAD != merge-base).
    let test_repo = TestRepo::new_on_main_with_remote();

    // Create a first loose commit so HEAD diverges from merge-base
    test_repo.write_file("first.txt", "first");
    test_repo
        .in_dir(|| {
            run(
                None,
                Some("First loose commit".to_string()),
                vec!["first.txt".to_string()],
            )
        })
        .unwrap();

    // Now create a second loose commit — should still work
    test_repo.write_file("second.txt", "second");
    let result = test_repo.in_dir(|| {
        run(
            None,
            Some("Second loose commit".to_string()),
            vec!["second.txt".to_string()],
        )
    });

    assert!(
        result.is_ok(),
        "loose commit with existing local commits failed: {:?}",
        result
    );

    let head = test_repo.head_commit();
    assert_eq!(head.summary().unwrap(), "Second loose commit");
    assert_eq!(head.parent_count(), 1);
    assert_eq!(
        head.parent(0).unwrap().summary().unwrap(),
        "First loose commit"
    );
}

#[test]
fn commit_with_branch_flag_does_not_create_loose() {
    // When -b is provided, even if HEAD == merge-base, a branch-targeted
    // commit should be created (not loose).
    let test_repo = TestRepo::new_with_remote();

    test_repo.write_file("file.txt", "content");

    let result = test_repo.in_dir(|| {
        run(
            Some("feature-new".to_string()), // explicit -b flag
            Some("Branch commit".to_string()),
            vec!["file.txt".to_string()],
        )
    });

    assert!(result.is_ok(), "commit failed: {:?}", result);

    // Should have created the branch and woven it
    assert!(test_repo.branch_exists("feature-new"));
    let head = test_repo.head_commit();
    assert_eq!(
        head.parent_count(),
        2,
        "HEAD should be a merge commit (branch woven)"
    );
}

// ── Prerequisites ────────────────────────────────────────────────────────

#[test]
fn commit_not_on_integration_branch_fails() {
    // No upstream tracking = not an integration branch
    let test_repo = TestRepo::new();
    test_repo.commit("A1", "a1.txt");
    test_repo.write_file("new.txt", "content");

    let result = test_repo.in_dir(|| {
        run(
            Some("feature-a".to_string()),
            Some("Message".to_string()),
            vec!["new.txt".to_string()],
        )
    });

    assert!(result.is_err());
    assert!(
        result
            .unwrap_err()
            .to_string()
            .contains("integration branch")
    );
}

// ── File resolution ──────────────────────────────────────────────────────

#[test]
fn commit_nonexistent_file_fails() {
    let test_repo = setup_with_woven_branch();

    let result = test_repo.in_dir(|| {
        run(
            Some("feature-a".to_string()),
            Some("Message".to_string()),
            vec!["nonexistent.txt".to_string()],
        )
    });

    assert!(result.is_err());
    // With the centralized resolver, a nonexistent file produces a "did not resolve to a file" error
    assert!(
        result.unwrap_err().to_string().contains("file"),
        "Error should mention file"
    );
}

#[test]
fn commit_accepts_staged_rename_only() {
    let test_repo = setup_with_woven_branch();

    // Create and commit a file first
    test_repo.write_file("original.txt", "content");
    test_repo.stage_files(&["original.txt"]);
    test_repo.commit_staged("Add original");

    // Rename via git mv (stages the rename)
    let workdir = test_repo.workdir();
    std::process::Command::new("git")
        .current_dir(&workdir)
        .args(["mv", "original.txt", "renamed.txt"])
        .output()
        .unwrap();

    // verify_has_staged_changes should accept a rename-only index
    let result = crate::core::repo::verify_has_staged_changes(&test_repo.repo);
    assert!(
        result.is_ok(),
        "staged rename should be accepted, got: {:?}",
        result.err()
    );
}

// ── Abort preserves working state ────────────────────────────────────────

/// Regression: loom abort after a commit conflict must preserve staged changes
/// on other files, unstaged changes, and new untracked files.
///
/// Conflict setup: feat1 branch commits `shared.txt`; we then try to commit
/// `shared.txt` to a new branch — the weave rebase conflicts because both
/// branches touch the same file.
#[test]
fn commit_abort_preserves_working_state() {
    let test_repo = TestRepo::new_with_remote();
    let base_oid = test_repo.find_remote_branch_target("origin/main");

    // Create feat1 with a commit that adds shared.txt.
    test_repo.create_branch_at("feat1", &base_oid.to_string());
    test_repo.switch_branch("feat1");
    test_repo.commit("feat1-content", "shared.txt");

    test_repo.switch_branch("integration");
    test_repo.commit("int", "int.txt"); // prevent fast-forward
    test_repo.merge_no_ff("feat1");

    // other-staged.txt is staged — commit.rs will save it aside and restore on abort.
    test_repo.write_file("other-staged.txt", "staged-content");
    test_repo.stage_files(&["other-staged.txt"]);
    test_repo.write_file("other-unstaged.txt", "unstaged-content");
    test_repo.write_file("new-file.txt", "new-content");

    // Write conflicting content to shared.txt (same file as feat1 commit).
    test_repo.write_file("shared.txt", "conflicting-write");

    let result = test_repo.in_dir(|| {
        run(
            Some("new-line".to_string()),
            Some("New line".to_string()),
            vec!["shared.txt".to_string()],
        )
    });
    assert!(
        result.is_ok(),
        "commit should pause on conflict: {:?}",
        result
    );

    let state_path = test_repo.repo.path().join("loom").join("state.json");
    assert!(
        state_path.exists(),
        "loom state must exist when commit is paused on conflict"
    );

    let workdir = test_repo.workdir();
    let git_dir = test_repo.repo.path().to_path_buf();
    crate::core::transaction::abort_cmd(&workdir, &git_dir).unwrap();

    // reset --mixed undoes the pre-rebase commit; shared.txt comes back as unstaged.
    assert_eq!(test_repo.read_file("shared.txt"), "conflicting-write");
    // saved_staged_patch explicitly re-stages other-staged.txt.
    assert_eq!(test_repo.read_file("other-staged.txt"), "staged-content");
    assert_eq!(
        test_repo.read_file("other-unstaged.txt"),
        "unstaged-content"
    );
    assert!(
        workdir.join("new-file.txt").exists(),
        "new untracked file must survive abort"
    );
    assert_eq!(test_repo.read_file("new-file.txt"), "new-content");
}