Skip to main content

node_auth/
logger.rs

1//! CLI-only logging and presentation. Library operations never initialize this logger.
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 { paths, git_status } => {
50            if let Some(status) = git_status {
51                match status {
52                    GitStatus::GitRepoNotIgnored => eprintln!(
53                        "{} Local .npmrc is tracked or not ignored by Git; it may expose credentials if committed.",
54                        "Warning:".yellow().bold()
55                    ),
56                    GitStatus::NotGitRepo => eprintln!(
57                        "{} Local .npmrc is outside a Git repository; keep credentials out of version control.",
58                        "Warning:".yellow().bold()
59                    ),
60                    GitStatus::Unavailable => eprintln!(
61                        "{} Could not verify Git ignore status for local .npmrc.",
62                        "Warning:".yellow().bold()
63                    ),
64                    GitStatus::GitRepoIgnored => {}
65                }
66            }
67            if !paths.is_empty() {
68                println!(
69                    "{} Updated {} configuration file(s).",
70                    "Success!".green().bold(),
71                    paths.len()
72                );
73            }
74        }
75    }
76}
77
78/// Present one CLI error on stderr.
79pub fn present_error(error: &AuthError) {
80    eprintln!("{} {error}", "Error:".red().bold());
81}