Skip to main content

anodizer_core/git/
commits.rs

1use anyhow::{Context as _, Result, bail};
2use std::path::{Path, PathBuf};
3use std::process::Command;
4
5use super::git_output_in;
6
7#[derive(Debug, Clone)]
8pub struct Commit {
9    pub hash: String,
10    pub short_hash: String,
11    pub message: String,
12    pub author_name: String,
13    pub author_email: String,
14    /// Full commit message body (everything after the subject line).
15    /// Contains trailers like `Co-Authored-By:`.
16    pub body: String,
17}
18
19/// Parse git log output (formatted as `%H%x1f%h%x1f%s%x1f%an%x1f%ae%x1f%b%x1e`)
20/// into a vec of [`Commit`]s.
21///
22/// Uses ASCII record separator (0x1e) between commits and unit separator (0x1f)
23/// between fields, so multi-line body text doesn't break parsing.
24///
25/// The single record decoder for this wire format: every changelog path
26/// (`parse_commit_output_with_files` here, and the changelog stage's git
27/// fetch) decodes through this function so the body / author fields can never
28/// drift between call sites.
29pub fn parse_commit_output(output: &str) -> Vec<Commit> {
30    if output.is_empty() {
31        return vec![];
32    }
33    output
34        .split('\x1e')
35        .filter(|record| !record.trim().is_empty())
36        .filter_map(|record| {
37            let fields: Vec<&str> = record.split('\x1f').collect();
38            if fields.len() >= 5 {
39                Some(Commit {
40                    hash: fields[0].trim().to_string(),
41                    short_hash: fields[1].to_string(),
42                    message: fields[2].to_string(),
43                    author_name: fields[3].to_string(),
44                    author_email: fields[4].to_string(),
45                    body: fields.get(5).unwrap_or(&"").trim().to_string(),
46                })
47            } else {
48                None
49            }
50        })
51        .collect()
52}
53
54fn cwd_or_dot() -> PathBuf {
55    std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
56}
57
58/// Get commits between two refs, optionally filtered to a path.
59pub fn get_commits_between(from: &str, to: &str, path_filter: Option<&str>) -> Result<Vec<Commit>> {
60    get_commits_between_in(&cwd_or_dot(), from, to, path_filter)
61}
62
63/// Path-taking sibling of [`get_commits_between`].
64pub fn get_commits_between_in(
65    cwd: &Path,
66    from: &str,
67    to: &str,
68    path_filter: Option<&str>,
69) -> Result<Vec<Commit>> {
70    get_commits_between_paths_in(
71        cwd,
72        from,
73        to,
74        &path_filter
75            .into_iter()
76            .map(String::from)
77            .collect::<Vec<_>>(),
78    )
79}
80
81/// Get commits between two refs, filtered to multiple paths (git log -- path1 path2 ...).
82pub fn get_commits_between_paths(from: &str, to: &str, paths: &[String]) -> Result<Vec<Commit>> {
83    get_commits_between_paths_in(&cwd_or_dot(), from, to, paths)
84}
85
86/// Path-taking sibling of [`get_commits_between_paths`].
87pub fn get_commits_between_paths_in(
88    cwd: &Path,
89    from: &str,
90    to: &str,
91    paths: &[String],
92) -> Result<Vec<Commit>> {
93    let range = format!("{}..{}", from, to);
94    let mut args = vec![
95        "-c".to_string(),
96        "log.showSignature=false".to_string(),
97        "log".to_string(),
98        "--pretty=format:%H%x1f%h%x1f%s%x1f%an%x1f%ae%x1f%b%x1e".to_string(),
99        range,
100    ];
101    if !paths.is_empty() {
102        args.push("--".to_string());
103        for p in paths {
104            args.push(p.clone());
105        }
106    }
107    let arg_refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
108    let output = git_output_in(cwd, &arg_refs)?;
109    Ok(parse_commit_output(&output))
110}
111
112/// Get all commits reachable from HEAD, optionally filtered to a path.
113/// Used for initial releases where there is no previous tag.
114pub fn get_all_commits(path_filter: Option<&str>) -> Result<Vec<Commit>> {
115    get_all_commits_in(&cwd_or_dot(), path_filter)
116}
117
118/// Path-taking sibling of [`get_all_commits`].
119pub fn get_all_commits_in(cwd: &Path, path_filter: Option<&str>) -> Result<Vec<Commit>> {
120    get_all_commits_paths_in(
121        cwd,
122        &path_filter
123            .into_iter()
124            .map(String::from)
125            .collect::<Vec<_>>(),
126    )
127}
128
129/// Get all commits reachable from HEAD, filtered to multiple paths.
130pub fn get_all_commits_paths(paths: &[String]) -> Result<Vec<Commit>> {
131    get_all_commits_paths_in(&cwd_or_dot(), paths)
132}
133
134/// Path-taking sibling of [`get_all_commits_paths`].
135pub fn get_all_commits_paths_in(cwd: &Path, paths: &[String]) -> Result<Vec<Commit>> {
136    let mut args = vec![
137        "-c".to_string(),
138        "log.showSignature=false".to_string(),
139        "log".to_string(),
140        "--pretty=format:%H%x1f%h%x1f%s%x1f%an%x1f%ae%x1f%b%x1e".to_string(),
141        "HEAD".to_string(),
142    ];
143    if !paths.is_empty() {
144        args.push("--".to_string());
145        for p in paths {
146            args.push(p.clone());
147        }
148    }
149    let arg_refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
150    let output = git_output_in(cwd, &arg_refs)?;
151    Ok(parse_commit_output(&output))
152}
153
154/// A commit paired with the workspace-relative paths it touched.
155///
156/// Produced by the `--name-only` fetch variants so the changelog renderers can
157/// apply a precise `changelog.paths` glob intersect over the git-pathspec
158/// scope (see [`crate::changelog_scope`]).
159#[derive(Debug, Clone)]
160pub struct CommitWithFiles {
161    /// The commit metadata.
162    pub commit: Commit,
163    /// Paths this commit touched, relative to the repo root.
164    pub files: Vec<String>,
165}
166
167/// Parse `git log --name-only` output (metadata formatted as
168/// `%H%x1f...%b%x1e`, followed by one touched-file path per line) into
169/// [`CommitWithFiles`].
170///
171/// git emits each commit as `<metadata>\x1e\n<file>\n<file>\n\n` (the touched
172/// files follow the `%x1e`-terminated metadata, then a blank line). Splitting
173/// on `\x1e` yields `[metadata_0, "\n<files_0>\n\n<metadata_1>", ...]`: the
174/// file block trailing each record up to the next metadata belongs to THAT
175/// record's commit.
176///
177/// The metadata record is multi-line because `%b` (the commit body) carries
178/// newlines, so the record runs from the first `\x1f`-bearing line through the
179/// end of the segment — NOT just the first matching line. Truncating to one
180/// line would drop body trailers (e.g. `Co-Authored-By:`) for every commit
181/// after the first, diverging from the full-body parse the changelog stage's
182/// `parse_git_log_records` performs.
183pub fn parse_commit_output_with_files(output: &str) -> Vec<CommitWithFiles> {
184    if output.is_empty() {
185        return vec![];
186    }
187    let segments: Vec<&str> = output.split('\x1e').collect();
188    let mut out: Vec<CommitWithFiles> = Vec::new();
189    // segments[i] for i>0 begins with the file block of commit i-1 followed by
190    // the metadata of commit i. The first segment is pure metadata (commit 0);
191    // the last segment is the file block of the final commit (no trailing
192    // metadata). Walk pairwise: metadata from this segment, files from the
193    // NEXT segment's leading lines (before its own metadata's first field).
194    for (idx, seg) in segments.iter().enumerate() {
195        // The metadata of commit `idx` is the part of `seg` AFTER the leading
196        // file block (file block present only for idx>0). For idx==0 the whole
197        // segment is metadata. For idx>0 the metadata record begins at the
198        // first `\x1f`-bearing line and continues to the segment end (a
199        // multi-line `%b` body keeps emitting newline-separated lines after the
200        // unit-separator fields), so the remainder is kept verbatim — joined
201        // from that line onward — rather than just the first matching line.
202        let metadata = if idx == 0 {
203            seg.trim_start_matches(['\n', '\r']).to_string()
204        } else {
205            let lines: Vec<&str> = seg.split('\n').collect();
206            match lines.iter().position(|line| line.contains('\x1f')) {
207                Some(start) => lines[start..].join("\n"),
208                None => String::new(),
209            }
210        };
211        if metadata.trim().is_empty() {
212            continue;
213        }
214        let commits = parse_commit_output(&metadata);
215        let Some(commit) = commits.into_iter().next() else {
216            continue;
217        };
218        // Files for THIS commit are the leading lines of the NEXT segment,
219        // before that segment's own metadata line.
220        let files = match segments.get(idx + 1) {
221            Some(next) => next
222                .split('\n')
223                .map(str::trim)
224                .take_while(|line| !line.contains('\x1f'))
225                .filter(|line| !line.is_empty())
226                .map(str::to_string)
227                .collect(),
228            None => Vec::new(),
229        };
230        out.push(CommitWithFiles { commit, files });
231    }
232    out
233}
234
235/// `--name-only` sibling of [`get_commits_between_paths_in`]: each commit is
236/// paired with the repo-relative paths it touched, for a precise
237/// `changelog.paths` glob intersect over the git-pathspec scope.
238pub fn get_commits_between_paths_with_files_in(
239    cwd: &Path,
240    from: &str,
241    to: &str,
242    paths: &[String],
243) -> Result<Vec<CommitWithFiles>> {
244    let range = format!("{}..{}", from, to);
245    let mut args = vec![
246        "-c".to_string(),
247        "log.showSignature=false".to_string(),
248        "log".to_string(),
249        "--name-only".to_string(),
250        "--pretty=format:%H%x1f%h%x1f%s%x1f%an%x1f%ae%x1f%b%x1e".to_string(),
251        range,
252    ];
253    if !paths.is_empty() {
254        args.push("--".to_string());
255        for p in paths {
256            args.push(p.clone());
257        }
258    }
259    let arg_refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
260    let output = git_output_in(cwd, &arg_refs)?;
261    Ok(parse_commit_output_with_files(&output))
262}
263
264/// `--name-only` sibling of [`get_all_commits_paths_in`].
265pub fn get_all_commits_paths_with_files_in(
266    cwd: &Path,
267    paths: &[String],
268) -> Result<Vec<CommitWithFiles>> {
269    let mut args = vec![
270        "-c".to_string(),
271        "log.showSignature=false".to_string(),
272        "log".to_string(),
273        "--name-only".to_string(),
274        "--pretty=format:%H%x1f%h%x1f%s%x1f%an%x1f%ae%x1f%b%x1e".to_string(),
275        "HEAD".to_string(),
276    ];
277    if !paths.is_empty() {
278        args.push("--".to_string());
279        for p in paths {
280            args.push(p.clone());
281        }
282    }
283    let arg_refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
284    let output = git_output_in(cwd, &arg_refs)?;
285    Ok(parse_commit_output_with_files(&output))
286}
287
288/// All commits reachable from an arbitrary `rev` (not just `HEAD`), filtered to
289/// `paths`. Used by the changelog stage to bound a no-lower-bound range at an
290/// explicit upper ref (`changelog ..<tag>`): the range is then every ancestor
291/// of `<tag>`, excluding commits made after it.
292pub fn get_commits_reachable_paths_in(
293    cwd: &Path,
294    rev: &str,
295    paths: &[String],
296) -> Result<Vec<Commit>> {
297    let mut args = vec![
298        "-c".to_string(),
299        "log.showSignature=false".to_string(),
300        "log".to_string(),
301        "--pretty=format:%H%x1f%h%x1f%s%x1f%an%x1f%ae%x1f%b%x1e".to_string(),
302        rev.to_string(),
303    ];
304    if !paths.is_empty() {
305        args.push("--".to_string());
306        for p in paths {
307            args.push(p.clone());
308        }
309    }
310    let arg_refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
311    let output = git_output_in(cwd, &arg_refs)?;
312    Ok(parse_commit_output(&output))
313}
314
315/// `--name-only` sibling of [`get_commits_reachable_paths_in`].
316pub fn get_commits_reachable_paths_with_files_in(
317    cwd: &Path,
318    rev: &str,
319    paths: &[String],
320) -> Result<Vec<CommitWithFiles>> {
321    let mut args = vec![
322        "-c".to_string(),
323        "log.showSignature=false".to_string(),
324        "log".to_string(),
325        "--name-only".to_string(),
326        "--pretty=format:%H%x1f%h%x1f%s%x1f%an%x1f%ae%x1f%b%x1e".to_string(),
327        rev.to_string(),
328    ];
329    if !paths.is_empty() {
330        args.push("--".to_string());
331        for p in paths {
332            args.push(p.clone());
333        }
334    }
335    let arg_refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
336    let output = git_output_in(cwd, &arg_refs)?;
337    Ok(parse_commit_output_with_files(&output))
338}
339
340/// Get last N commit subjects.
341pub fn get_last_commit_messages(count: usize) -> Result<Vec<String>> {
342    get_last_commit_messages_in(&cwd_or_dot(), count)
343}
344
345/// Path-taking sibling of [`get_last_commit_messages`].
346pub fn get_last_commit_messages_in(cwd: &Path, count: usize) -> Result<Vec<String>> {
347    let output = git_output_in(
348        cwd,
349        &[
350            "-c",
351            "log.showSignature=false",
352            "log",
353            &format!("-{count}"),
354            "--pretty=format:%s",
355        ],
356    )?;
357    Ok(output.lines().map(str::to_string).collect())
358}
359
360/// Get commit subjects between two refs.
361pub fn get_commit_messages_between(from: &str, to: &str) -> Result<Vec<String>> {
362    get_commit_messages_between_in(&cwd_or_dot(), from, to)
363}
364
365/// Path-taking sibling of [`get_commit_messages_between`].
366pub fn get_commit_messages_between_in(cwd: &Path, from: &str, to: &str) -> Result<Vec<String>> {
367    let output = git_output_in(
368        cwd,
369        &[
370            "-c",
371            "log.showSignature=false",
372            "log",
373            "--pretty=format:%s",
374            &format!("{from}..{to}"),
375        ],
376    )?;
377    Ok(output.lines().map(str::to_string).collect())
378}
379
380/// Get the current branch name.
381pub fn get_current_branch() -> Result<String> {
382    get_current_branch_in(&cwd_or_dot())
383}
384
385/// Return `true` when `name` looks like a branch (NOT an anodize-shaped
386/// release tag). Tag shapes: `^v\d+\.\d+\.\d+` (lockstep
387/// `v1.2.3[-pre][+build]`) or `^<crate>-v\d+\.\d+\.\d+`
388/// (per-crate `mycrate-v1.2.3[...]`).
389///
390/// Both regexes are start-anchored, and the per-crate `<crate>` segment is
391/// constrained to non-`/` characters. Without that, a branch like
392/// `feature/fix-v2.0.0` contains `-v2.0.0` and would be misclassified as a
393/// tag — leaving its `GITHUB_REF_NAME` fallback rejected. A real per-crate
394/// tag's name prefix is a crate name (no path separators), so anchoring on
395/// `^[^/]+-v` keeps that branch shape branch-like while still matching
396/// `mycrate-v1.2.3`.
397///
398/// Guards the `GITHUB_REF_NAME` fallback in [`get_current_branch_in`]: on
399/// a `push: tags:` workflow trigger, `GITHUB_REF_NAME` is the TAG name
400/// (e.g. `v0.4.5`), and accepting it would make `git push origin v0.4.5`
401/// from detached HEAD silently create a branch named after the tag.
402///
403/// Drift-risk pair with `cli::commands::tag::rollback`'s `LOCKSTEP_TAG_RE` /
404/// `PER_CRATE_TAG_RE`: those classify the same two anodize tag shapes but
405/// are fully anchored and strict (a rollback must touch only real tags).
406/// The patterns here are deliberately looser and prefix-only (branch-vs-tag
407/// disambiguation, not classification). Keep both in sync when the tag
408/// grammar changes — they are intentionally separate, not duplicated.
409pub fn is_branchlike(name: &str) -> bool {
410    use regex::Regex;
411    use std::sync::OnceLock;
412    static LOCKSTEP: OnceLock<Regex> = OnceLock::new();
413    static PER_CRATE: OnceLock<Regex> = OnceLock::new();
414    let lockstep = LOCKSTEP.get_or_init(|| Regex::new(r"^v\d+\.\d+\.\d+").expect("static regex"));
415    let per_crate =
416        PER_CRATE.get_or_init(|| Regex::new(r"^[^/]+-v\d+\.\d+\.\d+").expect("static regex"));
417    !(lockstep.is_match(name) || per_crate.is_match(name))
418}
419
420/// Path-taking sibling of [`get_current_branch`].
421///
422/// Handles detached-HEAD checkouts (e.g. `actions/checkout@v4` with `ref:`)
423/// by resolving the branch HEAD points at via `for-each-ref`, falling back
424/// to the remote's default branch and finally `GITHUB_REF_NAME` when set —
425/// so downstream `git push origin <branch>` produces a valid refspec
426/// instead of a literal `HEAD` that git can't auto-qualify.
427///
428/// The `GITHUB_REF_NAME` fallback is guarded by [`is_branchlike`]: on a
429/// `push: tags:` trigger, `GITHUB_REF_NAME` is the TAG name, and accepting
430/// it would push to a branch named after the tag. Tag-shaped values fall
431/// through to the bail at the end so callers hard-fail and prompt the
432/// operator for `--branch <name>` explicitly.
433pub fn get_current_branch_in(cwd: &Path) -> Result<String> {
434    get_current_branch_in_with_env(cwd, &crate::ProcessEnvSource)
435}
436
437/// [`EnvSource`](crate::EnvSource)-injecting form of [`get_current_branch_in`].
438///
439/// Reads the `GITHUB_REF_NAME` fallback from `env` rather than the process
440/// environment, so tests can drive the tag-shaped / branch-shaped fallback
441/// branches deterministically without mutating global env state.
442pub fn get_current_branch_in_with_env<E: crate::EnvSource + ?Sized>(
443    cwd: &Path,
444    env: &E,
445) -> Result<String> {
446    if let Ok(name) = git_output_in(cwd, &["symbolic-ref", "--short", "HEAD"]) {
447        return Ok(name);
448    }
449    if let Ok(out) = git_output_in(
450        cwd,
451        &[
452            "for-each-ref",
453            "--points-at",
454            "HEAD",
455            "--format=%(refname:short)",
456            "refs/heads/",
457        ],
458    ) && !out.is_empty()
459    {
460        let branches: Vec<&str> = out.lines().collect();
461        for preferred in ["master", "main"] {
462            if branches.contains(&preferred) {
463                return Ok(preferred.to_string());
464            }
465        }
466        if let Some(first) = branches.first() {
467            return Ok((*first).to_string());
468        }
469    }
470    if let Ok(out) = git_output_in(
471        cwd,
472        &["symbolic-ref", "--short", "refs/remotes/origin/HEAD"],
473    ) && let Some(name) = out.strip_prefix("origin/")
474    {
475        return Ok(name.to_string());
476    }
477    if let Some(name) = env.var("GITHUB_REF_NAME")
478        && !name.is_empty()
479        && is_branchlike(&name)
480    {
481        return Ok(name);
482    }
483    anyhow::bail!(
484        "could not resolve current branch: HEAD is detached and no fallback (points-at-HEAD branches, origin/HEAD, GITHUB_REF_NAME) succeeded"
485    )
486}
487
488/// Return remote branch short names that contain `sha` (e.g. `master`,
489/// `release/v1`). The bump commit's SHA is the deterministic anchor of
490/// the tag, so deriving the push branch from it is race-immune to the
491/// default branch moving between bump and rollback. Empty `Vec` when
492/// the SHA is not on any remote branch (orphan / not-yet-pushed).
493pub fn branches_containing_sha_in(cwd: &Path, sha: &str) -> Result<Vec<String>> {
494    let out = git_output_in(
495        cwd,
496        &[
497            "branch",
498            "-r",
499            "--contains",
500            sha,
501            "--format=%(refname:short)",
502        ],
503    )?;
504    Ok(out
505        .lines()
506        .filter_map(|line| line.trim().strip_prefix("origin/").map(str::to_string))
507        .filter(|name| !name.is_empty() && name != "HEAD")
508        .collect())
509}
510
511/// Check if there are any commits since a given tag.
512pub fn has_commits_since_tag(tag: &str) -> Result<bool> {
513    has_commits_since_tag_in(&cwd_or_dot(), tag)
514}
515
516/// Path-taking sibling of [`has_commits_since_tag`].
517pub fn has_commits_since_tag_in(cwd: &Path, tag: &str) -> Result<bool> {
518    let range = format!("{}..HEAD", tag);
519    let output = git_output_in(
520        cwd,
521        &["-c", "log.showSignature=false", "log", "--oneline", &range],
522    )?;
523    Ok(!output.is_empty())
524}
525
526/// Count the commits on HEAD since the most recent reachable tag.
527///
528/// Resolves the last tag with `git describe --tags --abbrev=0 HEAD`, then
529/// returns `git rev-list --count <tag>..HEAD`. When HEAD has no reachable
530/// tag (a repo whose first version tag has not landed yet), the total
531/// commit count on HEAD is returned instead (`git rev-list --count HEAD`).
532///
533/// `monorepo_prefix` constrains the `describe` to tags matching
534/// `<prefix>*` (via `--match`), so in a per-crate workspace the count is
535/// since the matching crate's tag rather than the nearest tag from ANY
536/// subproject. `None` considers all tags.
537///
538/// This is the stateless basis for the `{{ .NightlyBuild }}` template var:
539/// the count resets to a small number the moment a new version tag lands,
540/// so a nightly build counter increments per base version with no state
541/// anodizer must persist.
542///
543/// Returns `Ok(0)` for an empty repository (no commits) so callers never
544/// have to special-case the unborn-HEAD state.
545pub fn count_commits_since_last_tag_in(cwd: &Path, monorepo_prefix: Option<&str>) -> Result<u64> {
546    // `--abbrev=0` yields the bare tag name (no `-<n>-g<sha>` suffix).
547    // A repo with no reachable tag exits non-zero here; treat that as
548    // "count every commit on HEAD" rather than an error.
549    //
550    // `--match=<prefix>*` (when a monorepo prefix is set) restricts the
551    // describe to the matching crate's tags — without it, describe returns
552    // the nearest reachable tag from ANY subproject and the count would be
553    // since the wrong crate's tag. Mirrors `find_previous_tag_with_prefix_in`.
554    let match_arg;
555    let mut describe_args: Vec<&str> = vec!["describe", "--tags", "--abbrev=0"];
556    if let Some(prefix) = monorepo_prefix {
557        match_arg = format!("--match={}*", prefix);
558        describe_args.push(&match_arg);
559    }
560    describe_args.push("HEAD");
561    let range = match git_output_in(cwd, &describe_args) {
562        Ok(tag) if !tag.is_empty() => format!("{tag}..HEAD"),
563        _ => "HEAD".to_string(),
564    };
565    // An empty repo (unborn HEAD) makes `rev-list` fail; map that to 0.
566    let count = match git_output_in(cwd, &["rev-list", "--count", &range]) {
567        Ok(s) => s.trim().parse::<u64>().unwrap_or(0),
568        Err(_) => 0,
569    };
570    Ok(count)
571}
572
573/// Get the short commit hash of HEAD.
574pub fn get_short_commit() -> Result<String> {
575    get_short_commit_in(&cwd_or_dot())
576}
577
578/// Path-taking sibling of [`get_short_commit`].
579pub fn get_short_commit_in(cwd: &Path) -> Result<String> {
580    git_output_in(cwd, &["rev-parse", "--short", "HEAD"])
581}
582
583/// Default short-commit length used across error messages, log
584/// output, and any place that needs to truncate a full SHA for
585/// human display. Matches git's `--short` default (7) — and the
586/// `ShortCommit` template var populated by [`super::detect_git_info`]
587/// (which delegates to `git rev-parse --short`).
588pub const SHORT_COMMIT_LEN: usize = 7;
589
590/// Truncate a full commit SHA string to [`SHORT_COMMIT_LEN`]
591/// characters. Returns the input unchanged when it's already shorter
592/// or equal in length. Use this any time the SHA arrives as a string
593/// (e.g. deserialized from a manifest or read from a template var)
594/// rather than running `git rev-parse --short` again — saves a
595/// subprocess and keeps the length convention in one place.
596///
597/// Empty input returns empty; callers needing fail-closed semantics
598/// (e.g. publish-only's commit cross-check) check `is_empty()`
599/// before calling.
600pub fn short_commit_str(commit: &str) -> String {
601    if commit.len() > SHORT_COMMIT_LEN {
602        commit[..SHORT_COMMIT_LEN].to_string()
603    } else {
604        commit.to_string()
605    }
606}
607
608/// Get the full commit hash of HEAD.
609///
610/// The full commit SHA (resolved at git-pipe time and
611/// reused everywhere downstream). Used by the source-archive stage to
612/// produce deterministic archives across consecutive commits when
613/// `git_info` was not pre-populated by an earlier pipe.
614pub fn get_head_commit() -> Result<String> {
615    get_head_commit_in(&cwd_or_dot())
616}
617
618/// Path-taking sibling of [`get_head_commit`].
619pub fn get_head_commit_in(cwd: &Path) -> Result<String> {
620    git_output_in(cwd, &["rev-parse", "HEAD"])
621}
622
623/// Check if there are changes in a path since a given tag.
624pub fn has_changes_since(tag: &str, path: &str) -> Result<bool> {
625    has_changes_since_in(&cwd_or_dot(), tag, path)
626}
627
628/// Path-taking sibling of [`has_changes_since`].
629pub fn has_changes_since_in(cwd: &Path, tag: &str, path: &str) -> Result<bool> {
630    let output = git_output_in(
631        cwd,
632        &["diff", "--name-only", &format!("{}..HEAD", tag), "--", path],
633    )?;
634    Ok(!output.is_empty())
635}
636
637/// Get last N commit subjects that touched a specific path.
638pub fn get_last_commit_messages_path(count: usize, path: &str) -> Result<Vec<String>> {
639    get_last_commit_messages_path_in(&cwd_or_dot(), count, path)
640}
641
642/// Path-taking sibling of [`get_last_commit_messages_path`].
643pub fn get_last_commit_messages_path_in(
644    cwd: &Path,
645    count: usize,
646    path: &str,
647) -> Result<Vec<String>> {
648    let output = git_output_in(
649        cwd,
650        &[
651            "-c",
652            "log.showSignature=false",
653            "log",
654            &format!("-{count}"),
655            "--pretty=format:%s",
656            "--",
657            path,
658        ],
659    )?;
660    Ok(output.lines().map(str::to_string).collect())
661}
662
663/// Get commit subjects between two refs that touched a specific path.
664pub fn get_commit_messages_between_path(from: &str, to: &str, path: &str) -> Result<Vec<String>> {
665    get_commit_messages_between_path_in(&cwd_or_dot(), from, to, path)
666}
667
668/// Path-taking sibling of [`get_commit_messages_between_path`].
669pub fn get_commit_messages_between_path_in(
670    cwd: &Path,
671    from: &str,
672    to: &str,
673    path: &str,
674) -> Result<Vec<String>> {
675    let output = git_output_in(
676        cwd,
677        &[
678            "-c",
679            "log.showSignature=false",
680            "log",
681            "--pretty=format:%s",
682            &format!("{from}..{to}"),
683            "--",
684            path,
685        ],
686    )?;
687    Ok(output.lines().map(str::to_string).collect())
688}
689
690/// Stage specific files and create a commit.
691///
692/// Returns `Ok(true)` when a commit was created, `Ok(false)` when staging
693/// produced no diff (e.g. files are already at the target state) — callers
694/// that need idempotent bump-then-tag flows can use the boolean to decide
695/// whether to skip downstream commit-dependent work without inspecting git
696/// state separately.
697pub fn stage_and_commit(files: &[&str], message: &str) -> Result<bool> {
698    stage_and_commit_in(&cwd_or_dot(), files, message)
699}
700
701/// Path-taking sibling of [`stage_and_commit`].
702pub fn stage_and_commit_in(cwd: &Path, files: &[&str], message: &str) -> Result<bool> {
703    let mut args = vec!["add", "--"];
704    args.extend(files.iter().copied());
705    git_output_in(cwd, &args)?;
706    // Idempotency guard: `git add` happily stages nothing when the working
707    // tree already matches HEAD for the given paths. Running `git commit`
708    // after would fail with "nothing to commit" (printed to stdout, not
709    // stderr) and surface a confusing empty-stderr error. Detect the
710    // no-diff case here so callers can re-run safely.
711    let diff = Command::new("git")
712        .current_dir(cwd)
713        .args(["diff", "--cached", "--quiet", "--"])
714        .args(files)
715        .env("GIT_TERMINAL_PROMPT", "0")
716        .env("LC_ALL", "C")
717        .status()?;
718    if diff.success() {
719        return Ok(false);
720    }
721    git_output_in(cwd, &["commit", "-m", message])?;
722    Ok(true)
723}
724
725/// `git -C <workspace_root> -c log.showSignature=false log
726/// --pretty=format:%B%x1e <range> -- <rel_path>` — list commit message
727/// bodies (subject+body) for commits in `range` touching `rel_path`,
728/// using the `\x1e` (RS) byte as a between-commits separator so multi-line
729/// bodies survive parsing.
730///
731/// `range` is the git revision range as a string (e.g. `"HEAD"`,
732/// `"v0.3.0..HEAD"`); the empty string is invalid (caller must pre-filter).
733/// Returns `Ok(Vec::new())` when git fails so callers treat
734/// "range doesn't exist yet" as a non-error.
735pub fn log_subjects_for_range(
736    workspace_root: &std::path::Path,
737    range: &str,
738    rel_path: &str,
739) -> Result<Vec<String>> {
740    let out = Command::new("git")
741        .arg("-C")
742        .arg(workspace_root)
743        .args([
744            "-c",
745            "log.showSignature=false",
746            "log",
747            "--pretty=format:%B%x1e",
748            range,
749            "--",
750            rel_path,
751        ])
752        .env("GIT_TERMINAL_PROMPT", "0")
753        .env("LC_ALL", "C")
754        .output()?;
755    if !out.status.success() {
756        // Range may not exist yet (no last_tag, path not in history).
757        return Ok(Vec::new());
758    }
759    let text = String::from_utf8_lossy(&out.stdout);
760    Ok(text
761        .split('\x1e')
762        .map(|s| s.trim().to_string())
763        .filter(|s| !s.is_empty())
764        .collect())
765}
766
767/// `git -C <workspace_root> add <rel>` — stage a single relative path.
768pub fn add_path_in(workspace_root: &std::path::Path, rel: &std::path::Path) -> Result<()> {
769    let out = Command::new("git")
770        .arg("-C")
771        .arg(workspace_root)
772        .arg("add")
773        .arg(rel)
774        .env("GIT_TERMINAL_PROMPT", "0")
775        .env("LC_ALL", "C")
776        .output()
777        .context("failed to invoke git add")?;
778    if !out.status.success() {
779        let stderr_raw = String::from_utf8_lossy(&out.stderr);
780        let raw = format!("git add {} failed: {}", rel.display(), stderr_raw.trim());
781        bail!("{}", crate::redact::redact_process_env(&raw));
782    }
783    Ok(())
784}
785
786/// `git -C <workspace_root> commit [-S] -m <message>` — create a commit
787/// with the given message, optionally GPG-signed.
788pub fn commit_in(workspace_root: &std::path::Path, message: &str, sign: bool) -> Result<()> {
789    let mut cmd = Command::new("git");
790    cmd.arg("-C").arg(workspace_root).arg("commit");
791    if sign {
792        cmd.arg("-S");
793    }
794    cmd.arg("-m")
795        .arg(message)
796        .env("GIT_TERMINAL_PROMPT", "0")
797        .env("LC_ALL", "C");
798    let out = cmd.output().context("failed to invoke git commit")?;
799    if !out.status.success() {
800        let stderr_raw = String::from_utf8_lossy(&out.stderr);
801        let raw = format!("git commit failed: {}", stderr_raw.trim());
802        bail!("{}", crate::redact::redact_process_env(&raw));
803    }
804    Ok(())
805}
806
807/// `git diff --name-only <tag>..HEAD -- <paths>...` — return `true` when
808/// any of the named paths changed between `tag` and `HEAD`. Returns
809/// `Ok(false)` when git fails (e.g. not a git repo) so callers can treat
810/// the absence-of-info case as "no changes".
811pub fn paths_changed_since_tag(tag: &str, paths: &[&str]) -> Result<bool> {
812    paths_changed_since_tag_in(&cwd_or_dot(), tag, paths)
813}
814
815/// Path-taking sibling of [`paths_changed_since_tag`].
816pub fn paths_changed_since_tag_in(cwd: &Path, tag: &str, paths: &[&str]) -> Result<bool> {
817    let mut args: Vec<String> = vec![
818        "diff".to_string(),
819        "--name-only".to_string(),
820        format!("{tag}..HEAD"),
821        "--".to_string(),
822    ];
823    for p in paths {
824        args.push((*p).to_string());
825    }
826    let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();
827    let output = Command::new("git")
828        .current_dir(cwd)
829        .args(&arg_refs)
830        .env("GIT_TERMINAL_PROMPT", "0")
831        .env("LC_ALL", "C")
832        .output()?;
833    if output.status.success() {
834        Ok(!String::from_utf8_lossy(&output.stdout).trim().is_empty())
835    } else {
836        Ok(false)
837    }
838}
839
840/// `git -C <repo> rev-parse HEAD` — return HEAD's full commit hash for the
841/// given repository (or worktree). Path-taking sibling of
842/// [`get_head_commit`] so callers (the determinism harness, future CI
843/// glue) can resolve HEAD without `cd`-ing into the repo first.
844pub fn head_commit_hash_in(repo: &std::path::Path) -> Result<String> {
845    let out = Command::new("git")
846        .arg("-C")
847        .arg(repo)
848        .args(["rev-parse", "HEAD"])
849        .env("GIT_TERMINAL_PROMPT", "0")
850        .env("LC_ALL", "C")
851        .output()
852        .context("failed to invoke git rev-parse HEAD")?;
853    if !out.status.success() {
854        let stderr_raw = String::from_utf8_lossy(&out.stderr);
855        let raw = format!("git rev-parse HEAD failed: {}", stderr_raw.trim());
856        bail!("{}", crate::redact::redact_process_env(&raw));
857    }
858    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
859}
860
861/// Resolve a revision (sha, ref name, `HEAD`, etc.) to its full commit hash.
862///
863/// Wrapper over `git rev-parse <rev>` — errors when the revision can't be
864/// resolved (unknown sha, ambiguous short hash, not a git repo).
865pub fn rev_parse_in(cwd: &Path, rev: &str) -> Result<String> {
866    git_output_in(cwd, &["rev-parse", rev])
867}
868
869/// `git rev-parse --verify <rev>^{commit}` — resolve `rev` to a commit SHA,
870/// erroring when it does not name an existing commit. Stricter than
871/// [`rev_parse_in`]: `--verify` rejects ambiguous / non-existent refs (rather
872/// than echoing the input back), and the `^{commit}` peel rejects a ref that
873/// resolves to a non-commit object (e.g. a tree or blob SHA).
874pub fn rev_verify_commit_in(cwd: &Path, rev: &str) -> Result<String> {
875    git_output_in(
876        cwd,
877        &["rev-parse", "--verify", &format!("{}^{{commit}}", rev)],
878    )
879}
880
881/// `git rev-list <sha>..HEAD` — list the commit hashes (newest-first) that
882/// sit on top of `sha` but aren't in `sha`.
883///
884/// Returns an empty vec when `sha` IS `HEAD` (no commits between).
885pub fn commits_between_in(cwd: &Path, sha: &str) -> Result<Vec<String>> {
886    let range = format!("{}..HEAD", sha);
887    let out = git_output_in(cwd, &["rev-list", &range])?;
888    if out.is_empty() {
889        return Ok(Vec::new());
890    }
891    Ok(out.lines().map(|s| s.trim().to_string()).collect())
892}
893
894/// `git log -1 --format=%s <sha>` — return the subject line of a single
895/// commit. Used to render the "non-bump commit subject" list when the
896/// rollback safety check fires.
897pub fn commit_subject_in(cwd: &Path, sha: &str) -> Result<String> {
898    git_output_in(
899        cwd,
900        &[
901            "-c",
902            "log.showSignature=false",
903            "log",
904            "-1",
905            "--format=%s",
906            sha,
907        ],
908    )
909}
910
911/// `git log --format=%H%x1f%s <sha>..HEAD` — return every `(full_sha, subject)`
912/// pair in the range in one subprocess. Used by the rollback safety check so
913/// classifying N intervening commits is a single `git` spawn rather than
914/// `1 + N` (one `rev-list` plus one `log -1` per commit).
915///
916/// Empty range (sha IS HEAD) returns an empty vec.
917pub fn commits_with_subjects_in(cwd: &Path, sha: &str) -> Result<Vec<(String, String)>> {
918    let range = format!("{}..HEAD", sha);
919    let out = git_output_in(
920        cwd,
921        &[
922            "-c",
923            "log.showSignature=false",
924            "log",
925            "--format=%H%x1f%s",
926            &range,
927        ],
928    )?;
929    if out.is_empty() {
930        return Ok(Vec::new());
931    }
932    Ok(out
933        .lines()
934        .filter_map(|line| {
935            let mut parts = line.splitn(2, '\x1f');
936            let sha = parts.next()?.trim().to_string();
937            let subj = parts.next().unwrap_or("").to_string();
938            if sha.is_empty() {
939                None
940            } else {
941                Some((sha, subj))
942            }
943        })
944        .collect())
945}
946
947/// Committer identity (author + committer name/email) for the rare path
948/// where a git invocation lands on a host with no `user.email` /
949/// `user.name` configured — notably `actions/checkout@v6`, which does
950/// NOT set committer identity for the workflow runner. Resolved once per
951/// caller and threaded through to [`revert_commit_in`] so the CLI never
952/// mutates the repo's git config (env-only, scoped to the single spawn).
953///
954/// Convention: when both `name` and `email` are populated, the values
955/// are exported as `GIT_AUTHOR_NAME` / `GIT_AUTHOR_EMAIL` AND
956/// `GIT_COMMITTER_NAME` / `GIT_COMMITTER_EMAIL` on the git child
957/// processes (revert + amend). When `None`, the child inherits whatever
958/// the parent / repo config provides.
959#[derive(Debug, Clone, Default)]
960pub struct CommitterIdentity {
961    pub name: Option<String>,
962    pub email: Option<String>,
963}
964
965impl CommitterIdentity {
966    /// Return a default committer identity to use when `user.email` and
967    /// `user.name` are both unset on the host. Email uses the
968    /// short-hostname (best-effort; falls back to `"localhost"`) so a
969    /// reviewer can tell at a glance which machine emitted the
970    /// rollback commit.
971    pub fn default_for_rollback() -> Self {
972        let host = std::env::var("HOSTNAME")
973            .ok()
974            .or_else(|| std::env::var("COMPUTERNAME").ok())
975            .and_then(|h| h.split('.').next().map(str::to_string))
976            .filter(|h| !h.is_empty())
977            .unwrap_or_else(|| "localhost".to_string());
978        Self {
979            name: Some("anodize-rollback".to_string()),
980            email: Some(format!("anodize-rollback@{host}")),
981        }
982    }
983
984    fn apply_to(&self, cmd: &mut Command) {
985        if let Some(n) = &self.name {
986            cmd.env("GIT_AUTHOR_NAME", n).env("GIT_COMMITTER_NAME", n);
987        }
988        if let Some(e) = &self.email {
989            cmd.env("GIT_AUTHOR_EMAIL", e).env("GIT_COMMITTER_EMAIL", e);
990        }
991    }
992}
993
994/// Read `git config user.email` / `user.name` in `cwd`. Returns
995/// `(name, email)`, each `Some(value)` when configured (and non-empty)
996/// or `None` when unset. Used by [`revert_commit_in`] to detect the
997/// CI-checkout case where neither identity is configured and the
998/// committer env fallback must fire.
999fn read_git_identity(cwd: &Path) -> (Option<String>, Option<String>) {
1000    let one = |key: &str| -> Option<String> {
1001        let out = Command::new("git")
1002            .current_dir(cwd)
1003            .args(["config", "--get", key])
1004            .env("LC_ALL", "C")
1005            .env("GIT_TERMINAL_PROMPT", "0")
1006            .output()
1007            .ok()?;
1008        if !out.status.success() {
1009            return None;
1010        }
1011        let value = String::from_utf8_lossy(&out.stdout).trim().to_string();
1012        if value.is_empty() { None } else { Some(value) }
1013    };
1014    (one("user.name"), one("user.email"))
1015}
1016
1017/// Resolve the committer identity to use for a rollback-style commit.
1018/// When the host already has `user.name` AND `user.email` configured
1019/// (or `GIT_AUTHOR_*` / `GIT_COMMITTER_*` are set in the parent env),
1020/// returns an empty identity so the child inherits the existing
1021/// values. Otherwise returns a synthetic identity so the commit
1022/// doesn't fail with "Author identity unknown" on bare-CI hosts.
1023pub fn resolve_rollback_identity(cwd: &Path) -> CommitterIdentity {
1024    let env_author_set =
1025        std::env::var("GIT_AUTHOR_EMAIL").is_ok() && std::env::var("GIT_AUTHOR_NAME").is_ok();
1026    let env_committer_set =
1027        std::env::var("GIT_COMMITTER_EMAIL").is_ok() && std::env::var("GIT_COMMITTER_NAME").is_ok();
1028    if env_author_set && env_committer_set {
1029        return CommitterIdentity::default();
1030    }
1031    let (name, email) = read_git_identity(cwd);
1032    if name.is_some() && email.is_some() {
1033        return CommitterIdentity::default();
1034    }
1035    CommitterIdentity::default_for_rollback()
1036}
1037
1038/// Run `git revert --no-edit <sha>` in `cwd`, optionally followed by
1039/// `git commit --amend -m <message>`.
1040///
1041/// Refuses against a dirty working tree (`git revert` would surface a
1042/// less actionable "your local changes would be overwritten" message
1043/// otherwise). Mirrors the dirty-tree guard used by
1044/// `stage-publish/src/util/git_revert.rs`. The guard counts only
1045/// TRACKED modifications (`--untracked-files=no`): a revert never
1046/// touches untracked files, and a failure-recovery rollback runs right
1047/// after a release wrote `dist/` — in repos that don't gitignore their
1048/// dist, an untracked-counts-as-dirty guard would refuse every
1049/// post-release rollback. The one genuine hazard (an untracked file
1050/// where the revert must restore a tracked one) is refused by git
1051/// itself with an explicit "would be overwritten" error.
1052///
1053/// On revert failure (typically a merge conflict against later commits
1054/// on top of the bump), runs `git revert --abort` to restore the
1055/// working tree before bubbling the error — otherwise the next
1056/// rollback attempt would trip the dirty-tree guard and the operator
1057/// would be stuck.
1058///
1059/// `identity` is threaded through as committer env vars so the call
1060/// works on bare-CI hosts where the workflow checkout doesn't set
1061/// `user.email` / `user.name`. The env is scoped to the spawn; the
1062/// repo's git config is never mutated.
1063pub fn revert_commit_in(
1064    cwd: &Path,
1065    sha: &str,
1066    message: Option<&str>,
1067    identity: &CommitterIdentity,
1068) -> Result<()> {
1069    let status = Command::new("git")
1070        .args(["status", "--porcelain", "--untracked-files=no"])
1071        .current_dir(cwd)
1072        .env("LC_ALL", "C")
1073        .env("GIT_TERMINAL_PROMPT", "0")
1074        .output()
1075        .with_context(|| format!("revert_commit_in: git status in {}", cwd.display()))?;
1076    if !status.status.success() {
1077        let stderr_raw = String::from_utf8_lossy(&status.stderr);
1078        let raw = format!("git status failed: {}", stderr_raw.trim());
1079        bail!("{}", crate::redact::redact_process_env(&raw));
1080    }
1081    if !status.stdout.is_empty() {
1082        bail!(
1083            "refusing to revert in a dirty working tree at {}\nstatus:\n{}",
1084            cwd.display(),
1085            String::from_utf8_lossy(&status.stdout),
1086        );
1087    }
1088
1089    let mut revert_cmd = Command::new("git");
1090    revert_cmd
1091        .current_dir(cwd)
1092        .args(["revert", "--no-edit", sha])
1093        .env("LC_ALL", "C")
1094        .env("GIT_TERMINAL_PROMPT", "0");
1095    identity.apply_to(&mut revert_cmd);
1096    let out = revert_cmd
1097        .output()
1098        .with_context(|| format!("revert_commit_in: git revert in {}", cwd.display()))?;
1099    if !out.status.success() {
1100        let stderr_raw = String::from_utf8_lossy(&out.stderr);
1101        // Restore the working tree before bubbling — otherwise the dirty-tree
1102        // guard above traps a subsequent rollback retry forever.
1103        let _ = Command::new("git")
1104            .current_dir(cwd)
1105            .args(["revert", "--abort"])
1106            .env("LC_ALL", "C")
1107            .env("GIT_TERMINAL_PROMPT", "0")
1108            .output();
1109        let raw = format!(
1110            "git revert {sha} hit conflicts and was aborted (working tree restored). \
1111             The bump commit overlaps with later changes — resolve manually, \
1112             or re-run with --mode=reset to force.\nstderr: {}",
1113            stderr_raw.trim()
1114        );
1115        bail!("{}", crate::redact::redact_process_env(&raw));
1116    }
1117    if let Some(msg) = message {
1118        let mut amend_cmd = Command::new("git");
1119        amend_cmd
1120            .current_dir(cwd)
1121            .args(["commit", "--amend", "-m", msg])
1122            .env("LC_ALL", "C")
1123            .env("GIT_TERMINAL_PROMPT", "0");
1124        identity.apply_to(&mut amend_cmd);
1125        let out = amend_cmd.output().with_context(|| {
1126            format!("revert_commit_in: git commit --amend in {}", cwd.display())
1127        })?;
1128        if !out.status.success() {
1129            let stderr_raw = String::from_utf8_lossy(&out.stderr);
1130            let raw = format!("git commit --amend failed: {}", stderr_raw.trim());
1131            bail!("{}", crate::redact::redact_process_env(&raw));
1132        }
1133    }
1134    Ok(())
1135}
1136
1137/// Run `git reset --hard <sha>` in `cwd`. **Destructive** — rewrites HEAD
1138/// and the index in place; callers must surface a warning before invoking.
1139pub fn reset_hard_in(cwd: &Path, sha: &str) -> Result<()> {
1140    git_output_in(cwd, &["reset", "--hard", sha])?;
1141    Ok(())
1142}
1143
1144/// Push a branch (`HEAD:refs/heads/<branch>`) to the `origin` remote.
1145///
1146/// Errors when no `origin` remote is configured — callers driving local-only
1147/// flows should pass `--no-push` to skip the call entirely.
1148pub fn push_branch_in(cwd: &Path, branch: &str) -> Result<()> {
1149    if !super::has_remote_in(cwd, "origin") {
1150        bail!("no 'origin' remote configured, cannot push branch '{branch}'");
1151    }
1152    let refspec = format!("HEAD:refs/heads/{}", branch);
1153    let out = Command::new("git")
1154        .current_dir(cwd)
1155        .args(["push", "origin", &refspec])
1156        .env("GIT_TERMINAL_PROMPT", "0")
1157        .env("LC_ALL", "C")
1158        .output()
1159        .with_context(|| format!("push_branch_in: git push origin {refspec}"))?;
1160    if !out.status.success() {
1161        let stderr_raw = String::from_utf8_lossy(&out.stderr);
1162        let raw = format!("git push origin {} failed: {}", refspec, stderr_raw.trim());
1163        bail!("{}", crate::redact::redact_process_env(&raw));
1164    }
1165    Ok(())
1166}
1167
1168/// `git -C <repo> log -1 --format=%ct HEAD` — return HEAD's committer
1169/// timestamp (seconds since UNIX epoch) for the given repository. Used by
1170/// the determinism harness as the non-snapshot SDE seed.
1171pub fn head_commit_timestamp_in(repo: &std::path::Path) -> Result<i64> {
1172    let out = Command::new("git")
1173        .arg("-C")
1174        .arg(repo)
1175        .args(["log", "-1", "--format=%ct", "HEAD"])
1176        .env("GIT_TERMINAL_PROMPT", "0")
1177        .env("LC_ALL", "C")
1178        .output()
1179        .context("failed to invoke git log -1 --format=%ct HEAD")?;
1180    if !out.status.success() {
1181        let stderr_raw = String::from_utf8_lossy(&out.stderr);
1182        let raw = format!("git log -1 --format=%ct HEAD failed: {}", stderr_raw.trim());
1183        bail!("{}", crate::redact::redact_process_env(&raw));
1184    }
1185    let text = String::from_utf8_lossy(&out.stdout).trim().to_string();
1186    text.parse::<i64>()
1187        .with_context(|| format!("git log --format=%ct returned non-i64 timestamp: {}", text))
1188}
1189
1190#[cfg(test)]
1191mod tests {
1192    use super::*;
1193    use std::process::Command;
1194
1195    fn init_repo_with_commits(dir: &Path, files: &[&str]) {
1196        let run = |args: &[&str]| {
1197            let out = Command::new("git")
1198                .args(args)
1199                .current_dir(dir)
1200                .env("GIT_AUTHOR_NAME", "t")
1201                .env("GIT_AUTHOR_EMAIL", "t@t.com")
1202                .env("GIT_COMMITTER_NAME", "t")
1203                .env("GIT_COMMITTER_EMAIL", "t@t.com")
1204                .output()
1205                .unwrap();
1206            assert!(out.status.success(), "git {args:?} failed");
1207        };
1208        run(&["init"]);
1209        run(&["config", "user.email", "t@t.com"]);
1210        run(&["config", "user.name", "t"]);
1211        for (i, f) in files.iter().enumerate() {
1212            std::fs::write(dir.join(f), format!("c{i}")).unwrap();
1213            run(&["add", "."]);
1214            run(&["commit", "-m", &format!("commit-{i}: {f}")]);
1215        }
1216    }
1217
1218    #[test]
1219    fn get_head_commit_in_returns_tempdirs_head_sha() {
1220        let tmp = tempfile::tempdir().unwrap();
1221        init_repo_with_commits(tmp.path(), &["a"]);
1222        let expected = String::from_utf8(
1223            Command::new("git")
1224                .args(["rev-parse", "HEAD"])
1225                .current_dir(tmp.path())
1226                .output()
1227                .unwrap()
1228                .stdout,
1229        )
1230        .unwrap()
1231        .trim()
1232        .to_string();
1233        let sha = get_head_commit_in(tmp.path()).unwrap();
1234        assert_eq!(sha, expected);
1235    }
1236
1237    #[test]
1238    fn get_short_commit_in_returns_tempdirs_short_sha() {
1239        let tmp = tempfile::tempdir().unwrap();
1240        init_repo_with_commits(tmp.path(), &["a"]);
1241        let expected = String::from_utf8(
1242            Command::new("git")
1243                .args(["rev-parse", "--short", "HEAD"])
1244                .current_dir(tmp.path())
1245                .output()
1246                .unwrap()
1247                .stdout,
1248        )
1249        .unwrap()
1250        .trim()
1251        .to_string();
1252        let short = get_short_commit_in(tmp.path()).unwrap();
1253        assert_eq!(short, expected);
1254    }
1255
1256    #[test]
1257    fn has_commits_since_tag_in_returns_false_when_tag_is_head() {
1258        let tmp = tempfile::tempdir().unwrap();
1259        let dir = tmp.path();
1260        init_repo_with_commits(dir, &["a"]);
1261        let run = |args: &[&str]| {
1262            Command::new("git")
1263                .args(args)
1264                .current_dir(dir)
1265                .env("GIT_AUTHOR_NAME", "t")
1266                .env("GIT_AUTHOR_EMAIL", "t@t.com")
1267                .env("GIT_COMMITTER_NAME", "t")
1268                .env("GIT_COMMITTER_EMAIL", "t@t.com")
1269                .output()
1270                .unwrap();
1271        };
1272        run(&["tag", "v1.0.0"]);
1273        assert!(!has_commits_since_tag_in(dir, "v1.0.0").unwrap());
1274    }
1275
1276    fn git_in(dir: &Path, args: &[&str]) {
1277        let out = Command::new("git")
1278            .args(args)
1279            .current_dir(dir)
1280            .env("GIT_AUTHOR_NAME", "t")
1281            .env("GIT_AUTHOR_EMAIL", "t@t.com")
1282            .env("GIT_COMMITTER_NAME", "t")
1283            .env("GIT_COMMITTER_EMAIL", "t@t.com")
1284            .output()
1285            .unwrap();
1286        assert!(out.status.success(), "git {args:?} failed");
1287    }
1288
1289    #[test]
1290    fn count_commits_since_last_tag_counts_commits_after_tag() {
1291        let tmp = tempfile::tempdir().unwrap();
1292        let dir = tmp.path();
1293        // 2 commits, tag v1.0.0 at the 2nd, then 3 more commits.
1294        init_repo_with_commits(dir, &["a", "b"]);
1295        git_in(dir, &["tag", "v1.0.0"]);
1296        for f in ["c", "d", "e"] {
1297            std::fs::write(dir.join(f), "x").unwrap();
1298            git_in(dir, &["add", "."]);
1299            git_in(dir, &["commit", "-m", f]);
1300        }
1301        assert_eq!(count_commits_since_last_tag_in(dir, None).unwrap(), 3);
1302    }
1303
1304    #[test]
1305    fn count_commits_since_last_tag_resets_on_newer_tag() {
1306        let tmp = tempfile::tempdir().unwrap();
1307        let dir = tmp.path();
1308        init_repo_with_commits(dir, &["a"]);
1309        git_in(dir, &["tag", "v1.0.0"]);
1310        for f in ["b", "c"] {
1311            std::fs::write(dir.join(f), "x").unwrap();
1312            git_in(dir, &["add", "."]);
1313            git_in(dir, &["commit", "-m", f]);
1314        }
1315        assert_eq!(count_commits_since_last_tag_in(dir, None).unwrap(), 2);
1316        // A newer version tag lands -> counter resets to 0 at the tag.
1317        git_in(dir, &["tag", "v1.1.0"]);
1318        assert_eq!(count_commits_since_last_tag_in(dir, None).unwrap(), 0);
1319        std::fs::write(dir.join("d"), "x").unwrap();
1320        git_in(dir, &["add", "."]);
1321        git_in(dir, &["commit", "-m", "d"]);
1322        assert_eq!(count_commits_since_last_tag_in(dir, None).unwrap(), 1);
1323    }
1324
1325    #[test]
1326    fn count_commits_since_last_tag_counts_all_when_no_tag() {
1327        let tmp = tempfile::tempdir().unwrap();
1328        let dir = tmp.path();
1329        init_repo_with_commits(dir, &["a", "b", "c"]);
1330        // No tag at all -> count every commit on HEAD.
1331        assert_eq!(count_commits_since_last_tag_in(dir, None).unwrap(), 3);
1332    }
1333
1334    #[test]
1335    fn count_commits_since_last_tag_respects_monorepo_prefix() {
1336        // Per-crate workspace: tags for two subprojects interleave on one
1337        // branch. The `core/` count must be since the latest `core/*` tag,
1338        // NOT the nearer `api/*` tag from a different subproject.
1339        let tmp = tempfile::tempdir().unwrap();
1340        let dir = tmp.path();
1341        init_repo_with_commits(dir, &["a"]);
1342        git_in(dir, &["tag", "core/v1.0.0"]); // matching-prefix tag (older)
1343        for f in ["b", "c"] {
1344            std::fs::write(dir.join(f), "x").unwrap();
1345            git_in(dir, &["add", "."]);
1346            git_in(dir, &["commit", "-m", f]);
1347        }
1348        git_in(dir, &["tag", "api/v2.0.0"]); // DIFFERENT prefix, NEARER to HEAD
1349        std::fs::write(dir.join("d"), "x").unwrap();
1350        git_in(dir, &["add", "."]);
1351        git_in(dir, &["commit", "-m", "d"]);
1352
1353        // With prefix filtering: count since core/v1.0.0 = 3 commits (b, c, d).
1354        assert_eq!(
1355            count_commits_since_last_tag_in(dir, Some("core/")).unwrap(),
1356            3,
1357            "must count since the matching-prefix tag, ignoring api/v2.0.0",
1358        );
1359        // Without filtering (None): describe picks the nearer api/v2.0.0,
1360        // so the count is only 1 (d). This is the mutation-check baseline
1361        // proving the --match arg is load-bearing.
1362        assert_eq!(
1363            count_commits_since_last_tag_in(dir, None).unwrap(),
1364            1,
1365            "unfiltered count picks the nearest (wrong) subproject tag",
1366        );
1367    }
1368
1369    #[test]
1370    fn get_current_branch_in_returns_branch_name() {
1371        let tmp = tempfile::tempdir().unwrap();
1372        let dir = tmp.path();
1373        let run = |args: &[&str]| {
1374            let out = Command::new("git")
1375                .args(args)
1376                .current_dir(dir)
1377                .env("GIT_AUTHOR_NAME", "t")
1378                .env("GIT_AUTHOR_EMAIL", "t@t.com")
1379                .env("GIT_COMMITTER_NAME", "t")
1380                .env("GIT_COMMITTER_EMAIL", "t@t.com")
1381                .output()
1382                .unwrap();
1383            assert!(out.status.success(), "git {args:?} failed");
1384        };
1385        run(&["-c", "init.defaultBranch=t1-test-branch", "init"]);
1386        run(&["config", "user.email", "t@t.com"]);
1387        run(&["config", "user.name", "t"]);
1388        std::fs::write(dir.join("a"), "1").unwrap();
1389        run(&["add", "."]);
1390        run(&["commit", "-m", "c1"]);
1391        let branch = get_current_branch_in(dir).unwrap();
1392        assert_eq!(branch, "t1-test-branch");
1393    }
1394
1395    #[test]
1396    fn get_current_branch_in_resolves_detached_head_via_points_at() {
1397        let tmp = tempfile::tempdir().unwrap();
1398        let dir = tmp.path();
1399        let run = |args: &[&str]| {
1400            let out = Command::new("git")
1401                .args(args)
1402                .current_dir(dir)
1403                .env("GIT_AUTHOR_NAME", "t")
1404                .env("GIT_AUTHOR_EMAIL", "t@t.com")
1405                .env("GIT_COMMITTER_NAME", "t")
1406                .env("GIT_COMMITTER_EMAIL", "t@t.com")
1407                .output()
1408                .unwrap();
1409            assert!(out.status.success(), "git {args:?} failed");
1410        };
1411        run(&["-c", "init.defaultBranch=master", "init"]);
1412        run(&["config", "user.email", "t@t.com"]);
1413        run(&["config", "user.name", "t"]);
1414        std::fs::write(dir.join("a"), "1").unwrap();
1415        run(&["add", "."]);
1416        run(&["commit", "-m", "c1"]);
1417        let sha = get_head_commit_in(dir).unwrap();
1418        run(&["checkout", "--detach", &sha]);
1419        let branch = get_current_branch_in(dir).unwrap();
1420        assert_eq!(
1421            branch, "master",
1422            "detached HEAD pointing at master must resolve to master, not literal HEAD"
1423        );
1424    }
1425
1426    #[test]
1427    fn is_branchlike_rejects_lockstep_tag_shapes() {
1428        assert!(!is_branchlike("v0.4.5"));
1429        assert!(!is_branchlike("v1.2.3"));
1430        assert!(!is_branchlike("v10.20.30"));
1431        assert!(!is_branchlike("v1.2.3-rc.1"));
1432        assert!(!is_branchlike("v1.2.3+build.42"));
1433    }
1434
1435    #[test]
1436    fn is_branchlike_rejects_per_crate_tag_shapes() {
1437        assert!(!is_branchlike("mycrate-v1.2.3"));
1438        assert!(!is_branchlike("cfgd-operator-v0.4.0"));
1439        assert!(!is_branchlike("anodize-core-v1.2.3-rc.1"));
1440    }
1441
1442    #[test]
1443    fn is_branchlike_accepts_real_branch_names() {
1444        assert!(is_branchlike("master"));
1445        assert!(is_branchlike("main"));
1446        assert!(is_branchlike("publisher-required-config"));
1447        assert!(is_branchlike("release/v1.2.3-prep"));
1448        assert!(is_branchlike("dependabot/cargo/serde-1.0.200"));
1449    }
1450
1451    #[test]
1452    fn is_branchlike_accepts_slashed_branch_with_embedded_version() {
1453        // `feature/fix-v2.0.0` embeds `-v2.0.0` but is a branch, not a
1454        // per-crate tag: the unanchored `-v\d+\.\d+\.\d+` regex misclassified
1455        // it as a tag. The `^[^/]+-v` anchor keeps slashed branch names
1456        // branch-like.
1457        assert!(is_branchlike("feature/fix-v2.0.0"));
1458        assert!(is_branchlike("hotfix/release-v1.0.0-blocker"));
1459        assert!(is_branchlike("user/wip-v3.1.4"));
1460    }
1461
1462    #[test]
1463    fn get_current_branch_in_rejects_tag_shaped_github_ref_name() {
1464        let tmp = tempfile::tempdir().unwrap();
1465        let dir = tmp.path();
1466        let run = |args: &[&str]| {
1467            let out = Command::new("git")
1468                .args(args)
1469                .current_dir(dir)
1470                .env("GIT_AUTHOR_NAME", "t")
1471                .env("GIT_AUTHOR_EMAIL", "t@t.com")
1472                .env("GIT_COMMITTER_NAME", "t")
1473                .env("GIT_COMMITTER_EMAIL", "t@t.com")
1474                .output()
1475                .unwrap();
1476            assert!(out.status.success(), "git {args:?} failed");
1477        };
1478        // Build a repo whose HEAD is detached AND no local branch points
1479        // at it, so every fallback BEFORE GITHUB_REF_NAME fails. The only
1480        // way the fallback chain produces a value is via the env var.
1481        run(&["-c", "init.defaultBranch=master", "init"]);
1482        run(&["config", "user.email", "t@t.com"]);
1483        run(&["config", "user.name", "t"]);
1484        std::fs::write(dir.join("a"), "1").unwrap();
1485        run(&["add", "."]);
1486        run(&["commit", "-m", "c1"]);
1487        let sha = get_head_commit_in(dir).unwrap();
1488        // Move master forward so the detached HEAD has no branch
1489        // pointing at it; for-each-ref --points-at HEAD returns empty.
1490        std::fs::write(dir.join("a"), "2").unwrap();
1491        run(&["add", "."]);
1492        run(&["commit", "-m", "c2"]);
1493        run(&["checkout", "--detach", &sha]);
1494
1495        // GITHUB_REF_NAME is injected via the env seam, so each branch of the
1496        // fallback is driven without mutating process-global env.
1497
1498        // Tag-shaped: must NOT be accepted; bail surfaces.
1499        let env = crate::MapEnvSource::new().with("GITHUB_REF_NAME", "v0.4.5");
1500        let err = get_current_branch_in_with_env(dir, &env).unwrap_err();
1501        assert!(
1502            err.to_string().contains("could not resolve current branch"),
1503            "tag-shaped GITHUB_REF_NAME must trigger bail: {err}"
1504        );
1505
1506        // Per-crate-shaped: must NOT be accepted either.
1507        let env = crate::MapEnvSource::new().with("GITHUB_REF_NAME", "mycrate-v1.2.3");
1508        let err = get_current_branch_in_with_env(dir, &env).unwrap_err();
1509        assert!(
1510            err.to_string().contains("could not resolve current branch"),
1511            "per-crate tag GITHUB_REF_NAME must trigger bail: {err}"
1512        );
1513
1514        // Real branch name: accepted.
1515        let env = crate::MapEnvSource::new().with("GITHUB_REF_NAME", "master");
1516        let branch = get_current_branch_in_with_env(dir, &env).unwrap();
1517        assert_eq!(branch, "master");
1518    }
1519
1520    #[test]
1521    fn branches_containing_sha_in_returns_empty_without_remote() {
1522        let tmp = tempfile::tempdir().unwrap();
1523        let dir = tmp.path();
1524        let run = |args: &[&str]| {
1525            let out = Command::new("git")
1526                .args(args)
1527                .current_dir(dir)
1528                .env("GIT_AUTHOR_NAME", "t")
1529                .env("GIT_AUTHOR_EMAIL", "t@t.com")
1530                .env("GIT_COMMITTER_NAME", "t")
1531                .env("GIT_COMMITTER_EMAIL", "t@t.com")
1532                .output()
1533                .unwrap();
1534            assert!(out.status.success(), "git {args:?} failed");
1535        };
1536        run(&["-c", "init.defaultBranch=master", "init"]);
1537        run(&["config", "user.email", "t@t.com"]);
1538        run(&["config", "user.name", "t"]);
1539        std::fs::write(dir.join("a"), "1").unwrap();
1540        run(&["add", "."]);
1541        run(&["commit", "-m", "c1"]);
1542        let sha = get_head_commit_in(dir).unwrap();
1543        // No remote configured → `git branch -r --contains` returns
1544        // empty, which the helper surfaces as `Vec::new()` so the
1545        // caller can fall back to local branch resolution.
1546        let branches = branches_containing_sha_in(dir, &sha).unwrap();
1547        assert!(branches.is_empty(), "no remote → no remote branches");
1548    }
1549
1550    #[test]
1551    fn branches_containing_sha_in_finds_remote_branch_after_push() {
1552        let tmp = tempfile::tempdir().unwrap();
1553        let bare = tempfile::tempdir().unwrap();
1554        let dir = tmp.path();
1555        let run_in = |cwd: &Path, args: &[&str]| {
1556            let out = Command::new("git")
1557                .args(args)
1558                .current_dir(cwd)
1559                .env("GIT_AUTHOR_NAME", "t")
1560                .env("GIT_AUTHOR_EMAIL", "t@t.com")
1561                .env("GIT_COMMITTER_NAME", "t")
1562                .env("GIT_COMMITTER_EMAIL", "t@t.com")
1563                .output()
1564                .unwrap();
1565            assert!(out.status.success(), "git {args:?} failed");
1566        };
1567        run_in(
1568            bare.path(),
1569            &["-c", "init.defaultBranch=master", "init", "--bare"],
1570        );
1571        run_in(dir, &["-c", "init.defaultBranch=master", "init"]);
1572        run_in(dir, &["config", "user.email", "t@t.com"]);
1573        run_in(dir, &["config", "user.name", "t"]);
1574        run_in(
1575            dir,
1576            &["remote", "add", "origin", bare.path().to_str().unwrap()],
1577        );
1578        std::fs::write(dir.join("a"), "1").unwrap();
1579        run_in(dir, &["add", "."]);
1580        run_in(dir, &["commit", "-m", "c1"]);
1581        let sha = get_head_commit_in(dir).unwrap();
1582        run_in(dir, &["push", "-u", "origin", "master"]);
1583
1584        let branches = branches_containing_sha_in(dir, &sha).unwrap();
1585        assert_eq!(branches, vec!["master".to_string()]);
1586    }
1587
1588    #[test]
1589    fn stage_and_commit_in_returns_false_when_no_diff() {
1590        let tmp = tempfile::tempdir().unwrap();
1591        let dir = tmp.path();
1592        init_repo_with_commits(dir, &["a"]);
1593        // File is committed and unchanged — staging it should not produce
1594        // a diff, and stage_and_commit must report Ok(false) instead of
1595        // bailing on the "nothing to commit" path.
1596        let created = stage_and_commit_in(dir, &["a"], "chore: should be a no-op").unwrap();
1597        assert!(!created, "no diff → no commit should be created");
1598        let log = Command::new("git")
1599            .args(["log", "--oneline"])
1600            .current_dir(dir)
1601            .output()
1602            .unwrap();
1603        let log_text = String::from_utf8_lossy(&log.stdout);
1604        assert!(
1605            !log_text.contains("should be a no-op"),
1606            "stage_and_commit_in must not create a commit when no diff: {log_text}"
1607        );
1608    }
1609
1610    #[test]
1611    fn stage_and_commit_in_returns_true_when_file_changed() {
1612        let tmp = tempfile::tempdir().unwrap();
1613        let dir = tmp.path();
1614        init_repo_with_commits(dir, &["a"]);
1615        std::fs::write(dir.join("a"), "changed").unwrap();
1616        let created = stage_and_commit_in(dir, &["a"], "chore: real change").unwrap();
1617        assert!(created, "real change → commit must be created");
1618        let log = Command::new("git")
1619            .args(["log", "-1", "--pretty=%s"])
1620            .current_dir(dir)
1621            .output()
1622            .unwrap();
1623        let subject = String::from_utf8_lossy(&log.stdout).trim().to_string();
1624        assert_eq!(subject, "chore: real change");
1625    }
1626
1627    #[test]
1628    fn git_output_in_error_falls_back_to_stdout_when_stderr_empty() {
1629        let tmp = tempfile::tempdir().unwrap();
1630        let dir = tmp.path();
1631        init_repo_with_commits(dir, &["a"]);
1632        // `git commit -m ...` with an unchanged tree prints "nothing to
1633        // commit" to STDOUT (not stderr); the error message must surface
1634        // that detail instead of `failed: ` with nothing after.
1635        let err = git_output_in(dir, &["commit", "-m", "no-op"]).unwrap_err();
1636        let msg = err.to_string();
1637        assert!(
1638            msg.contains("nothing to commit") || msg.contains("clean"),
1639            "error must include stdout detail when stderr is empty: {msg}"
1640        );
1641    }
1642
1643    /// `CommitterIdentity::default_for_rollback` produces a populated
1644    /// (name + email) identity. The exact host-derived suffix isn't
1645    /// load-bearing — what matters is that both fields are present so
1646    /// `apply_to` produces all four `GIT_AUTHOR_*` / `GIT_COMMITTER_*`
1647    /// envs on the spawn.
1648    #[test]
1649    fn default_for_rollback_populates_both_name_and_email() {
1650        let id = CommitterIdentity::default_for_rollback();
1651        assert_eq!(id.name.as_deref(), Some("anodize-rollback"));
1652        let email = id.email.expect("email must be Some");
1653        assert!(
1654            email.starts_with("anodize-rollback@"),
1655            "email must use the anodize-rollback@<host> shape; got {email}"
1656        );
1657        assert!(!email.ends_with('@'), "host portion must not be empty");
1658    }
1659
1660    /// `revert_commit_in` with an injected `CommitterIdentity` writes a
1661    /// commit whose author/committer match the identity. Exercises the
1662    /// env-injection path end-to-end against a real fixture repo whose
1663    /// only configured identity is the override — so a future regression
1664    /// that drops the env threading would show up as the commit
1665    /// inheriting the host's `user.email` instead.
1666    #[test]
1667    fn revert_commit_in_uses_injected_identity_envs() {
1668        let tmp = tempfile::tempdir().unwrap();
1669        let dir = tmp.path();
1670        let run_env = |args: &[&str], extra: &[(&str, &str)]| {
1671            let mut cmd = Command::new("git");
1672            cmd.args(args)
1673                .current_dir(dir)
1674                .env("GIT_AUTHOR_NAME", "bootstrap")
1675                .env("GIT_AUTHOR_EMAIL", "bootstrap@b.com")
1676                .env("GIT_COMMITTER_NAME", "bootstrap")
1677                .env("GIT_COMMITTER_EMAIL", "bootstrap@b.com");
1678            for (k, v) in extra {
1679                cmd.env(k, v);
1680            }
1681            let out = cmd.output().unwrap();
1682            assert!(
1683                out.status.success(),
1684                "git {args:?} failed: {}",
1685                String::from_utf8_lossy(&out.stderr)
1686            );
1687        };
1688        run_env(&["init", "-b", "master"], &[]);
1689        std::fs::write(dir.join("a"), "0").unwrap();
1690        run_env(&["add", "."], &[]);
1691        run_env(&["commit", "-m", "initial"], &[]);
1692        std::fs::write(dir.join("a"), "1").unwrap();
1693        run_env(&["add", "."], &[]);
1694        run_env(&["commit", "-m", "chore(release): v1.0.0"], &[]);
1695        let bump_sha = get_head_commit_in(dir).unwrap();
1696
1697        // Inject a distinct identity so the resulting revert commit can
1698        // be attributed unambiguously to the env path (the bootstrap
1699        // commits used a different identity above).
1700        let identity = CommitterIdentity {
1701            name: Some("rollback-bot".to_string()),
1702            email: Some("rollback-bot@anodize.test".to_string()),
1703        };
1704        revert_commit_in(dir, &bump_sha, Some("chore(release): rollback"), &identity)
1705            .expect("revert with injected identity must succeed");
1706
1707        // The new HEAD commit's author email must be the injected one,
1708        // proving the env threading reached the git child.
1709        let out = Command::new("git")
1710            .current_dir(dir)
1711            .args(["log", "-1", "--format=%ae"])
1712            .env("GIT_TERMINAL_PROMPT", "0")
1713            .env("LC_ALL", "C")
1714            .output()
1715            .unwrap();
1716        let author_email = String::from_utf8_lossy(&out.stdout).trim().to_string();
1717        assert_eq!(
1718            author_email, "rollback-bot@anodize.test",
1719            "revert commit must carry the injected committer identity"
1720        );
1721
1722        // Repo config must remain unchanged — env-only fallback, no
1723        // `git config user.email ...` mutation.
1724        let cfg = Command::new("git")
1725            .current_dir(dir)
1726            .args(["config", "--local", "--get", "user.email"])
1727            .env("GIT_TERMINAL_PROMPT", "0")
1728            .env("LC_ALL", "C")
1729            .output()
1730            .unwrap();
1731        assert!(
1732            !cfg.status.success() || cfg.stdout.is_empty(),
1733            "revert must not write user.email into the repo's local config; got: {}",
1734            String::from_utf8_lossy(&cfg.stdout)
1735        );
1736    }
1737
1738    /// B-R4: a revert that hits conflicts (because later commits overlap
1739    /// with the bump) must run `git revert --abort`, restoring the working
1740    /// tree so the operator isn't trapped by the dirty-tree guard on the
1741    /// next attempt. Bail message must mention "aborted".
1742    #[test]
1743    fn revert_commit_in_aborts_on_conflict_and_leaves_tree_clean() {
1744        let tmp = tempfile::tempdir().unwrap();
1745        let dir = tmp.path();
1746        let run = |args: &[&str]| {
1747            let out = Command::new("git")
1748                .args(args)
1749                .current_dir(dir)
1750                .env("GIT_AUTHOR_NAME", "t")
1751                .env("GIT_AUTHOR_EMAIL", "t@t.com")
1752                .env("GIT_COMMITTER_NAME", "t")
1753                .env("GIT_COMMITTER_EMAIL", "t@t.com")
1754                .output()
1755                .unwrap();
1756            assert!(
1757                out.status.success(),
1758                "git {args:?} failed: {}",
1759                String::from_utf8_lossy(&out.stderr)
1760            );
1761        };
1762        run(&["init", "-b", "master"]);
1763        run(&["config", "user.email", "t@t.com"]);
1764        run(&["config", "user.name", "t"]);
1765        // Initial commit: file `x` with line "v1".
1766        std::fs::write(dir.join("x"), "v1\n").unwrap();
1767        run(&["add", "."]);
1768        run(&["commit", "-m", "initial"]);
1769        // "Bump" commit: change to "v2".
1770        std::fs::write(dir.join("x"), "v2\n").unwrap();
1771        run(&["add", "."]);
1772        run(&["commit", "-m", "chore(release): v2"]);
1773        let bump_sha = get_head_commit_in(dir).unwrap();
1774        // Later overlapping commit: change to "v3". A revert of the bump
1775        // would try to restore "v1" from a base of "v2", but HEAD is now
1776        // "v3" — that's the canonical revert-conflict shape.
1777        std::fs::write(dir.join("x"), "v3\n").unwrap();
1778        run(&["add", "."]);
1779        run(&["commit", "-m", "feat: overlap"]);
1780
1781        let identity = CommitterIdentity::default();
1782        let err = revert_commit_in(dir, &bump_sha, None, &identity)
1783            .expect_err("revert against overlapping HEAD must conflict and bail");
1784        let msg = format!("{err}");
1785        assert!(
1786            msg.contains("aborted"),
1787            "bail message must mention abort recovery: {msg}"
1788        );
1789
1790        // Working tree must be clean post-bail: no REVERT_HEAD, no
1791        // unmerged paths. The next rollback attempt must NOT hit the
1792        // dirty-tree guard.
1793        assert!(
1794            !dir.join(".git/REVERT_HEAD").exists(),
1795            ".git/REVERT_HEAD must be cleaned up after --abort"
1796        );
1797        let status_out = Command::new("git")
1798            .args(["status", "--porcelain"])
1799            .current_dir(dir)
1800            .output()
1801            .unwrap();
1802        assert!(
1803            status_out.stdout.is_empty(),
1804            "working tree must be clean after revert --abort; got:\n{}",
1805            String::from_utf8_lossy(&status_out.stdout)
1806        );
1807    }
1808
1809    /// S-R7: `commits_with_subjects_in` returns every (sha, subject)
1810    /// pair in one git spawn. Asserts both correctness (matches per-commit
1811    /// `commit_subject_in`) and that the range bound is exclusive on the
1812    /// `<sha>` side.
1813    #[test]
1814    fn commits_with_subjects_in_returns_all_pairs_in_one_call() {
1815        let tmp = tempfile::tempdir().unwrap();
1816        let dir = tmp.path();
1817        let run = |args: &[&str]| {
1818            let out = Command::new("git")
1819                .args(args)
1820                .current_dir(dir)
1821                .env("GIT_AUTHOR_NAME", "t")
1822                .env("GIT_AUTHOR_EMAIL", "t@t.com")
1823                .env("GIT_COMMITTER_NAME", "t")
1824                .env("GIT_COMMITTER_EMAIL", "t@t.com")
1825                .output()
1826                .unwrap();
1827            assert!(out.status.success(), "git {args:?} failed");
1828        };
1829        run(&["init", "-b", "master"]);
1830        run(&["config", "user.email", "t@t.com"]);
1831        run(&["config", "user.name", "t"]);
1832        std::fs::write(dir.join("a"), "0").unwrap();
1833        run(&["add", "."]);
1834        run(&["commit", "-m", "initial"]);
1835        let base = get_head_commit_in(dir).unwrap();
1836        std::fs::write(dir.join("a"), "1").unwrap();
1837        run(&["add", "."]);
1838        run(&["commit", "-m", "feat: A with extra detail"]);
1839        std::fs::write(dir.join("a"), "2").unwrap();
1840        run(&["add", "."]);
1841        run(&["commit", "-m", "fix: B"]);
1842
1843        let pairs = commits_with_subjects_in(dir, &base).unwrap();
1844        assert_eq!(pairs.len(), 2, "two commits sit on top of base");
1845        // Newest-first ordering (matches `git log` default).
1846        assert_eq!(pairs[0].1, "fix: B");
1847        assert_eq!(pairs[1].1, "feat: A with extra detail");
1848
1849        // Empty range (sha IS HEAD) → empty vec.
1850        let head = get_head_commit_in(dir).unwrap();
1851        assert!(commits_with_subjects_in(dir, &head).unwrap().is_empty());
1852    }
1853
1854    #[test]
1855    fn parse_commit_output_with_files_pairs_each_commit_with_its_files() {
1856        // Two commits: newest first (git log order). Each metadata record is
1857        // `%H%x1f%h%x1f%s%x1f%an%x1f%ae%x1f%b%x1e`, then `--name-only` files.
1858        let raw = "h1\x1fs1\x1ffix: B\x1ft\x1ft@t\x1f\x1e\ncrates/cli/main.rs\n\nh0\x1fs0\x1ffeat: A\x1ft\x1ft@t\x1f\x1e\ncrates/core/lib.rs\nCargo.toml\n";
1859        let parsed = parse_commit_output_with_files(raw);
1860        assert_eq!(parsed.len(), 2);
1861        assert_eq!(parsed[0].commit.message, "fix: B");
1862        assert_eq!(parsed[0].files, vec!["crates/cli/main.rs".to_string()]);
1863        assert_eq!(parsed[1].commit.message, "feat: A");
1864        assert_eq!(
1865            parsed[1].files,
1866            vec!["crates/core/lib.rs".to_string(), "Cargo.toml".to_string()]
1867        );
1868    }
1869
1870    #[test]
1871    fn parse_commit_output_with_files_preserves_multiline_body_at_idx_gt_0() {
1872        // A multi-line `%b` body for the SECOND commit (idx>0): the body spans
1873        // several newline-separated lines, and the parser must keep the full
1874        // record — not just its first line — so trailers like `Co-Authored-By:`
1875        // survive, matching the metadata-only `parse_git_log_records` path.
1876        let body0 = "detail line one\ndetail line two\n\nCo-Authored-By: Bob <bob@b.com>";
1877        let raw = format!(
1878            "h1\x1fs1\x1ffix: B\x1ft\x1ft@t\x1f\x1e\ncrates/cli/main.rs\n\n\
1879             h0\x1fs0\x1ffeat: A\x1ft\x1ft@t\x1f{body0}\x1e\ncrates/core/lib.rs\n"
1880        );
1881        let parsed = parse_commit_output_with_files(&raw);
1882        assert_eq!(parsed.len(), 2);
1883        // The idx>0 commit retains its FULL multi-line body and trailer.
1884        assert_eq!(parsed[1].commit.message, "feat: A");
1885        assert_eq!(parsed[1].commit.body, body0);
1886        assert!(
1887            parsed[1]
1888                .commit
1889                .body
1890                .contains("Co-Authored-By: Bob <bob@b.com>"),
1891            "multi-line body trailer dropped: {:?}",
1892            parsed[1].commit.body
1893        );
1894        assert_eq!(parsed[1].files, vec!["crates/core/lib.rs".to_string()]);
1895    }
1896
1897    #[test]
1898    fn get_commits_between_paths_with_files_in_reports_touched_files() {
1899        let tmp = tempfile::tempdir().unwrap();
1900        let dir = tmp.path();
1901        let run = |args: &[&str]| {
1902            assert!(
1903                Command::new("git")
1904                    .args(args)
1905                    .current_dir(dir)
1906                    .env("GIT_AUTHOR_NAME", "t")
1907                    .env("GIT_AUTHOR_EMAIL", "t@t.com")
1908                    .env("GIT_COMMITTER_NAME", "t")
1909                    .env("GIT_COMMITTER_EMAIL", "t@t.com")
1910                    .output()
1911                    .unwrap()
1912                    .status
1913                    .success()
1914            );
1915        };
1916        run(&["init"]);
1917        run(&["config", "user.email", "t@t.com"]);
1918        run(&["config", "user.name", "t"]);
1919        std::fs::write(dir.join("base"), "0").unwrap();
1920        run(&["add", "."]);
1921        run(&["commit", "-m", "initial"]);
1922        let base = get_head_commit_in(dir).unwrap();
1923        std::fs::create_dir_all(dir.join("crates/core")).unwrap();
1924        std::fs::write(dir.join("crates/core/lib.rs"), "1").unwrap();
1925        run(&["add", "."]);
1926        run(&["commit", "-m", "feat: core"]);
1927
1928        let pairs = get_commits_between_paths_with_files_in(dir, &base, "HEAD", &[]).unwrap();
1929        assert_eq!(pairs.len(), 1);
1930        assert_eq!(pairs[0].commit.message, "feat: core");
1931        assert_eq!(pairs[0].files, vec!["crates/core/lib.rs".to_string()]);
1932    }
1933
1934    #[test]
1935    fn get_commits_between_paths_with_files_in_preserves_multiline_body_for_later_commits() {
1936        // Real `git log --name-only` over TWO post-base commits, the OLDER one
1937        // (idx>0 in the newest-first output) carrying a multi-line body with a
1938        // `Co-Authored-By:` trailer. The full body must survive — proving the
1939        // narrowed fetch path agrees with the metadata-only path on body
1940        // content, not just the subject.
1941        let tmp = tempfile::tempdir().unwrap();
1942        let dir = tmp.path();
1943        let run = |args: &[&str]| {
1944            assert!(
1945                Command::new("git")
1946                    .args(args)
1947                    .current_dir(dir)
1948                    .env("GIT_AUTHOR_NAME", "t")
1949                    .env("GIT_AUTHOR_EMAIL", "t@t.com")
1950                    .env("GIT_COMMITTER_NAME", "t")
1951                    .env("GIT_COMMITTER_EMAIL", "t@t.com")
1952                    .output()
1953                    .unwrap()
1954                    .status
1955                    .success()
1956            );
1957        };
1958        run(&["init"]);
1959        run(&["config", "user.email", "t@t.com"]);
1960        run(&["config", "user.name", "t"]);
1961        std::fs::write(dir.join("base"), "0").unwrap();
1962        run(&["add", "."]);
1963        run(&["commit", "-m", "initial"]);
1964        let base = get_head_commit_in(dir).unwrap();
1965
1966        // Older of the two reported commits — multi-line body + trailer.
1967        std::fs::write(dir.join("a.rs"), "1").unwrap();
1968        run(&["add", "."]);
1969        run(&[
1970            "commit",
1971            "-m",
1972            "feat: with body\n\nfirst body line\nsecond body line\n\nCo-Authored-By: Bob <bob@b.com>",
1973        ]);
1974        // Newer commit (idx 0 in newest-first output), single-line.
1975        std::fs::write(dir.join("b.rs"), "2").unwrap();
1976        run(&["add", "."]);
1977        run(&["commit", "-m", "fix: later"]);
1978
1979        let pairs = get_commits_between_paths_with_files_in(dir, &base, "HEAD", &[]).unwrap();
1980        assert_eq!(pairs.len(), 2);
1981        // Newest-first: [0] = "fix: later", [1] = "feat: with body" (idx>0).
1982        assert_eq!(pairs[0].commit.message, "fix: later");
1983        let body = &pairs[1].commit.body;
1984        assert!(
1985            body.contains("first body line") && body.contains("second body line"),
1986            "multi-line body truncated for idx>0 commit: {body:?}"
1987        );
1988        assert!(
1989            body.contains("Co-Authored-By: Bob <bob@b.com>"),
1990            "Co-Authored-By trailer dropped for idx>0 commit: {body:?}"
1991        );
1992    }
1993
1994    // ---- parse_commit_output: the single wire-format record decoder ----
1995
1996    #[test]
1997    fn parse_commit_output_empty_input_yields_no_commits() {
1998        assert!(parse_commit_output("").is_empty());
1999    }
2000
2001    #[test]
2002    fn parse_commit_output_decodes_all_six_fields() {
2003        // %H%x1f%h%x1f%s%x1f%an%x1f%ae%x1f%b%x1e for a single commit.
2004        let raw =
2005            "abc123def\x1fabc123d\x1ffeat: add thing\x1fAlice\x1falice@x.com\x1fbody text\x1e";
2006        let commits = parse_commit_output(raw);
2007        assert_eq!(commits.len(), 1);
2008        let c = &commits[0];
2009        assert_eq!(c.hash, "abc123def");
2010        assert_eq!(c.short_hash, "abc123d");
2011        assert_eq!(c.message, "feat: add thing");
2012        assert_eq!(c.author_name, "Alice");
2013        assert_eq!(c.author_email, "alice@x.com");
2014        assert_eq!(c.body, "body text");
2015    }
2016
2017    #[test]
2018    fn parse_commit_output_trims_hash_and_body_but_keeps_inner_subject() {
2019        // Per the decoder: hash and body are trimmed; the subject (field 2)
2020        // is taken verbatim. A leading-newline body must come back trimmed.
2021        let raw = "  abc  \x1fabc\x1ffix: keep  spaces\x1ft\x1ft@t\x1f\n\nbody\n\x1e";
2022        let commits = parse_commit_output(raw);
2023        assert_eq!(commits.len(), 1);
2024        assert_eq!(commits[0].hash, "abc", "hash is trimmed");
2025        assert_eq!(commits[0].message, "fix: keep  spaces", "subject verbatim");
2026        assert_eq!(commits[0].body, "body", "body is trimmed");
2027    }
2028
2029    #[test]
2030    fn parse_commit_output_absent_body_field_defaults_to_empty() {
2031        // Exactly 5 fields (no %b segment) is still a valid record; body == "".
2032        let raw = "h\x1fh\x1fsubject\x1fname\x1fmail\x1e";
2033        let commits = parse_commit_output(raw);
2034        assert_eq!(commits.len(), 1);
2035        assert_eq!(commits[0].body, "");
2036        assert_eq!(commits[0].message, "subject");
2037    }
2038
2039    #[test]
2040    fn parse_commit_output_skips_records_with_too_few_fields() {
2041        // A record with <5 unit-separated fields is malformed and dropped,
2042        // while a well-formed sibling record in the same stream survives.
2043        let raw = "only\x1ftwo\x1e\
2044                   h\x1fh\x1fgood: subject\x1fn\x1fe\x1fbody\x1e";
2045        let commits = parse_commit_output(raw);
2046        assert_eq!(commits.len(), 1, "malformed record dropped, good one kept");
2047        assert_eq!(commits[0].message, "good: subject");
2048    }
2049
2050    #[test]
2051    fn parse_commit_output_multiline_body_survives_record_separator_split() {
2052        // Two commits separated by \x1e; the first body spans newlines and
2053        // carries a trailer — the \x1e (not \n) split keeps it intact.
2054        let raw = "h1\x1fh1\x1ffeat: A\x1fA\x1fa@x\x1fline one\nline two\n\nCo-Authored-By: B <b@x>\x1e\
2055                   h0\x1fh0\x1ffix: B\x1fB\x1fb@x\x1f\x1e";
2056        let commits = parse_commit_output(raw);
2057        assert_eq!(commits.len(), 2);
2058        assert_eq!(commits[0].message, "feat: A");
2059        assert!(commits[0].body.contains("line one\nline two"));
2060        assert!(commits[0].body.contains("Co-Authored-By: B <b@x>"));
2061        assert_eq!(commits[1].message, "fix: B");
2062        assert_eq!(commits[1].body, "");
2063    }
2064
2065    // ---- short_commit_str: pure SHA truncation ----
2066
2067    #[test]
2068    fn short_commit_str_truncates_long_sha_to_seven() {
2069        assert_eq!(short_commit_str("abcdef0123456789"), "abcdef0");
2070        assert_eq!(short_commit_str("abcdef0123456789").len(), SHORT_COMMIT_LEN);
2071    }
2072
2073    #[test]
2074    fn short_commit_str_returns_shorter_or_equal_input_unchanged() {
2075        assert_eq!(short_commit_str("abc"), "abc", "shorter than 7 unchanged");
2076        assert_eq!(
2077            short_commit_str("abcdefg"),
2078            "abcdefg",
2079            "exactly 7 unchanged"
2080        );
2081        assert_eq!(short_commit_str(""), "", "empty stays empty");
2082    }
2083
2084    // ---- real-repo fixture helpers for the shelling functions ----
2085
2086    /// Run a git command in `dir` with a pinned identity, asserting success.
2087    fn g(dir: &Path, args: &[&str]) {
2088        let out = Command::new("git")
2089            .args(args)
2090            .current_dir(dir)
2091            .env("GIT_AUTHOR_NAME", "Ada")
2092            .env("GIT_AUTHOR_EMAIL", "ada@x.com")
2093            .env("GIT_COMMITTER_NAME", "Ada")
2094            .env("GIT_COMMITTER_EMAIL", "ada@x.com")
2095            .env("GIT_AUTHOR_DATE", "1715000000 +0000")
2096            .env("GIT_COMMITTER_DATE", "1715000000 +0000")
2097            .output()
2098            .unwrap();
2099        assert!(
2100            out.status.success(),
2101            "git {args:?} failed: {}",
2102            String::from_utf8_lossy(&out.stderr)
2103        );
2104    }
2105
2106    /// `git init -b master` + identity config; no commits yet.
2107    fn init_bare_repo(dir: &Path) {
2108        g(dir, &["init", "-b", "master"]);
2109        g(dir, &["config", "user.email", "ada@x.com"]);
2110        g(dir, &["config", "user.name", "Ada"]);
2111    }
2112
2113    /// Write `path`=`content`, stage all, commit with `subject`.
2114    fn commit_file(dir: &Path, path: &str, content: &str, subject: &str) {
2115        let full = dir.join(path);
2116        if let Some(parent) = full.parent() {
2117            std::fs::create_dir_all(parent).unwrap();
2118        }
2119        std::fs::write(full, content).unwrap();
2120        g(dir, &["add", "."]);
2121        g(dir, &["commit", "-m", subject]);
2122    }
2123
2124    // ---- get_commits_between_in / paths variants ----
2125
2126    #[test]
2127    fn get_commits_between_in_returns_only_post_base_commits() {
2128        let tmp = tempfile::tempdir().unwrap();
2129        let dir = tmp.path();
2130        init_bare_repo(dir);
2131        commit_file(dir, "a", "0", "initial");
2132        let base = get_head_commit_in(dir).unwrap();
2133        commit_file(dir, "a", "1", "feat: one");
2134        commit_file(dir, "a", "2", "fix: two");
2135
2136        let commits = get_commits_between_in(dir, &base, "HEAD", None).unwrap();
2137        assert_eq!(commits.len(), 2, "two commits sit above base");
2138        // git log default is newest-first.
2139        assert_eq!(commits[0].message, "fix: two");
2140        assert_eq!(commits[1].message, "feat: one");
2141        assert_eq!(commits[1].author_name, "Ada");
2142        assert_eq!(commits[1].author_email, "ada@x.com");
2143    }
2144
2145    #[test]
2146    fn get_commits_between_in_path_filter_excludes_untouched_files() {
2147        let tmp = tempfile::tempdir().unwrap();
2148        let dir = tmp.path();
2149        init_bare_repo(dir);
2150        commit_file(dir, "base", "0", "initial");
2151        let base = get_head_commit_in(dir).unwrap();
2152        commit_file(dir, "src/lib.rs", "1", "feat: touch lib");
2153        commit_file(dir, "docs/readme", "2", "docs: touch docs only");
2154
2155        // Filter to src/ — only the lib commit should be reported.
2156        let commits = get_commits_between_in(dir, &base, "HEAD", Some("src")).unwrap();
2157        assert_eq!(commits.len(), 1, "only the src-touching commit survives");
2158        assert_eq!(commits[0].message, "feat: touch lib");
2159    }
2160
2161    #[test]
2162    fn get_commits_between_paths_in_unions_multiple_paths() {
2163        let tmp = tempfile::tempdir().unwrap();
2164        let dir = tmp.path();
2165        init_bare_repo(dir);
2166        commit_file(dir, "base", "0", "initial");
2167        let base = get_head_commit_in(dir).unwrap();
2168        commit_file(dir, "a/x", "1", "feat: a");
2169        commit_file(dir, "b/y", "2", "feat: b");
2170        commit_file(dir, "c/z", "3", "feat: c");
2171
2172        // Two paths -> union of commits touching either a/ or b/.
2173        let commits =
2174            get_commits_between_paths_in(dir, &base, "HEAD", &["a".into(), "b".into()]).unwrap();
2175        let subjects: Vec<&str> = commits.iter().map(|c| c.message.as_str()).collect();
2176        assert_eq!(
2177            commits.len(),
2178            2,
2179            "a and b touched, c excluded: {subjects:?}"
2180        );
2181        assert!(subjects.contains(&"feat: a"));
2182        assert!(subjects.contains(&"feat: b"));
2183        assert!(!subjects.contains(&"feat: c"));
2184    }
2185
2186    // ---- get_all_commits_* ----
2187
2188    #[test]
2189    fn get_all_commits_in_returns_every_commit_on_head() {
2190        let tmp = tempfile::tempdir().unwrap();
2191        let dir = tmp.path();
2192        init_bare_repo(dir);
2193        commit_file(dir, "a", "0", "first");
2194        commit_file(dir, "a", "1", "second");
2195        commit_file(dir, "a", "2", "third");
2196
2197        let commits = get_all_commits_in(dir, None).unwrap();
2198        assert_eq!(commits.len(), 3);
2199        assert_eq!(commits[0].message, "third", "newest-first");
2200        assert_eq!(commits[2].message, "first");
2201    }
2202
2203    #[test]
2204    fn get_all_commits_paths_in_filters_to_path() {
2205        let tmp = tempfile::tempdir().unwrap();
2206        let dir = tmp.path();
2207        init_bare_repo(dir);
2208        commit_file(dir, "keep/x", "0", "feat: keep");
2209        commit_file(dir, "drop/y", "1", "feat: drop");
2210
2211        let commits = get_all_commits_paths_in(dir, &["keep".into()]).unwrap();
2212        assert_eq!(commits.len(), 1);
2213        assert_eq!(commits[0].message, "feat: keep");
2214    }
2215
2216    #[test]
2217    fn get_all_commits_paths_with_files_in_pairs_files() {
2218        let tmp = tempfile::tempdir().unwrap();
2219        let dir = tmp.path();
2220        init_bare_repo(dir);
2221        commit_file(dir, "crates/core/lib.rs", "0", "feat: core");
2222
2223        let pairs = get_all_commits_paths_with_files_in(dir, &[]).unwrap();
2224        assert_eq!(pairs.len(), 1);
2225        assert_eq!(pairs[0].commit.message, "feat: core");
2226        assert_eq!(pairs[0].files, vec!["crates/core/lib.rs".to_string()]);
2227    }
2228
2229    // ---- get_commits_reachable_paths_in: bound at an explicit ref ----
2230
2231    #[test]
2232    fn get_commits_reachable_paths_in_stops_at_the_given_rev() {
2233        let tmp = tempfile::tempdir().unwrap();
2234        let dir = tmp.path();
2235        init_bare_repo(dir);
2236        commit_file(dir, "a", "0", "first");
2237        commit_file(dir, "a", "1", "second");
2238        let mid = get_head_commit_in(dir).unwrap();
2239        commit_file(dir, "a", "2", "third-after-mid");
2240
2241        // Reachable from `mid` excludes the commit made after it.
2242        let commits = get_commits_reachable_paths_in(dir, &mid, &[]).unwrap();
2243        let subjects: Vec<&str> = commits.iter().map(|c| c.message.as_str()).collect();
2244        assert_eq!(commits.len(), 2, "only ancestors of mid: {subjects:?}");
2245        assert!(subjects.contains(&"first"));
2246        assert!(subjects.contains(&"second"));
2247        assert!(!subjects.contains(&"third-after-mid"));
2248    }
2249
2250    #[test]
2251    fn get_commits_reachable_paths_with_files_in_pairs_touched_files() {
2252        let tmp = tempfile::tempdir().unwrap();
2253        let dir = tmp.path();
2254        init_bare_repo(dir);
2255        commit_file(dir, "src/main.rs", "0", "feat: main");
2256        let head = get_head_commit_in(dir).unwrap();
2257
2258        let pairs = get_commits_reachable_paths_with_files_in(dir, &head, &[]).unwrap();
2259        assert_eq!(pairs.len(), 1);
2260        assert_eq!(pairs[0].commit.message, "feat: main");
2261        assert_eq!(pairs[0].files, vec!["src/main.rs".to_string()]);
2262    }
2263
2264    // ---- subject-only message helpers ----
2265
2266    #[test]
2267    fn get_last_commit_messages_in_returns_n_subjects_newest_first() {
2268        let tmp = tempfile::tempdir().unwrap();
2269        let dir = tmp.path();
2270        init_bare_repo(dir);
2271        commit_file(dir, "a", "0", "one");
2272        commit_file(dir, "a", "1", "two");
2273        commit_file(dir, "a", "2", "three");
2274
2275        let msgs = get_last_commit_messages_in(dir, 2).unwrap();
2276        assert_eq!(msgs, vec!["three".to_string(), "two".to_string()]);
2277    }
2278
2279    #[test]
2280    fn get_commit_messages_between_in_lists_post_base_subjects() {
2281        let tmp = tempfile::tempdir().unwrap();
2282        let dir = tmp.path();
2283        init_bare_repo(dir);
2284        commit_file(dir, "a", "0", "initial");
2285        let base = get_head_commit_in(dir).unwrap();
2286        commit_file(dir, "a", "1", "feat: x");
2287        commit_file(dir, "a", "2", "fix: y");
2288
2289        let msgs = get_commit_messages_between_in(dir, &base, "HEAD").unwrap();
2290        assert_eq!(msgs, vec!["fix: y".to_string(), "feat: x".to_string()]);
2291    }
2292
2293    #[test]
2294    fn get_last_commit_messages_path_in_filters_to_path() {
2295        let tmp = tempfile::tempdir().unwrap();
2296        let dir = tmp.path();
2297        init_bare_repo(dir);
2298        commit_file(dir, "keep/a", "0", "feat: keep");
2299        commit_file(dir, "other/b", "1", "feat: other");
2300
2301        let msgs = get_last_commit_messages_path_in(dir, 10, "keep").unwrap();
2302        assert_eq!(msgs, vec!["feat: keep".to_string()]);
2303    }
2304
2305    #[test]
2306    fn get_commit_messages_between_path_in_filters_range_and_path() {
2307        let tmp = tempfile::tempdir().unwrap();
2308        let dir = tmp.path();
2309        init_bare_repo(dir);
2310        commit_file(dir, "base", "0", "initial");
2311        let base = get_head_commit_in(dir).unwrap();
2312        commit_file(dir, "src/x", "1", "feat: src");
2313        commit_file(dir, "doc/y", "2", "docs: doc");
2314
2315        let msgs = get_commit_messages_between_path_in(dir, &base, "HEAD", "src").unwrap();
2316        assert_eq!(msgs, vec!["feat: src".to_string()]);
2317    }
2318
2319    // ---- diff / change-detection helpers ----
2320
2321    #[test]
2322    fn has_changes_since_in_detects_path_touched_after_tag() {
2323        let tmp = tempfile::tempdir().unwrap();
2324        let dir = tmp.path();
2325        init_bare_repo(dir);
2326        commit_file(dir, "watched", "0", "initial");
2327        g(dir, &["tag", "v1.0.0"]);
2328        // No change yet -> false.
2329        assert!(!has_changes_since_in(dir, "v1.0.0", "watched").unwrap());
2330        commit_file(dir, "watched", "1", "feat: change watched");
2331        // Now changed -> true.
2332        assert!(has_changes_since_in(dir, "v1.0.0", "watched").unwrap());
2333        // A different, untouched path -> false.
2334        assert!(!has_changes_since_in(dir, "v1.0.0", "unrelated").unwrap());
2335    }
2336
2337    #[test]
2338    fn paths_changed_since_tag_in_true_when_any_path_changed() {
2339        let tmp = tempfile::tempdir().unwrap();
2340        let dir = tmp.path();
2341        init_bare_repo(dir);
2342        commit_file(dir, "a", "0", "initial");
2343        g(dir, &["tag", "v1.0.0"]);
2344        commit_file(dir, "b", "1", "feat: add b");
2345
2346        // b changed; checking [a, b] -> true (b matched).
2347        assert!(paths_changed_since_tag_in(dir, "v1.0.0", &["a", "b"]).unwrap());
2348        // Only a (unchanged) -> false.
2349        assert!(!paths_changed_since_tag_in(dir, "v1.0.0", &["a"]).unwrap());
2350    }
2351
2352    #[test]
2353    fn paths_changed_since_tag_in_returns_false_when_git_fails() {
2354        // Non-existent tag makes `git diff` fail; the helper maps that to
2355        // Ok(false) rather than bubbling an error.
2356        let tmp = tempfile::tempdir().unwrap();
2357        let dir = tmp.path();
2358        init_bare_repo(dir);
2359        commit_file(dir, "a", "0", "initial");
2360        assert!(!paths_changed_since_tag_in(dir, "nope-no-such-tag", &["a"]).unwrap());
2361    }
2362
2363    // ---- rev resolution helpers ----
2364
2365    #[test]
2366    fn head_commit_hash_in_matches_rev_parse_head() {
2367        let tmp = tempfile::tempdir().unwrap();
2368        let dir = tmp.path();
2369        init_bare_repo(dir);
2370        commit_file(dir, "a", "0", "initial");
2371        let expected = get_head_commit_in(dir).unwrap();
2372        assert_eq!(head_commit_hash_in(dir).unwrap(), expected);
2373    }
2374
2375    #[test]
2376    fn head_commit_hash_in_errors_on_non_repo() {
2377        let tmp = tempfile::tempdir().unwrap();
2378        // No git init -> rev-parse HEAD fails.
2379        assert!(head_commit_hash_in(tmp.path()).is_err());
2380    }
2381
2382    #[test]
2383    fn rev_parse_in_resolves_branch_to_full_sha() {
2384        let tmp = tempfile::tempdir().unwrap();
2385        let dir = tmp.path();
2386        init_bare_repo(dir);
2387        commit_file(dir, "a", "0", "initial");
2388        let head = get_head_commit_in(dir).unwrap();
2389        assert_eq!(rev_parse_in(dir, "master").unwrap(), head);
2390    }
2391
2392    #[test]
2393    fn rev_verify_commit_in_accepts_commit_rejects_unknown() {
2394        let tmp = tempfile::tempdir().unwrap();
2395        let dir = tmp.path();
2396        init_bare_repo(dir);
2397        commit_file(dir, "a", "0", "initial");
2398        let head = get_head_commit_in(dir).unwrap();
2399        assert_eq!(rev_verify_commit_in(dir, "HEAD").unwrap(), head);
2400        // A made-up ref must not verify.
2401        assert!(rev_verify_commit_in(dir, "deadbeefdeadbeef").is_err());
2402    }
2403
2404    #[test]
2405    fn commits_between_in_lists_shas_above_base_and_empty_at_head() {
2406        let tmp = tempfile::tempdir().unwrap();
2407        let dir = tmp.path();
2408        init_bare_repo(dir);
2409        commit_file(dir, "a", "0", "initial");
2410        let base = get_head_commit_in(dir).unwrap();
2411        commit_file(dir, "a", "1", "second");
2412        let head = get_head_commit_in(dir).unwrap();
2413
2414        let shas = commits_between_in(dir, &base).unwrap();
2415        assert_eq!(
2416            shas,
2417            vec![head.clone()],
2418            "exactly the one commit above base"
2419        );
2420        // sha IS HEAD -> empty range.
2421        assert!(commits_between_in(dir, &head).unwrap().is_empty());
2422    }
2423
2424    #[test]
2425    fn commit_subject_in_returns_single_commit_subject() {
2426        let tmp = tempfile::tempdir().unwrap();
2427        let dir = tmp.path();
2428        init_bare_repo(dir);
2429        commit_file(dir, "a", "0", "feat: only-subject\n\nignored body");
2430        let head = get_head_commit_in(dir).unwrap();
2431        assert_eq!(commit_subject_in(dir, &head).unwrap(), "feat: only-subject");
2432    }
2433
2434    #[test]
2435    fn head_commit_timestamp_in_returns_pinned_committer_epoch() {
2436        let tmp = tempfile::tempdir().unwrap();
2437        let dir = tmp.path();
2438        init_bare_repo(dir);
2439        // Pinned GIT_COMMITTER_DATE in `g` is 1715000000 +0000.
2440        commit_file(dir, "a", "0", "initial");
2441        assert_eq!(head_commit_timestamp_in(dir).unwrap(), 1_715_000_000);
2442    }
2443
2444    // ---- log_subjects_for_range ----
2445
2446    #[test]
2447    fn log_subjects_for_range_returns_full_bodies_for_path() {
2448        let tmp = tempfile::tempdir().unwrap();
2449        let dir = tmp.path();
2450        init_bare_repo(dir);
2451        commit_file(dir, "watched", "0", "feat: A\n\nbody of A");
2452        commit_file(dir, "watched", "1", "fix: B");
2453
2454        let bodies = log_subjects_for_range(dir, "HEAD", "watched").unwrap();
2455        assert_eq!(bodies.len(), 2);
2456        // %B is subject+body; newest-first.
2457        assert!(bodies[0].starts_with("fix: B"));
2458        assert!(bodies[1].contains("feat: A") && bodies[1].contains("body of A"));
2459    }
2460
2461    #[test]
2462    fn log_subjects_for_range_returns_empty_when_range_invalid() {
2463        let tmp = tempfile::tempdir().unwrap();
2464        let dir = tmp.path();
2465        init_bare_repo(dir);
2466        commit_file(dir, "a", "0", "initial");
2467        // A range referencing a non-existent ref makes git fail; the helper
2468        // maps that to an empty Vec, not an error.
2469        let bodies = log_subjects_for_range(dir, "no-such-ref..HEAD", "a").unwrap();
2470        assert!(bodies.is_empty());
2471    }
2472
2473    // ---- add_path_in + commit_in ----
2474
2475    #[test]
2476    fn add_path_in_then_commit_in_creates_commit() {
2477        let tmp = tempfile::tempdir().unwrap();
2478        let dir = tmp.path();
2479        init_bare_repo(dir);
2480        commit_file(dir, "seed", "0", "initial");
2481        std::fs::write(dir.join("new.txt"), "hello").unwrap();
2482
2483        add_path_in(dir, std::path::Path::new("new.txt")).unwrap();
2484        commit_in(dir, "feat: add new.txt", false).unwrap();
2485
2486        let subject = String::from_utf8(
2487            Command::new("git")
2488                .args(["log", "-1", "--pretty=%s"])
2489                .current_dir(dir)
2490                .output()
2491                .unwrap()
2492                .stdout,
2493        )
2494        .unwrap()
2495        .trim()
2496        .to_string();
2497        assert_eq!(subject, "feat: add new.txt");
2498    }
2499
2500    #[test]
2501    fn add_path_in_errors_on_missing_file() {
2502        let tmp = tempfile::tempdir().unwrap();
2503        let dir = tmp.path();
2504        init_bare_repo(dir);
2505        let err = add_path_in(dir, std::path::Path::new("does-not-exist")).unwrap_err();
2506        assert!(
2507            err.to_string().contains("git add"),
2508            "error must name the failing git add: {err}"
2509        );
2510    }
2511
2512    // ---- reset_hard_in ----
2513
2514    #[test]
2515    fn reset_hard_in_moves_head_and_restores_tree() {
2516        let tmp = tempfile::tempdir().unwrap();
2517        let dir = tmp.path();
2518        init_bare_repo(dir);
2519        commit_file(dir, "a", "first", "first");
2520        let target = get_head_commit_in(dir).unwrap();
2521        commit_file(dir, "a", "second", "second");
2522        assert_ne!(get_head_commit_in(dir).unwrap(), target);
2523
2524        reset_hard_in(dir, &target).unwrap();
2525        assert_eq!(get_head_commit_in(dir).unwrap(), target, "HEAD moved back");
2526        assert_eq!(
2527            std::fs::read_to_string(dir.join("a")).unwrap(),
2528            "first",
2529            "working tree restored to target content"
2530        );
2531    }
2532
2533    // ---- push_branch_in error path (no remote) ----
2534
2535    #[test]
2536    fn push_branch_in_bails_without_origin_remote() {
2537        let tmp = tempfile::tempdir().unwrap();
2538        let dir = tmp.path();
2539        init_bare_repo(dir);
2540        commit_file(dir, "a", "0", "initial");
2541        let err = push_branch_in(dir, "master").unwrap_err();
2542        assert!(
2543            err.to_string().contains("no 'origin' remote"),
2544            "missing-remote bail must be explicit: {err}"
2545        );
2546    }
2547
2548    // ---- resolve_rollback_identity / read_git_identity ----
2549
2550    #[test]
2551    #[serial_test::serial(git_env)]
2552    fn resolve_rollback_identity_inherits_when_repo_has_identity() {
2553        let tmp = tempfile::tempdir().unwrap();
2554        let dir = tmp.path();
2555        init_bare_repo(dir); // sets user.name + user.email
2556
2557        // Clear any inherited GIT_AUTHOR_*/COMMITTER_* env so the resolver
2558        // falls through to reading the repo config (which IS configured).
2559        struct EnvGuard(Vec<(&'static str, Option<String>)>);
2560        impl Drop for EnvGuard {
2561            fn drop(&mut self) {
2562                for (k, v) in &self.0 {
2563                    match v {
2564                        // env-ok: restore/clear inside #[serial(git_env)] test; no concurrent reader
2565                        Some(val) => unsafe { std::env::set_var(k, val) },
2566                        // env-ok: restore/clear inside #[serial(git_env)] test; no concurrent reader
2567                        None => unsafe { std::env::remove_var(k) },
2568                    }
2569                }
2570            }
2571        }
2572        let keys = [
2573            "GIT_AUTHOR_NAME",
2574            "GIT_AUTHOR_EMAIL",
2575            "GIT_COMMITTER_NAME",
2576            "GIT_COMMITTER_EMAIL",
2577        ];
2578        let _g = EnvGuard(keys.iter().map(|k| (*k, std::env::var(k).ok())).collect());
2579        for k in keys {
2580            // env-ok: restore/clear inside #[serial(git_env)] test; no concurrent reader
2581            unsafe { std::env::remove_var(k) };
2582        }
2583
2584        // Repo has user.name + user.email -> inherit (empty identity).
2585        let id = resolve_rollback_identity(dir);
2586        assert!(
2587            id.name.is_none() && id.email.is_none(),
2588            "configured repo identity must be inherited, not overridden: {id:?}"
2589        );
2590    }
2591
2592    #[test]
2593    #[serial_test::serial(git_env)]
2594    fn resolve_rollback_identity_synthesizes_when_no_identity_anywhere() {
2595        let tmp = tempfile::tempdir().unwrap();
2596        let dir = tmp.path();
2597        // init WITHOUT configuring user.name / user.email.
2598        g(dir, &["init", "-b", "master"]);
2599
2600        struct EnvGuard(Vec<(&'static str, Option<String>)>);
2601        impl Drop for EnvGuard {
2602            fn drop(&mut self) {
2603                for (k, v) in &self.0 {
2604                    match v {
2605                        // env-ok: restore/clear inside #[serial(git_env)] test; no concurrent reader
2606                        Some(val) => unsafe { std::env::set_var(k, val) },
2607                        // env-ok: restore/clear inside #[serial(git_env)] test; no concurrent reader
2608                        None => unsafe { std::env::remove_var(k) },
2609                    }
2610                }
2611            }
2612        }
2613        let keys = [
2614            "GIT_AUTHOR_NAME",
2615            "GIT_AUTHOR_EMAIL",
2616            "GIT_COMMITTER_NAME",
2617            "GIT_COMMITTER_EMAIL",
2618        ];
2619        let _g = EnvGuard(keys.iter().map(|k| (*k, std::env::var(k).ok())).collect());
2620        for k in keys {
2621            // env-ok: restore/clear inside #[serial(git_env)] test; no concurrent reader
2622            unsafe { std::env::remove_var(k) };
2623        }
2624
2625        // Best-effort: global git config may still supply an identity on the
2626        // host. Only assert the synthetic path when the repo truly has none.
2627        let (n, e) = read_git_identity(dir);
2628        if n.is_none() || e.is_none() {
2629            let id = resolve_rollback_identity(dir);
2630            assert_eq!(id.name.as_deref(), Some("anodize-rollback"));
2631            assert!(
2632                id.email
2633                    .as_deref()
2634                    .unwrap_or("")
2635                    .starts_with("anodize-rollback@"),
2636                "synthetic identity required when no config present: {id:?}"
2637            );
2638        }
2639    }
2640
2641    #[test]
2642    fn read_git_identity_reads_configured_values() {
2643        let tmp = tempfile::tempdir().unwrap();
2644        let dir = tmp.path();
2645        g(dir, &["init", "-b", "master"]);
2646        g(dir, &["config", "user.name", "Configured Name"]);
2647        g(dir, &["config", "user.email", "configured@x.com"]);
2648
2649        let (name, email) = read_git_identity(dir);
2650        assert_eq!(name.as_deref(), Some("Configured Name"));
2651        assert_eq!(email.as_deref(), Some("configured@x.com"));
2652    }
2653}