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 npm, yarn, pnpm, and Bun 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  /// Path to the bunfig.toml file to read registry configs from.
43  /// Defaults to project-level ./bunfig.toml.
44  #[arg(long)]
45  pub repo_config_bun: Option<PathBuf>,
46
47  /// Explicitly enable or disable updating Yarn configuration (.yarnrc.yml).
48  /// By default, Yarn is updated if .yarnrc.yml exists or is explicitly specified.
49  #[arg(long)]
50  pub yarn: Option<bool>,
51
52  /// Explicitly enable or disable reading Bun configuration (bunfig.toml).
53  /// By default, Bun is enabled if ./bunfig.toml exists or is explicitly specified.
54  #[arg(long)]
55  pub bun: Option<bool>,
56
57  /// Store Bun's token in .env.local and reference NODE_AUTH_TOKEN from bunfig.toml.
58  #[arg(long, conflicts_with = "local_credential")]
59  pub bun_env: bool,
60
61  /// Explicit token to use instead of querying ADC or gcloud.
62  #[arg(long, env = "NODE_AUTH_TOKEN")]
63  pub token: Option<String>,
64
65  /// Allow all HTTPS registry domains to receive the auth token (not only *-npm.pkg.dev).
66  #[arg(long)]
67  pub allow_all_domains: bool,
68
69  /// Print verbose output during execution.
70  #[arg(short = 'v', long = "verbose")]
71  pub verbose: bool,
72
73  /// Only retrieve and print the access token to stdout without modifying files.
74  #[arg(long)]
75  pub print_token: bool,
76}
77
78impl std::fmt::Debug for Cli {
79  fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80    formatter
81      .debug_struct("Cli")
82      .field("repo_config", &self.repo_config)
83      .field("credential_config", &self.credential_config)
84      .field("local_credential", &self.local_credential)
85      .field("repo_config_yarn", &self.repo_config_yarn)
86      .field("credential_config_yarn", &self.credential_config_yarn)
87      .field("repo_config_bun", &self.repo_config_bun)
88      .field("yarn", &self.yarn)
89      .field("bun", &self.bun)
90      .field("bun_env", &self.bun_env)
91      .field("token", &self.token.as_ref().map(|_| "[redacted]"))
92      .field("allow_all_domains", &self.allow_all_domains)
93      .field("verbose", &self.verbose)
94      .field("print_token", &self.print_token)
95      .finish()
96  }
97}
98
99impl Cli {
100  /// Converts the parsed CLI arguments into library execution [`Options`].
101  pub fn to_options(&self) -> Options {
102    Options {
103      repo_config: self.repo_config.clone(),
104      credential_config: self.credential_config.clone(),
105      repo_config_yarn: self.repo_config_yarn.clone(),
106      credential_config_yarn: self.credential_config_yarn.clone(),
107      repo_config_bun: self.repo_config_bun.clone(),
108      local_credential: self.local_credential,
109      token: self.token.clone(),
110      allow_all_domains: self.allow_all_domains,
111      yarn: self.yarn,
112      bun: self.bun,
113      bun_env: self.bun_env,
114      print_token: self.print_token,
115    }
116  }
117}
118
119/// Parse arguments, run the library, and present the result for either binary.
120pub async fn execute() -> ExitCode {
121  let cli = Cli::parse();
122  logger::init(cli.verbose);
123  match run(&cli.to_options()).await {
124    Ok(outcome) => {
125      logger::present_outcome(outcome);
126      ExitCode::SUCCESS
127    }
128    Err(error) => {
129      logger::present_error(&error);
130      ExitCode::FAILURE
131    }
132  }
133}
134
135#[cfg(test)]
136mod tests {
137  use super::*;
138
139  #[test]
140  fn test_cli_verbose_flags() {
141    let cli_short = Cli::try_parse_from(["node-auth", "-v"]).unwrap();
142    assert!(cli_short.verbose);
143
144    let cli_long = Cli::try_parse_from(["node-auth", "--verbose"]).unwrap();
145    assert!(cli_long.verbose);
146
147    let cli_default = Cli::try_parse_from(["node-auth"]).unwrap();
148    assert!(!cli_default.verbose);
149  }
150
151  #[test]
152  fn test_cli_local_credential_flags() {
153    let cli_short = Cli::try_parse_from(["node-auth", "-l"]).unwrap();
154    assert!(cli_short.local_credential);
155
156    let cli_long = Cli::try_parse_from(["node-auth", "--local-credential"]).unwrap();
157    assert!(cli_long.local_credential);
158  }
159
160  #[test]
161  fn test_cli_print_token_flag() {
162    let cli =
163      Cli::try_parse_from(["node-auth", "--print-token", "--token", "custom-token"]).unwrap();
164    assert!(cli.print_token);
165    assert_eq!(cli.token.as_deref(), Some("custom-token"));
166  }
167
168  #[test]
169  fn test_cli_bun_flags() {
170    let cli = Cli::try_parse_from([
171      "node-auth",
172      "--bun",
173      "true",
174      "--repo-config-bun",
175      "custom-bunfig.toml",
176      "--bun-env",
177    ])
178    .unwrap();
179    assert_eq!(cli.bun, Some(true));
180    assert_eq!(
181      cli.repo_config_bun.as_deref(),
182      Some(std::path::Path::new("custom-bunfig.toml"))
183    );
184    assert!(cli.bun_env);
185
186    assert!(Cli::try_parse_from(["node-auth", "--bun-env", "--local-credential"]).is_err());
187  }
188
189  #[test]
190  fn test_cli_to_options() {
191    let cli = Cli::try_parse_from(["node-auth", "-v", "-l", "--token", "tok"]).unwrap();
192    let options = cli.to_options();
193    assert!(cli.verbose);
194    assert!(options.local_credential);
195    assert_eq!(options.token.as_deref(), Some("tok"));
196  }
197
198  #[test]
199  fn test_debug_redacts_tokens() {
200    let cli = Cli::try_parse_from(["node-auth", "--token", "super-secret-token"]).unwrap();
201    let cli_debug = format!("{cli:?}");
202    assert!(cli_debug.contains("[redacted]"));
203    assert!(!cli_debug.contains("super-secret-token"));
204
205    let options_debug = format!("{:?}", cli.to_options());
206    assert!(options_debug.contains("[redacted]"));
207    assert!(!options_debug.contains("super-secret-token"));
208  }
209}