git-loom 0.19.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
use crate::core::test_helpers::TestRepo;

// ── Integration tests ────────────────────────────────────────────────

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

    // Create a commit that introduces file1.txt with specific content
    test_repo.commit("Add file1", "file1.txt");

    // Modify file1.txt in the working tree (change existing content)
    test_repo.write_file("file1.txt", "modified content");

    test_repo.in_dir(|| {
        let result = super::run(false, vec![]);
        assert!(result.is_ok(), "absorb failed: {:?}", result);

        // file1.txt should now be clean (absorbed into the commit)
        test_repo.assert_working_tree_clean();

        // Commit message should be preserved
        assert_eq!(test_repo.get_message(0), "Add file1");
    });
}

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

    test_repo.commit("Add file1", "file1.txt");
    test_repo.commit("Add file2", "file2.txt");

    // Modify both files
    test_repo.write_file("file1.txt", "modified file1");
    test_repo.write_file("file2.txt", "modified file2");

    test_repo.in_dir(|| {
        let result = super::run(false, vec![]);
        assert!(result.is_ok(), "absorb failed: {:?}", result);

        // Both files should be clean
        test_repo.assert_working_tree_clean();

        // Commit messages preserved
        assert_eq!(test_repo.get_message(0), "Add file2");
        assert_eq!(test_repo.get_message(1), "Add file1");
    });
}

#[test]
fn absorb_skips_new_file() {
    let test_repo = TestRepo::new_with_remote();
    test_repo.commit("Add file1", "file1.txt");

    // Modify tracked file and create a new untracked file
    test_repo.write_file("file1.txt", "modified");
    test_repo.write_file("new_file.txt", "brand new");

    test_repo.in_dir(|| {
        // diff HEAD --name-only only shows tracked changes, so new_file.txt
        // won't even be in the list unless user passes it explicitly.
        // Let's pass both explicitly to test the skip path.
        let result = super::run(
            false,
            vec!["file1.txt".to_string(), "new_file.txt".to_string()],
        );
        assert!(result.is_ok(), "absorb failed: {:?}", result);

        // new_file.txt should still exist in working tree (skipped)
        assert_eq!(test_repo.read_file("new_file.txt"), "brand new");
    });
}

#[test]
fn absorb_skips_pure_addition() {
    let test_repo = TestRepo::new_with_remote();
    // Write multi-line content and commit it manually (so file content != message)
    test_repo.write_file("file1.txt", "line1\nline2\n");
    test_repo.stage_files(&["file1.txt"]);
    test_repo.commit_staged("Add file1");

    // Add lines without modifying existing ones
    test_repo.write_file("file1.txt", "line1\nline2\nnew line3\n");

    test_repo.in_dir(|| {
        let result = super::run(true, vec![]);
        // Should succeed as dry-run but skip the file (pure addition)
        // The error "No files could be absorbed" is expected when all are skipped
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("No files could be absorbed"),
            "Expected 'No files could be absorbed' error, got: {}",
            err_msg
        );
    });
}

#[test]
fn absorb_dry_run() {
    let test_repo = TestRepo::new_with_remote();
    test_repo.commit("Add file1", "file1.txt");

    let original_head = test_repo.head_oid();
    test_repo.write_file("file1.txt", "modified content");

    test_repo.in_dir(|| {
        let result = super::run(true, vec![]);
        assert!(result.is_ok(), "dry-run absorb failed: {:?}", result);

        // HEAD should NOT have changed (dry-run)
        assert_eq!(
            test_repo.head_oid(),
            original_head,
            "dry-run should not modify HEAD"
        );

        // Working tree changes should still be there
        assert_eq!(test_repo.read_file("file1.txt"), "modified content");
    });
}

#[test]
fn absorb_with_file_filter() {
    let test_repo = TestRepo::new_with_remote();
    test_repo.commit("Add file1", "file1.txt");
    test_repo.commit("Add file2", "file2.txt");

    // Modify both files
    test_repo.write_file("file1.txt", "modified file1");
    test_repo.write_file("file2.txt", "modified file2");

    test_repo.in_dir(|| {
        // Only absorb file1
        let result = super::run(false, vec!["file1.txt".to_string()]);
        assert!(result.is_ok(), "absorb failed: {:?}", result);

        // file2.txt should still have uncommitted changes
        assert_eq!(
            test_repo.read_file("file2.txt"),
            "modified file2",
            "file2 should still have working tree changes"
        );
    });
}

#[test]
fn absorb_no_changes_error() {
    let test_repo = TestRepo::new_with_remote();
    test_repo.commit("Add file1", "file1.txt");

    test_repo.in_dir(|| {
        let result = super::run(false, vec![]);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("Nothing to absorb"),
            "Expected 'Nothing to absorb' error, got: {}",
            err
        );
    });
}

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

    // Create an absorbable file
    test_repo.commit("Add tracked", "tracked.txt");

    // Modify tracked file (will be absorbed) and create a new untracked file
    test_repo.write_file("tracked.txt", "modified tracked");
    test_repo.write_file("untracked.txt", "new content");

    test_repo.in_dir(|| {
        // Pass both files explicitly — untracked.txt will be skipped (new file)
        let result = super::run(
            false,
            vec!["tracked.txt".to_string(), "untracked.txt".to_string()],
        );
        assert!(result.is_ok(), "absorb failed: {:?}", result);

        // untracked.txt should still exist with its content (skipped)
        assert_eq!(test_repo.read_file("untracked.txt"), "new content");
    });
}

#[test]
fn absorb_skips_multiple_sources() {
    let test_repo = TestRepo::new_with_remote();
    // Create two commits each introducing content in the same file.
    // Use manual staging to control exact file content per commit.
    test_repo.write_file("shared.txt", "line1 from c1\n");
    test_repo.stage_files(&["shared.txt"]);
    test_repo.commit_staged("Commit 1");

    test_repo.write_file("shared.txt", "line1 from c1\nline2 from c2\n");
    test_repo.stage_files(&["shared.txt"]);
    test_repo.commit_staged("Commit 2");

    // Modify lines from both commits
    test_repo.write_file("shared.txt", "MODIFIED line1\nMODIFIED line2\n");

    test_repo.in_dir(|| {
        let result = super::run(true, vec![]);
        // All files should be skipped → error
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("No files could be absorbed"),
            "Expected 'No files could be absorbed', got: {}",
            err_msg
        );
    });
}

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

    // Create a commit on the integration branch
    test_repo.commit("In-scope commit", "in_scope.txt");

    // Modify the in-scope file - verify it works
    test_repo.write_file("in_scope.txt", "modified");

    test_repo.in_dir(|| {
        let result = super::run(false, vec![]);
        assert!(result.is_ok(), "absorb should succeed for in-scope file");
    });
}

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

    // Create feature branch off base with a commit
    test_repo.create_branch_at("feat1", &base_oid.to_string());
    test_repo.switch_branch("feat1");
    test_repo.write_file("feature.txt", "initial feature content");
    test_repo.stage_files(&["feature.txt"]);
    test_repo.commit_staged("Feature 1");

    // Merge feat1 into integration branch
    test_repo.switch_branch("integration");
    test_repo.merge_no_ff("feat1");

    // Modify the feature file in working tree
    test_repo.write_file("feature.txt", "updated feature content");

    test_repo.in_dir(|| {
        let result = super::run(false, vec![]);
        assert!(
            result.is_ok(),
            "absorb with woven branches failed: {:?}",
            result
        );

        // Working tree should be clean (feature.txt absorbed)
        test_repo.assert_working_tree_clean();
    });
}

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

    // Create two commits with content in distant regions of the same file.
    // Need enough gap (>6 lines) between regions so git diff produces separate hunks.
    // Commit 1: lines 1-3 plus padding
    test_repo.write_file(
        "shared.txt",
        "line1 from c1\nline2 from c1\nline3 from c1\n\
         pad1\npad2\npad3\npad4\npad5\npad6\npad7\npad8\n",
    );
    test_repo.stage_files(&["shared.txt"]);
    test_repo.commit_staged("Commit 1");

    // Commit 2: appends lines far away from commit 1's region
    test_repo.write_file(
        "shared.txt",
        "line1 from c1\nline2 from c1\nline3 from c1\n\
         pad1\npad2\npad3\npad4\npad5\npad6\npad7\npad8\n\
         line12 from c2\nline13 from c2\nline14 from c2\n",
    );
    test_repo.stage_files(&["shared.txt"]);
    test_repo.commit_staged("Commit 2");

    // Modify lines from both commits — separate hunks due to distance
    test_repo.write_file(
        "shared.txt",
        "MODIFIED line1\nline2 from c1\nline3 from c1\n\
         pad1\npad2\npad3\npad4\npad5\npad6\npad7\npad8\n\
         MODIFIED line12\nline13 from c2\nline14 from c2\n",
    );

    test_repo.in_dir(|| {
        let result = super::run(false, vec![]);
        assert!(
            result.is_ok(),
            "hunk-level absorb should succeed: {:?}",
            result
        );

        // Working tree should be clean — both hunks absorbed
        test_repo.assert_working_tree_clean();

        // Commit messages preserved
        assert_eq!(test_repo.get_message(0), "Commit 2");
        assert_eq!(test_repo.get_message(1), "Commit 1");
    });
}

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

    test_repo.write_file("file.txt", "line1\nline2\nline3\n");
    test_repo.stage_files(&["file.txt"]);
    test_repo.commit_staged("Add file");

    // Modify line1 (absorbable) and append new lines (pure addition)
    test_repo.write_file(
        "file.txt",
        "MODIFIED line1\nline2\nline3\nnew line4\nnew line5\n",
    );

    test_repo.in_dir(|| {
        let result = super::run(false, vec![]);
        assert!(
            result.is_ok(),
            "mixed split absorb should succeed: {:?}",
            result
        );

        // The modified hunk should be absorbed, but pure addition stays in working tree
        let content = test_repo.read_file("file.txt");
        assert!(
            content.contains("new line4"),
            "pure addition hunk should remain in working tree"
        );
    });
}

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

    // Create two commits with separate files
    test_repo.write_file("absorbable.txt", "original content\n");
    test_repo.stage_files(&["absorbable.txt"]);
    test_repo.commit_staged("Add absorbable");

    test_repo.write_file("skippable.txt", "line1\nline2\n");
    test_repo.stage_files(&["skippable.txt"]);
    test_repo.commit_staged("Add skippable");

    // Modify absorbable.txt (will be absorbed into its commit)
    test_repo.write_file("absorbable.txt", "modified content\n");

    // Append pure-addition lines to skippable.txt (will be skipped)
    test_repo.write_file("skippable.txt", "line1\nline2\nnew line3\n");

    test_repo.in_dir(|| {
        let result = super::run(
            false,
            vec!["absorbable.txt".to_string(), "skippable.txt".to_string()],
        );
        assert!(result.is_ok(), "absorb failed: {:?}", result);

        // absorbable.txt should be clean (absorbed into its commit)
        let abs_diff =
            crate::git::diff_head_file(&std::path::PathBuf::from("."), "absorbable.txt").unwrap();
        assert!(
            abs_diff.is_empty(),
            "absorbable.txt should be clean after absorb, but has diff:\n{}",
            abs_diff
        );

        // skippable.txt should still have the pure-addition leftover
        let content = test_repo.read_file("skippable.txt");
        assert!(
            content.contains("new line3"),
            "skippable.txt should retain its skipped changes"
        );
    });
}

#[test]
fn absorb_file_with_sql_comment_lines() {
    let test_repo = TestRepo::new_with_remote();
    // Create a SQL file with comment lines
    test_repo.write_file("query.sql", "SELECT *\n-- main query\nFROM users\n");
    test_repo.stage_files(&["query.sql"]);
    test_repo.commit_staged("Add SQL query");

    // Modify the comment line
    test_repo.write_file("query.sql", "SELECT *\n-- updated query\nFROM users\n");

    test_repo.in_dir(|| {
        let result = super::run(false, vec![]);
        assert!(
            result.is_ok(),
            "absorb should handle -- lines: {:?}",
            result.err()
        );
        test_repo.assert_working_tree_clean();
        // Verify the change was absorbed
        let content = test_repo.read_file("query.sql");
        assert!(
            content.contains("-- updated query"),
            "absorbed content should contain the updated SQL comment"
        );
    });
}

#[test]
fn absorb_staged_only_changes() {
    let test_repo = TestRepo::new_with_remote();
    test_repo.commit("Add file", "target.txt");

    // Stage a change without leaving unstaged modifications
    test_repo.write_file("target.txt", "staged content\n");
    test_repo.stage_files(&["target.txt"]);

    test_repo.in_dir(|| {
        let result = super::run(false, vec![]);
        assert!(
            result.is_ok(),
            "absorb should handle staged-only changes: {:?}",
            result.err()
        );
        test_repo.assert_working_tree_clean();
    });
}

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

/// Regression: loom abort for absorb must restore the pre-absorb HEAD
/// (`reset_hard_to`) and re-apply saved staged/worktree patches.
///
/// Absorb creates fixup commits before the rebase, advancing HEAD. If the
/// rebase is aborted, `git rebase --abort` only restores HEAD to the
/// post-fixup state, not the original pre-absorb HEAD. The `reset_hard_to`
/// rollback field corrects this.
///
/// This test simulates absorb's pre-rebase state directly (saves patches,
/// clears working changes, creates a fixup commit, injects LoomState) and
/// then calls abort_cmd to verify the full rollback path.
#[test]
fn absorb_abort_preserves_working_state() {
    let test_repo = TestRepo::new_with_remote();

    // Commit the files that will serve as bystanders and the absorb target.
    // They must be committed so that `git diff HEAD` / `git diff --cached`
    // can capture modifications to them.
    test_repo.write_file("feature.txt", "original\n");
    test_repo.write_file("other-staged.txt", "original-staged\n");
    test_repo.write_file("other-unstaged.txt", "original-unstaged\n");
    test_repo.stage_files(&["feature.txt", "other-staged.txt", "other-unstaged.txt"]);
    test_repo.commit_staged("Initial setup");

    let pre_absorb_oid = test_repo.head_oid();

    // Set up bystander modifications (what the user has before running absorb).
    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"); // new untracked file

    // Modify feature.txt (this is what absorb would absorb).
    test_repo.write_file("feature.txt", "modified\n");

    let workdir = test_repo.workdir();
    let git_dir = test_repo.repo.path().to_path_buf();

    // Mirror absorb's pre-rebase cleanup sequence:
    // 1. Save staged diff (other-staged.txt).
    let saved_staged = crate::git::diff_cached_files(&workdir, &["other-staged.txt"]).unwrap();
    // 2. Unstage everything so that git diff HEAD captures all working changes.
    crate::git::run_git(&workdir, &["restore", "--staged", "."]).unwrap();
    // 3. Save full working-tree diff (other-staged.txt unstaged + other-unstaged.txt + feature.txt).
    let saved_worktree = crate::git::diff_head(&workdir).unwrap();
    // 4. Clear the working tree back to HEAD (absorb does this before creating fixup commits).
    //    new-file.txt is untracked and is not touched by `restore`.
    crate::git::run_git(&workdir, &["restore", "--staged", "--worktree", "."]).unwrap();

    // 5. Simulate absorb creating a fixup commit (HEAD moves past pre_absorb_oid).
    test_repo.write_file("feature.txt", "modified\n");
    test_repo.stage_files(&["feature.txt"]);
    test_repo.commit_staged("fixup! Initial setup");

    // Inject LoomState as absorb would save it before the rebase.
    let state = crate::core::transaction::LoomState {
        command: "absorb".to_string(),
        rollback: crate::core::transaction::Rollback {
            reset_hard_to: pre_absorb_oid.to_string(),
            saved_staged_patch: saved_staged,
            saved_worktree_patch: saved_worktree,
            ..Default::default()
        },
        context: serde_json::json!({ "dry_run": false }),
    };
    crate::core::transaction::save(&git_dir, &state).unwrap();

    // Abort (no active rebase; just applies rollback fields).
    crate::core::transaction::abort_cmd(&workdir, &git_dir).unwrap();

    // HEAD must be at the pre-absorb position (reset_hard_to undo the fixup commit).
    assert_eq!(
        test_repo.head_oid(),
        pre_absorb_oid,
        "HEAD must be restored to pre-absorb state"
    );

    // Bystander state preserved.
    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");
}