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, Subcommand};
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  args_conflicts_with_subcommands = true
16)]
17pub struct Cli {
18  /// Configure dynamic package-manager authentication.
19  #[command(subcommand)]
20  pub command: Option<Command>,
21
22  /// Path to the .npmrc file to read registry configs from.
23  /// Defaults to project-level .npmrc if present, otherwise user-level ~/.npmrc.
24  #[arg(long, env = "NODE_AUTH_REPO_CONFIG")]
25  pub repo_config: Option<PathBuf>,
26
27  /// Path to the .npmrc file to write credentials to.
28  /// Defaults to user-level ~/.npmrc.
29  #[arg(long, env = "NODE_AUTH_CREDENTIAL_CONFIG")]
30  pub credential_config: Option<PathBuf>,
31
32  /// Forces writing credentials to the current directory's .npmrc (creating it if missing).
33  /// Emits a warning if running in a Git repository without .npmrc in .gitignore.
34  #[arg(short = 'l', long)]
35  pub local_credential: bool,
36
37  /// Path to the .yarnrc.yml file to read registry configs from.
38  /// Defaults to project-level .yarnrc.yml if present, otherwise user-level ~/.yarnrc.yml.
39  #[arg(long)]
40  pub repo_config_yarn: Option<PathBuf>,
41
42  /// Path to the .yarnrc.yml file to write credentials to.
43  /// Defaults to user-level ~/.yarnrc.yml.
44  #[arg(long)]
45  pub credential_config_yarn: Option<PathBuf>,
46
47  /// Path to the bunfig.toml file to read registry configs from.
48  /// Defaults to project-level ./bunfig.toml.
49  #[arg(long)]
50  pub repo_config_bun: Option<PathBuf>,
51
52  /// Explicitly enable or disable updating Yarn configuration (.yarnrc.yml).
53  /// By default, Yarn is updated if .yarnrc.yml exists or is explicitly specified.
54  #[arg(long)]
55  pub yarn: Option<bool>,
56
57  /// Explicitly enable or disable reading Bun configuration (bunfig.toml).
58  /// By default, Bun is enabled if ./bunfig.toml exists or is explicitly specified.
59  #[arg(long)]
60  pub bun: Option<bool>,
61
62  /// Store Bun's token in .env.local and reference NODE_AUTH_TOKEN from bunfig.toml.
63  #[arg(long, conflicts_with = "local_credential")]
64  pub bun_env: bool,
65
66  /// Explicit token to use instead of querying ADC or gcloud.
67  #[arg(long, env = "NODE_AUTH_TOKEN")]
68  pub token: Option<String>,
69
70  /// Allow all HTTPS registry domains to receive the auth token (not only *-npm.pkg.dev).
71  #[arg(long)]
72  pub allow_all_domains: bool,
73
74  /// Print verbose output during execution.
75  #[arg(short = 'v', long = "verbose")]
76  pub verbose: bool,
77
78  /// Only retrieve and print the access token to stdout without modifying files.
79  #[arg(long)]
80  pub print_token: bool,
81}
82
83/// Optional configuration commands; existing flag-only invocations retain their behavior.
84#[derive(Subcommand, Clone, Debug, PartialEq, Eq)]
85pub enum Command {
86  /// Configure dynamic authentication without retrieving or writing access tokens.
87  Configure {
88    /// Package manager to configure.
89    #[command(subcommand)]
90    manager: ConfigureManager,
91  },
92}
93
94/// Supported native package-manager integrations.
95#[derive(Subcommand, Clone, Debug, PartialEq, Eq)]
96pub enum ConfigureManager {
97  /// Set GAR token helpers in pnpm's trusted user auth.ini (pnpm >=11.13.0).
98  Pnpm {
99    /// Additional .npmrc file to discover GAR registry definitions from.
100    #[arg(long)]
101    repo_config: Option<PathBuf>,
102    /// Installed node-auth-token executable (defaults to sibling, then absolute PATH).
103    #[arg(long)]
104    token_helper: Option<PathBuf>,
105  },
106}
107
108impl std::fmt::Debug for Cli {
109  fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110    formatter
111      .debug_struct("Cli")
112      .field("command", &self.command)
113      .field("repo_config", &self.repo_config)
114      .field("credential_config", &self.credential_config)
115      .field("local_credential", &self.local_credential)
116      .field("repo_config_yarn", &self.repo_config_yarn)
117      .field("credential_config_yarn", &self.credential_config_yarn)
118      .field("repo_config_bun", &self.repo_config_bun)
119      .field("yarn", &self.yarn)
120      .field("bun", &self.bun)
121      .field("bun_env", &self.bun_env)
122      .field("token", &self.token.as_ref().map(|_| "[redacted]"))
123      .field("allow_all_domains", &self.allow_all_domains)
124      .field("verbose", &self.verbose)
125      .field("print_token", &self.print_token)
126      .finish()
127  }
128}
129
130impl Cli {
131  /// Converts the parsed CLI arguments into library execution [`Options`].
132  pub fn to_options(&self) -> Options {
133    Options {
134      repo_config: self.repo_config.clone(),
135      credential_config: self.credential_config.clone(),
136      repo_config_yarn: self.repo_config_yarn.clone(),
137      credential_config_yarn: self.credential_config_yarn.clone(),
138      repo_config_bun: self.repo_config_bun.clone(),
139      local_credential: self.local_credential,
140      token: self.token.clone(),
141      allow_all_domains: self.allow_all_domains,
142      yarn: self.yarn,
143      bun: self.bun,
144      bun_env: self.bun_env,
145      print_token: self.print_token,
146    }
147  }
148}
149
150/// Parse arguments, run the library, and present the result for either binary.
151pub async fn execute() -> ExitCode {
152  let cli = Cli::parse();
153
154  logger::init(cli.verbose);
155
156  if let Some(Command::Configure {
157    manager: ConfigureManager::Pnpm {
158      repo_config,
159      token_helper,
160    },
161  }) = &cli.command
162  {
163    return match crate::pnpm::configure(repo_config.as_deref(), token_helper.as_deref()) {
164      Ok((path, changed)) => {
165        println!(
166          "{} pnpm authentication: {}",
167          if changed {
168            "Configured"
169          } else {
170            "Already configured"
171          },
172          path.display()
173        );
174        ExitCode::SUCCESS
175      }
176      Err(error) => {
177        logger::present_error(&error);
178        ExitCode::FAILURE
179      }
180    };
181  }
182
183  match run(&cli.to_options()).await {
184    Ok(outcome) => {
185      logger::present_outcome(outcome);
186      ExitCode::SUCCESS
187    }
188    Err(error) => {
189      logger::present_error(&error);
190      ExitCode::FAILURE
191    }
192  }
193}
194
195#[cfg(test)]
196mod tests {
197  use super::*;
198
199  #[test]
200  fn test_cli_verbose_flags() {
201    let cli_short = Cli::try_parse_from(["node-auth", "-v"]).unwrap();
202    assert!(cli_short.verbose);
203
204    let cli_long = Cli::try_parse_from(["node-auth", "--verbose"]).unwrap();
205    assert!(cli_long.verbose);
206
207    let cli_default = Cli::try_parse_from(["node-auth"]).unwrap();
208    assert!(!cli_default.verbose);
209  }
210
211  #[test]
212  fn test_cli_local_credential_flags() {
213    let cli_short = Cli::try_parse_from(["node-auth", "-l"]).unwrap();
214    assert!(cli_short.local_credential);
215
216    let cli_long = Cli::try_parse_from(["node-auth", "--local-credential"]).unwrap();
217    assert!(cli_long.local_credential);
218  }
219
220  #[test]
221  fn test_cli_print_token_flag() {
222    let cli =
223      Cli::try_parse_from(["node-auth", "--print-token", "--token", "custom-token"]).unwrap();
224    assert!(cli.print_token);
225    assert_eq!(cli.token.as_deref(), Some("custom-token"));
226  }
227
228  #[test]
229  fn test_cli_bun_flags() {
230    let cli = Cli::try_parse_from([
231      "node-auth",
232      "--bun",
233      "true",
234      "--repo-config-bun",
235      "custom-bunfig.toml",
236      "--bun-env",
237    ])
238    .unwrap();
239    assert_eq!(cli.bun, Some(true));
240    assert_eq!(
241      cli.repo_config_bun.as_deref(),
242      Some(std::path::Path::new("custom-bunfig.toml"))
243    );
244    assert!(cli.bun_env);
245
246    assert!(Cli::try_parse_from(["node-auth", "--bun-env", "--local-credential"]).is_err());
247  }
248
249  #[test]
250  fn test_cli_to_options() {
251    let cli = Cli::try_parse_from(["node-auth", "-v", "-l", "--token", "tok"]).unwrap();
252    let options = cli.to_options();
253    assert!(cli.verbose);
254    assert!(options.local_credential);
255    assert_eq!(options.token.as_deref(), Some("tok"));
256  }
257
258  #[test]
259  fn test_debug_redacts_tokens() {
260    let cli = Cli::try_parse_from(["node-auth", "--token", "super-secret-token"]).unwrap();
261    let cli_debug = format!("{cli:?}");
262    assert!(cli_debug.contains("[redacted]"));
263    assert!(!cli_debug.contains("super-secret-token"));
264
265    let options_debug = format!("{:?}", cli.to_options());
266    assert!(options_debug.contains("[redacted]"));
267    assert!(!options_debug.contains("super-secret-token"));
268  }
269}