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
11pub 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
19pub 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
50type LoginCacheKey = (String, String, String);
52
53static COMMIT_LOGIN_CACHE: OnceLock<Mutex<HashMap<LoginCacheKey, Option<String>>>> =
58 OnceLock::new();
59
60pub 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
81pub 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 {
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
131pub 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
152pub fn resolve_github_token(explicit: Option<&str>) -> Option<String> {
156 resolve_github_token_with_env(explicit, &|key| std::env::var(key).ok())
157}
158
159fn redact_gh_stderr(stderr: &str, token: Option<&str>) -> String {
167 let mut env: Vec<(String, String)> = std::env::vars().collect();
168 if let Some(tok) = token
169 && !tok.is_empty()
170 {
171 env.push(("GITHUB_TOKEN".to_string(), tok.to_string()));
172 }
173 crate::redact::with_env(stderr, &env)
174}
175
176pub fn gh_api_get_paginated(endpoint: &str, token: Option<&str>) -> Result<Vec<serde_json::Value>> {
181 gh_api_get_paginated_with_binary(Path::new("gh"), endpoint, token)
182}
183
184pub fn gh_api_get_paginated_with_binary(
187 gh_binary: &Path,
188 endpoint: &str,
189 token: Option<&str>,
190) -> Result<Vec<serde_json::Value>> {
191 let mut cmd = Command::new(gh_binary);
192 cmd.args(["api", "--paginate", endpoint]);
193 if let Some(tok) = token {
194 cmd.env("GITHUB_TOKEN", tok);
195 }
196 let output = cmd
197 .stdout(std::process::Stdio::piped())
198 .stderr(std::process::Stdio::piped())
199 .output()
200 .with_context(|| format!("failed to spawn gh CLI ({})", gh_binary.display()))?;
201
202 if !output.status.success() {
203 let stderr_raw = String::from_utf8_lossy(&output.stderr);
204 let raw = format!("gh api GET {} failed: {}", endpoint, stderr_raw.trim());
205 bail!("{}", redact_gh_stderr(&raw, token));
206 }
207
208 let stdout = String::from_utf8_lossy(&output.stdout);
209
210 if let Ok(serde_json::Value::Array(arr)) = serde_json::from_str::<serde_json::Value>(&stdout) {
213 return Ok(arr);
214 }
215 if let Ok(val) = serde_json::from_str::<serde_json::Value>(&stdout) {
216 return Ok(vec![val]);
218 }
219
220 let mut all_items = Vec::new();
223 for chunk in stdout.split_inclusive(']') {
224 let trimmed = chunk.trim();
225 if trimmed.is_empty() {
226 continue;
227 }
228 if let Ok(serde_json::Value::Array(arr)) =
229 serde_json::from_str::<serde_json::Value>(trimmed)
230 {
231 all_items.extend(arr);
232 } else if let Ok(val) = serde_json::from_str::<serde_json::Value>(trimmed) {
233 all_items.push(val);
234 } else {
235 let snippet = &trimmed[..trimmed.len().min(200)];
243 let redacted = crate::redact::redact_process_env(snippet);
244 tracing::warn!(
245 "gh_api_get_paginated: failed to parse JSON chunk ({} bytes): {:?}",
246 trimmed.len(),
247 redacted,
248 );
249 }
250 }
251 Ok(all_items)
252}
253
254fn gh_api_post_with_binary(
258 gh_binary: &Path,
259 endpoint: &str,
260 body: &serde_json::Value,
261 log: &crate::log::StageLogger,
262) -> Result<serde_json::Value> {
263 let body_str = serde_json::to_string(body)?;
264
265 let mut cmd = Command::new(gh_binary);
266 cmd.args(["api", "--method", "POST", endpoint, "--input", "-"]);
267
268 let redacting_log = log.clone().with_env(std::env::vars().collect::<Vec<_>>());
275 let output = crate::run::run_checked_with_stdin(
276 &mut cmd,
277 body_str.as_bytes(),
278 &redacting_log,
279 "gh CLI",
280 )?;
281
282 let response: serde_json::Value = serde_json::from_slice(&output.stdout)
283 .with_context(|| format!("failed to parse GitHub API response from {}", endpoint))?;
284 Ok(response)
285}
286
287pub fn create_tag_via_github_api(
295 tag: &str,
296 message: &str,
297 dry_run: bool,
298 log: &crate::log::StageLogger,
299 strict: bool,
300) -> Result<()> {
301 create_tag_via_github_api_in(
302 &std::env::current_dir()?,
303 Path::new("gh"),
304 tag,
305 message,
306 dry_run,
307 log,
308 strict,
309 )
310}
311
312#[allow(clippy::too_many_arguments)]
320pub fn create_tag_via_github_api_in(
321 cwd: &Path,
322 gh_binary: &Path,
323 tag: &str,
324 message: &str,
325 dry_run: bool,
326 log: &crate::log::StageLogger,
327 strict: bool,
328) -> Result<()> {
329 if dry_run {
330 log.status(&format!(
331 "(dry-run) would create tag {} via GitHub API (\"{}\")",
332 tag, message
333 ));
334 return Ok(());
335 }
336
337 let (owner, repo) = detect_github_repo_in(cwd)?;
339
340 let sha = git_output_in(cwd, &["rev-parse", "HEAD"])?;
342
343 let body = serde_json::json!({
344 "tag": tag,
345 "message": message,
346 "object": sha,
347 "type": "commit",
348 "tagger": {
349 "name": git_output_in(cwd, &["config", "user.name"]).unwrap_or_else(|_| "anodizer".to_string()),
350 "email": git_output_in(cwd, &["config", "user.email"]).unwrap_or_else(|_| "anodizer@users.noreply.github.com".to_string()),
351 "date": crate::sde::resolve_now().to_rfc3339(),
352 }
353 });
354
355 let tag_endpoint = format!("/repos/{owner}/{repo}/git/tags");
356 let response = match gh_api_post_with_binary(gh_binary, &tag_endpoint, &body, log) {
357 Ok(resp) => resp,
358 Err(e) => {
359 if e.to_string().contains("failed to spawn gh CLI") {
360 if strict {
361 anyhow::bail!(
362 "gh CLI not found, cannot create tag via GitHub API (strict mode)"
363 );
364 }
365 log.warn("gh CLI not found, falling back to local git tag + push");
366 return create_and_push_tag_in(cwd, tag, message, dry_run, log, strict);
367 }
368 return Err(e);
369 }
370 };
371
372 let tag_sha = response["sha"]
373 .as_str()
374 .ok_or_else(|| anyhow::anyhow!("GitHub API response missing 'sha' field"))?;
375
376 let ref_body = serde_json::json!({
377 "ref": format!("refs/tags/{}", tag),
378 "sha": tag_sha,
379 });
380
381 let ref_endpoint = format!("/repos/{owner}/{repo}/git/refs");
382 gh_api_post_with_binary(gh_binary, &ref_endpoint, &ref_body, log)?;
383
384 Ok(())
385}
386
387#[cfg(test)]
388mod tests {
389 use super::*;
390
391 #[test]
393 fn create_tag_dry_run_short_circuits() {
394 let log = crate::log::StageLogger::new("test", crate::log::Verbosity::Quiet);
395 let result = create_tag_via_github_api("v1.0.0", "msg", true, &log, false);
397 assert!(result.is_ok(), "dry-run must succeed: {result:?}");
398 }
399
400 #[test]
404 fn redact_gh_stderr_replaces_token_value() {
405 let secret = "ghp_abcdefghijklmnopqrstuvwxyz0123456789";
406 let stderr = format!("HTTP 401: token {secret} is invalid");
407 let redacted = redact_gh_stderr(&stderr, Some(secret));
408 assert_eq!(redacted, "HTTP 401: token $GITHUB_TOKEN is invalid");
411 }
412
413 #[test]
414 fn redact_gh_stderr_with_no_token_still_strips_url_creds() {
415 let stderr = "auth failed: https://user:secret-pw@github.com/o/r.git rejected";
418 let redacted = redact_gh_stderr(stderr, None);
419 assert_eq!(
422 redacted,
423 "auth failed: https://<redacted>@github.com/o/r.git rejected"
424 );
425 }
426
427 #[test]
428 fn redact_gh_stderr_empty_token_is_noop_on_token_field() {
429 let stderr = "plain error message without credentials";
432 let redacted = redact_gh_stderr(stderr, Some(""));
433 assert_eq!(redacted, stderr);
434 }
435
436 #[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 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 #[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 #[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 #[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 #[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 #[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 #[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}