#![allow(
clippy::disallowed_methods,
clippy::disallowed_types,
reason = "Error reporter runs in sync contexts (pre-runtime, signal handlers)"
)]
use std::{
io::Write as _,
path::{Path, PathBuf},
sync::LazyLock,
};
use regex::Regex;
use serde::Serialize;
#[derive(Debug, Clone, Serialize)]
pub(crate) struct ErrorReport {
pub id: String,
pub source: String,
pub command: String,
pub platform: String,
pub exit_code: i32,
pub error_code: String,
pub error_message: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub hint: Option<String>,
pub timestamp: String,
}
impl ErrorReport {
pub(crate) fn from_error(
command: &str,
platform: &str,
error_message: &str,
error_code: &str,
) -> Self {
Self {
id: generate_unique_id(),
source: "cli".into(),
command: command.into(),
platform: platform.into(),
exit_code: 1,
error_code: error_code.into(),
error_message: sanitize_error_message(error_message),
hint: None,
timestamp: iso8601_utc_now(),
}
}
pub(crate) fn write_to_disk(&self, repo_root: &Path) -> std::io::Result<()> {
let dir = repo_root.join(".cache").join("bug-reports");
std::fs::create_dir_all(&dir)?;
let path = dir.join("pending.json");
let json = serde_json::to_string_pretty(self)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
let mut file = std::fs::File::create(&path)?;
#[cfg(unix)]
set_pending_file_permissions(&file)?;
file.write_all(json.as_bytes())?;
Ok(())
}
}
static GITHUB_TOKEN_RE: LazyLock<Regex> = LazyLock::new(|| {
#[allow(
clippy::expect_used,
reason = "regex pattern is a compile-time literal; a compile failure is a programming \
error"
)]
Regex::new(r"(?:ghp_[A-Za-z0-9]+|github_pat_[A-Za-z0-9_]+)")
.expect("GitHub token regex must be statically valid")
});
fn sanitize_error_message(message: &str) -> String {
let sanitized = if let Some(home) = dirs::home_dir() {
let home_str = home.to_string_lossy();
message.replace(home_str.as_ref(), "~")
} else {
message.to_string()
};
GITHUB_TOKEN_RE
.replace_all(&sanitized, "[REDACTED]")
.into_owned()
}
#[cfg(unix)]
fn set_pending_file_permissions(file: &std::fs::File) -> std::io::Result<()> {
use std::os::unix::fs::PermissionsExt as _;
file.set_permissions(std::fs::Permissions::from_mode(0o600))
}
pub(crate) fn maybe_report_error(
command: &str,
platform: &str,
error_message: &str,
error_code: &str,
) -> std::io::Result<()> {
if should_skip_reporting() {
return Ok(());
}
if !is_co_contribution_enabled() {
return Ok(());
}
let report = ErrorReport::from_error(command, platform, error_message, error_code);
let repo_root = find_repo_root()?;
report.write_to_disk(&repo_root)
}
fn is_co_contribution_enabled() -> bool {
if let Ok(repo_root) = find_repo_root() {
let project_settings = repo_root.join(".claude/settings.json");
if read_co_contribution_flag(&project_settings) {
return true;
}
}
if let Some(home) = dirs::home_dir() {
let global_settings = home.join(".claude/settings.json");
if read_co_contribution_flag(&global_settings) {
return true;
}
}
false
}
pub(crate) fn read_co_contribution_flag(path: &Path) -> bool {
let Ok(content) = std::fs::read_to_string(path) else {
return false;
};
let Ok(json) = serde_json::from_str::<serde_json::Value>(&content) else {
return false;
};
json.pointer("/gitflow/co_contribution")
.and_then(serde_json::Value::as_bool)
.unwrap_or(false)
}
fn should_skip_reporting() -> bool {
use is_terminal::IsTerminal;
std::io::stderr().is_terminal()
}
fn generate_unique_id() -> String {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_nanos());
let pid = std::process::id();
let mixed = nanos ^ (u128::from(pid) * 0x9E37_79B9_7F4A_7C15);
format!("{mixed:032x}")
}
fn find_repo_root() -> std::io::Result<PathBuf> {
let output = std::process::Command::new("git")
.args(["rev-parse", "--show-toplevel"])
.output()?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("git rev-parse --show-toplevel failed: {stderr}"),
));
}
let path_str = String::from_utf8_lossy(&output.stdout);
Ok(PathBuf::from(path_str.trim()))
}
fn iso8601_utc_now() -> String {
let secs = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
unix_secs_to_iso8601(secs)
}
#[allow(
clippy::cast_possible_wrap,
clippy::cast_lossless,
clippy::cast_sign_loss,
reason = "Howard Hinnant's algorithm operates on mixed-sign integer ranges within known bounds"
)]
fn unix_secs_to_iso8601(unix_secs: u64) -> String {
let day_secs = unix_secs % 86_400;
let hours = day_secs / 3_600;
let minutes = (day_secs % 3_600) / 60;
let seconds = day_secs % 60;
let days = (unix_secs / 86_400) as i64;
let z = days + 719_468;
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
let doe = (z - era * 146_097) as u64; let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); let mp = (5 * doy + 2) / 153; let d = doy - (153 * mp + 2) / 5 + 1; let m = if mp < 10 { mp + 3 } else { mp - 9 }; let y = yoe as i64 + era * 400;
let y = if m <= 2 { y + 1 } else { y };
format!("{y:04}-{m:02}-{d:02}T{hours:02}:{minutes:02}:{seconds:02}Z")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_should_create_error_report_from_error() {
let report =
ErrorReport::from_error("issue create", "github", "auth failed", "AUTH_FAILED");
assert_eq!(report.source, "cli");
assert_eq!(report.command, "issue create");
assert_eq!(report.platform, "github");
assert_eq!(report.exit_code, 1);
assert_eq!(report.error_code, "AUTH_FAILED");
assert_eq!(report.error_message, "auth failed");
assert!(report.hint.is_none());
assert!(!report.id.is_empty());
assert!(report.timestamp.ends_with('Z'));
assert!(report.timestamp.contains('T'));
}
#[test]
fn test_should_write_pending_json_to_disk() {
let tmp = tempfile::tempdir().expect("tempdir");
let report = ErrorReport::from_error("pr list", "gitlab", "not found", "NOT_FOUND");
report.write_to_disk(tmp.path()).expect("write_to_disk");
let pending = tmp.path().join(".cache/bug-reports/pending.json");
assert!(pending.exists(), "pending.json must be created");
let contents = std::fs::read_to_string(&pending).expect("read pending.json");
let parsed: serde_json::Value = serde_json::from_str(&contents).expect("valid JSON");
assert_eq!(parsed["source"], "cli");
assert_eq!(parsed["command"], "pr list");
assert_eq!(parsed["platform"], "gitlab");
assert_eq!(parsed["error_code"], "NOT_FOUND");
assert_eq!(parsed["error_message"], "not found");
assert_eq!(parsed["exit_code"], 1);
assert!(parsed.get("id").is_some());
assert!(parsed.get("timestamp").is_some());
}
#[test]
fn test_should_sanitize_home_directory_in_error_message() {
let home = dirs::home_dir().expect("home dir must resolve in tests");
let home_str = home.to_string_lossy();
let message = format!("failed to read {home_str}/.claude/settings.json");
let sanitized = sanitize_error_message(&message);
assert_eq!(
sanitized, "failed to read ~/.claude/settings.json",
"home directory path must be replaced with ~"
);
}
#[test]
fn test_should_sanitize_token_in_error_message() {
let classic = "auth failed: token ghp_1234567890abcdefghijklmnopqrstuvwxyz rejected";
let sanitized = sanitize_error_message(classic);
assert!(
!sanitized.contains("ghp_"),
"classic GitHub token must be redacted: {sanitized}"
);
assert!(sanitized.contains("[REDACTED]"));
let fine_grained =
"clone failed: \
github_pat_1234567890abcdef_GHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let sanitized = sanitize_error_message(fine_grained);
assert!(
!sanitized.contains("github_pat_"),
"fine-grained GitHub token must be redacted: {sanitized}"
);
assert!(sanitized.contains("[REDACTED]"));
}
#[test]
fn test_should_not_modify_safe_error_message() {
let message = "issue not found: pull request #42 does not exist";
assert_eq!(sanitize_error_message(message), message);
}
#[test]
fn test_should_set_pending_json_permissions_to_600() {
let tmp = tempfile::tempdir().expect("tempdir");
let report = ErrorReport::from_error("pr list", "gitlab", "not found", "NOT_FOUND");
report.write_to_disk(tmp.path()).expect("write_to_disk");
let pending = tmp.path().join(".cache/bug-reports/pending.json");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
let metadata = std::fs::metadata(&pending).expect("metadata");
assert_eq!(
metadata.permissions().mode() & 0o777,
0o600,
"pending.json must be readable/writable only by the owner"
);
}
#[cfg(not(unix))]
{
assert!(pending.exists(), "pending.json must be created");
}
}
#[test]
fn test_should_generate_unique_id() {
let id1 = generate_unique_id();
std::thread::sleep(std::time::Duration::from_millis(2));
let id2 = generate_unique_id();
assert_ne!(id1, id2, "successive calls must produce distinct IDs");
assert_eq!(id1.len(), 32);
assert_eq!(id2.len(), 32);
}
#[test]
fn test_should_skip_when_interactive_terminal() {
use is_terminal::IsTerminal;
let is_tty = std::io::stderr().is_terminal();
assert_eq!(
should_skip_reporting(),
is_tty,
"should_skip_reporting() must equal stderr.is_terminal()"
);
}
#[test]
fn test_should_format_iso8601_unix_epoch() {
assert_eq!(unix_secs_to_iso8601(0), "1970-01-01T00:00:00Z");
}
#[test]
fn test_should_format_iso8601_known_date() {
assert_eq!(unix_secs_to_iso8601(1_704_067_200), "2024-01-01T00:00:00Z");
}
#[test]
fn test_should_format_iso8601_with_time() {
assert_eq!(unix_secs_to_iso8601(45_296), "1970-01-01T12:34:56Z");
}
#[test]
fn test_should_format_iso8601_day_after_epoch() {
assert_eq!(unix_secs_to_iso8601(86_400), "1970-01-02T00:00:00Z");
}
#[test]
fn test_should_return_false_for_missing_settings_file() {
let tmp = tempfile::tempdir().expect("tempdir");
let missing = tmp.path().join("nonexistent.json");
assert!(!read_co_contribution_flag(&missing));
}
#[test]
fn test_should_return_false_for_settings_without_gitflow() {
let tmp = tempfile::tempdir().expect("tempdir");
let path = tmp.path().join("settings.json");
std::fs::write(&path, r#"{"hooks": {}}"#).expect("write");
assert!(!read_co_contribution_flag(&path));
}
#[test]
fn test_should_return_false_for_gitflow_without_co_contribution() {
let tmp = tempfile::tempdir().expect("tempdir");
let path = tmp.path().join("settings.json");
std::fs::write(&path, r#"{"gitflow": {}}"#).expect("write");
assert!(!read_co_contribution_flag(&path));
}
#[test]
fn test_should_return_true_for_co_contribution_enabled() {
let tmp = tempfile::tempdir().expect("tempdir");
let path = tmp.path().join("settings.json");
std::fs::write(&path, r#"{"gitflow": {"co_contribution": true}}"#).expect("write");
assert!(read_co_contribution_flag(&path));
}
#[test]
fn test_should_return_false_for_co_contribution_disabled() {
let tmp = tempfile::tempdir().expect("tempdir");
let path = tmp.path().join("settings.json");
std::fs::write(&path, r#"{"gitflow": {"co_contribution": false}}"#).expect("write");
assert!(!read_co_contribution_flag(&path));
}
#[test]
fn test_should_return_false_for_invalid_json() {
let tmp = tempfile::tempdir().expect("tempdir");
let path = tmp.path().join("settings.json");
std::fs::write(&path, "not json").expect("write");
assert!(!read_co_contribution_flag(&path));
}
}