git-synchronizer 0.1.1

Easily synchronize your local branches and worktrees
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
use std::path::Path;
use std::process::Command;

use anyhow::{Context, Result, bail};

/// Run a git command and return its stdout as a trimmed string.
///
/// If `verbose` is true the command is printed to stderr before execution.
fn run_git(args: &[&str], verbose: bool, workdir: Option<&Path>) -> Result<String> {
    if verbose {
        eprintln!("  $ git {}", args.join(" "));
    }

    let mut cmd = Command::new("git");
    cmd.args(args);
    if let Some(dir) = workdir {
        cmd.current_dir(dir);
    }

    let output = cmd
        .output()
        .with_context(|| format!("failed to execute: git {}", args.join(" ")))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!(
            "git {} failed (exit {}):\n{}",
            args.join(" "),
            output.status,
            stderr.trim()
        );
    }

    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}

/// Run an external command (not git) and return its stdout as a trimmed string.
///
/// If `verbose` is true the command is printed to stderr before execution.
fn run_cmd(bin: &str, args: &[&str], verbose: bool, workdir: Option<&Path>) -> Result<String> {
    if verbose {
        eprintln!("  $ {} {}", bin, args.join(" "));
    }

    let mut cmd = Command::new(bin);
    cmd.args(args);
    if let Some(dir) = workdir {
        cmd.current_dir(dir);
    }

    let output = cmd
        .output()
        .with_context(|| format!("failed to execute: {} {}", bin, args.join(" ")))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!(
            "{} {} failed (exit {}):\n{}",
            bin,
            args.join(" "),
            output.status,
            stderr.trim()
        );
    }

    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}

/// Check if the worktrunk CLI (`wt`) is available on `$PATH`.
pub fn worktrunk_available() -> bool {
    Command::new("wt")
        .arg("--version")
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .is_ok()
}

/// A thin wrapper around git CLI invocations.
pub struct Git {
    verbose: bool,
    workdir: Option<std::path::PathBuf>,
}

impl Git {
    pub fn new(verbose: bool) -> Self {
        Self {
            verbose,
            workdir: None,
        }
    }

    /// Create a Git instance that operates in a specific directory.
    #[cfg(test)]
    pub fn with_workdir(verbose: bool, workdir: &Path) -> Self {
        Self {
            verbose,
            workdir: Some(workdir.to_path_buf()),
        }
    }

    fn run(&self, args: &[&str]) -> Result<String> {
        run_git(args, self.verbose, self.workdir.as_deref())
    }

    fn run_wt(&self, args: &[&str]) -> Result<String> {
        run_cmd("wt", args, self.verbose, self.workdir.as_deref())
    }

    // ── Repository info ──────────────────────────────────────────────

    /// Return the current branch name.
    pub fn current_branch(&self) -> Result<String> {
        self.run(&["rev-parse", "--abbrev-ref", "HEAD"])
    }

    /// Return the list of configured remotes.
    pub fn remotes(&self) -> Result<Vec<String>> {
        let out = self.run(&["remote"])?;
        Ok(out.lines().map(|l| l.to_string()).collect())
    }

    // ── Fetch ────────────────────────────────────────────────────────

    /// Fetch all remotes and prune deleted remote-tracking branches.
    pub fn remote_update_prune(&self) -> Result<()> {
        self.run(&["remote", "update", "--prune"])?;
        Ok(())
    }

    // ── Branch queries ───────────────────────────────────────────────

    /// Return local branches that have been merged into `target`.
    pub fn merged_branches(&self, target: &str) -> Result<Vec<String>> {
        let out = self.run(&["branch", "--merged", target])?;
        Ok(parse_branch_list(&out))
    }

    /// Return all local branch names.
    pub fn local_branches(&self) -> Result<Vec<String>> {
        let out = self.run(&["branch", "--format=%(refname:short)"])?;
        Ok(out
            .lines()
            .filter(|l| !l.is_empty())
            .map(|l| l.to_string())
            .collect())
    }

    /// Return remote-tracking branches merged into `target` for the given remote.
    pub fn merged_remote_branches(&self, target: &str, remote: &str) -> Result<Vec<String>> {
        let out = self.run(&["branch", "-r", "--merged", target])?;
        let prefix = format!("{remote}/");
        Ok(out
            .lines()
            .map(|l| l.trim())
            .filter(|l| l.starts_with(&prefix) && !l.contains("->"))
            .map(|l| l.strip_prefix(&prefix).unwrap_or(l).to_string())
            .collect())
    }

    /// Use `git cherry` to detect rebase-merged branches.
    ///
    /// Returns branch names whose commits have all been applied upstream.
    pub fn cherry_merged(&self, upstream: &str, branch: &str) -> Result<bool> {
        let out = self.run(&["cherry", upstream, branch])?;
        // If all lines start with `-`, every commit was cherry-picked upstream.
        Ok(!out.is_empty() && out.lines().all(|l| l.starts_with('-')))
    }

    // ── Branch mutations ─────────────────────────────────────────────

    /// Delete a local branch (force).
    ///
    /// Uses `-D` instead of `-d` because the caller has already verified the
    /// branch is merged into a protected target. The soft `-d` flag only
    /// checks against HEAD which fails when running from a linked worktree
    /// whose HEAD differs from the merge target.
    pub fn branch_delete(&self, branch: &str) -> Result<()> {
        self.run(&["branch", "-D", branch])?;
        Ok(())
    }

    /// Delete a branch on a remote (with --force-with-lease for safety).
    pub fn push_delete(&self, remote: &str, branch: &str) -> Result<()> {
        self.run(&["push", "--delete", "--force-with-lease", remote, branch])?;
        Ok(())
    }

    // ── Worktree operations ──────────────────────────────────────────

    /// Parsed worktree entry from `git worktree list --porcelain`.
    pub fn worktree_list(&self) -> Result<Vec<Worktree>> {
        let out = self.run(&["worktree", "list", "--porcelain"])?;
        Ok(parse_worktree_list(&out))
    }

    /// Remove a worktree by path.
    pub fn worktree_remove(&self, path: &str) -> Result<()> {
        self.run(&["worktree", "remove", path])?;
        Ok(())
    }

    // ── Worktrunk integration ────────────────────────────────────────

    /// Check if a worktrunk config section exists in git config.
    ///
    /// Worktrunk stores its state under the `[worktrunk]` git config section.
    /// Its presence indicates the repository is managed by worktrunk.
    pub fn worktrunk_config_exists(&self) -> Result<bool> {
        self.config_section_exists("worktrunk")
    }

    /// Remove a worktree via the worktrunk CLI, triggering pre/post-remove hooks.
    ///
    /// Uses `--foreground` to wait for hooks to complete, `--yes` to skip
    /// wt's approval prompts (git-sync already confirmed with the user), and
    /// `--no-delete-branch` because git-sync manages branch deletion separately.
    pub fn worktrunk_remove(&self, branch: &str) -> Result<()> {
        self.run_wt(&[
            "remove",
            branch,
            "--foreground",
            "--yes",
            "--no-delete-branch",
        ])?;
        Ok(())
    }

    /// Remove a worktree via the worktrunk CLI using its path.
    ///
    /// Used for detached HEAD worktrees or orphans where the branch name
    /// is not available. Falls back to path-based removal.
    pub fn worktrunk_remove_by_path(&self, path: &str) -> Result<()> {
        self.run_wt(&[
            "remove",
            path,
            "--foreground",
            "--yes",
            "--no-delete-branch",
        ])?;
        Ok(())
    }

    // ── Config operations ────────────────────────────────────────────

    /// Get all values for a multi-valued config key.
    pub fn config_get_all(&self, key: &str) -> Result<Vec<String>> {
        match self.run(&["config", "--get-all", key]) {
            Ok(out) => Ok(out
                .lines()
                .filter(|l| !l.is_empty())
                .map(|l| l.to_string())
                .collect()),
            Err(_) => Ok(vec![]),
        }
    }

    /// Get a single config value.
    pub fn config_get(&self, key: &str) -> Result<Option<String>> {
        match self.run(&["config", "--get", key]) {
            Ok(val) if !val.is_empty() => Ok(Some(val)),
            _ => Ok(None),
        }
    }

    /// Set a single-valued config key.
    ///
    /// Uses `--local` to ensure the value is written to the shared
    /// `.git/config` even when `extensions.worktreeConfig` is enabled
    /// (where the default write scope would target the per-worktree
    /// config file instead).
    pub fn config_set(&self, key: &str, value: &str) -> Result<()> {
        self.run(&["config", "--local", key, value])?;
        Ok(())
    }

    /// Add a value to a multi-valued config key.
    ///
    /// Uses `--local` to target the shared `.git/config`.
    /// See [`config_set`](Self::config_set) for rationale.
    pub fn config_add(&self, key: &str, value: &str) -> Result<()> {
        self.run(&["config", "--local", "--add", key, value])?;
        Ok(())
    }

    /// Remove all values for a config key.
    ///
    /// Uses `--local` to target the shared `.git/config`.
    /// See [`config_set`](Self::config_set) for rationale.
    pub fn config_unset_all(&self, key: &str) -> Result<()> {
        // --unset-all exits non-zero if the key doesn't exist; that's fine.
        let _ = self.run(&["config", "--local", "--unset-all", key]);
        Ok(())
    }

    /// Check whether a config section exists.
    pub fn config_section_exists(&self, section: &str) -> Result<bool> {
        match self.run(&["config", "--get-regexp", &format!("^{section}\\.")]) {
            Ok(out) => Ok(!out.is_empty()),
            Err(_) => Ok(false),
        }
    }

    // ── Per-branch protection ────────────────────────────────────────

    /// Return the names of branches that have
    /// `branch.<name>.sync-protected = true` in git config.
    pub fn branch_protected_list(&self) -> Result<Vec<String>> {
        let pattern = r"^branch\..*\.sync-protected$";
        match self.run(&["config", "--get-regexp", pattern]) {
            Ok(out) => {
                let mut branches = Vec::new();
                for line in out.lines().filter(|l| !l.is_empty()) {
                    // Each line: "branch.<name>.sync-protected true"
                    let mut parts = line.splitn(2, ' ');
                    if let (Some(key), Some(value)) = (parts.next(), parts.next())
                        && value.trim().eq_ignore_ascii_case("true")
                    {
                        // Extract branch name from "branch.<name>.sync-protected"
                        if let Some(name) = key
                            .strip_prefix("branch.")
                            .and_then(|s| s.strip_suffix(".sync-protected"))
                        {
                            branches.push(name.to_string());
                        }
                    }
                }
                Ok(branches)
            }
            Err(_) => Ok(vec![]),
        }
    }

    /// Set or unset per-branch protection for a given branch.
    ///
    /// When `protected` is `true`, sets `branch.<name>.sync-protected = true`.
    /// When `false`, unsets the key entirely.
    ///
    /// Uses `--local` to target the shared `.git/config`.
    /// See [`config_set`](Self::config_set) for rationale.
    pub fn set_branch_protected(&self, branch: &str, protected: bool) -> Result<()> {
        let key = format!("branch.{branch}.sync-protected");
        if protected {
            self.run(&["config", "--local", &key, "true"])?;
        } else {
            // --unset exits non-zero if the key doesn't exist; that's fine.
            let _ = self.run(&["config", "--local", "--unset", &key]);
        }
        Ok(())
    }
}

// ── Parsing helpers ──────────────────────────────────────────────────

/// A worktree entry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Worktree {
    pub path: String,
    pub head: Option<String>,
    pub branch: Option<String>,
    pub is_bare: bool,
}

/// Parse `git branch` output (with leading `*`, `+` and whitespace).
///
/// `*` marks the current branch, `+` marks branches checked out in
/// other linked worktrees — both are stripped.
fn parse_branch_list(output: &str) -> Vec<String> {
    output
        .lines()
        .map(|l| l.trim())
        .filter(|l| !l.is_empty() && !l.starts_with('*'))
        .map(|l| l.strip_prefix("+ ").unwrap_or(l).to_string())
        .collect()
}

/// Parse `git worktree list --porcelain` output.
fn parse_worktree_list(output: &str) -> Vec<Worktree> {
    let mut worktrees = Vec::new();
    let mut current: Option<Worktree> = None;

    for line in output.lines() {
        if let Some(path) = line.strip_prefix("worktree ") {
            if let Some(wt) = current.take() {
                worktrees.push(wt);
            }
            current = Some(Worktree {
                path: path.to_string(),
                head: None,
                branch: None,
                is_bare: false,
            });
        } else if let Some(head) = line.strip_prefix("HEAD ") {
            if let Some(ref mut wt) = current {
                wt.head = Some(head.to_string());
            }
        } else if let Some(branch) = line.strip_prefix("branch ") {
            if let Some(ref mut wt) = current {
                // Strip refs/heads/ prefix
                wt.branch = Some(
                    branch
                        .strip_prefix("refs/heads/")
                        .unwrap_or(branch)
                        .to_string(),
                );
            }
        } else if line == "bare"
            && let Some(ref mut wt) = current
        {
            wt.is_bare = true;
        }
    }

    if let Some(wt) = current {
        worktrees.push(wt);
    }

    worktrees
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_branch_list() {
        let output = "  feature/foo\n* main\n  bugfix/bar\n";
        let branches = parse_branch_list(output);
        assert_eq!(branches, vec!["feature/foo", "bugfix/bar"]);
    }

    #[test]
    fn test_parse_branch_list_strips_worktree_marker() {
        let output = "  feature/foo\n* main\n+ feature/wt\n  bugfix/bar\n";
        let branches = parse_branch_list(output);
        assert_eq!(branches, vec!["feature/foo", "feature/wt", "bugfix/bar"]);
    }

    #[test]
    fn test_parse_branch_list_empty() {
        let branches = parse_branch_list("");
        assert!(branches.is_empty());
    }

    #[test]
    fn test_parse_worktree_list() {
        let output = "\
worktree /home/user/project
HEAD abc1234
branch refs/heads/main

worktree /home/user/project-feature
HEAD def5678
branch refs/heads/feature/foo

worktree /home/user/project-bare
HEAD 000000
bare
";
        let worktrees = parse_worktree_list(output);
        assert_eq!(worktrees.len(), 3);

        assert_eq!(worktrees[0].path, "/home/user/project");
        assert_eq!(worktrees[0].branch.as_deref(), Some("main"));
        assert!(!worktrees[0].is_bare);

        assert_eq!(worktrees[1].path, "/home/user/project-feature");
        assert_eq!(worktrees[1].branch.as_deref(), Some("feature/foo"));

        assert_eq!(worktrees[2].path, "/home/user/project-bare");
        assert!(worktrees[2].is_bare);
    }

    #[test]
    fn test_parse_worktree_list_empty() {
        let worktrees = parse_worktree_list("");
        assert!(worktrees.is_empty());
    }

    /// Integration test: verify basic git operations in a temporary repo.
    #[test]
    fn test_git_in_temp_repo() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let path = dir.path();

        // Initialize a bare-minimum repo
        Command::new("git")
            .args(["init", "--initial-branch=main"])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["config", "user.email", "test@test.com"])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["config", "user.name", "Test"])
            .current_dir(path)
            .output()?;

        // Create an initial commit
        std::fs::write(path.join("README.md"), "# test")?;
        Command::new("git")
            .args(["add", "."])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["commit", "-m", "init"])
            .current_dir(path)
            .output()?;

        let git = Git::with_workdir(false, path);

        // Test current branch
        assert_eq!(git.current_branch()?, "main");

        // Test local branches
        let branches = git.local_branches()?;
        assert_eq!(branches, vec!["main"]);

        // Create a feature branch and merge it
        Command::new("git")
            .args(["checkout", "-b", "feature/test"])
            .current_dir(path)
            .output()?;
        std::fs::write(path.join("feature.txt"), "feature")?;
        Command::new("git")
            .args(["add", "."])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["commit", "-m", "feature"])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["checkout", "main"])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["merge", "feature/test"])
            .current_dir(path)
            .output()?;

        // The feature branch should show up as merged
        let merged = git.merged_branches("main")?;
        assert!(merged.contains(&"feature/test".to_string()));

        // Config operations
        git.config_add("sync.protected", "main")?;
        git.config_add("sync.protected", "release/*")?;
        let protected = git.config_get_all("sync.protected")?;
        assert_eq!(protected, vec!["main", "release/*"]);

        assert!(git.config_section_exists("sync")?);
        assert!(!git.config_section_exists("nonexistent")?);

        Ok(())
    }

    #[test]
    fn test_branch_delete() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let path = dir.path();

        Command::new("git")
            .args(["init", "--initial-branch=main"])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["config", "user.email", "test@test.com"])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["config", "user.name", "Test"])
            .current_dir(path)
            .output()?;
        std::fs::write(path.join("README.md"), "# test")?;
        Command::new("git")
            .args(["add", "."])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["commit", "-m", "init"])
            .current_dir(path)
            .output()?;

        // Create and merge a branch
        Command::new("git")
            .args(["checkout", "-b", "feature/to-delete"])
            .current_dir(path)
            .output()?;
        std::fs::write(path.join("f.txt"), "feature")?;
        Command::new("git")
            .args(["add", "."])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["commit", "-m", "feature"])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["checkout", "main"])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["merge", "feature/to-delete"])
            .current_dir(path)
            .output()?;

        let git = Git::with_workdir(false, path);

        let branches = git.local_branches()?;
        assert!(branches.contains(&"feature/to-delete".to_string()));

        git.branch_delete("feature/to-delete")?;

        let branches = git.local_branches()?;
        assert!(!branches.contains(&"feature/to-delete".to_string()));

        Ok(())
    }

    #[test]
    fn test_remotes_empty() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let path = dir.path();

        Command::new("git")
            .args(["init", "--initial-branch=main"])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["config", "user.email", "test@test.com"])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["config", "user.name", "Test"])
            .current_dir(path)
            .output()?;
        std::fs::write(path.join("README.md"), "# test")?;
        Command::new("git")
            .args(["add", "."])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["commit", "-m", "init"])
            .current_dir(path)
            .output()?;

        let git = Git::with_workdir(false, path);
        let remotes = git.remotes()?;
        assert!(remotes.is_empty());

        Ok(())
    }

    #[test]
    fn test_cherry_merged() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let path = dir.path();

        Command::new("git")
            .args(["init", "--initial-branch=main"])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["config", "user.email", "test@test.com"])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["config", "user.name", "Test"])
            .current_dir(path)
            .output()?;
        std::fs::write(path.join("README.md"), "# test")?;
        Command::new("git")
            .args(["add", "."])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["commit", "-m", "init"])
            .current_dir(path)
            .output()?;

        // Create a feature branch
        Command::new("git")
            .args(["checkout", "-b", "feature/cherry-test"])
            .current_dir(path)
            .output()?;
        std::fs::write(path.join("cherry.txt"), "cherry content")?;
        Command::new("git")
            .args(["add", "."])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["commit", "-m", "cherry commit"])
            .current_dir(path)
            .output()?;
        let sha_output = Command::new("git")
            .args(["rev-parse", "HEAD"])
            .current_dir(path)
            .output()?;
        let sha = String::from_utf8_lossy(&sha_output.stdout)
            .trim()
            .to_string();

        // Add a diverging commit on main so cherry-pick creates a different SHA
        Command::new("git")
            .args(["checkout", "main"])
            .current_dir(path)
            .output()?;
        std::fs::write(path.join("diverge.txt"), "diverge")?;
        Command::new("git")
            .args(["add", "."])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["commit", "-m", "diverge"])
            .current_dir(path)
            .output()?;

        // Cherry-pick the feature commit onto the now-diverged main
        Command::new("git")
            .args(["cherry-pick", &sha])
            .current_dir(path)
            .output()?;

        let git = Git::with_workdir(false, path);

        // The branch's commit was cherry-picked, so cherry_merged should be true
        assert!(git.cherry_merged("main", "feature/cherry-test")?);

        // Create an unmerged branch
        Command::new("git")
            .args(["checkout", "-b", "feature/not-cherry"])
            .current_dir(path)
            .output()?;
        std::fs::write(path.join("not-cherry.txt"), "not cherry")?;
        Command::new("git")
            .args(["add", "."])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["commit", "-m", "not cherry-picked"])
            .current_dir(path)
            .output()?;

        // This branch's commit was NOT cherry-picked, so cherry_merged should be false
        assert!(!git.cherry_merged("main", "feature/not-cherry")?);

        Ok(())
    }

    #[test]
    fn test_worktree_list_integration() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let path = dir.path();

        Command::new("git")
            .args(["init", "--initial-branch=main"])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["config", "user.email", "test@test.com"])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["config", "user.name", "Test"])
            .current_dir(path)
            .output()?;
        std::fs::write(path.join("README.md"), "# test")?;
        Command::new("git")
            .args(["add", "."])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["commit", "-m", "init"])
            .current_dir(path)
            .output()?;

        // Create a branch and worktree
        Command::new("git")
            .args(["branch", "feature/wt"])
            .current_dir(path)
            .output()?;
        let wt_path = path.join("wt-dir");
        Command::new("git")
            .args(["worktree", "add", wt_path.to_str().unwrap(), "feature/wt"])
            .current_dir(path)
            .output()?;

        let git = Git::with_workdir(false, path);
        let worktrees = git.worktree_list()?;

        // Should have at least 2 worktrees: main repo + the added one
        assert!(worktrees.len() >= 2);

        let wt_branches: Vec<Option<&str>> =
            worktrees.iter().map(|wt| wt.branch.as_deref()).collect();
        assert!(wt_branches.contains(&Some("main")));
        assert!(wt_branches.contains(&Some("feature/wt")));

        Ok(())
    }

    #[test]
    fn test_branch_protected_list_empty() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let path = dir.path();

        Command::new("git")
            .args(["init", "--initial-branch=main"])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["config", "user.email", "test@test.com"])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["config", "user.name", "Test"])
            .current_dir(path)
            .output()?;
        std::fs::write(path.join("README.md"), "# test")?;
        Command::new("git")
            .args(["add", "."])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["commit", "-m", "init"])
            .current_dir(path)
            .output()?;

        let git = Git::with_workdir(false, path);
        let protected = git.branch_protected_list()?;
        assert!(protected.is_empty());

        Ok(())
    }

    #[test]
    fn test_branch_protected_list() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let path = dir.path();

        Command::new("git")
            .args(["init", "--initial-branch=main"])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["config", "user.email", "test@test.com"])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["config", "user.name", "Test"])
            .current_dir(path)
            .output()?;
        std::fs::write(path.join("README.md"), "# test")?;
        Command::new("git")
            .args(["add", "."])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["commit", "-m", "init"])
            .current_dir(path)
            .output()?;

        // Mark two branches as protected via per-branch config
        Command::new("git")
            .args(["config", "branch.develop.sync-protected", "true"])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["config", "branch.staging.sync-protected", "true"])
            .current_dir(path)
            .output()?;

        let git = Git::with_workdir(false, path);
        let mut protected = git.branch_protected_list()?;
        protected.sort();
        assert_eq!(protected, vec!["develop", "staging"]);

        Ok(())
    }

    #[test]
    fn test_set_branch_protected_and_unset() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let path = dir.path();

        Command::new("git")
            .args(["init", "--initial-branch=main"])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["config", "user.email", "test@test.com"])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["config", "user.name", "Test"])
            .current_dir(path)
            .output()?;
        std::fs::write(path.join("README.md"), "# test")?;
        Command::new("git")
            .args(["add", "."])
            .current_dir(path)
            .output()?;
        Command::new("git")
            .args(["commit", "-m", "init"])
            .current_dir(path)
            .output()?;

        let git = Git::with_workdir(false, path);

        // Set protection
        git.set_branch_protected("develop", true)?;
        let protected = git.branch_protected_list()?;
        assert_eq!(protected, vec!["develop"]);

        // Unset protection
        git.set_branch_protected("develop", false)?;
        let protected = git.branch_protected_list()?;
        assert!(protected.is_empty());

        // Unsetting a non-existent key should not error
        git.set_branch_protected("nonexistent", false)?;

        Ok(())
    }

    // ── Worktree-config tests ────────────────────────────────────────

    /// Helper: create a repo with `extensions.worktreeConfig = true` and
    /// a linked worktree, returning (tempdir, main_path, worktree_path).
    fn init_repo_with_worktree_config()
    -> Result<(tempfile::TempDir, std::path::PathBuf, std::path::PathBuf)> {
        let dir = tempfile::tempdir()?;
        let main_path = dir.path().join("main-repo");
        std::fs::create_dir_all(&main_path)?;

        Command::new("git")
            .args(["init", "--initial-branch=main"])
            .current_dir(&main_path)
            .output()?;
        Command::new("git")
            .args(["config", "user.email", "test@test.com"])
            .current_dir(&main_path)
            .output()?;
        Command::new("git")
            .args(["config", "user.name", "Test"])
            .current_dir(&main_path)
            .output()?;

        std::fs::write(main_path.join("README.md"), "# test")?;
        Command::new("git")
            .args(["add", "."])
            .current_dir(&main_path)
            .output()?;
        Command::new("git")
            .args(["commit", "-m", "init"])
            .current_dir(&main_path)
            .output()?;

        // Enable extensions.worktreeConfig
        Command::new("git")
            .args(["config", "extensions.worktreeConfig", "true"])
            .current_dir(&main_path)
            .output()?;

        // Create a branch and a linked worktree
        Command::new("git")
            .args(["branch", "feature/wt"])
            .current_dir(&main_path)
            .output()?;
        let wt_path = dir.path().join("linked-wt");
        Command::new("git")
            .args(["worktree", "add", wt_path.to_str().unwrap(), "feature/wt"])
            .current_dir(&main_path)
            .output()?;

        Ok((dir, main_path, wt_path))
    }

    #[test]
    fn test_config_set_from_linked_worktree_writes_to_shared_config() -> Result<()> {
        let (_dir, main_path, wt_path) = init_repo_with_worktree_config()?;

        // Write config from the linked worktree
        let git_wt = Git::with_workdir(false, &wt_path);
        git_wt.config_set("sync.worktrunk", "true")?;

        // Read from the main worktree — must see the value
        let git_main = Git::with_workdir(false, &main_path);
        let val = git_main.config_get("sync.worktrunk")?;
        assert_eq!(val.as_deref(), Some("true"));

        Ok(())
    }

    #[test]
    fn test_config_add_from_linked_worktree_writes_to_shared_config() -> Result<()> {
        let (_dir, main_path, wt_path) = init_repo_with_worktree_config()?;

        // Add config values from the linked worktree
        let git_wt = Git::with_workdir(false, &wt_path);
        git_wt.config_add("sync.protected", "main")?;
        git_wt.config_add("sync.protected", "release/*")?;

        // Read from the main worktree
        let git_main = Git::with_workdir(false, &main_path);
        let protected = git_main.config_get_all("sync.protected")?;
        assert_eq!(protected, vec!["main", "release/*"]);

        Ok(())
    }

    #[test]
    fn test_config_unset_all_from_linked_worktree_clears_shared_config() -> Result<()> {
        let (_dir, main_path, wt_path) = init_repo_with_worktree_config()?;

        // Set some values from the main worktree
        let git_main = Git::with_workdir(false, &main_path);
        git_main.config_add("sync.protected", "main")?;
        git_main.config_add("sync.protected", "develop")?;

        // Unset from the linked worktree
        let git_wt = Git::with_workdir(false, &wt_path);
        git_wt.config_unset_all("sync.protected")?;

        // Verify from the main worktree
        let protected = git_main.config_get_all("sync.protected")?;
        assert!(protected.is_empty());

        Ok(())
    }

    #[test]
    fn test_set_branch_protected_from_linked_worktree() -> Result<()> {
        let (_dir, main_path, wt_path) = init_repo_with_worktree_config()?;

        // Set per-branch protection from the linked worktree
        let git_wt = Git::with_workdir(false, &wt_path);
        git_wt.set_branch_protected("develop", true)?;

        // Read from the main worktree
        let git_main = Git::with_workdir(false, &main_path);
        let protected = git_main.branch_protected_list()?;
        assert_eq!(protected, vec!["develop"]);

        // Unset from the linked worktree
        git_wt.set_branch_protected("develop", false)?;
        let protected = git_main.branch_protected_list()?;
        assert!(protected.is_empty());

        Ok(())
    }

    #[test]
    fn test_config_section_exists_across_worktrees() -> Result<()> {
        let (_dir, main_path, wt_path) = init_repo_with_worktree_config()?;

        // Write from linked worktree
        let git_wt = Git::with_workdir(false, &wt_path);
        git_wt.config_add("sync.protected", "main")?;

        // Section should be visible from both worktrees
        assert!(git_wt.config_section_exists("sync")?);
        let git_main = Git::with_workdir(false, &main_path);
        assert!(git_main.config_section_exists("sync")?);

        Ok(())
    }
}