1use 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
35pub 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
45pub 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
72 if let Some(status) = bun_env_git_status {
73 match status {
74 GitStatus::GitRepoNotIgnored => eprintln!(
75 "{} .env.local is tracked or not ignored by Git; it may expose credentials if committed.",
76 "Warning:".yellow().bold()
77 ),
78 GitStatus::NotGitRepo => eprintln!(
79 "{} .env.local is outside a Git repository; keep credentials out of version control.",
80 "Warning:".yellow().bold()
81 ),
82 GitStatus::Unavailable => eprintln!(
83 "{} Could not verify Git ignore status for .env.local.",
84 "Warning:".yellow().bold()
85 ),
86 GitStatus::GitRepoIgnored => {}
87 }
88 }
89
90 if !paths.is_empty() {
91 println!(
92 "{} Updated {} configuration file(s).",
93 "Success!".green().bold(),
94 paths.len()
95 );
96 }
97 }
98 }
99}
100
101pub fn present_error(error: &AuthError) {
103 eprintln!("{} {}", "Error:".red().bold(), format_error(error));
104}
105
106fn format_error(error: &AuthError) -> String {
108 match error {
109 AuthError::NoNpmRegistry => format!(
110 "{error}.\n\
111 Ensure your .npmrc contains a registry line such as:\n\
112 @my-scope:registry=https://<region>-npm.pkg.dev/<project>/<repo>/\n\
113 Run `gcloud artifacts print-settings npm` to generate configuration."
114 ),
115 AuthError::CredentialsUnavailable => format!(
116 "{error}.\n\
117 Please run:\n\
118 • `gcloud auth application-default login`\n\
119 • `gcloud auth login`\n\
120 or export `GOOGLE_APPLICATION_CREDENTIALS=<path/to/service/account/key.json>`"
121 ),
122 AuthError::BunEnvLocalCredentialConflict => {
123 "Configuration error: --bun-env cannot be used with --local-credential".to_string()
124 }
125 AuthError::BunEnvDisabledConflict => {
126 "Configuration error: --bun-env cannot be used with --bun false".to_string()
127 }
128 _ => error.to_string(),
129 }
130}
131
132#[cfg(test)]
133mod tests {
134 use super::*;
135
136 #[test]
137 fn npm_guidance_has_explicit_line_layout() {
138 assert_eq!(
139 format_error(&AuthError::NoNpmRegistry),
140 concat!(
141 "Configuration error: No eligible registry configuration found in .npmrc.\n",
142 "Ensure your .npmrc contains a registry line such as:\n",
143 "@my-scope:registry=https://<region>-npm.pkg.dev/<project>/<repo>/\n",
144 "Run `gcloud artifacts print-settings npm` to generate configuration."
145 )
146 );
147 }
148
149 #[test]
150 fn authentication_guidance_has_explicit_line_layout() {
151 assert_eq!(
152 format_error(&AuthError::CredentialsUnavailable),
153 concat!(
154 "Authentication error: Failed to get credentials from ADC or gcloud.\n",
155 "Please run:\n",
156 "• `gcloud auth application-default login`\n",
157 "• `gcloud auth login`\n",
158 "or export `GOOGLE_APPLICATION_CREDENTIALS=<path/to/service/account/key.json>`"
159 )
160 );
161 }
162
163 #[test]
164 fn option_conflicts_use_cli_flag_names() {
165 assert_eq!(
166 format_error(&AuthError::BunEnvLocalCredentialConflict),
167 "Configuration error: --bun-env cannot be used with --local-credential"
168 );
169 assert_eq!(
170 format_error(&AuthError::BunEnvDisabledConflict),
171 "Configuration error: --bun-env cannot be used with --bun false"
172 );
173 }
174
175 #[test]
176 fn ordinary_errors_keep_their_diagnostic() {
177 let error = AuthError::Config("Invalid registry URL".to_string());
178 assert_eq!(format_error(&error), error.to_string());
179 }
180}