Skip to content

Commit

Permalink
fix: invalid .expect when parsing args with intro of pop install comm…
Browse files Browse the repository at this point in the history
…and (#187)
  • Loading branch information
peterwht authored May 22, 2024
1 parent 047bee3 commit 422b9b0
Showing 1 changed file with 33 additions and 8 deletions.
41 changes: 33 additions & 8 deletions crates/pop-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use commands::*;
use pop_telemetry::{config_file_path, record_cli_command, record_cli_used, Telemetry};
use serde_json::{json, Value};
#[cfg(feature = "parachain")]
use std::{fs::create_dir_all, path::PathBuf};
use std::{env::args, fs::create_dir_all, path::PathBuf};

#[derive(Parser)]
#[command(author, version, about, styles=style::get_styles())]
Expand Down Expand Up @@ -113,17 +113,18 @@ async fn main() -> Result<()> {
#[cfg(feature = "telemetry")]
if let Some(tel) = maybe_tel.clone() {
// `args` is guaranteed to have at least 3 elements as clap will display help message if not set.
let args: Vec<_> = std::env::args().collect();
let command = args.get(1).expect("expected command missing");
let subcommand = args.get(2).expect("expected sub-command missing");
let (command, subcommand) = parse_args(args().collect());

if let Ok(sub_data) = &res {
// Best effort to send on first try, no action if failure.
let _ =
record_cli_command(tel.clone(), command, json!({subcommand: sub_data.to_string()}))
.await;
let _ = record_cli_command(
tel.clone(),
&command,
json!({&subcommand: sub_data.to_string()}),
)
.await;
} else {
let _ = record_cli_command(tel, "error", json!({command: subcommand})).await;
let _ = record_cli_command(tel, "error", json!({&command: &subcommand})).await;
}
}

Expand Down Expand Up @@ -157,6 +158,14 @@ fn init() -> Result<Option<Telemetry>> {
Ok(maybe_tel)
}

fn parse_args(args: Vec<String>) -> (String, String) {
// command is always present as clap will print help if not set
let command = args.get(1).expect("expected command missing").to_string();
// subcommand may not exist
let subcommand = args.get(2).unwrap_or(&"".to_string()).to_string();
(command.clone(), subcommand.clone())
}

#[cfg(test)]
mod tests {
use super::*;
Expand All @@ -174,4 +183,20 @@ mod tests {
assert_eq!(path.file_name().unwrap().to_str().unwrap().to_string(), "pop");
Ok(())
}

#[test]
fn parse_args_works() {
for args in vec![
vec!["pop", "install"],
vec!["pop", "new", "parachain"],
vec!["pop", "new", "parachain", "extra"],
] {
// map args<&str> to args<String>
let (command, subcommand) = parse_args(args.iter().map(|s| s.to_string()).collect());
assert_eq!(command, args[1]);
if args.len() > 2 {
assert_eq!(subcommand, args[2]);
}
}
}
}

0 comments on commit 422b9b0

Please sign in to comment.