From 1a226c9c2b7cf215909e2241ab9eb97d443d47c1 Mon Sep 17 00:00:00 2001 From: cat_in_136 Date: Sun, 2 Jun 2024 14:24:50 +0900 Subject: [PATCH] refactor of moving cargo wrapper handling to src/cli.rs --- src/cli.rs | 26 ++++++++++++++++++++++---- src/main.rs | 11 ++--------- 2 files changed, 24 insertions(+), 13 deletions(-) diff --git a/src/cli.rs b/src/cli.rs index 5b1f2c1..e0391cb 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -1,6 +1,6 @@ use clap::{ builder::{PathBufValueParser, PossibleValuesParser, TypedValueParser, ValueParserFactory}, - Arg, Command, Parser, ValueEnum, + Arg, ArgMatches, Command, CommandFactory, FromArgMatches, Parser, ValueEnum, }; use std::ffi::OsStr; use std::path::PathBuf; @@ -9,7 +9,7 @@ use std::path::PathBuf; #[derive(Debug, Parser)] #[command(name = "cargo")] #[command(bin_name = "cargo")] -pub enum CargoWrapper { +enum CargoWrapper { GenerateRpm(Cli), } @@ -88,6 +88,20 @@ pub struct Cli { pub variant: Vec, } +impl Cli { + pub fn get_matches_and_try_parse() -> Result<(Self, ArgMatches), clap::Error> { + let mut args = std::env::args(); + let mut matches = if let Some("generate-rpm") = args.nth(1).as_deref() { + ::command().get_matches() + } else { + ::command().get_matches() + }; + let arg = Self::from_arg_matches_mut(&mut matches)?; + + Ok((arg, matches)) + } +} + impl Default for Cli { fn default() -> Self { Cli::parse_from([""]) @@ -176,8 +190,12 @@ mod tests { use super::*; #[test] fn verify_cli() { - use clap::CommandFactory; - Cli::command().debug_assert() + ::command().debug_assert() + } + + #[test] + fn verify_cargo_wrapper() { + ::command().debug_assert() } #[test] diff --git a/src/main.rs b/src/main.rs index 07a0b12..ada624e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,5 @@ use crate::{build_target::BuildTarget, config::BuilderConfig}; -use clap::Parser; -use cli::{CargoWrapper, Cli}; +use cli::Cli; use std::{ fs, path::{Path, PathBuf}, @@ -54,13 +53,7 @@ fn determine_output_dir( } fn run() -> Result<(), Error> { - let mut args = std::env::args(); - let args = if let Some("generate-rpm") = args.nth(1).as_deref() { - let CargoWrapper::GenerateRpm(args) = CargoWrapper::parse(); - args - } else { - Cli::parse() - }; + let (args, matcher) = Cli::get_matches_and_try_parse().unwrap_or_else(|e| e.exit()); let build_target = BuildTarget::new(&args); let extra_metadata = collect_metadata(&args);