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
//! Git-flow operations implemented with plain `git` commands.
use crate::config::GitFlowConfig;
use std::path::{Path, PathBuf};
use std::process::Command;
use tracing::{debug, info, warn};
/// Errors produced by git-flow operations.
#[derive(Debug, thiserror::Error)]
pub enum GitError {
/// Spawning git failed.
#[error("failed to execute git: {0}")]
Io(#[from] std::io::Error),
/// Git returned a non-success status.
#[error("git command failed: {0}")]
Command(String),
}
/// Repository helper bound to a project root.
#[derive(Debug, Clone)]
pub struct GitFlow {
root: PathBuf,
config: GitFlowConfig,
}
/// Summary of a feature branch for the `devflow list` command.
#[derive(Debug, Clone)]
pub struct BranchInfo {
/// Branch name (e.g. "feature/phase-05").
pub name: String,
/// Number of commits this branch has that develop doesn't.
pub ahead: usize,
/// Number of commits develop has that this branch doesn't.
pub behind: usize,
/// ISO-8601 date of the last commit on this branch.
pub last_commit: String,
}
impl GitFlow {
/// Create a git-flow helper for a project root, using the hardcoded
/// git-flow constants (`main`, `develop`, `feature/`).
pub fn new(root: impl AsRef<Path>) -> Self {
Self {
root: root.as_ref().to_path_buf(),
config: GitFlowConfig::default(),
}
}
/// Create a feature branch from the develop branch.
///
/// Returns an error if the branch already exists (use
/// [`feature_start_force`] to overwrite).
pub fn feature_start(&self, phase: u32) -> Result<String, GitError> {
let branch = format!("{}phase-{:02}", self.config.feature_prefix, phase);
info!("creating feature branch: {branch}");
self.git(["checkout", &self.config.develop])?;
self.git(["checkout", "-b", &branch])?;
Ok(branch)
}
/// Create or reset a feature branch, overwriting it if it already exists.
pub fn feature_start_force(&self, phase: u32) -> Result<String, GitError> {
let branch = format!("{}phase-{:02}", self.config.feature_prefix, phase);
warn!("force-creating feature branch: {branch}");
self.git(["checkout", &self.config.develop])?;
self.git(["checkout", "-B", &branch])?;
Ok(branch)
}
/// Merge a feature branch into develop and delete it.
pub fn feature_finish(&self, phase: u32) -> Result<String, GitError> {
let branch = format!("{}phase-{:02}", self.config.feature_prefix, phase);
info!("finishing feature branch: {branch}");
self.git(["checkout", &self.config.develop])?;
self.git(["merge", "--no-ff", &branch])?;
self.git(["branch", "-d", &branch])?;
Ok(branch)
}
/// Create or reset a release branch from the current `HEAD`.
///
/// The release branch is cut from wherever the caller currently is — the
/// branch being shipped — not from `develop`. `devflow ship` writes the
/// version bump into the working tree first, so branching from `HEAD`
/// keeps any commits unique to the shipped branch in the release.
pub fn release_start(&self, version: &str) -> Result<String, GitError> {
let branch = format!("release/{version}");
info!("creating release branch: {branch}");
self.git(["checkout", "-B", &branch])?;
Ok(branch)
}
/// Merge a release branch into main and develop, tag it, and delete it.
pub fn release_finish(&self, version: &str) -> Result<String, GitError> {
let branch = format!("release/{version}");
info!("finishing release branch: {branch}");
self.git(["checkout", &self.config.main])?;
self.git(["merge", "--no-ff", &branch])?;
// `-c tag.gpgSign=false` scopes the override to this invocation only
// (never the user's global/repo config) — without it, a global
// `tag.gpgsign=true` forces this lightweight tag into an
// annotated+signed one requiring a message, which blocks on
// `$EDITOR` in what must be a headless, unattended flow (Phase 13
// dogfood finding).
self.git(["-c", "tag.gpgSign=false", "tag", &format!("v{version}")])?;
self.git(["checkout", &self.config.develop])?;
self.git(["merge", "--no-ff", &branch])?;
self.git(["branch", "-d", &branch])?;
Ok(branch)
}
/// Create an annotated-free lightweight tag at the current `HEAD`.
///
/// Passes `-c tag.gpgSign=false` scoped to this invocation only — a
/// global `tag.gpgsign=true` (common for developers who sign their own
/// tags) otherwise forces this lightweight tag into an annotated+signed
/// one requiring a message, which blocks on `$EDITOR` in what must be a
/// headless, unattended flow (Phase 13 dogfood finding: VersionBump hung
/// on a live `devflow start --mode auto` run).
pub fn tag(&self, tag: &str) -> Result<(), GitError> {
info!("tagging {tag}");
self.git(["-c", "tag.gpgSign=false", "tag", tag])
}
/// Delete a single local branch.
///
/// With `force`, uses `git branch -D` (deletes even if unmerged); otherwise
/// `git branch -d` (refuses to delete unmerged work). Protected branches
/// (`main`, `develop`) are never deleted.
pub fn delete_branch(&self, branch: &str, force: bool) -> Result<(), GitError> {
if branch == self.config.main || branch == self.config.develop {
return Err(GitError::Command(format!(
"refusing to delete protected branch `{branch}`"
)));
}
let flag = if force { "-D" } else { "-d" };
if force {
warn!("force-deleting branch: {branch}");
} else {
info!("deleting branch: {branch}");
}
self.git(["branch", flag, branch])
}
/// Whether a local branch exists.
pub fn branch_exists(&self, branch: &str) -> bool {
Command::new("git")
.args([
"rev-parse",
"--verify",
"--quiet",
&format!("refs/heads/{branch}"),
])
.current_dir(&self.root)
.output()
.map(|o| o.status.success())
.unwrap_or(false)
}
/// The commit SHA at the tip of `branch`.
pub fn branch_tip(&self, branch: &str) -> Result<String, GitError> {
Ok(self.git_output(["rev-parse", branch])?.trim().to_string())
}
/// Create `branch` at `start_point` if it does not already exist, without
/// checking it out (leaves the current checkout untouched).
pub fn ensure_branch(&self, branch: &str, start_point: &str) -> Result<(), GitError> {
if self.branch_exists(branch) {
return Ok(());
}
self.git(["branch", branch, start_point])
}
/// Fast-forward `target`'s ref to `source` (must be a descendant).
///
/// `target` must not be checked out in any worktree. Errors if the move
/// would not be a fast-forward.
pub fn fast_forward_branch(&self, target: &str, source: &str) -> Result<(), GitError> {
let is_ancestor = Command::new("git")
.args(["merge-base", "--is-ancestor", target, source])
.current_dir(&self.root)
.output()?
.status
.success();
if !is_ancestor {
return Err(GitError::Command(format!(
"{target} is not an ancestor of {source}; refusing non-fast-forward update"
)));
}
self.git(["branch", "-f", target, source])
}
/// Rebase the branch checked out at `dir` onto `onto`.
///
/// Runs `git rebase` inside the given worktree directory. On conflict the
/// rebase is aborted and an error is returned so the caller can surface it.
pub fn rebase_in(&self, dir: &Path, onto: &str) -> Result<(), GitError> {
debug!("rebasing worktree at {} onto {onto}", dir.display());
match git_in(dir, &["rebase", onto]) {
Ok(()) => Ok(()),
Err(err) => {
// Leave the worktree clean for the user to retry.
warn!("rebase conflict in {}; aborting", dir.display());
let _ = git_in(dir, &["rebase", "--abort"]);
Err(err)
}
}
}
/// Check out an existing branch in the main worktree.
pub fn checkout(&self, branch: &str) -> Result<(), GitError> {
debug!("checking out branch: {branch}");
self.git(["checkout", branch])
}
/// Delete `branch` on `origin` (best-effort; errors if no remote/branch).
pub fn delete_remote_branch(&self, branch: &str) -> Result<(), GitError> {
info!("deleting remote branch: {branch}");
self.git(["push", "origin", "--delete", branch])
}
/// Whether the repository has at least one configured remote.
pub fn has_remote(&self) -> bool {
self.git_output(["remote"])
.map(|s| !s.trim().is_empty())
.unwrap_or(false)
}
/// Push `branch` to `origin`, setting upstream.
pub fn push(&self, branch: &str) -> Result<(), GitError> {
info!("pushing branch: {branch}");
self.git(["push", "-u", "origin", branch])
}
/// Delete local branches already merged into `develop`.
///
/// WR-04 (13-REVIEW.md): passes `develop` explicitly rather than relying
/// on `git branch --merged`'s default of "whatever HEAD currently is" —
/// if the main checkout is ever left on a branch other than `develop`
/// when this runs, an implicit baseline would silently prune branches
/// merged into that other branch instead.
///
/// Deletion uses `-D`, not `-d`: `-d` verifies merged-into-HEAD, which
/// contradicts the `--merged develop` listing above in exactly the
/// checkout-not-on-develop scenario WR-04 targets (every genuinely
/// merged branch would be refused as "not fully merged"). The listing IS
/// the merge safety check. A branch git still refuses to delete (e.g.
/// checked out in a worktree) is logged and skipped so one failure
/// doesn't abort the rest of the sweep.
pub fn cleanup_merged(&self) -> Result<Vec<String>, GitError> {
let output = self.git_output(["branch", "--merged", &self.config.develop])?;
let protected = [self.config.main.as_str(), self.config.develop.as_str()];
let mut deleted = Vec::new();
for line in output.lines() {
// git's porcelain marker is an exact two-char prefix ("* " for
// the current branch, "+ " for a worktree checkout, " "
// otherwise) — strip it positionally rather than trimming
// marker CHARACTERS, which would mangle a branch legitimately
// named e.g. "+foo" (WR-03, revised).
let branch = line
.strip_prefix("* ")
.or_else(|| line.strip_prefix("+ "))
.unwrap_or(line)
.trim();
// Skip blanks, protected trunks, and the detached-HEAD line
// ("(HEAD detached at ...)"), which is not a branch name.
if branch.is_empty() || branch.starts_with('(') || protected.contains(&branch) {
continue;
}
info!("cleaning up merged branch: {branch}");
match self.git(["branch", "-D", branch]) {
Ok(()) => deleted.push(branch.to_string()),
Err(err) => warn!("could not delete merged branch {branch}: {err}"),
}
}
Ok(deleted)
}
/// Stage all changes and commit with the given message.
/// Returns Ok(()) whether or not there were changes to commit.
pub fn commit_all(&self, message: &str) -> Result<(), GitError> {
debug!("committing all changes: {message}");
self.git(["add", "."])?;
// --allow-empty so we don't fail when there are no changes
match self.git_raw(&["commit", "--allow-empty", "-m", message]) {
Ok(()) => Ok(()),
// If the commit produced no changes and we used --allow-empty,
// this should still succeed. But just in case, ignore "nothing to commit".
Err(GitError::Command(ref msg)) if msg.contains("nothing to commit") => Ok(()),
Err(e) => Err(e),
}
}
/// Return divergence from develop: (ahead, behind) commit counts.
///
/// If currently on the develop branch, returns (0, 0).
/// `ahead` = commits on current branch not yet on develop.
/// `behind` = commits on develop not yet on current branch.
pub fn divergence_from_develop(&self) -> Result<(usize, usize), GitError> {
let current = self
.git_output(["rev-parse", "--abbrev-ref", "HEAD"])?
.trim()
.to_string();
if current == self.config.develop {
return Ok((0, 0));
}
let ahead = self
.rev_count(&format!("{}..{current}", self.config.develop))
.unwrap_or(0);
let behind = self
.rev_count(&format!("{current}..{}", self.config.develop))
.unwrap_or(0);
Ok((ahead, behind))
}
/// List all feature branches with divergence from develop.
///
/// Returns branches matching `feature/phase-*` with ahead/behind counts
/// and last commit dates. Protected branches (main, develop) are excluded.
pub fn list_feature_branches(&self) -> Result<Vec<BranchInfo>, GitError> {
let prefix = &self.config.feature_prefix;
let branches = self.git_output(["branch", "--format=%(refname:short)"])?;
let mut result = Vec::new();
for name in branches.lines().map(|l| l.trim()) {
if name.is_empty()
|| name == self.config.main
|| name == self.config.develop
|| !name.starts_with(prefix)
{
continue;
}
let ahead = self
.rev_count(&format!("{dev}..{name}", dev = self.config.develop))
.unwrap_or(0);
let behind = self
.rev_count(&format!("{name}..{dev}", dev = self.config.develop))
.unwrap_or(0);
let last_commit = self
.git_output(["log", "-1", "--format=%aI", name])
.map(|s| s.trim().to_string())
.unwrap_or_default();
result.push(BranchInfo {
name: name.to_string(),
ahead,
behind,
last_commit,
});
}
// Sort by phase number so phase-01 comes before phase-10.
result.sort_by(|a, b| a.name.cmp(&b.name));
Ok(result)
}
/// Count revisions in the given range. Returns None if the command fails.
fn rev_count(&self, range: &str) -> Option<usize> {
self.git_output(["rev-list", "--count", range])
.ok()
.and_then(|s| s.trim().parse().ok())
}
fn git_raw(&self, args: &[&str]) -> Result<(), GitError> {
debug!("git {}", args.join(" "));
let output = Command::new("git")
.args(args)
.current_dir(&self.root)
.output()?;
if output.status.success() {
Ok(())
} else {
Err(GitError::Command(stderr_or_status(&output)))
}
}
fn git<const N: usize>(&self, args: [&str; N]) -> Result<(), GitError> {
debug!("git {}", args.iter().copied().collect::<Vec<_>>().join(" "));
let output = Command::new("git")
.args(args)
.current_dir(&self.root)
.output()?;
if output.status.success() {
Ok(())
} else {
Err(GitError::Command(stderr_or_status(&output)))
}
}
fn git_output<const N: usize>(&self, args: [&str; N]) -> Result<String, GitError> {
let output = Command::new("git")
.args(args)
.current_dir(&self.root)
.output()?;
if output.status.success() {
Ok(String::from_utf8_lossy(&output.stdout).to_string())
} else {
Err(GitError::Command(stderr_or_status(&output)))
}
}
}
/// Run a git command in an arbitrary directory (e.g. a worktree).
fn git_in(dir: &Path, args: &[&str]) -> Result<(), GitError> {
debug!("git (in {}) {}", dir.display(), args.join(" "));
let output = Command::new("git").args(args).current_dir(dir).output()?;
if output.status.success() {
Ok(())
} else {
Err(GitError::Command(stderr_or_status(&output)))
}
}
fn stderr_or_status(output: &std::process::Output) -> String {
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
if stderr.is_empty() {
format!("exited with {}", output.status)
} else {
stderr
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::process::Command;
use tempfile::TempDir;
/// Run a git command in `root`, asserting success.
fn git(root: &Path, args: &[&str]) {
let output = Command::new("git")
.args(args)
.current_dir(root)
.output()
.expect("spawn git");
assert!(
output.status.success(),
"git {args:?} failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
fn current_branch(root: &Path) -> String {
let output = Command::new("git")
.args(["rev-parse", "--abbrev-ref", "HEAD"])
.current_dir(root)
.output()
.expect("rev-parse");
String::from_utf8_lossy(&output.stdout).trim().to_string()
}
fn commit_file(root: &Path, name: &str) {
std::fs::write(root.join(name), name).unwrap();
git(root, &["add", "."]);
git(root, &["commit", "-q", "-m", &format!("add {name}")]);
}
/// Initialize a repo with `main` and `develop` branches and one commit.
fn init_repo() -> TempDir {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
git(root, &["init", "-q"]);
git(root, &["config", "user.email", "test@example.com"]);
git(root, &["config", "user.name", "Test"]);
git(root, &["config", "commit.gpgsign", "false"]);
git(root, &["config", "tag.gpgsign", "false"]);
// Disable any globally-configured hooks (e.g. gitleaks) for isolation.
git(root, &["config", "core.hooksPath", "/dev/null"]);
commit_file(root, "README.md");
git(root, &["branch", "-M", "main"]);
git(root, &["checkout", "-q", "-b", "develop"]);
dir
}
fn flow(root: &Path) -> GitFlow {
GitFlow::new(root)
}
#[test]
fn feature_start_branches_from_develop() {
let repo = init_repo();
let root = repo.path();
let branch = flow(root).feature_start(3).expect("feature_start");
assert_eq!(branch, "feature/phase-03");
assert_eq!(current_branch(root), "feature/phase-03");
}
#[test]
fn list_feature_branches_reports_ahead_and_behind_semantics() {
let repo = init_repo();
let root = repo.path();
let gf = flow(root);
gf.feature_start(12).expect("feature_start");
commit_file(root, "feature-one.txt");
commit_file(root, "feature-two.txt");
git(root, &["checkout", "-q", "develop"]);
commit_file(root, "develop-only.txt");
let branches = gf.list_feature_branches().unwrap();
let branch = branches
.iter()
.find(|branch| branch.name == "feature/phase-12")
.unwrap();
assert_eq!(branch.ahead, 2);
assert_eq!(branch.behind, 1);
}
#[test]
fn feature_finish_merges_into_develop_and_deletes() {
let repo = init_repo();
let root = repo.path();
let gf = flow(root);
gf.feature_start(1).expect("start");
commit_file(root, "feature.txt");
let branch = gf.feature_finish(1).expect("finish");
assert_eq!(branch, "feature/phase-01");
assert_eq!(current_branch(root), "develop");
// Branch is deleted and its work is now on develop.
let branches = Command::new("git")
.args(["branch"])
.current_dir(root)
.output()
.unwrap();
let listing = String::from_utf8_lossy(&branches.stdout);
assert!(!listing.contains("feature/phase-01"));
assert!(root.join("feature.txt").exists());
}
#[test]
fn release_start_and_finish_tags_main_and_merges_both() {
let repo = init_repo();
let root = repo.path();
let gf = flow(root);
// Add work on develop so the release has content.
commit_file(root, "work.txt");
let branch = gf.release_start("1.2.0").expect("release_start");
assert_eq!(branch, "release/1.2.0");
gf.release_finish("1.2.0").expect("release_finish");
assert_eq!(current_branch(root), "develop");
// Tag exists.
let tags = Command::new("git")
.args(["tag"])
.current_dir(root)
.output()
.unwrap();
assert!(String::from_utf8_lossy(&tags.stdout).contains("v1.2.0"));
// Release branch deleted.
let branches = Command::new("git")
.args(["branch"])
.current_dir(root)
.output()
.unwrap();
assert!(!String::from_utf8_lossy(&branches.stdout).contains("release/1.2.0"));
}
/// A global/repo `tag.gpgsign=true` must not turn `tag()`'s lightweight
/// tag into an annotated+signed one — that would require a tag message
/// and block on `$EDITOR`, silently hanging a headless, unattended run
/// (Phase 13 dogfood finding: VersionBump hung on a live
/// `devflow start --mode auto` run because the operator's global
/// gitconfig sets `tag.gpgsign=true`).
#[test]
fn tag_stays_lightweight_when_gpgsign_is_forced_on() {
let repo = init_repo();
let root = repo.path();
// Simulate an operator whose global config signs tags by default —
// override the test harness's own `tag.gpgsign false` to prove
// `tag()`'s per-invocation `-c` override wins regardless.
git(root, &["config", "tag.gpgsign", "true"]);
flow(root)
.tag("v9.9.9")
.expect("tag must not block on $EDITOR");
let tags = Command::new("git")
.args(["tag", "-l"])
.current_dir(root)
.output()
.unwrap();
assert!(String::from_utf8_lossy(&tags.stdout).contains("v9.9.9"));
// Confirm it's a lightweight tag (points directly at the commit),
// not an annotated tag object (which `cat-file -t` would report as
// "tag" rather than "commit").
let obj_type = Command::new("git")
.args(["cat-file", "-t", "v9.9.9"])
.current_dir(root)
.output()
.unwrap();
assert_eq!(
String::from_utf8_lossy(&obj_type.stdout).trim(),
"commit",
"tag() must stay lightweight even when tag.gpgsign=true"
);
}
#[test]
fn release_start_branches_from_current_head_not_develop() {
let repo = init_repo();
let root = repo.path();
let gf = flow(root);
// Ship from a feature branch carrying a commit that is NOT on develop.
gf.feature_start(5).expect("feature_start");
commit_file(root, "feature-only.txt");
let feature_tip = gf.branch_tip("feature/phase-05").expect("feature tip");
let branch = gf.release_start("2.0.0").expect("release_start");
assert_eq!(branch, "release/2.0.0");
assert_eq!(current_branch(root), "release/2.0.0");
// The release branch tip must descend from the feature commit — i.e.
// the feature-only work is present, not dropped to develop's HEAD.
let release_tip = gf.branch_tip("release/2.0.0").expect("release tip");
let is_ancestor = Command::new("git")
.args(["merge-base", "--is-ancestor", &feature_tip, &release_tip])
.current_dir(root)
.output()
.unwrap()
.status
.success();
assert!(
is_ancestor,
"release branch must descend from the shipped feature commit"
);
assert!(root.join("feature-only.txt").exists());
}
#[test]
fn cleanup_merged_removes_merged_but_keeps_protected() {
let repo = init_repo();
let root = repo.path();
let gf = flow(root);
// Create and merge a feature branch into develop.
gf.feature_start(2).expect("start");
commit_file(root, "f.txt");
gf.feature_finish(2).expect("finish");
// Create an already-merged stray branch off develop.
git(root, &["branch", "stale-merged"]);
let deleted = gf.cleanup_merged().expect("cleanup");
assert!(deleted.contains(&"stale-merged".to_string()));
// Protected branches survive.
assert!(!deleted.contains(&"develop".to_string()));
assert!(!deleted.contains(&"main".to_string()));
}
/// WR-04 (13-REVIEW.md): `cleanup_merged` must compute "merged" relative
/// to `develop` explicitly, not whatever the main checkout's current
/// HEAD happens to be. If the main checkout is left on a divergent
/// branch, an implicit-HEAD baseline would wrongly identify (and
/// delete) a branch that's merged into that other branch but was never
/// actually merged into `develop`.
#[test]
fn cleanup_merged_is_relative_to_develop_not_current_head() {
let repo = init_repo();
let root = repo.path();
let gf = flow(root);
// `topic` diverges from develop with a unique commit develop never
// sees, then `premature` branches off `topic`'s tip — so
// `premature` is merged into `topic` but NOT into `develop`.
git(root, &["checkout", "-q", "-b", "topic", "develop"]);
commit_file(root, "topic-only.txt");
git(root, &["checkout", "-q", "-b", "premature", "topic"]);
// Leave the main checkout on `topic` — NOT `develop` — before
// calling cleanup_merged, mirroring an operator who forgot to
// check out develop first. (`topic` itself is also technically
// "merged into HEAD" under an implicit baseline since it IS HEAD,
// which git's own `-d` correctly refuses as the checked-out branch
// — so the call's overall Ok/Err is not itself decisive here; check
// the actual side effect on `premature` instead.)
git(root, &["checkout", "-q", "topic"]);
let _ = gf.cleanup_merged();
assert!(
gf.branch_exists("premature"),
"premature is merged into topic (current HEAD) but not into \
develop — it must survive cleanup_merged when the baseline is develop"
);
}
/// WR-03 (13-REVIEW.md), revised: `git branch --merged` prefixes a
/// branch checked out in a linked worktree with `+ `. The prefix must be
/// stripped positionally (not by trimming marker characters, which would
/// mangle a branch legitimately named "+foo"), and a branch git refuses
/// to delete — a worktree checkout can never be deleted, by design —
/// must be skipped with a warning rather than aborting the sweep before
/// the remaining merged branches.
#[test]
fn cleanup_merged_skips_worktree_branch_and_continues_sweep() {
let repo = init_repo();
let root = repo.path();
let gf = flow(root);
// Merge a branch into develop WITHOUT deleting it (feature_finish
// deletes on merge, which would leave nothing to check out).
git(
root,
&["checkout", "-q", "-b", "worktree-merged", "develop"],
);
commit_file(root, "g.txt");
git(root, &["checkout", "-q", "develop"]);
git(root, &["merge", "-q", "--no-ff", "worktree-merged"]);
// Check the merged branch out in a linked worktree so
// `git branch --merged` reports it with a `+ ` prefix.
let wt_dir = tempfile::tempdir().unwrap();
git(
root,
&[
"worktree",
"add",
wt_dir.path().to_str().unwrap(),
"worktree-merged",
],
);
// A second merged branch that sorts after "worktree-merged" would be
// reached only if the sweep survives the worktree refusal; "zz-" also
// guards against luck in iteration order via the branch before it.
git(root, &["branch", "aa-stale"]);
git(root, &["branch", "zz-stale"]);
let deleted = gf
.cleanup_merged()
.expect("a skipped worktree branch must not abort the sweep");
assert!(deleted.contains(&"aa-stale".to_string()));
assert!(deleted.contains(&"zz-stale".to_string()));
assert!(
!deleted.contains(&"worktree-merged".to_string()),
"worktree checkout cannot be deleted"
);
assert!(gf.branch_exists("worktree-merged"));
}
/// The delete side must agree with the `--merged develop` listing: `-d`
/// verifies merged-into-HEAD, so with the main checkout parked on a
/// stale branch every genuinely-merged branch was refused as "not fully
/// merged" — in exactly the scenario WR-04 exists for.
#[test]
fn cleanup_merged_deletes_when_head_is_not_on_develop() {
let repo = init_repo();
let root = repo.path();
let gf = flow(root);
// `old` is parked before the merge below, so nothing merged later is
// reachable from HEAD while it's checked out.
git(root, &["checkout", "-q", "-b", "old", "develop"]);
git(root, &["checkout", "-q", "develop"]);
git(root, &["checkout", "-q", "-b", "merged-feature", "develop"]);
commit_file(root, "h.txt");
git(root, &["checkout", "-q", "develop"]);
git(root, &["merge", "-q", "--no-ff", "merged-feature"]);
git(root, &["checkout", "-q", "old"]);
let deleted = gf.cleanup_merged().expect("cleanup");
assert!(
deleted.contains(&"merged-feature".to_string()),
"merged-into-develop branch must be deleted even when HEAD is elsewhere: {deleted:?}"
);
assert!(!gf.branch_exists("merged-feature"));
}
#[test]
fn delete_branch_removes_unmerged_with_force_and_protects_trunk() {
let repo = init_repo();
let root = repo.path();
let gf = flow(root);
// Create a feature branch with an unmerged commit.
gf.feature_start(8).expect("start");
commit_file(root, "unmerged.txt");
// Switch back to develop so the branch isn't checked out.
git(root, &["checkout", "-q", "develop"]);
// -d would refuse (unmerged); force deletes it.
assert!(gf.delete_branch("feature/phase-08", false).is_err());
gf.delete_branch("feature/phase-08", true)
.expect("force delete");
let branches = Command::new("git")
.args(["branch"])
.current_dir(root)
.output()
.unwrap();
assert!(!String::from_utf8_lossy(&branches.stdout).contains("feature/phase-08"));
// Protected branches are never deleted.
assert!(gf.delete_branch("develop", true).is_err());
assert!(gf.delete_branch("main", true).is_err());
}
#[test]
fn sequentagent_helpers_integrate_and_rebase_cleanly() {
let repo = init_repo();
let root = repo.path();
let gf = flow(root);
// Base branch off develop, not checked out anywhere.
gf.ensure_branch("feature/phase-07", "develop")
.expect("ensure base");
assert!(gf.branch_exists("feature/phase-07"));
assert!(!gf.branch_tip("feature/phase-07").unwrap().is_empty());
// ensure_branch is idempotent.
gf.ensure_branch("feature/phase-07", "develop")
.expect("ensure again");
// Two agent worktrees off the same base tip.
let wt_a = root.join(".worktrees/a");
let wt_b = root.join(".worktrees/b");
crate::worktree::add(root, &wt_a, "feat-a", "feature/phase-07", true).expect("add A");
crate::worktree::add(root, &wt_b, "feat-b", "feature/phase-07", true).expect("add B");
// Agent A commits a new file, then we integrate A into the base (ff).
std::fs::write(wt_a.join("a.txt"), "from-a\n").unwrap();
git(&wt_a, &["add", "."]);
git(&wt_a, &["commit", "-q", "-m", "a work"]);
gf.fast_forward_branch("feature/phase-07", "feat-a")
.expect("ff base to A");
assert_eq!(
gf.branch_tip("feature/phase-07").unwrap(),
gf.branch_tip("feat-a").unwrap()
);
// Agent B (no overlapping changes) rebases onto the updated base cleanly.
gf.rebase_in(&wt_b, "feature/phase-07")
.expect("clean rebase");
// B now contains A's file.
assert!(wt_b.join("a.txt").exists());
}
#[test]
fn rebase_in_aborts_and_errors_on_conflict() {
let repo = init_repo();
let root = repo.path();
let gf = flow(root);
gf.ensure_branch("feature/phase-07", "develop")
.expect("ensure base");
// Worktree B is created off the ORIGINAL base, then edits a.txt.
let wt_b = root.join(".worktrees/b");
crate::worktree::add(root, &wt_b, "feat-b", "feature/phase-07", true).expect("add B");
std::fs::write(wt_b.join("a.txt"), "from-b\n").unwrap();
git(&wt_b, &["add", "."]);
git(&wt_b, &["commit", "-q", "-m", "b edits a"]);
// Meanwhile the base advances with a conflicting a.txt (via worktree A).
let wt_a = root.join(".worktrees/a");
crate::worktree::add(root, &wt_a, "feat-a", "feature/phase-07", true).expect("add A");
std::fs::write(wt_a.join("a.txt"), "from-base\n").unwrap();
git(&wt_a, &["add", "."]);
git(&wt_a, &["commit", "-q", "-m", "base edits a"]);
gf.fast_forward_branch("feature/phase-07", "feat-a")
.expect("ff base to A");
// Rebasing B onto the updated base conflicts on a.txt → error + abort.
let err = gf.rebase_in(&wt_b, "feature/phase-07").unwrap_err();
assert!(matches!(err, GitError::Command(_)));
// The abort left no rebase-in-progress state behind.
assert!(!root.join(".git/worktrees/b/rebase-merge").exists());
// B is still usable: its own commit is intact.
assert_eq!(
std::fs::read_to_string(wt_b.join("a.txt")).unwrap(),
"from-b\n"
);
}
#[test]
fn merge_of_missing_branch_is_an_error() {
let repo = init_repo();
let root = repo.path();
// feature_finish for a phase that was never started: checkout develop
// succeeds, but merging the nonexistent feature branch fails.
let err = flow(root).feature_finish(99).unwrap_err();
assert!(matches!(err, GitError::Command(_)));
}
}