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  logger::init(cli.verbose);
154  if let Some(Command::Configure {
155    manager: ConfigureManager::Pnpm {
156      repo_config,
157      token_helper,
158    },
159  }) = &cli.command
160  {
161    return match crate::pnpm::configure(repo_config.as_deref(), token_helper.as_deref()) {
162      Ok((path, changed)) => {
163        println!(
164          "{} pnpm authentication: {}",
165          if changed {
166            "Configured"
167          } else {
168            "Already configured"
169          },
170          path.display()
171        );
172        ExitCode::SUCCESS
173      }
174      Err(error) => {
175        logger::present_error(&error);
176        ExitCode::FAILURE
177      }
178    };
179  }
180  match run(&cli.to_options()).await {
181    Ok(outcome) => {
182      logger::present_outcome(outcome);
183      ExitCode::SUCCESS
184    }
185    Err(error) => {
186      logger::present_error(&error);
187      ExitCode::FAILURE
188    }
189  }
190}
191
192#[cfg(test)]
193mod tests {
194  use super::*;
195
196  #[test]
197  fn test_cli_verbose_flags() {
198    let cli_short = Cli::try_parse_from(["node-auth", "-v"]).unwrap();
199    assert!(cli_short.verbose);
200
201    let cli_long = Cli::try_parse_from(["node-auth", "--verbose"]).unwrap();
202    assert!(cli_long.verbose);
203
204    let cli_default = Cli::try_parse_from(["node-auth"]).unwrap();
205    assert!(!cli_default.verbose);
206  }
207
208  #[test]
209  fn test_cli_local_credential_flags() {
210    let cli_short = Cli::try_parse_from(["node-auth", "-l"]).unwrap();
211    assert!(cli_short.local_credential);
212
213    let cli_long = Cli::try_parse_from(["node-auth", "--local-credential"]).unwrap();
214    assert!(cli_long.local_credential);
215  }
216
217  #[test]
218  fn test_cli_print_token_flag() {
219    let cli =
220      Cli::try_parse_from(["node-auth", "--print-token", "--token", "custom-token"]).unwrap();
221    assert!(cli.print_token);
222    assert_eq!(cli.token.as_deref(), Some("custom-token"));
223  }
224
225  #[test]
226  fn test_cli_bun_flags() {
227    let cli = Cli::try_parse_from([
228      "node-auth",
229      "--bun",
230      "true",
231      "--repo-config-bun",
232      "custom-bunfig.toml",
233      "--bun-env",
234    ])
235    .unwrap();
236    assert_eq!(cli.bun, Some(true));
237    assert_eq!(
238      cli.repo_config_bun.as_deref(),
239      Some(std::path::Path::new("custom-bunfig.toml"))
240    );
241    assert!(cli.bun_env);
242
243    assert!(Cli::try_parse_from(["node-auth", "--bun-env", "--local-credential"]).is_err());
244  }
245
246  #[test]
247  fn test_cli_to_options() {
248    let cli = Cli::try_parse_from(["node-auth", "-v", "-l", "--token", "tok"]).unwrap();
249    let options = cli.to_options();
250    assert!(cli.verbose);
251    assert!(options.local_credential);
252    assert_eq!(options.token.as_deref(), Some("tok"));
253  }
254
255  #[test]
256  fn test_debug_redacts_tokens() {
257    let cli = Cli::try_parse_from(["node-auth", "--token", "super-secret-token"]).unwrap();
258    let cli_debug = format!("{cli:?}");
259    assert!(cli_debug.contains("[redacted]"));
260    assert!(!cli_debug.contains("super-secret-token"));
261
262    let options_debug = format!("{:?}", cli.to_options());
263    assert!(options_debug.contains("[redacted]"));
264    assert!(!options_debug.contains("super-secret-token"));
265  }
266}