Skip to main content

anodizer_core/git/
github_api.rs

1use anyhow::{Context as _, Result, bail};
2use std::collections::HashMap;
3use std::path::Path;
4use std::process::Command;
5use std::sync::{Mutex, OnceLock};
6
7use super::git_output_in;
8use super::remote::detect_github_repo_in;
9use super::tags::create_and_push_tag_in;
10
11/// GET a GitHub API endpoint via the `gh` CLI (single request, no pagination).
12///
13/// Returns the parsed JSON response. Useful for endpoints that return a single
14/// object (e.g. the Compare API) rather than a paginated array.
15pub fn gh_api_get(endpoint: &str, token: Option<&str>) -> Result<serde_json::Value> {
16    gh_api_get_with_binary(Path::new("gh"), endpoint, token)
17}
18
19/// GET a GitHub API endpoint via `gh_binary` (single request, no pagination).
20///
21/// Path-taking sibling of [`gh_api_get`] so tests can point at a missing or
22/// stub binary inside a `tempfile::tempdir()` without mutating `PATH`.
23/// When `gh_binary` has no separator (e.g. `Path::new("gh")`),
24/// [`Command::new`] falls back to a PATH lookup — the production
25/// behavior — so the wrapper is a true no-op in normal use.
26pub fn gh_api_get_with_binary(
27    gh_binary: &Path,
28    endpoint: &str,
29    token: Option<&str>,
30) -> Result<serde_json::Value> {
31    let mut cmd = Command::new(gh_binary);
32    cmd.args(["api", endpoint]);
33    if let Some(tok) = token {
34        cmd.env("GITHUB_TOKEN", tok);
35    }
36    let output = cmd
37        .stdout(std::process::Stdio::piped())
38        .stderr(std::process::Stdio::piped())
39        .output()
40        .with_context(|| format!("failed to spawn gh CLI ({})", gh_binary.display()))?;
41    if !output.status.success() {
42        let stderr_raw = String::from_utf8_lossy(&output.stderr);
43        let raw = format!("gh api GET {} failed: {}", endpoint, stderr_raw.trim());
44        bail!("{}", redact_gh_stderr(&raw, token));
45    }
46    let stdout = String::from_utf8_lossy(&output.stdout);
47    serde_json::from_str(&stdout).context("failed to parse gh api response")
48}
49
50/// Cache key for [`COMMIT_LOGIN_CACHE`]: `(owner, repo, author_email)`.
51type LoginCacheKey = (String, String, String);
52
53/// Process-wide memo of commit-author login lookups. Failed lookups are
54/// cached as `None` so an offline / unauthenticated run costs at most one
55/// API attempt per unique author email, even when several CLI entry points
56/// render changelogs for many crates in the same invocation.
57static COMMIT_LOGIN_CACHE: OnceLock<Mutex<HashMap<LoginCacheKey, Option<String>>>> =
58    OnceLock::new();
59
60/// Resolve a commit author's GitHub login from a representative commit SHA
61/// via `GET /repos/{owner}/{repo}/commits/{sha}` → `.author.login`.
62///
63/// Best-effort by design: any failure (no `gh`, no auth, offline, unknown
64/// SHA, commit email not linked to a GitHub account) returns `None` with at
65/// most a debug-level trace — callers fall back to name-based rendering and
66/// must never fail a release pipeline over a missing login.
67///
68/// Results (including failures) are memoized process-wide per
69/// `(owner, repo, email)`, so each unique author email costs one API call
70/// per run regardless of how many commits or crates reference it.
71pub fn commit_author_login(
72    owner: &str,
73    repo: &str,
74    email: &str,
75    sha: &str,
76    token: Option<&str>,
77) -> Option<String> {
78    commit_author_login_with_binary(Path::new("gh"), owner, repo, email, sha, token)
79}
80
81/// Path-taking sibling of [`commit_author_login`] so tests can point at a
82/// missing or stub binary without mutating `PATH`.
83pub fn commit_author_login_with_binary(
84    gh_binary: &Path,
85    owner: &str,
86    repo: &str,
87    email: &str,
88    sha: &str,
89    token: Option<&str>,
90) -> Option<String> {
91    if owner.is_empty() || repo.is_empty() || email.is_empty() || sha.is_empty() {
92        return None;
93    }
94    let key = (owner.to_string(), repo.to_string(), email.to_string());
95    let cache = COMMIT_LOGIN_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
96    // A poisoned lock only means another thread panicked mid-insert; the map
97    // itself is still a valid memo, so recover it rather than panic here.
98    {
99        let guard = match cache.lock() {
100            Ok(g) => g,
101            Err(poisoned) => poisoned.into_inner(),
102        };
103        if let Some(hit) = guard.get(&key) {
104            return hit.clone();
105        }
106    }
107    let endpoint = format!("/repos/{owner}/{repo}/commits/{sha}");
108    let resolved = match gh_api_get_with_binary(gh_binary, &endpoint, token) {
109        Ok(v) => v
110            .pointer("/author/login")
111            .and_then(|l| l.as_str())
112            .filter(|s| !s.is_empty())
113            .map(str::to_string),
114        Err(e) => {
115            tracing::debug!(
116                "commit_author_login: lookup for {} failed (keeping name-based rendering): {}",
117                email,
118                e
119            );
120            None
121        }
122    };
123    let mut guard = match cache.lock() {
124        Ok(g) => g,
125        Err(poisoned) => poisoned.into_inner(),
126    };
127    guard.insert(key, resolved.clone());
128    resolved
129}
130
131/// Resolve the GitHub token for API calls through the codebase-standard
132/// chain: explicit value (CLI flag / context option) → `ANODIZER_GITHUB_TOKEN`
133/// → `GITHUB_TOKEN`. Empty strings count as absent at every link — GitHub
134/// Actions materializes missing secrets as `""`, which must not
135/// short-circuit the fallback to the next link.
136///
137/// `env` is the injectable env source (pass `Context::env_var` or a
138/// map-backed closure in tests) so the chain is testable without mutating
139/// process env.
140pub fn resolve_github_token_with_env(
141    explicit: Option<&str>,
142    env: &dyn Fn(&str) -> Option<String>,
143) -> Option<String> {
144    let non_empty = |s: String| if s.is_empty() { None } else { Some(s) };
145    explicit
146        .filter(|t| !t.is_empty())
147        .map(str::to_string)
148        .or_else(|| env("ANODIZER_GITHUB_TOKEN").and_then(non_empty))
149        .or_else(|| env("GITHUB_TOKEN").and_then(non_empty))
150}
151
152/// Process-env wrapper of [`resolve_github_token_with_env`] for call sites
153/// without a `Context` (e.g. the `bump`/`tag` changelog-sync write path,
154/// whose commands expose no `--token` flag).
155pub fn resolve_github_token(explicit: Option<&str>) -> Option<String> {
156    resolve_github_token_with_env(explicit, &|key| std::env::var(key).ok())
157}
158
159/// Redact secrets from `gh` CLI stderr before interpolating into a bail
160/// message. `token` is the `GITHUB_TOKEN` value passed to the
161/// subprocess; if the user-supplied token leaks (e.g. via a verbose `gh`
162/// error that echoes the auth header), it is replaced with `$GITHUB_TOKEN`
163/// regardless of whether the value matches the `redact::is_secret`
164/// heuristics. Also strips inline URL credentials and any other secret
165/// env-var values reachable from the parent process env.
166fn redact_gh_stderr(stderr: &str, token: Option<&str>) -> String {
167    let stripped = crate::redact::redact_url_credentials(stderr);
168    let mut env: Vec<(String, String)> = std::env::vars().collect();
169    if let Some(tok) = token
170        && !tok.is_empty()
171    {
172        env.push(("GITHUB_TOKEN".to_string(), tok.to_string()));
173    }
174    crate::redact::string(&stripped, &env)
175}
176
177/// GET a GitHub API endpoint via the `gh` CLI, with pagination.
178///
179/// Returns a JSON array of all pages concatenated. The caller is responsible for
180/// ensuring that `gh` is installed and authenticated.
181pub fn gh_api_get_paginated(endpoint: &str, token: Option<&str>) -> Result<Vec<serde_json::Value>> {
182    gh_api_get_paginated_with_binary(Path::new("gh"), endpoint, token)
183}
184
185/// Paginated GET via `gh_binary`. Path-taking sibling of
186/// [`gh_api_get_paginated`].
187pub fn gh_api_get_paginated_with_binary(
188    gh_binary: &Path,
189    endpoint: &str,
190    token: Option<&str>,
191) -> Result<Vec<serde_json::Value>> {
192    let mut cmd = Command::new(gh_binary);
193    cmd.args(["api", "--paginate", endpoint]);
194    if let Some(tok) = token {
195        cmd.env("GITHUB_TOKEN", tok);
196    }
197    let output = cmd
198        .stdout(std::process::Stdio::piped())
199        .stderr(std::process::Stdio::piped())
200        .output()
201        .with_context(|| format!("failed to spawn gh CLI ({})", gh_binary.display()))?;
202
203    if !output.status.success() {
204        let stderr_raw = String::from_utf8_lossy(&output.stderr);
205        let raw = format!("gh api GET {} failed: {}", endpoint, stderr_raw.trim());
206        bail!("{}", redact_gh_stderr(&raw, token));
207    }
208
209    let stdout = String::from_utf8_lossy(&output.stdout);
210
211    // Try parsing the entire response first before falling back to splitting.
212    // This avoids the split_inclusive(']') approach corrupting non-array responses.
213    if let Ok(serde_json::Value::Array(arr)) = serde_json::from_str::<serde_json::Value>(&stdout) {
214        return Ok(arr);
215    }
216    if let Ok(val) = serde_json::from_str::<serde_json::Value>(&stdout) {
217        // Single object response (e.g. non-list endpoint) — wrap in a vec.
218        return Ok(vec![val]);
219    }
220
221    // Whole-parse failed — gh --paginate may return multiple JSON arrays
222    // concatenated (e.g. `[...][...]`). Split on `]` boundaries and parse each chunk.
223    let mut all_items = Vec::new();
224    for chunk in stdout.split_inclusive(']') {
225        let trimmed = chunk.trim();
226        if trimmed.is_empty() {
227            continue;
228        }
229        if let Ok(serde_json::Value::Array(arr)) =
230            serde_json::from_str::<serde_json::Value>(trimmed)
231        {
232            all_items.extend(arr);
233        } else if let Ok(val) = serde_json::from_str::<serde_json::Value>(trimmed) {
234            all_items.push(val);
235        } else {
236            // Log unparseable chunks so corrupt data doesn't go unnoticed.
237            // The chunk may carry secret-shaped request/response data, and the
238            // tracing subscriber performs NO redaction of its own — so redact
239            // here (process-env secret values + inline URL credentials) before
240            // emitting. Cap the logged chunk at 200 bytes — an HTTP body in an
241            // error context should convey "what server said" without dumping a
242            // multi-MB stack trace to the user's terminal.
243            let snippet = &trimmed[..trimmed.len().min(200)];
244            let redacted = crate::redact::redact_process_env(snippet);
245            tracing::warn!(
246                "gh_api_get_paginated: failed to parse JSON chunk ({} bytes): {:?}",
247                trimmed.len(),
248                redacted,
249            );
250        }
251    }
252    Ok(all_items)
253}
254
255/// POST via `gh_binary`. Internal helper consumed by
256/// [`create_tag_via_github_api_in`]; takes an explicit binary path so
257/// tests can drive the failure path against a missing or stub binary.
258fn gh_api_post_with_binary(
259    gh_binary: &Path,
260    endpoint: &str,
261    body: &serde_json::Value,
262    log: &crate::log::StageLogger,
263) -> Result<serde_json::Value> {
264    let body_str = serde_json::to_string(body)?;
265
266    let mut cmd = Command::new(gh_binary);
267    cmd.args(["api", "--method", "POST", endpoint, "--input", "-"]);
268
269    // `gh api` may echo a token from the parent env (`GITHUB_TOKEN` /
270    // `GH_TOKEN`) on stderr; carry the full process env on a logger clone so
271    // the helper's redaction matches the prior `redact_process_env` coverage
272    // (broader than this caller's attached env). The "gh CLI" label keeps the
273    // spawn-failure string the caller pattern-matches on
274    // (`failed to spawn gh CLI`) for its git-fallback decision.
275    let redacting_log = log.clone().with_env(std::env::vars().collect::<Vec<_>>());
276    let output = crate::run::run_checked_with_stdin(
277        &mut cmd,
278        body_str.as_bytes(),
279        &redacting_log,
280        "gh CLI",
281    )?;
282
283    let response: serde_json::Value = serde_json::from_slice(&output.stdout)
284        .with_context(|| format!("failed to parse GitHub API response from {}", endpoint))?;
285    Ok(response)
286}
287
288/// Create a tag via the GitHub API (using the `gh` CLI).
289///
290/// This avoids the need for local git push access. Requires the `gh` CLI to be
291/// installed and authenticated (`gh auth login`). The GitHub API creates a
292/// lightweight tag object pointing at the HEAD commit on the default branch.
293///
294/// Falls back to [`create_and_push_tag_in`] if `gh` is not available.
295pub fn create_tag_via_github_api(
296    tag: &str,
297    message: &str,
298    dry_run: bool,
299    log: &crate::log::StageLogger,
300    strict: bool,
301) -> Result<()> {
302    create_tag_via_github_api_in(
303        &std::env::current_dir()?,
304        Path::new("gh"),
305        tag,
306        message,
307        dry_run,
308        log,
309        strict,
310    )
311}
312
313/// Path-taking sibling of [`create_tag_via_github_api`].
314///
315/// `cwd` is the repository the tag should be created against (used for
316/// `git remote get-url origin` and `git rev-parse HEAD` lookups, plus
317/// the local `git tag -a` fallback when `gh_binary` is missing).
318/// `gh_binary` is the path to the `gh` CLI; pass `Path::new("gh")` to
319/// keep the production PATH-lookup behavior.
320#[allow(clippy::too_many_arguments)]
321pub fn create_tag_via_github_api_in(
322    cwd: &Path,
323    gh_binary: &Path,
324    tag: &str,
325    message: &str,
326    dry_run: bool,
327    log: &crate::log::StageLogger,
328    strict: bool,
329) -> Result<()> {
330    if dry_run {
331        log.status(&format!(
332            "(dry-run) would create tag {} via GitHub API (\"{}\")",
333            tag, message
334        ));
335        return Ok(());
336    }
337
338    // Detect owner/repo from the origin remote.
339    let (owner, repo) = detect_github_repo_in(cwd)?;
340
341    // Get the current HEAD SHA to point the tag at.
342    let sha = git_output_in(cwd, &["rev-parse", "HEAD"])?;
343
344    let body = serde_json::json!({
345        "tag": tag,
346        "message": message,
347        "object": sha,
348        "type": "commit",
349        "tagger": {
350            "name": git_output_in(cwd, &["config", "user.name"]).unwrap_or_else(|_| "anodizer".to_string()),
351            "email": git_output_in(cwd, &["config", "user.email"]).unwrap_or_else(|_| "anodizer@users.noreply.github.com".to_string()),
352            "date": crate::sde::resolve_now().to_rfc3339(),
353        }
354    });
355
356    let tag_endpoint = format!("/repos/{owner}/{repo}/git/tags");
357    let response = match gh_api_post_with_binary(gh_binary, &tag_endpoint, &body, log) {
358        Ok(resp) => resp,
359        Err(e) => {
360            if e.to_string().contains("failed to spawn gh CLI") {
361                if strict {
362                    anyhow::bail!(
363                        "gh CLI not found, cannot create tag via GitHub API (strict mode)"
364                    );
365                }
366                log.warn("gh CLI not found, falling back to local git tag + push");
367                return create_and_push_tag_in(cwd, tag, message, dry_run, log, strict);
368            }
369            return Err(e);
370        }
371    };
372
373    let tag_sha = response["sha"]
374        .as_str()
375        .ok_or_else(|| anyhow::anyhow!("GitHub API response missing 'sha' field"))?;
376
377    let ref_body = serde_json::json!({
378        "ref": format!("refs/tags/{}", tag),
379        "sha": tag_sha,
380    });
381
382    let ref_endpoint = format!("/repos/{owner}/{repo}/git/refs");
383    gh_api_post_with_binary(gh_binary, &ref_endpoint, &ref_body, log)?;
384
385    Ok(())
386}
387
388#[cfg(test)]
389mod tests {
390    use super::*;
391
392    /// `dry_run=true` must short-circuit before any subprocess spawn.
393    #[test]
394    fn create_tag_dry_run_short_circuits() {
395        let log = crate::log::StageLogger::new("test", crate::log::Verbosity::Quiet);
396        // Even with no git repo / no gh CLI, dry-run must succeed.
397        let result = create_tag_via_github_api("v1.0.0", "msg", true, &log, false);
398        assert!(result.is_ok(), "dry-run must succeed: {result:?}");
399    }
400
401    /// Redact: the token must be replaced with the literal `$GITHUB_TOKEN`
402    /// placeholder when it appears verbatim in the stderr output. Catches
403    /// the case where `gh` echoes the auth header in a verbose error.
404    #[test]
405    fn redact_gh_stderr_replaces_token_value() {
406        let secret = "ghp_abcdefghijklmnopqrstuvwxyz0123456789";
407        let stderr = format!("HTTP 401: token {secret} is invalid");
408        let redacted = redact_gh_stderr(&stderr, Some(secret));
409        assert!(
410            !redacted.contains(secret),
411            "token leaked into redacted output: {redacted}"
412        );
413    }
414
415    #[test]
416    fn redact_gh_stderr_with_no_token_still_strips_url_creds() {
417        // Inline URL credentials must be redacted even with no explicit
418        // token argument.
419        let stderr = "auth failed: https://user:secret-pw@github.com/o/r.git rejected";
420        let redacted = redact_gh_stderr(stderr, None);
421        assert!(
422            !redacted.contains("secret-pw"),
423            "URL credential leaked: {redacted}"
424        );
425    }
426
427    #[test]
428    fn redact_gh_stderr_empty_token_is_noop_on_token_field() {
429        // An empty Some("") token must not pollute the env vector with a
430        // zero-length value (that would match every position in the string).
431        let stderr = "plain error message without credentials";
432        let redacted = redact_gh_stderr(stderr, Some(""));
433        assert_eq!(redacted, stderr);
434    }
435
436    /// A missing `gh` binary must degrade to `None` (never an error/panic):
437    /// the changelog pipeline keeps name-based rendering. The failure is
438    /// memoized, so the second call returns the cached `None` without
439    /// re-attempting a spawn.
440    #[test]
441    fn commit_author_login_missing_binary_degrades_to_none_and_caches() {
442        let tmp = tempfile::tempdir().unwrap();
443        let missing = tmp.path().join("nonexistent-gh");
444        let first = commit_author_login_with_binary(
445            &missing,
446            "owner-cal-test",
447            "repo-cal-test",
448            "a@example.com",
449            "0123456789abcdef0123456789abcdef01234567",
450            None,
451        );
452        assert_eq!(first, None, "missing binary must yield None");
453        // Cached-failure path: same (owner, repo, email) key short-circuits
454        // before any spawn attempt.
455        let second = commit_author_login_with_binary(
456            &missing,
457            "owner-cal-test",
458            "repo-cal-test",
459            "a@example.com",
460            "fedcba9876543210fedcba9876543210fedcba98",
461            None,
462        );
463        assert_eq!(second, None);
464    }
465
466    /// Empty inputs short-circuit to `None` without touching the cache or
467    /// spawning anything.
468    #[test]
469    fn commit_author_login_empty_inputs_are_none() {
470        let gh = Path::new("gh");
471        assert_eq!(
472            commit_author_login_with_binary(gh, "", "r", "e", "s", None),
473            None
474        );
475        assert_eq!(
476            commit_author_login_with_binary(gh, "o", "", "e", "s", None),
477            None
478        );
479        assert_eq!(
480            commit_author_login_with_binary(gh, "o", "r", "", "s", None),
481            None
482        );
483        assert_eq!(
484            commit_author_login_with_binary(gh, "o", "r", "e", "", None),
485            None
486        );
487    }
488
489    /// Chain order: explicit beats `ANODIZER_GITHUB_TOKEN` beats
490    /// `GITHUB_TOKEN`; empty strings are absent at every link. Uses a
491    /// map-backed env closure — no process-env mutation, no network.
492    #[test]
493    fn resolve_github_token_chain_order_and_empty_filtering() {
494        let env_with = |pairs: &[(&str, &str)]| {
495            let map: HashMap<String, String> = pairs
496                .iter()
497                .map(|(k, v)| (k.to_string(), v.to_string()))
498                .collect();
499            move |key: &str| map.get(key).cloned()
500        };
501
502        let both = env_with(&[
503            ("ANODIZER_GITHUB_TOKEN", "anod-tok"),
504            ("GITHUB_TOKEN", "gh-tok"),
505        ]);
506        assert_eq!(
507            resolve_github_token_with_env(Some("explicit-tok"), &both),
508            Some("explicit-tok".to_string()),
509            "explicit token must win over both env vars"
510        );
511        assert_eq!(
512            resolve_github_token_with_env(None, &both),
513            Some("anod-tok".to_string()),
514            "ANODIZER_GITHUB_TOKEN must win over GITHUB_TOKEN"
515        );
516
517        let gh_only = env_with(&[("GITHUB_TOKEN", "gh-tok")]);
518        assert_eq!(
519            resolve_github_token_with_env(None, &gh_only),
520            Some("gh-tok".to_string()),
521            "GITHUB_TOKEN alone must resolve (the CI-gap pin)"
522        );
523        assert_eq!(
524            resolve_github_token_with_env(Some(""), &gh_only),
525            Some("gh-tok".to_string()),
526            "empty explicit token must fall through to env"
527        );
528
529        let empty_anod = env_with(&[("ANODIZER_GITHUB_TOKEN", ""), ("GITHUB_TOKEN", "gh-tok")]);
530        assert_eq!(
531            resolve_github_token_with_env(None, &empty_anod),
532            Some("gh-tok".to_string()),
533            "empty ANODIZER_GITHUB_TOKEN (GHA missing-secret materialization) must not short-circuit"
534        );
535
536        let none = env_with(&[]);
537        assert_eq!(resolve_github_token_with_env(None, &none), None);
538        assert_eq!(resolve_github_token_with_env(Some(""), &none), None);
539    }
540
541    /// `gh_api_get_with_binary` must surface a user-actionable spawn
542    /// failure when the binary path doesn't exist on disk.
543    ///
544    /// Drives the function with a temp-dir-relative path that points to
545    /// nothing, asserting the error mentions "spawn gh" so the operator
546    /// can correlate it with their missing-`gh` install state.
547    #[test]
548    fn gh_api_get_with_binary_bails_when_binary_missing() {
549        let tmp = tempfile::tempdir().unwrap();
550        let missing = tmp.path().join("nonexistent-gh");
551        let err = gh_api_get_with_binary(&missing, "/repos/x/y", None)
552            .expect_err("missing binary must error");
553        let msg = err.to_string();
554        assert!(
555            msg.contains("spawn gh") || msg.contains(&missing.display().to_string()),
556            "expected actionable error mentioning spawn gh or the binary path, got: {msg}"
557        );
558    }
559
560    /// Same guarantee for the paginated sibling.
561    #[test]
562    fn gh_api_get_paginated_with_binary_bails_when_binary_missing() {
563        let tmp = tempfile::tempdir().unwrap();
564        let missing = tmp.path().join("nonexistent-gh");
565        let err = gh_api_get_paginated_with_binary(&missing, "/repos/x/y", None)
566            .expect_err("missing binary must error");
567        let msg = err.to_string();
568        assert!(
569            msg.contains("spawn gh") || msg.contains(&missing.display().to_string()),
570            "expected actionable error mentioning spawn gh or the binary path, got: {msg}"
571        );
572    }
573
574    /// `create_tag_via_github_api_in` with `strict=true` must error
575    /// when `cwd` is not a git repo — the inner `detect_github_repo_in`
576    /// drives `git remote get-url origin` and fails there.
577    ///
578    /// Skips when `git` isn't on PATH (mirrors `tool_on_path` patterns
579    /// elsewhere in the suite).
580    #[test]
581    fn create_tag_via_github_api_in_bails_when_not_a_git_repo() {
582        if Command::new("git")
583            .arg("--version")
584            .output()
585            .map(|o| !o.status.success())
586            .unwrap_or(true)
587        {
588            return;
589        }
590        let tmp = tempfile::tempdir().unwrap();
591        let log = crate::log::StageLogger::new("test", crate::log::Verbosity::Quiet);
592        let err = create_tag_via_github_api_in(
593            tmp.path(),
594            Path::new("gh"),
595            "v1.0.0",
596            "msg",
597            false,
598            &log,
599            true,
600        )
601        .expect_err("non-git cwd must error");
602        let msg = err.to_string();
603        assert!(
604            msg.contains("git") || msg.contains("remote"),
605            "expected error to mention git or remote, got: {msg}"
606        );
607    }
608
609    /// Dry-run short-circuit must also fire on the cwd-injectable entry
610    /// point — covers the new branch without re-hitting the inner
611    /// detection codepath.
612    #[test]
613    fn create_tag_via_github_api_in_dry_run_short_circuits() {
614        let tmp = tempfile::tempdir().unwrap();
615        let log = crate::log::StageLogger::new("test", crate::log::Verbosity::Quiet);
616        let result = create_tag_via_github_api_in(
617            tmp.path(),
618            Path::new("gh"),
619            "v1.0.0",
620            "msg",
621            true,
622            &log,
623            false,
624        );
625        assert!(result.is_ok(), "dry-run must succeed: {result:?}");
626    }
627}