Skip to main content

node_auth/
logger.rs

1//! CLI-only logging and presentation.
2
3use crate::vcs::GitStatus;
4use crate::{AuthError, RunOutcome};
5use colored::Colorize;
6use log::{Level, LevelFilter, Log, Metadata, Record};
7
8struct CliLogger;
9static LOGGER: CliLogger = CliLogger;
10
11impl Log for CliLogger {
12  fn enabled(&self, metadata: &Metadata) -> bool {
13    metadata.level() <= log::max_level()
14  }
15
16  fn log(&self, record: &Record) {
17    if self.enabled(record.metadata()) {
18      eprintln!("{} {}", level_label(record.level()), record.args());
19    }
20  }
21
22  fn flush(&self) {}
23}
24
25fn level_label(level: Level) -> String {
26  match level {
27    Level::Error => "[ERROR]".red().bold().to_string(),
28    Level::Warn => "[WARN]".yellow().bold().to_string(),
29    Level::Info => "[INFO]".green().bold().to_string(),
30    Level::Debug => "[DEBUG]".cyan().bold().to_string(),
31    Level::Trace => "[TRACE]".magenta().bold().to_string(),
32  }
33}
34
35/// Initialize logging for a CLI invocation. All diagnostic output goes to stderr.
36pub fn init(verbose: bool) {
37  let _ = log::set_logger(&LOGGER);
38  log::set_max_level(if verbose {
39    LevelFilter::Debug
40  } else {
41    LevelFilter::Warn
42  });
43}
44
45/// Present a successful library result to a CLI user.
46pub fn present_outcome(outcome: RunOutcome) {
47  match outcome {
48    RunOutcome::Token(token) => println!("{token}"),
49    RunOutcome::Updated {
50      paths,
51      git_status,
52      bun_env_git_status,
53    } => {
54      if let Some(status) = git_status {
55        match status {
56          GitStatus::GitRepoNotIgnored => eprintln!(
57            "{} Local .npmrc is tracked or not ignored by Git; it may expose credentials if committed.",
58            "Warning:".yellow().bold()
59          ),
60          GitStatus::NotGitRepo => eprintln!(
61            "{} Local .npmrc is outside a Git repository; keep credentials out of version control.",
62            "Warning:".yellow().bold()
63          ),
64          GitStatus::Unavailable => eprintln!(
65            "{} Could not verify Git ignore status for local .npmrc.",
66            "Warning:".yellow().bold()
67          ),
68          GitStatus::GitRepoIgnored => {}
69        }
70      }
71      if let Some(status) = bun_env_git_status {
72        match status {
73          GitStatus::GitRepoNotIgnored => eprintln!(
74            "{} .env.local is tracked or not ignored by Git; it may expose credentials if committed.",
75            "Warning:".yellow().bold()
76          ),
77          GitStatus::NotGitRepo => eprintln!(
78            "{} .env.local is outside a Git repository; keep credentials out of version control.",
79            "Warning:".yellow().bold()
80          ),
81          GitStatus::Unavailable => eprintln!(
82            "{} Could not verify Git ignore status for .env.local.",
83            "Warning:".yellow().bold()
84          ),
85          GitStatus::GitRepoIgnored => {}
86        }
87      }
88      if !paths.is_empty() {
89        println!(
90          "{} Updated {} configuration file(s).",
91          "Success!".green().bold(),
92          paths.len()
93        );
94      }
95    }
96  }
97}
98
99/// Present one CLI error on stderr.
100pub fn present_error(error: &AuthError) {
101  eprintln!("{} {}", "Error:".red().bold(), format_error(error));
102}
103
104// Keep remediation and command-line option names in the CLI presentation layer.
105fn format_error(error: &AuthError) -> String {
106  match error {
107    AuthError::NoNpmRegistry => format!(
108      "{error}.\n\
109       Ensure your .npmrc contains a registry line such as:\n\
110       @my-scope:registry=https://<region>-npm.pkg.dev/<project>/<repo>/\n\
111       Run `gcloud artifacts print-settings npm` to generate configuration."
112    ),
113    AuthError::CredentialsUnavailable => format!(
114      "{error}.\n\
115       Please run:\n\
116       • `gcloud auth application-default login`\n\
117       • `gcloud auth login`\n\
118       or export `GOOGLE_APPLICATION_CREDENTIALS=<path/to/service/account/key.json>`"
119    ),
120    AuthError::BunEnvLocalCredentialConflict => {
121      "Configuration error: --bun-env cannot be used with --local-credential".to_string()
122    }
123    AuthError::BunEnvDisabledConflict => {
124      "Configuration error: --bun-env cannot be used with --bun false".to_string()
125    }
126    _ => error.to_string(),
127  }
128}
129
130#[cfg(test)]
131mod tests {
132  use super::*;
133
134  #[test]
135  fn npm_guidance_has_explicit_line_layout() {
136    assert_eq!(
137      format_error(&AuthError::NoNpmRegistry),
138      concat!(
139        "Configuration error: No eligible registry configuration found in .npmrc.\n",
140        "Ensure your .npmrc contains a registry line such as:\n",
141        "@my-scope:registry=https://<region>-npm.pkg.dev/<project>/<repo>/\n",
142        "Run `gcloud artifacts print-settings npm` to generate configuration."
143      )
144    );
145  }
146
147  #[test]
148  fn authentication_guidance_has_explicit_line_layout() {
149    assert_eq!(
150      format_error(&AuthError::CredentialsUnavailable),
151      concat!(
152        "Authentication error: Failed to get credentials from ADC or gcloud.\n",
153        "Please run:\n",
154        "• `gcloud auth application-default login`\n",
155        "• `gcloud auth login`\n",
156        "or export `GOOGLE_APPLICATION_CREDENTIALS=<path/to/service/account/key.json>`"
157      )
158    );
159  }
160
161  #[test]
162  fn option_conflicts_use_cli_flag_names() {
163    assert_eq!(
164      format_error(&AuthError::BunEnvLocalCredentialConflict),
165      "Configuration error: --bun-env cannot be used with --local-credential"
166    );
167    assert_eq!(
168      format_error(&AuthError::BunEnvDisabledConflict),
169      "Configuration error: --bun-env cannot be used with --bun false"
170    );
171  }
172
173  #[test]
174  fn ordinary_errors_keep_their_diagnostic() {
175    let error = AuthError::Config("Invalid registry URL".to_string());
176    assert_eq!(format_error(&error), error.to_string());
177  }
178}