gitgrip 0.19.0

Multi-repo workflow tool - manage multiple git repositories as one
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
//! Integration tests for the sync command.

mod common;

use common::assertions::{assert_file_exists, assert_on_branch};
use common::fixtures::{write_griptree_config, WorkspaceBuilder};
use common::git_helpers;
use std::fs;
use std::path::Path;
use std::process::Command;

fn git(dir: &Path, args: &[&str]) {
    let output = Command::new("git")
        .current_dir(dir)
        .args(args)
        .output()
        .unwrap_or_else(|e| panic!("failed to run git {:?}: {}", args, e));
    assert!(
        output.status.success(),
        "git {:?} failed in {}: {}",
        args,
        dir.display(),
        String::from_utf8_lossy(&output.stderr)
    );
}

#[tokio::test]
async fn test_sync_clones_missing_repos() {
    let ws = WorkspaceBuilder::new()
        .add_repo("frontend")
        .add_repo("backend")
        .build();

    // Remove one repo to simulate "not cloned"
    std::fs::remove_dir_all(ws.repo_path("backend")).unwrap();
    assert!(!ws.repo_path("backend").exists());

    let manifest = ws.load_manifest();

    let result = gitgrip::cli::commands::sync::run_sync(
        &ws.workspace_root,
        &manifest,
        false,
        false,
        None,
        None,
        false,
        false,
        false,
        false,
    )
    .await;
    assert!(result.is_ok(), "sync should succeed: {:?}", result.err());

    // backend should now be cloned
    assert!(ws.repo_path("backend").join(".git").exists());
    assert_on_branch(&ws.repo_path("backend"), "main");
}

#[tokio::test]
async fn test_sync_pulls_existing_repos() {
    let ws = WorkspaceBuilder::new().add_repo("app").build();

    // Push a new commit to the bare remote (simulating upstream changes)
    let staging = ws._temp.path().join("sync-staging");
    git_helpers::clone_repo(&ws.remote_url("app"), &staging);
    git_helpers::commit_file(&staging, "new-file.txt", "content", "Add new file");
    git_helpers::push_branch(&staging, "origin", "main");

    let manifest = ws.load_manifest();

    let result = gitgrip::cli::commands::sync::run_sync(
        &ws.workspace_root,
        &manifest,
        false,
        false,
        None,
        None,
        false,
        false,
        false,
        false,
    )
    .await;
    assert!(result.is_ok(), "sync should succeed: {:?}", result.err());

    // The new file should now exist in the workspace repo
    assert_file_exists(&ws.repo_path("app").join("new-file.txt"));
}

#[tokio::test]
async fn test_sync_uses_griptree_upstream_mapping() {
    let ws = WorkspaceBuilder::new().add_repo("app").build();

    let staging = ws._temp.path().join("sync-upstream-staging");
    git_helpers::clone_repo(&ws.remote_url("app"), &staging);
    git_helpers::create_branch(&staging, "dev");
    git_helpers::commit_file(&staging, "dev-only.txt", "dev", "Add dev file");
    git_helpers::push_branch(&staging, "origin", "dev");

    git_helpers::create_branch(&ws.repo_path("app"), "feat/griptree");

    write_griptree_config(&ws.workspace_root, "feat/griptree", "app", "origin/dev");
    let manifest = ws.load_manifest();

    let result = gitgrip::cli::commands::sync::run_sync(
        &ws.workspace_root,
        &manifest,
        false,
        false,
        None,
        None,
        false,
        false,
        false,
        false,
    )
    .await;
    assert!(result.is_ok(), "sync should succeed: {:?}", result.err());

    assert_file_exists(&ws.repo_path("app").join("dev-only.txt"));
}

#[tokio::test]
async fn test_sync_sets_tracking_upstream_for_griptree_base_branch() {
    let ws = WorkspaceBuilder::new().add_repo("app").build();

    git_helpers::create_branch(&ws.repo_path("app"), "feat/griptree");
    assert_eq!(
        git_helpers::branch_upstream(&ws.repo_path("app"), "feat/griptree"),
        None
    );

    write_griptree_config(&ws.workspace_root, "feat/griptree", "app", "origin/main");
    let manifest = ws.load_manifest();

    let result = gitgrip::cli::commands::sync::run_sync(
        &ws.workspace_root,
        &manifest,
        false,
        false,
        None,
        None,
        false,
        false,
        false,
        false,
    )
    .await;
    assert!(result.is_ok(), "sync should succeed: {:?}", result.err());

    assert_eq!(
        git_helpers::branch_upstream(&ws.repo_path("app"), "feat/griptree"),
        Some("origin/main".to_string())
    );
}

#[tokio::test]
async fn test_sync_handles_up_to_date() {
    let ws = WorkspaceBuilder::new().add_repo("app").build();

    let manifest = ws.load_manifest();

    // Sync when already up to date
    let result = gitgrip::cli::commands::sync::run_sync(
        &ws.workspace_root,
        &manifest,
        false,
        false,
        None,
        None,
        false,
        false,
        false,
        false,
    )
    .await;
    assert!(
        result.is_ok(),
        "sync should succeed when up to date: {:?}",
        result.err()
    );
}

#[tokio::test]
async fn test_sync_skips_griptree_base_with_local_commits_ahead() {
    let ws = WorkspaceBuilder::new().add_repo("app").build();

    git_helpers::create_branch(&ws.repo_path("app"), "feat/griptree");
    git_helpers::commit_file(
        &ws.repo_path("app"),
        "local-only.txt",
        "local",
        "Add local-only file",
    );

    let staging = ws._temp.path().join("sync-diverge-staging");
    git_helpers::clone_repo(&ws.remote_url("app"), &staging);
    git_helpers::commit_file(&staging, "upstream.txt", "upstream", "Add upstream file");
    git_helpers::push_branch(&staging, "origin", "main");

    write_griptree_config(&ws.workspace_root, "feat/griptree", "app", "origin/main");
    let manifest = ws.load_manifest();

    let result = gitgrip::cli::commands::sync::run_sync(
        &ws.workspace_root,
        &manifest,
        false,
        false,
        None,
        None,
        false,
        false,
        false,
        false,
    )
    .await;
    assert!(result.is_ok(), "sync should succeed: {:?}", result.err());

    assert_file_exists(&ws.repo_path("app").join("local-only.txt"));
    assert!(
        !ws.repo_path("app").join("upstream.txt").exists(),
        "expected sync to skip pulling upstream changes"
    );
    assert_on_branch(&ws.repo_path("app"), "feat/griptree");
}

#[tokio::test]
async fn test_sync_reset_refs_hard_resets_reference_repo() {
    let ws = WorkspaceBuilder::new().add_reference_repo("ref").build();

    let remote_sha = git_helpers::get_head_sha(&ws.remote_path("ref"));

    git_helpers::commit_file(
        &ws.repo_path("ref"),
        "local-only.txt",
        "local",
        "Add local-only file",
    );

    let local_sha = git_helpers::get_head_sha(&ws.repo_path("ref"));
    assert_ne!(local_sha, remote_sha);

    let manifest = ws.load_manifest();
    let result = gitgrip::cli::commands::sync::run_sync(
        &ws.workspace_root,
        &manifest,
        false,
        false,
        None,
        None,
        false,
        true,
        false,
        false,
    )
    .await;
    assert!(result.is_ok(), "sync should succeed: {:?}", result.err());

    let synced_sha = git_helpers::get_head_sha(&ws.repo_path("ref"));
    let remote_sha_after = git_helpers::get_head_sha(&ws.remote_path("ref"));
    assert_eq!(synced_sha, remote_sha_after);
    assert!(
        !ws.repo_path("ref").join("local-only.txt").exists(),
        "expected reset to discard local changes"
    );
}

#[tokio::test]
async fn test_sync_reset_refs_checks_out_upstream_branch() {
    let ws = WorkspaceBuilder::new().add_reference_repo("ref").build();

    let staging = ws._temp.path().join("sync-ref-staging");
    git_helpers::clone_repo(&ws.remote_url("ref"), &staging);
    git_helpers::create_branch(&staging, "dev");
    git_helpers::commit_file(&staging, "dev-only.txt", "dev", "Add dev file");
    git_helpers::push_branch(&staging, "origin", "dev");

    git_helpers::create_branch(&ws.repo_path("ref"), "codi-gripspace");

    write_griptree_config(&ws.workspace_root, "feat/griptree", "ref", "origin/dev");
    let manifest = ws.load_manifest();

    let result = gitgrip::cli::commands::sync::run_sync(
        &ws.workspace_root,
        &manifest,
        false,
        false,
        None,
        None,
        false,
        true,
        false,
        false,
    )
    .await;
    assert!(result.is_ok(), "sync should succeed: {:?}", result.err());

    assert_on_branch(&ws.repo_path("ref"), "dev");
    assert_file_exists(&ws.repo_path("ref").join("dev-only.txt"));
}

#[tokio::test]
async fn test_sync_reset_refs_falls_back_to_detached_when_branch_locked_in_worktree() {
    let ws = WorkspaceBuilder::new().add_reference_repo("ref").build();

    let staging = ws._temp.path().join("sync-ref-locked-branch-staging");
    git_helpers::clone_repo(&ws.remote_url("ref"), &staging);
    git_helpers::create_branch(&staging, "dev");
    git_helpers::commit_file(&staging, "dev-only.txt", "dev", "Add dev file");
    git_helpers::push_branch(&staging, "origin", "dev");

    let ref_repo = ws.repo_path("ref");
    git(&ref_repo, &["fetch", "origin", "dev:dev"]);

    let locked_worktree = ws._temp.path().join("ref-dev-worktree");
    git(
        &ref_repo,
        &["worktree", "add", locked_worktree.to_str().unwrap(), "dev"],
    );

    git_helpers::commit_file(&ref_repo, "local-only.txt", "local", "Add local-only file");

    write_griptree_config(&ws.workspace_root, "feat/griptree", "ref", "origin/dev");
    let manifest = ws.load_manifest();

    let result = gitgrip::cli::commands::sync::run_sync(
        &ws.workspace_root,
        &manifest,
        false,
        false,
        None,
        None,
        false,
        true,
        false,
        false,
    )
    .await;
    assert!(result.is_ok(), "sync should succeed: {:?}", result.err());

    assert_file_exists(&ref_repo.join("dev-only.txt"));
    assert!(
        !ref_repo.join("local-only.txt").exists(),
        "expected reset to discard local changes"
    );

    let repo = gitgrip::git::open_repo(&ref_repo).expect("open repo");
    let head = gitgrip::git::get_current_branch(&repo).expect("current branch");
    assert!(
        head.starts_with("(HEAD detached at "),
        "expected detached HEAD fallback, got: {}",
        head
    );

    git(
        &ref_repo,
        &[
            "worktree",
            "remove",
            "--force",
            locked_worktree.to_str().unwrap(),
        ],
    );
}

#[tokio::test]
async fn test_sync_multiple_repos() {
    let ws = WorkspaceBuilder::new()
        .add_repo("alpha")
        .add_repo("beta")
        .add_repo("gamma")
        .build();

    // Remove alpha and beta to test clone
    std::fs::remove_dir_all(ws.repo_path("alpha")).unwrap();
    std::fs::remove_dir_all(ws.repo_path("beta")).unwrap();

    let manifest = ws.load_manifest();

    let result = gitgrip::cli::commands::sync::run_sync(
        &ws.workspace_root,
        &manifest,
        false,
        false,
        None,
        None,
        false,
        false,
        false,
        false,
    )
    .await;
    assert!(result.is_ok(), "sync should succeed: {:?}", result.err());

    // All should now be cloned
    assert!(ws.repo_path("alpha").join(".git").exists());
    assert!(ws.repo_path("beta").join(".git").exists());
    assert!(ws.repo_path("gamma").join(".git").exists());
}

#[tokio::test]
async fn test_sync_quiet_mode() {
    let ws = WorkspaceBuilder::new()
        .add_repo("frontend")
        .add_repo("backend")
        .build();

    let manifest = ws.load_manifest();

    // Quiet sync on already-synced repos should succeed (suppresses "up to date" messages)
    let result = gitgrip::cli::commands::sync::run_sync(
        &ws.workspace_root,
        &manifest,
        false,
        true,
        None,
        None,
        false,
        false,
        false,
        false,
    )
    .await;
    assert!(
        result.is_ok(),
        "quiet sync should succeed: {:?}",
        result.err()
    );
}

#[tokio::test]
async fn test_sync_sequential_mode() {
    let ws = WorkspaceBuilder::new()
        .add_repo("frontend")
        .add_repo("backend")
        .build();

    let manifest = ws.load_manifest();

    // Sequential sync (--sequential flag)
    let result = gitgrip::cli::commands::sync::run_sync(
        &ws.workspace_root,
        &manifest,
        false,
        false,
        None,
        None,
        true,
        false,
        false,
        false,
    )
    .await;
    assert!(
        result.is_ok(),
        "sequential sync should succeed: {:?}",
        result.err()
    );
}

#[tokio::test]
async fn test_sync_clone_failure_invalid_url() {
    let ws = WorkspaceBuilder::new().add_repo("app").build();
    let mut manifest = ws.load_manifest();

    // Force clone path: delete repo and replace URL with invalid path
    fs::remove_dir_all(ws.repo_path("app")).unwrap();
    assert!(!ws.repo_path("app").exists());
    manifest.repos.get_mut("app").expect("app repo config").url =
        Some("file:///does-not-exist/repo.git".to_string());

    let result = gitgrip::cli::commands::sync::run_sync(
        &ws.workspace_root,
        &manifest,
        false,
        false,
        None,
        None,
        false,
        false,
        false,
        false,
    )
    .await;
    assert!(result.is_ok(), "sync should not crash: {:?}", result.err());

    // Clone should fail, leaving no git metadata
    assert!(
        !ws.repo_path("app").join(".git").exists(),
        "expected clone to fail without .git"
    );
}

#[tokio::test]
async fn test_sync_existing_repo_missing_git_dir() {
    let ws = WorkspaceBuilder::new().add_repo("app").build();
    let manifest = ws.load_manifest();

    // Corrupt repo by removing .git
    fs::remove_dir_all(ws.repo_path("app").join(".git")).unwrap();
    assert!(!ws.repo_path("app").join(".git").exists());

    let result = gitgrip::cli::commands::sync::run_sync(
        &ws.workspace_root,
        &manifest,
        false,
        false,
        None,
        None,
        false,
        false,
        false,
        false,
    )
    .await;
    assert!(result.is_ok(), "sync should not crash: {:?}", result.err());

    // Sync should report error and leave repo unchanged (still missing .git)
    assert!(
        !ws.repo_path("app").join(".git").exists(),
        "expected sync to fail for non-git directory"
    );
}

/// Helper to append workspace hooks to the manifest YAML
fn append_hooks_to_manifest(workspace_root: &Path, hooks_yaml: &str) {
    let manifest_path = workspace_root
        .join(".gitgrip")
        .join("spaces")
        .join("main")
        .join("gripspace.yml");
    let mut content = fs::read_to_string(&manifest_path).unwrap();
    content.push_str(hooks_yaml);
    fs::write(&manifest_path, content).unwrap();
}

#[tokio::test]
async fn test_sync_runs_post_sync_hooks_always() {
    let ws = WorkspaceBuilder::new().add_repo("app").build();

    // Add a hook that creates a marker file (condition: always)
    let marker = ws.workspace_root.join("hook-ran.txt");
    let hooks_yaml = format!(
        r#"
workspace:
  hooks:
    post-sync:
      - name: create-marker
        command: echo "hook executed" > "{}"
        condition: always
"#,
        marker.display()
    );
    append_hooks_to_manifest(&ws.workspace_root, &hooks_yaml);

    let manifest = ws.load_manifest();
    let result = gitgrip::cli::commands::sync::run_sync(
        &ws.workspace_root,
        &manifest,
        false,
        true,
        None,
        None,
        false,
        false,
        false,
        false,
    )
    .await;
    assert!(result.is_ok(), "sync should succeed: {:?}", result.err());
    assert!(marker.exists(), "hook marker file should have been created");
}

#[tokio::test]
async fn test_sync_hook_failure_is_warning_not_error() {
    let ws = WorkspaceBuilder::new().add_repo("app").build();

    // Add a hook that fails
    let hooks_yaml = r#"
workspace:
  hooks:
    post-sync:
      - name: failing-hook
        command: exit 1
        condition: always
"#;
    append_hooks_to_manifest(&ws.workspace_root, hooks_yaml);

    let manifest = ws.load_manifest();
    let result = gitgrip::cli::commands::sync::run_sync(
        &ws.workspace_root,
        &manifest,
        false,
        true,
        None,
        None,
        false,
        false,
        false,
        false,
    )
    .await;
    // Sync should still succeed even though hook failed
    assert!(
        result.is_ok(),
        "sync should succeed even when hook fails: {:?}",
        result.err()
    );
}

#[tokio::test]
async fn test_sync_no_hooks_flag_skips_hooks() {
    let ws = WorkspaceBuilder::new().add_repo("app").build();

    // Add a hook that creates a marker file
    let marker = ws.workspace_root.join("no-hooks-marker.txt");
    let hooks_yaml = format!(
        r#"
workspace:
  hooks:
    post-sync:
      - name: create-marker
        command: echo "should not run" > "{}"
        condition: always
"#,
        marker.display()
    );
    append_hooks_to_manifest(&ws.workspace_root, &hooks_yaml);

    let manifest = ws.load_manifest();
    let result = gitgrip::cli::commands::sync::run_sync(
        &ws.workspace_root,
        &manifest,
        false,
        true,
        None,
        None,
        false,
        false,
        false,
        true, // no_hooks = true
    )
    .await;
    assert!(result.is_ok(), "sync should succeed: {:?}", result.err());
    assert!(
        !marker.exists(),
        "hook marker file should NOT exist when --no-hooks is set"
    );
}

/// grip#468: `gr sync` should auto-reclone spaces/main when it exists but has no .git
#[tokio::test]
async fn test_sync_reclones_non_git_manifest_dir() {
    use tempfile::TempDir;

    let temp = TempDir::new().unwrap();
    let workspace_root = temp.path().join("workspace");
    let remotes_dir = temp.path().join("remotes");
    fs::create_dir_all(&workspace_root).unwrap();
    fs::create_dir_all(&remotes_dir).unwrap();

    // Set up a bare remote for the manifest repo
    let manifest_remote = remotes_dir.join("manifest.git");
    git_helpers::init_bare_repo(&manifest_remote);

    // Commit a gripspace.yml to the manifest remote via a staging repo
    let manifest_staging = temp.path().join("manifest-staging");
    git_helpers::init_repo(&manifest_staging);
    let manifest_url = format!("file://{}", manifest_remote.display());
    let manifest_yaml = "version: 1\nrepos: {}\n";
    git_helpers::commit_file(
        &manifest_staging,
        "gripspace.yml",
        manifest_yaml,
        "Initial manifest",
    );
    git_helpers::add_remote(&manifest_staging, "origin", &manifest_url);
    git_helpers::push_upstream(&manifest_staging, "origin", "main");

    // Clone the manifest remote into spaces/main/ (normal first-time setup)
    let spaces_main = workspace_root.join(".gitgrip").join("spaces").join("main");
    git_helpers::clone_repo(&manifest_url, &spaces_main);

    // Verify it's a proper git clone before we corrupt it
    assert!(
        spaces_main.join(".git").exists(),
        "pre-condition: should be a git repo"
    );

    // Simulate corruption: remove .git from spaces/main/ (the bug scenario)
    fs::remove_dir_all(spaces_main.join(".git")).unwrap();
    assert!(
        !spaces_main.join(".git").exists(),
        "pre-condition: .git removed"
    );

    // Build a manifest that includes manifest.url so recover_manifest_repo can re-clone
    let manifest_with_url = format!(
        "version: 1\nmanifest:\n  url: {}\n  default_branch: main\nrepos: {{}}\n",
        manifest_url
    );
    fs::write(spaces_main.join("gripspace.yml"), &manifest_with_url).unwrap();

    let manifest = gitgrip::core::manifest::Manifest::parse_raw(&manifest_with_url)
        .expect("failed to parse test manifest");

    let result = gitgrip::cli::commands::sync::run_sync(
        &workspace_root,
        &manifest,
        false,
        true, // quiet
        None,
        None,
        false,
        false,
        false,
        false,
    )
    .await;

    assert!(
        result.is_ok(),
        "sync should succeed after auto-recovery: {:?}",
        result.err()
    );

    // spaces/main/ should now have a .git (re-cloned)
    assert!(
        spaces_main.join(".git").exists(),
        "spaces/main/ should be a git repo after auto-recovery"
    );
}