Skip to main content

node_auth/
cli.rs

1//! Command-line argument parsing and CLI definitions for `node-auth`.
2
3use crate::Options;
4use crate::{logger, run};
5use clap::Parser;
6use std::path::PathBuf;
7use std::process::ExitCode;
8
9/// Command-line arguments for the `node-auth` CLI.
10#[derive(Parser, Clone, PartialEq, Eq)]
11#[command(
12    name = "node-auth",
13    about = "Authenticates Node (npm, yarn, pnpm) to Google Artifact Registry using Google Cloud ADC",
14    version
15)]
16pub struct Cli {
17    /// Path to the .npmrc file to read registry configs from.
18    /// Defaults to project-level .npmrc if present, otherwise user-level ~/.npmrc.
19    #[arg(long, env = "NODE_AUTH_REPO_CONFIG")]
20    pub repo_config: Option<PathBuf>,
21
22    /// Path to the .npmrc file to write credentials to.
23    /// Defaults to user-level ~/.npmrc.
24    #[arg(long, env = "NODE_AUTH_CREDENTIAL_CONFIG")]
25    pub credential_config: Option<PathBuf>,
26
27    /// Forces writing credentials to the current directory's .npmrc (creating it if missing).
28    /// Emits a warning if running in a Git repository without .npmrc in .gitignore.
29    #[arg(short = 'l', long)]
30    pub local_credential: bool,
31
32    /// Path to the .yarnrc.yml file to read registry configs from.
33    /// Defaults to project-level .yarnrc.yml if present, otherwise user-level ~/.yarnrc.yml.
34    #[arg(long)]
35    pub repo_config_yarn: Option<PathBuf>,
36
37    /// Path to the .yarnrc.yml file to write credentials to.
38    /// Defaults to user-level ~/.yarnrc.yml.
39    #[arg(long)]
40    pub credential_config_yarn: Option<PathBuf>,
41
42    /// Explicitly enable or disable updating Yarn configuration (.yarnrc.yml).
43    /// By default, Yarn is updated if .yarnrc.yml exists or is explicitly specified.
44    #[arg(long)]
45    pub yarn: Option<bool>,
46
47    /// Explicit token to use instead of querying ADC or gcloud.
48    #[arg(long, env = "NODE_AUTH_TOKEN")]
49    pub token: Option<String>,
50
51    /// Allow all registry domains to attach the auth token to (not only *-npm.pkg.dev).
52    #[arg(long)]
53    pub allow_all_domains: bool,
54
55    /// Print verbose output during execution.
56    #[arg(short = 'v', long = "verbose")]
57    pub verbose: bool,
58
59    /// Only retrieve and print the access token to stdout without modifying files.
60    #[arg(long)]
61    pub print_token: bool,
62}
63
64impl std::fmt::Debug for Cli {
65    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66        formatter
67            .debug_struct("Cli")
68            .field("repo_config", &self.repo_config)
69            .field("credential_config", &self.credential_config)
70            .field("local_credential", &self.local_credential)
71            .field("repo_config_yarn", &self.repo_config_yarn)
72            .field("credential_config_yarn", &self.credential_config_yarn)
73            .field("yarn", &self.yarn)
74            .field("token", &self.token.as_ref().map(|_| "[redacted]"))
75            .field("allow_all_domains", &self.allow_all_domains)
76            .field("verbose", &self.verbose)
77            .field("print_token", &self.print_token)
78            .finish()
79    }
80}
81
82impl Cli {
83    /// Converts the parsed CLI arguments into library execution [`Options`].
84    pub fn to_options(&self) -> Options {
85        Options {
86            repo_config: self.repo_config.clone(),
87            credential_config: self.credential_config.clone(),
88            repo_config_yarn: self.repo_config_yarn.clone(),
89            credential_config_yarn: self.credential_config_yarn.clone(),
90            local_credential: self.local_credential,
91            token: self.token.clone(),
92            allow_all_domains: self.allow_all_domains,
93            yarn: self.yarn,
94            print_token: self.print_token,
95        }
96    }
97}
98
99/// Parse arguments, run the library, and present the result for either binary.
100pub async fn execute() -> ExitCode {
101    let cli = Cli::parse();
102    logger::init(cli.verbose);
103    match run(&cli.to_options()).await {
104        Ok(outcome) => {
105            logger::present_outcome(outcome);
106            ExitCode::SUCCESS
107        }
108        Err(error) => {
109            logger::present_error(&error);
110            ExitCode::FAILURE
111        }
112    }
113}
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118
119    #[test]
120    fn test_cli_verbose_flags() {
121        let cli_short = Cli::try_parse_from(["node-auth", "-v"]).unwrap();
122        assert!(cli_short.verbose);
123
124        let cli_long = Cli::try_parse_from(["node-auth", "--verbose"]).unwrap();
125        assert!(cli_long.verbose);
126
127        let cli_default = Cli::try_parse_from(["node-auth"]).unwrap();
128        assert!(!cli_default.verbose);
129    }
130
131    #[test]
132    fn test_cli_local_credential_flags() {
133        let cli_short = Cli::try_parse_from(["node-auth", "-l"]).unwrap();
134        assert!(cli_short.local_credential);
135
136        let cli_long = Cli::try_parse_from(["node-auth", "--local-credential"]).unwrap();
137        assert!(cli_long.local_credential);
138    }
139
140    #[test]
141    fn test_cli_print_token_flag() {
142        let cli =
143            Cli::try_parse_from(["node-auth", "--print-token", "--token", "custom-token"]).unwrap();
144        assert!(cli.print_token);
145        assert_eq!(cli.token.as_deref(), Some("custom-token"));
146    }
147
148    #[test]
149    fn test_cli_to_options() {
150        let cli = Cli::try_parse_from(["node-auth", "-v", "-l", "--token", "tok"]).unwrap();
151        let options = cli.to_options();
152        assert!(cli.verbose);
153        assert!(options.local_credential);
154        assert_eq!(options.token.as_deref(), Some("tok"));
155    }
156
157    #[test]
158    fn test_debug_redacts_tokens() {
159        let cli = Cli::try_parse_from(["node-auth", "--token", "super-secret-token"]).unwrap();
160        let cli_debug = format!("{cli:?}");
161        assert!(cli_debug.contains("[redacted]"));
162        assert!(!cli_debug.contains("super-secret-token"));
163
164        let options_debug = format!("{:?}", cli.to_options());
165        assert!(options_debug.contains("[redacted]"));
166        assert!(!options_debug.contains("super-secret-token"));
167    }
168}