Skip to main content

devflow_core/
git.rs

1//! Git-flow operations implemented with plain `git` commands.
2
3use crate::config::GitFlowConfig;
4use std::path::{Path, PathBuf};
5use std::process::Command;
6use tracing::{debug, info, warn};
7
8/// Errors produced by git-flow operations.
9#[derive(Debug, thiserror::Error)]
10pub enum GitError {
11    /// Spawning git failed.
12    #[error("failed to execute git: {0}")]
13    Io(#[from] std::io::Error),
14    /// Git returned a non-success status.
15    #[error("git command failed: {0}")]
16    Command(String),
17}
18
19/// Repository helper bound to a project root.
20#[derive(Debug, Clone)]
21pub struct GitFlow {
22    root: PathBuf,
23    config: GitFlowConfig,
24}
25
26/// Summary of a feature branch for the `devflow list` command.
27#[derive(Debug, Clone)]
28pub struct BranchInfo {
29    /// Branch name (e.g. "feature/phase-05").
30    pub name: String,
31    /// Number of commits this branch has that develop doesn't.
32    pub ahead: usize,
33    /// Number of commits develop has that this branch doesn't.
34    pub behind: usize,
35    /// ISO-8601 date of the last commit on this branch.
36    pub last_commit: String,
37}
38
39impl GitFlow {
40    /// Create a git-flow helper for a project root, using the hardcoded
41    /// git-flow constants (`main`, `develop`, `feature/`).
42    pub fn new(root: impl AsRef<Path>) -> Self {
43        Self {
44            root: root.as_ref().to_path_buf(),
45            config: GitFlowConfig::default(),
46        }
47    }
48
49    /// Create a feature branch from the develop branch.
50    ///
51    /// Returns an error if the branch already exists (use
52    /// [`feature_start_force`] to overwrite).
53    pub fn feature_start(&self, phase: u32) -> Result<String, GitError> {
54        let branch = format!("{}phase-{:02}", self.config.feature_prefix, phase);
55        info!("creating feature branch: {branch}");
56        self.git(["checkout", &self.config.develop])?;
57        self.git(["checkout", "-b", &branch])?;
58        Ok(branch)
59    }
60
61    /// Create or reset a feature branch, overwriting it if it already exists.
62    pub fn feature_start_force(&self, phase: u32) -> Result<String, GitError> {
63        let branch = format!("{}phase-{:02}", self.config.feature_prefix, phase);
64        warn!("force-creating feature branch: {branch}");
65        self.git(["checkout", &self.config.develop])?;
66        self.git(["checkout", "-B", &branch])?;
67        Ok(branch)
68    }
69
70    /// Merge a feature branch into develop and delete it.
71    pub fn feature_finish(&self, phase: u32) -> Result<String, GitError> {
72        let branch = self.merge_feature_into_develop(phase)?;
73        self.git(["branch", "-d", &branch])?;
74        Ok(branch)
75    }
76
77    /// Merge a feature branch into develop without deleting it.
78    ///
79    /// Default DevFlow runs keep the feature branch checked out in a linked
80    /// worktree, so deletion belongs to the later best-effort cleanup hook.
81    pub fn merge_feature_into_develop(&self, phase: u32) -> Result<String, GitError> {
82        let branch = format!("{}phase-{:02}", self.config.feature_prefix, phase);
83        info!("merging feature branch: {branch}");
84        self.git(["checkout", &self.config.develop])?;
85        self.git(["merge", "--no-ff", &branch])?;
86        Ok(branch)
87    }
88
89    /// Whether a phase feature branch has nothing left to merge into develop.
90    ///
91    /// An absent branch is not proof of a merge. Callers must fail closed
92    /// rather than treating a deleted or never-created branch as shipped.
93    pub fn is_merged_into_develop(&self, phase: u32) -> bool {
94        let branch = format!("{}phase-{:02}", self.config.feature_prefix, phase);
95        if !self.branch_exists(&branch) {
96            return false;
97        }
98
99        Command::new("git")
100            .args(["merge-base", "--is-ancestor", &branch, &self.config.develop])
101            .current_dir(&self.root)
102            .output()
103            .map(|output| output.status.success())
104            .unwrap_or(false)
105    }
106
107    /// Create or reset a release branch from the current `HEAD`.
108    ///
109    /// The release branch is cut from wherever the caller currently is — the
110    /// branch being shipped — not from `develop`. `devflow ship` writes the
111    /// version bump into the working tree first, so branching from `HEAD`
112    /// keeps any commits unique to the shipped branch in the release.
113    pub fn release_start(&self, version: &str) -> Result<String, GitError> {
114        let branch = format!("release/{version}");
115        info!("creating release branch: {branch}");
116        self.git(["checkout", "-B", &branch])?;
117        Ok(branch)
118    }
119
120    /// Merge a release branch into main and develop, tag it, and delete it.
121    pub fn release_finish(&self, version: &str) -> Result<String, GitError> {
122        let branch = format!("release/{version}");
123        info!("finishing release branch: {branch}");
124        self.git(["checkout", &self.config.main])?;
125        self.git(["merge", "--no-ff", &branch])?;
126        // `-c tag.gpgSign=false` scopes the override to this invocation only
127        // (never the user's global/repo config) — without it, a global
128        // `tag.gpgsign=true` forces this lightweight tag into an
129        // annotated+signed one requiring a message, which blocks on
130        // `$EDITOR` in what must be a headless, unattended flow (Phase 13
131        // dogfood finding).
132        self.git(["-c", "tag.gpgSign=false", "tag", &format!("v{version}")])?;
133        self.git(["checkout", &self.config.develop])?;
134        self.git(["merge", "--no-ff", &branch])?;
135        self.git(["branch", "-d", &branch])?;
136        Ok(branch)
137    }
138
139    /// Create an annotated-free lightweight tag at the current `HEAD`.
140    ///
141    /// Passes `-c tag.gpgSign=false` scoped to this invocation only — a
142    /// global `tag.gpgsign=true` (common for developers who sign their own
143    /// tags) otherwise forces this lightweight tag into an annotated+signed
144    /// one requiring a message, which blocks on `$EDITOR` in what must be a
145    /// headless, unattended flow (Phase 13 dogfood finding: VersionBump hung
146    /// on a live `devflow start --mode auto` run).
147    pub fn tag(&self, tag: &str) -> Result<(), GitError> {
148        info!("tagging {tag}");
149        self.git(["-c", "tag.gpgSign=false", "tag", tag])
150    }
151
152    /// Delete a single local branch.
153    ///
154    /// With `force`, uses `git branch -D` (deletes even if unmerged); otherwise
155    /// `git branch -d` (refuses to delete unmerged work). Protected branches
156    /// (`main`, `develop`) are never deleted.
157    pub fn delete_branch(&self, branch: &str, force: bool) -> Result<(), GitError> {
158        if branch == self.config.main || branch == self.config.develop {
159            return Err(GitError::Command(format!(
160                "refusing to delete protected branch `{branch}`"
161            )));
162        }
163        let flag = if force { "-D" } else { "-d" };
164        if force {
165            warn!("force-deleting branch: {branch}");
166        } else {
167            info!("deleting branch: {branch}");
168        }
169        self.git(["branch", flag, branch])
170    }
171
172    /// Whether a local branch exists.
173    pub fn branch_exists(&self, branch: &str) -> bool {
174        Command::new("git")
175            .args([
176                "rev-parse",
177                "--verify",
178                "--quiet",
179                &format!("refs/heads/{branch}"),
180            ])
181            .current_dir(&self.root)
182            .output()
183            .map(|o| o.status.success())
184            .unwrap_or(false)
185    }
186
187    /// The commit SHA at the tip of `branch`.
188    pub fn branch_tip(&self, branch: &str) -> Result<String, GitError> {
189        Ok(self.git_output(["rev-parse", branch])?.trim().to_string())
190    }
191
192    /// Create `branch` at `start_point` if it does not already exist, without
193    /// checking it out (leaves the current checkout untouched).
194    pub fn ensure_branch(&self, branch: &str, start_point: &str) -> Result<(), GitError> {
195        if self.branch_exists(branch) {
196            return Ok(());
197        }
198        self.git(["branch", branch, start_point])
199    }
200
201    /// Fast-forward `target`'s ref to `source` (must be a descendant).
202    ///
203    /// `target` must not be checked out in any worktree. Errors if the move
204    /// would not be a fast-forward.
205    pub fn fast_forward_branch(&self, target: &str, source: &str) -> Result<(), GitError> {
206        let is_ancestor = Command::new("git")
207            .args(["merge-base", "--is-ancestor", target, source])
208            .current_dir(&self.root)
209            .output()?
210            .status
211            .success();
212        if !is_ancestor {
213            return Err(GitError::Command(format!(
214                "{target} is not an ancestor of {source}; refusing non-fast-forward update"
215            )));
216        }
217        self.git(["branch", "-f", target, source])
218    }
219
220    /// Rebase the branch checked out at `dir` onto `onto`.
221    ///
222    /// Runs `git rebase` inside the given worktree directory. On conflict the
223    /// rebase is aborted and an error is returned so the caller can surface it.
224    pub fn rebase_in(&self, dir: &Path, onto: &str) -> Result<(), GitError> {
225        debug!("rebasing worktree at {} onto {onto}", dir.display());
226        match git_in(dir, &["rebase", onto]) {
227            Ok(()) => Ok(()),
228            Err(err) => {
229                // Leave the worktree clean for the user to retry.
230                warn!("rebase conflict in {}; aborting", dir.display());
231                let _ = git_in(dir, &["rebase", "--abort"]);
232                Err(err)
233            }
234        }
235    }
236
237    /// Check out an existing branch in the main worktree.
238    pub fn checkout(&self, branch: &str) -> Result<(), GitError> {
239        debug!("checking out branch: {branch}");
240        self.git(["checkout", branch])
241    }
242
243    /// Delete `branch` on `origin` (best-effort; errors if no remote/branch).
244    pub fn delete_remote_branch(&self, branch: &str) -> Result<(), GitError> {
245        info!("deleting remote branch: {branch}");
246        self.git(["push", "origin", "--delete", branch])
247    }
248
249    /// Whether the repository has at least one configured remote.
250    pub fn has_remote(&self) -> bool {
251        self.git_output(["remote"])
252            .map(|s| !s.trim().is_empty())
253            .unwrap_or(false)
254    }
255
256    /// Push `branch` to `origin`, setting upstream.
257    pub fn push(&self, branch: &str) -> Result<(), GitError> {
258        info!("pushing branch: {branch}");
259        self.git(["push", "-u", "origin", branch])
260    }
261
262    /// Delete local branches already merged into `develop`.
263    ///
264    /// WR-04 (13-REVIEW.md): passes `develop` explicitly rather than relying
265    /// on `git branch --merged`'s default of "whatever HEAD currently is" —
266    /// if the main checkout is ever left on a branch other than `develop`
267    /// when this runs, an implicit baseline would silently prune branches
268    /// merged into that other branch instead.
269    ///
270    /// Deletion uses `-D`, not `-d`: `-d` verifies merged-into-HEAD, which
271    /// contradicts the `--merged develop` listing above in exactly the
272    /// checkout-not-on-develop scenario WR-04 targets (every genuinely
273    /// merged branch would be refused as "not fully merged"). The listing IS
274    /// the merge safety check. A branch git still refuses to delete (e.g.
275    /// checked out in a worktree) is logged and skipped so one failure
276    /// doesn't abort the rest of the sweep.
277    pub fn cleanup_merged(&self) -> Result<Vec<String>, GitError> {
278        let output = self.git_output(["branch", "--merged", &self.config.develop])?;
279        let protected = [self.config.main.as_str(), self.config.develop.as_str()];
280        let mut deleted = Vec::new();
281        for line in output.lines() {
282            // git's porcelain marker is an exact two-char prefix ("* " for
283            // the current branch, "+ " for a worktree checkout, "  "
284            // otherwise) — strip it positionally rather than trimming
285            // marker CHARACTERS, which would mangle a branch legitimately
286            // named e.g. "+foo" (WR-03, revised).
287            let branch = line
288                .strip_prefix("* ")
289                .or_else(|| line.strip_prefix("+ "))
290                .unwrap_or(line)
291                .trim();
292            // Skip blanks, protected trunks, and the detached-HEAD line
293            // ("(HEAD detached at ...)"), which is not a branch name.
294            if branch.is_empty() || branch.starts_with('(') || protected.contains(&branch) {
295                continue;
296            }
297            info!("cleaning up merged branch: {branch}");
298            match self.git(["branch", "-D", branch]) {
299                Ok(()) => deleted.push(branch.to_string()),
300                Err(err) => warn!("could not delete merged branch {branch}: {err}"),
301            }
302        }
303        Ok(deleted)
304    }
305
306    /// Stage all changes and commit with the given message.
307    /// Returns Ok(()) whether or not there were changes to commit.
308    pub fn commit_all(&self, message: &str) -> Result<(), GitError> {
309        debug!("committing all changes: {message}");
310        self.git(["add", "."])?;
311        // --allow-empty so we don't fail when there are no changes
312        match self.git_raw(&["commit", "--allow-empty", "-m", message]) {
313            Ok(()) => Ok(()),
314            // If the commit produced no changes and we used --allow-empty,
315            // this should still succeed. But just in case, ignore "nothing to commit".
316            Err(GitError::Command(ref msg)) if msg.contains("nothing to commit") => Ok(()),
317            Err(e) => Err(e),
318        }
319    }
320
321    /// Stage a single relative path and commit with the given message.
322    /// Mirrors `commit_all`, but scoped to one path, for hooks that must not
323    /// sweep in unrelated dirty state left by other hooks or the workflow.
324    /// Returns Ok(()) whether or not the path had changes to commit. Unlike
325    /// `commit_all`, a path with no changes produces **no commit** — it is a
326    /// genuine no-op, not a forced empty commit, so a caller such as
327    /// `hooks::version_bump` can never tag a release on a commit containing
328    /// nothing (19b/D-16).
329    pub fn commit_path(&self, relative_path: &str, message: &str) -> Result<(), GitError> {
330        debug!("committing {relative_path}: {message}");
331        // `add` first so a brand-new file is known to git — a pathspec-only
332        // commit errors on a path git has never seen. The trailing pathspec is
333        // what actually scopes the commit: without it, `commit` writes whatever
334        // else is already in the index, which is exactly the sweep-in this
335        // function exists to prevent.
336        self.git(["add", relative_path])?;
337        match self.git_raw_combined(&["commit", "-m", message, "--", relative_path]) {
338            Ok(()) => Ok(()),
339            // No forcing flag above, so this arm is now the live no-op path:
340            // a path with nothing staged makes git exit non-zero with
341            // "nothing to commit", and we convert that back to Ok(()) rather
342            // than let it propagate as an error (19b/D-16, T-19-11).
343            Err(GitError::Command(ref msg)) if msg.contains("nothing to commit") => Ok(()),
344            Err(e) => Err(e),
345        }
346    }
347
348    /// Return divergence from develop: (ahead, behind) commit counts.
349    ///
350    /// If currently on the develop branch, returns (0, 0).
351    /// `ahead` = commits on current branch not yet on develop.
352    /// `behind` = commits on develop not yet on current branch.
353    pub fn divergence_from_develop(&self) -> Result<(usize, usize), GitError> {
354        let current = self
355            .git_output(["rev-parse", "--abbrev-ref", "HEAD"])?
356            .trim()
357            .to_string();
358        if current == self.config.develop {
359            return Ok((0, 0));
360        }
361        let ahead = self
362            .rev_count(&format!("{}..{current}", self.config.develop))
363            .unwrap_or(0);
364        let behind = self
365            .rev_count(&format!("{current}..{}", self.config.develop))
366            .unwrap_or(0);
367        Ok((ahead, behind))
368    }
369
370    /// List all feature branches with divergence from develop.
371    ///
372    /// Returns branches matching `feature/phase-*` with ahead/behind counts
373    /// and last commit dates. Protected branches (main, develop) are excluded.
374    pub fn list_feature_branches(&self) -> Result<Vec<BranchInfo>, GitError> {
375        let prefix = &self.config.feature_prefix;
376        let branches = self.git_output(["branch", "--format=%(refname:short)"])?;
377        let mut result = Vec::new();
378        for name in branches.lines().map(|l| l.trim()) {
379            if name.is_empty()
380                || name == self.config.main
381                || name == self.config.develop
382                || !name.starts_with(prefix)
383            {
384                continue;
385            }
386            let ahead = self
387                .rev_count(&format!("{dev}..{name}", dev = self.config.develop))
388                .unwrap_or(0);
389            let behind = self
390                .rev_count(&format!("{name}..{dev}", dev = self.config.develop))
391                .unwrap_or(0);
392            let last_commit = self
393                .git_output(["log", "-1", "--format=%aI", name])
394                .map(|s| s.trim().to_string())
395                .unwrap_or_default();
396            result.push(BranchInfo {
397                name: name.to_string(),
398                ahead,
399                behind,
400                last_commit,
401            });
402        }
403        // Sort by phase number so phase-01 comes before phase-10.
404        result.sort_by(|a, b| a.name.cmp(&b.name));
405        Ok(result)
406    }
407
408    /// Count revisions in the given range. Returns None if the command fails.
409    fn rev_count(&self, range: &str) -> Option<usize> {
410        self.git_output(["rev-list", "--count", range])
411            .ok()
412            .and_then(|s| s.trim().parse().ok())
413    }
414
415    fn git_raw(&self, args: &[&str]) -> Result<(), GitError> {
416        debug!("git {}", args.join(" "));
417        // Pin the subprocess locale to C (Antigravity review, 19b): commit_path's
418        // "nothing to commit" match arm above compares against git's own
419        // English-locale output, which a non-English LC_ALL/LANG would
420        // localize, silently defeating the match and reopening 19b under a
421        // localized environment (T-19-14). Scoped to this one call path only.
422        let output = Command::new("git")
423            .args(args)
424            .env("LC_ALL", "C")
425            .env("LANG", "C")
426            .current_dir(&self.root)
427            .output()?;
428        if output.status.success() {
429            Ok(())
430        } else {
431            Err(GitError::Command(stderr_or_status(&output)))
432        }
433    }
434
435    /// Like [`git_raw`](Self::git_raw), but the error text combines stdout
436    /// with stderr instead of inspecting stderr alone.
437    ///
438    /// Discovered empirically while implementing 19b: `git commit`'s
439    /// "nothing to commit, working tree clean" message is written to
440    /// **stdout**, not stderr. `stderr_or_status` only ever inspects
441    /// `output.stderr`, so a plain `git_raw` error can never contain that
442    /// text — `commit_path`'s `nothing to commit` match arm (immediately
443    /// above its call site) would never fire, no matter how the arm itself
444    /// is written. This sibling exists solely so `commit_path` can see it;
445    /// `commit_all` keeps calling `git_raw` unchanged (D-17 out of scope),
446    /// and `git_raw`'s own error-mapping branch is untouched by this
447    /// addition.
448    fn git_raw_combined(&self, args: &[&str]) -> Result<(), GitError> {
449        debug!("git {}", args.join(" "));
450        let output = Command::new("git")
451            .args(args)
452            .env("LC_ALL", "C")
453            .env("LANG", "C")
454            .current_dir(&self.root)
455            .output()?;
456        if output.status.success() {
457            Ok(())
458        } else {
459            let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
460            let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
461            let combined = match (stderr.is_empty(), stdout.is_empty()) {
462                (false, false) => format!("{stderr}\n{stdout}"),
463                (false, true) => stderr,
464                (true, false) => stdout,
465                (true, true) => format!("exited with {}", output.status),
466            };
467            Err(GitError::Command(combined))
468        }
469    }
470
471    fn git<const N: usize>(&self, args: [&str; N]) -> Result<(), GitError> {
472        debug!("git {}", args.iter().copied().collect::<Vec<_>>().join(" "));
473        let output = Command::new("git")
474            .args(args)
475            .current_dir(&self.root)
476            .output()?;
477        if output.status.success() {
478            Ok(())
479        } else {
480            Err(GitError::Command(stderr_or_status(&output)))
481        }
482    }
483
484    fn git_output<const N: usize>(&self, args: [&str; N]) -> Result<String, GitError> {
485        let output = Command::new("git")
486            .args(args)
487            .current_dir(&self.root)
488            .output()?;
489        if output.status.success() {
490            Ok(String::from_utf8_lossy(&output.stdout).to_string())
491        } else {
492            Err(GitError::Command(stderr_or_status(&output)))
493        }
494    }
495}
496
497/// Run a git command in an arbitrary directory (e.g. a worktree).
498fn git_in(dir: &Path, args: &[&str]) -> Result<(), GitError> {
499    debug!("git (in {}) {}", dir.display(), args.join(" "));
500    let output = Command::new("git").args(args).current_dir(dir).output()?;
501    if output.status.success() {
502        Ok(())
503    } else {
504        Err(GitError::Command(stderr_or_status(&output)))
505    }
506}
507
508fn stderr_or_status(output: &std::process::Output) -> String {
509    let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
510    if stderr.is_empty() {
511        format!("exited with {}", output.status)
512    } else {
513        stderr
514    }
515}
516
517#[cfg(test)]
518mod tests {
519    use super::*;
520    use std::process::Command;
521    use tempfile::TempDir;
522
523    /// Run a git command in `root`, asserting success.
524    fn git(root: &Path, args: &[&str]) {
525        let output = Command::new("git")
526            .args(args)
527            .current_dir(root)
528            .output()
529            .expect("spawn git");
530        assert!(
531            output.status.success(),
532            "git {args:?} failed: {}",
533            String::from_utf8_lossy(&output.stderr)
534        );
535    }
536
537    fn current_branch(root: &Path) -> String {
538        let output = Command::new("git")
539            .args(["rev-parse", "--abbrev-ref", "HEAD"])
540            .current_dir(root)
541            .output()
542            .expect("rev-parse");
543        String::from_utf8_lossy(&output.stdout).trim().to_string()
544    }
545
546    fn commit_file(root: &Path, name: &str) {
547        std::fs::write(root.join(name), name).unwrap();
548        git(root, &["add", "."]);
549        git(root, &["commit", "-q", "-m", &format!("add {name}")]);
550    }
551
552    /// Initialize a repo with `main` and `develop` branches and one commit.
553    fn init_repo() -> TempDir {
554        let dir = tempfile::tempdir().unwrap();
555        let root = dir.path();
556        git(root, &["init", "-q"]);
557        git(root, &["config", "user.email", "test@example.com"]);
558        git(root, &["config", "user.name", "Test"]);
559        git(root, &["config", "commit.gpgsign", "false"]);
560        git(root, &["config", "tag.gpgsign", "false"]);
561        // Disable any globally-configured hooks (e.g. gitleaks) for isolation.
562        git(root, &["config", "core.hooksPath", "/dev/null"]);
563        commit_file(root, "README.md");
564        git(root, &["branch", "-M", "main"]);
565        git(root, &["checkout", "-q", "-b", "develop"]);
566        dir
567    }
568
569    fn flow(root: &Path) -> GitFlow {
570        GitFlow::new(root)
571    }
572
573    #[test]
574    fn feature_start_branches_from_develop() {
575        let repo = init_repo();
576        let root = repo.path();
577        let branch = flow(root).feature_start(3).expect("feature_start");
578        assert_eq!(branch, "feature/phase-03");
579        assert_eq!(current_branch(root), "feature/phase-03");
580    }
581
582    #[test]
583    fn list_feature_branches_reports_ahead_and_behind_semantics() {
584        let repo = init_repo();
585        let root = repo.path();
586        let gf = flow(root);
587
588        gf.feature_start(12).expect("feature_start");
589        commit_file(root, "feature-one.txt");
590        commit_file(root, "feature-two.txt");
591        git(root, &["checkout", "-q", "develop"]);
592        commit_file(root, "develop-only.txt");
593
594        let branches = gf.list_feature_branches().unwrap();
595        let branch = branches
596            .iter()
597            .find(|branch| branch.name == "feature/phase-12")
598            .unwrap();
599
600        assert_eq!(branch.ahead, 2);
601        assert_eq!(branch.behind, 1);
602    }
603
604    #[test]
605    fn feature_finish_merges_into_develop_and_deletes() {
606        let repo = init_repo();
607        let root = repo.path();
608        let gf = flow(root);
609
610        gf.feature_start(1).expect("start");
611        commit_file(root, "feature.txt");
612
613        let branch = gf.feature_finish(1).expect("finish");
614        assert_eq!(branch, "feature/phase-01");
615        assert_eq!(current_branch(root), "develop");
616
617        // Branch is deleted and its work is now on develop.
618        let branches = Command::new("git")
619            .args(["branch"])
620            .current_dir(root)
621            .output()
622            .unwrap();
623        let listing = String::from_utf8_lossy(&branches.stdout);
624        assert!(!listing.contains("feature/phase-01"));
625        assert!(root.join("feature.txt").exists());
626    }
627
628    #[test]
629    fn release_start_and_finish_tags_main_and_merges_both() {
630        let repo = init_repo();
631        let root = repo.path();
632        let gf = flow(root);
633
634        // Add work on develop so the release has content.
635        commit_file(root, "work.txt");
636        let branch = gf.release_start("1.2.0").expect("release_start");
637        assert_eq!(branch, "release/1.2.0");
638
639        gf.release_finish("1.2.0").expect("release_finish");
640        assert_eq!(current_branch(root), "develop");
641
642        // Tag exists.
643        let tags = Command::new("git")
644            .args(["tag"])
645            .current_dir(root)
646            .output()
647            .unwrap();
648        assert!(String::from_utf8_lossy(&tags.stdout).contains("v1.2.0"));
649
650        // Release branch deleted.
651        let branches = Command::new("git")
652            .args(["branch"])
653            .current_dir(root)
654            .output()
655            .unwrap();
656        assert!(!String::from_utf8_lossy(&branches.stdout).contains("release/1.2.0"));
657    }
658
659    /// A global/repo `tag.gpgsign=true` must not turn `tag()`'s lightweight
660    /// tag into an annotated+signed one — that would require a tag message
661    /// and block on `$EDITOR`, silently hanging a headless, unattended run
662    /// (Phase 13 dogfood finding: VersionBump hung on a live
663    /// `devflow start --mode auto` run because the operator's global
664    /// gitconfig sets `tag.gpgsign=true`).
665    #[test]
666    fn tag_stays_lightweight_when_gpgsign_is_forced_on() {
667        let repo = init_repo();
668        let root = repo.path();
669        // Simulate an operator whose global config signs tags by default —
670        // override the test harness's own `tag.gpgsign false` to prove
671        // `tag()`'s per-invocation `-c` override wins regardless.
672        git(root, &["config", "tag.gpgsign", "true"]);
673
674        flow(root)
675            .tag("v9.9.9")
676            .expect("tag must not block on $EDITOR");
677
678        let tags = Command::new("git")
679            .args(["tag", "-l"])
680            .current_dir(root)
681            .output()
682            .unwrap();
683        assert!(String::from_utf8_lossy(&tags.stdout).contains("v9.9.9"));
684
685        // Confirm it's a lightweight tag (points directly at the commit),
686        // not an annotated tag object (which `cat-file -t` would report as
687        // "tag" rather than "commit").
688        let obj_type = Command::new("git")
689            .args(["cat-file", "-t", "v9.9.9"])
690            .current_dir(root)
691            .output()
692            .unwrap();
693        assert_eq!(
694            String::from_utf8_lossy(&obj_type.stdout).trim(),
695            "commit",
696            "tag() must stay lightweight even when tag.gpgsign=true"
697        );
698    }
699
700    #[test]
701    fn commit_path_stages_only_the_given_path_leaving_other_dirt_uncommitted() {
702        // The property that distinguishes commit_path from commit_all
703        // (17-12, Task 2b): a hook using commit_path must never sweep in
704        // unrelated dirty state.
705        let repo = init_repo();
706        let root = repo.path();
707        std::fs::write(root.join("CHANGELOG.md"), "# Changelog\n").unwrap();
708        std::fs::write(root.join("unrelated.txt"), "not part of this commit\n").unwrap();
709
710        // Stage the unrelated file BEFORE calling commit_path. An untracked
711        // file is excluded by any implementation and so proves nothing; an
712        // already-staged one is the real failure mode — a bare `git commit`
713        // writes the whole index and would sweep it in.
714        Command::new("git")
715            .args(["add", "unrelated.txt"])
716            .current_dir(root)
717            .status()
718            .unwrap();
719
720        flow(root)
721            .commit_path("CHANGELOG.md", "docs: add changelog entry")
722            .expect("commit_path");
723
724        let committed = Command::new("git")
725            .args(["log", "-1", "--name-only", "--pretty=format:"])
726            .current_dir(root)
727            .output()
728            .unwrap();
729        let committed_files = String::from_utf8_lossy(&committed.stdout);
730        assert!(committed_files.contains("CHANGELOG.md"));
731        assert!(!committed_files.contains("unrelated.txt"));
732
733        let status = Command::new("git")
734            .args(["status", "--porcelain"])
735            .current_dir(root)
736            .output()
737            .unwrap();
738        let status = String::from_utf8_lossy(&status.stdout);
739        assert!(
740            status.contains("A  unrelated.txt"),
741            "unrelated.txt must remain staged-but-uncommitted, got: {status}"
742        );
743    }
744
745    /// `git rev-list --count HEAD`, parsed. Shared by the three tests below
746    /// so a failure reports both counts instead of a bare assertion.
747    fn rev_list_count(root: &Path) -> u32 {
748        let output = Command::new("git")
749            .args(["rev-list", "--count", "HEAD"])
750            .current_dir(root)
751            .output()
752            .unwrap();
753        assert!(output.status.success(), "git rev-list --count HEAD failed");
754        String::from_utf8_lossy(&output.stdout)
755            .trim()
756            .parse::<u32>()
757            .expect("rev-list --count HEAD must print an integer")
758    }
759
760    /// 19b/D-16: `hooks::version_bump` (hooks.rs:242) calls `commit_path` and
761    /// then tags whatever commit it last produced (hooks.rs:249). If a
762    /// terminal-batch retry calls `commit_path` again with byte-identical
763    /// content (the file untouched since the first call), a forced commit
764    /// here means the release tag can end up naming a commit that contains
765    /// nothing new. This pins the exact retry scenario: two calls, unchanged
766    /// content, `git rev-list --count HEAD` must not move between them.
767    #[test]
768    fn commit_path_twice_with_identical_content_creates_only_one_commit() {
769        let repo = init_repo();
770        let root = repo.path();
771        std::fs::write(root.join("CHANGELOG.md"), "# Changelog\n").unwrap();
772
773        flow(root)
774            .commit_path("CHANGELOG.md", "docs: add changelog entry")
775            .expect("first commit_path call");
776        let n1 = rev_list_count(root);
777
778        // The file is not touched again -- this is the retry scenario, not
779        // a second genuine change.
780        flow(root)
781            .commit_path("CHANGELOG.md", "docs: add changelog entry")
782            .expect("second commit_path call");
783        let n2 = rev_list_count(root);
784
785        assert_eq!(
786            n2, n1,
787            "a repeat commit_path call on unchanged content must not add a \
788             commit: n1={n1}, n2={n2}"
789        );
790    }
791
792    /// 19b/D-16, T-19-11: separates the "no commit" claim from the "no
793    /// error" claim so a future change can't satisfy one by breaking the
794    /// other. `hooks.rs` propagates `commit_path`'s `Result` with `?` at both
795    /// call sites (changelog_append:225, version_bump:242) -- turning a
796    /// genuine no-op into `Err` would stall the terminal hook batch (see
797    /// T-19-11 in this plan's threat model), so both properties must hold
798    /// simultaneously.
799    #[test]
800    fn commit_path_with_no_changes_returns_ok_without_committing() {
801        let repo = init_repo();
802        let root = repo.path();
803        std::fs::write(root.join("CHANGELOG.md"), "# Changelog\n").unwrap();
804        flow(root)
805            .commit_path("CHANGELOG.md", "docs: add changelog entry")
806            .expect("initial commit_path");
807        let n1 = rev_list_count(root);
808
809        // CHANGELOG.md is already committed and unmodified -- a single call
810        // here has nothing to commit.
811        let result = flow(root).commit_path("CHANGELOG.md", "docs: add changelog entry");
812        let n2 = rev_list_count(root);
813
814        assert!(
815            result.is_ok(),
816            "no-op call must return Ok(()), got: {result:?}"
817        );
818        assert_eq!(
819            n2, n1,
820            "no-op call must not create a commit: n1={n1}, n2={n2}"
821        );
822    }
823
824    /// Edge case the fix must NOT change: `commit_path` on a path that does
825    /// not exist on disk still errors at the staging step (`git add` fails
826    /// on an unknown pathspec). Asserted explicitly so the fix for the
827    /// no-change case above cannot be over-applied into "commit_path never
828    /// fails".
829    #[test]
830    fn commit_path_on_nonexistent_path_still_errors() {
831        let repo = init_repo();
832        let root = repo.path();
833
834        let result = flow(root).commit_path("does-not-exist.md", "docs: add changelog entry");
835
836        assert!(
837            result.is_err(),
838            "commit_path on an unknown pathspec must still error, got: {result:?}"
839        );
840    }
841
842    #[test]
843    fn release_start_branches_from_current_head_not_develop() {
844        let repo = init_repo();
845        let root = repo.path();
846        let gf = flow(root);
847
848        // Ship from a feature branch carrying a commit that is NOT on develop.
849        gf.feature_start(5).expect("feature_start");
850        commit_file(root, "feature-only.txt");
851        let feature_tip = gf.branch_tip("feature/phase-05").expect("feature tip");
852
853        let branch = gf.release_start("2.0.0").expect("release_start");
854        assert_eq!(branch, "release/2.0.0");
855        assert_eq!(current_branch(root), "release/2.0.0");
856
857        // The release branch tip must descend from the feature commit — i.e.
858        // the feature-only work is present, not dropped to develop's HEAD.
859        let release_tip = gf.branch_tip("release/2.0.0").expect("release tip");
860        let is_ancestor = Command::new("git")
861            .args(["merge-base", "--is-ancestor", &feature_tip, &release_tip])
862            .current_dir(root)
863            .output()
864            .unwrap()
865            .status
866            .success();
867        assert!(
868            is_ancestor,
869            "release branch must descend from the shipped feature commit"
870        );
871        assert!(root.join("feature-only.txt").exists());
872    }
873
874    #[test]
875    fn cleanup_merged_removes_merged_but_keeps_protected() {
876        let repo = init_repo();
877        let root = repo.path();
878        let gf = flow(root);
879
880        // Create and merge a feature branch into develop.
881        gf.feature_start(2).expect("start");
882        commit_file(root, "f.txt");
883        gf.feature_finish(2).expect("finish");
884
885        // Create an already-merged stray branch off develop.
886        git(root, &["branch", "stale-merged"]);
887
888        let deleted = gf.cleanup_merged().expect("cleanup");
889        assert!(deleted.contains(&"stale-merged".to_string()));
890        // Protected branches survive.
891        assert!(!deleted.contains(&"develop".to_string()));
892        assert!(!deleted.contains(&"main".to_string()));
893    }
894
895    /// WR-04 (13-REVIEW.md): `cleanup_merged` must compute "merged" relative
896    /// to `develop` explicitly, not whatever the main checkout's current
897    /// HEAD happens to be. If the main checkout is left on a divergent
898    /// branch, an implicit-HEAD baseline would wrongly identify (and
899    /// delete) a branch that's merged into that other branch but was never
900    /// actually merged into `develop`.
901    #[test]
902    fn cleanup_merged_is_relative_to_develop_not_current_head() {
903        let repo = init_repo();
904        let root = repo.path();
905        let gf = flow(root);
906
907        // `topic` diverges from develop with a unique commit develop never
908        // sees, then `premature` branches off `topic`'s tip — so
909        // `premature` is merged into `topic` but NOT into `develop`.
910        git(root, &["checkout", "-q", "-b", "topic", "develop"]);
911        commit_file(root, "topic-only.txt");
912        git(root, &["checkout", "-q", "-b", "premature", "topic"]);
913
914        // Leave the main checkout on `topic` — NOT `develop` — before
915        // calling cleanup_merged, mirroring an operator who forgot to
916        // check out develop first. (`topic` itself is also technically
917        // "merged into HEAD" under an implicit baseline since it IS HEAD,
918        // which git's own `-d` correctly refuses as the checked-out branch
919        // — so the call's overall Ok/Err is not itself decisive here; check
920        // the actual side effect on `premature` instead.)
921        git(root, &["checkout", "-q", "topic"]);
922
923        let _ = gf.cleanup_merged();
924        assert!(
925            gf.branch_exists("premature"),
926            "premature is merged into topic (current HEAD) but not into \
927             develop — it must survive cleanup_merged when the baseline is develop"
928        );
929    }
930
931    /// WR-03 (13-REVIEW.md), revised: `git branch --merged` prefixes a
932    /// branch checked out in a linked worktree with `+ `. The prefix must be
933    /// stripped positionally (not by trimming marker characters, which would
934    /// mangle a branch legitimately named "+foo"), and a branch git refuses
935    /// to delete — a worktree checkout can never be deleted, by design —
936    /// must be skipped with a warning rather than aborting the sweep before
937    /// the remaining merged branches.
938    #[test]
939    fn cleanup_merged_skips_worktree_branch_and_continues_sweep() {
940        let repo = init_repo();
941        let root = repo.path();
942        let gf = flow(root);
943
944        // Merge a branch into develop WITHOUT deleting it (feature_finish
945        // deletes on merge, which would leave nothing to check out).
946        git(
947            root,
948            &["checkout", "-q", "-b", "worktree-merged", "develop"],
949        );
950        commit_file(root, "g.txt");
951        git(root, &["checkout", "-q", "develop"]);
952        git(root, &["merge", "-q", "--no-ff", "worktree-merged"]);
953
954        // Check the merged branch out in a linked worktree so
955        // `git branch --merged` reports it with a `+ ` prefix.
956        let wt_dir = tempfile::tempdir().unwrap();
957        git(
958            root,
959            &[
960                "worktree",
961                "add",
962                wt_dir.path().to_str().unwrap(),
963                "worktree-merged",
964            ],
965        );
966
967        // A second merged branch that sorts after "worktree-merged" would be
968        // reached only if the sweep survives the worktree refusal; "zz-" also
969        // guards against luck in iteration order via the branch before it.
970        git(root, &["branch", "aa-stale"]);
971        git(root, &["branch", "zz-stale"]);
972
973        let deleted = gf
974            .cleanup_merged()
975            .expect("a skipped worktree branch must not abort the sweep");
976        assert!(deleted.contains(&"aa-stale".to_string()));
977        assert!(deleted.contains(&"zz-stale".to_string()));
978        assert!(
979            !deleted.contains(&"worktree-merged".to_string()),
980            "worktree checkout cannot be deleted"
981        );
982        assert!(gf.branch_exists("worktree-merged"));
983    }
984
985    /// The delete side must agree with the `--merged develop` listing: `-d`
986    /// verifies merged-into-HEAD, so with the main checkout parked on a
987    /// stale branch every genuinely-merged branch was refused as "not fully
988    /// merged" — in exactly the scenario WR-04 exists for.
989    #[test]
990    fn cleanup_merged_deletes_when_head_is_not_on_develop() {
991        let repo = init_repo();
992        let root = repo.path();
993        let gf = flow(root);
994
995        // `old` is parked before the merge below, so nothing merged later is
996        // reachable from HEAD while it's checked out.
997        git(root, &["checkout", "-q", "-b", "old", "develop"]);
998        git(root, &["checkout", "-q", "develop"]);
999        git(root, &["checkout", "-q", "-b", "merged-feature", "develop"]);
1000        commit_file(root, "h.txt");
1001        git(root, &["checkout", "-q", "develop"]);
1002        git(root, &["merge", "-q", "--no-ff", "merged-feature"]);
1003        git(root, &["checkout", "-q", "old"]);
1004
1005        let deleted = gf.cleanup_merged().expect("cleanup");
1006        assert!(
1007            deleted.contains(&"merged-feature".to_string()),
1008            "merged-into-develop branch must be deleted even when HEAD is elsewhere: {deleted:?}"
1009        );
1010        assert!(!gf.branch_exists("merged-feature"));
1011    }
1012
1013    #[test]
1014    fn delete_branch_removes_unmerged_with_force_and_protects_trunk() {
1015        let repo = init_repo();
1016        let root = repo.path();
1017        let gf = flow(root);
1018
1019        // Create a feature branch with an unmerged commit.
1020        gf.feature_start(8).expect("start");
1021        commit_file(root, "unmerged.txt");
1022        // Switch back to develop so the branch isn't checked out.
1023        git(root, &["checkout", "-q", "develop"]);
1024
1025        // -d would refuse (unmerged); force deletes it.
1026        assert!(gf.delete_branch("feature/phase-08", false).is_err());
1027        gf.delete_branch("feature/phase-08", true)
1028            .expect("force delete");
1029        let branches = Command::new("git")
1030            .args(["branch"])
1031            .current_dir(root)
1032            .output()
1033            .unwrap();
1034        assert!(!String::from_utf8_lossy(&branches.stdout).contains("feature/phase-08"));
1035
1036        // Protected branches are never deleted.
1037        assert!(gf.delete_branch("develop", true).is_err());
1038        assert!(gf.delete_branch("main", true).is_err());
1039    }
1040
1041    #[test]
1042    fn sequentagent_helpers_integrate_and_rebase_cleanly() {
1043        let repo = init_repo();
1044        let root = repo.path();
1045        let gf = flow(root);
1046
1047        // Base branch off develop, not checked out anywhere.
1048        gf.ensure_branch("feature/phase-07", "develop")
1049            .expect("ensure base");
1050        assert!(gf.branch_exists("feature/phase-07"));
1051        assert!(!gf.branch_tip("feature/phase-07").unwrap().is_empty());
1052        // ensure_branch is idempotent.
1053        gf.ensure_branch("feature/phase-07", "develop")
1054            .expect("ensure again");
1055
1056        // Two agent worktrees off the same base tip.
1057        let wt_a = root.join(".worktrees/a");
1058        let wt_b = root.join(".worktrees/b");
1059        crate::worktree::add(root, &wt_a, "feat-a", "feature/phase-07", true).expect("add A");
1060        crate::worktree::add(root, &wt_b, "feat-b", "feature/phase-07", true).expect("add B");
1061
1062        // Agent A commits a new file, then we integrate A into the base (ff).
1063        std::fs::write(wt_a.join("a.txt"), "from-a\n").unwrap();
1064        git(&wt_a, &["add", "."]);
1065        git(&wt_a, &["commit", "-q", "-m", "a work"]);
1066        gf.fast_forward_branch("feature/phase-07", "feat-a")
1067            .expect("ff base to A");
1068        assert_eq!(
1069            gf.branch_tip("feature/phase-07").unwrap(),
1070            gf.branch_tip("feat-a").unwrap()
1071        );
1072
1073        // Agent B (no overlapping changes) rebases onto the updated base cleanly.
1074        gf.rebase_in(&wt_b, "feature/phase-07")
1075            .expect("clean rebase");
1076        // B now contains A's file.
1077        assert!(wt_b.join("a.txt").exists());
1078    }
1079
1080    #[test]
1081    fn rebase_in_aborts_and_errors_on_conflict() {
1082        let repo = init_repo();
1083        let root = repo.path();
1084        let gf = flow(root);
1085
1086        gf.ensure_branch("feature/phase-07", "develop")
1087            .expect("ensure base");
1088
1089        // Worktree B is created off the ORIGINAL base, then edits a.txt.
1090        let wt_b = root.join(".worktrees/b");
1091        crate::worktree::add(root, &wt_b, "feat-b", "feature/phase-07", true).expect("add B");
1092        std::fs::write(wt_b.join("a.txt"), "from-b\n").unwrap();
1093        git(&wt_b, &["add", "."]);
1094        git(&wt_b, &["commit", "-q", "-m", "b edits a"]);
1095
1096        // Meanwhile the base advances with a conflicting a.txt (via worktree A).
1097        let wt_a = root.join(".worktrees/a");
1098        crate::worktree::add(root, &wt_a, "feat-a", "feature/phase-07", true).expect("add A");
1099        std::fs::write(wt_a.join("a.txt"), "from-base\n").unwrap();
1100        git(&wt_a, &["add", "."]);
1101        git(&wt_a, &["commit", "-q", "-m", "base edits a"]);
1102        gf.fast_forward_branch("feature/phase-07", "feat-a")
1103            .expect("ff base to A");
1104
1105        // Rebasing B onto the updated base conflicts on a.txt → error + abort.
1106        let err = gf.rebase_in(&wt_b, "feature/phase-07").unwrap_err();
1107        assert!(matches!(err, GitError::Command(_)));
1108        // The abort left no rebase-in-progress state behind.
1109        assert!(!root.join(".git/worktrees/b/rebase-merge").exists());
1110        // B is still usable: its own commit is intact.
1111        assert_eq!(
1112            std::fs::read_to_string(wt_b.join("a.txt")).unwrap(),
1113            "from-b\n"
1114        );
1115    }
1116
1117    #[test]
1118    fn merge_of_missing_branch_is_an_error() {
1119        let repo = init_repo();
1120        let root = repo.path();
1121        // feature_finish for a phase that was never started: checkout develop
1122        // succeeds, but merging the nonexistent feature branch fails.
1123        let err = flow(root).feature_finish(99).unwrap_err();
1124        assert!(matches!(err, GitError::Command(_)));
1125    }
1126}