Simplify argument parsing

This commit is contained in:
Laurențiu Nicola 2020-08-01 09:25:23 +03:00
parent a015714def
commit 562491b16b
2 changed files with 27 additions and 24 deletions

View file

@ -44,15 +44,16 @@ pub(crate) enum Command {
ProcMacro, ProcMacro,
RunServer, RunServer,
Version, Version,
Help,
} }
impl Args { impl Args {
pub(crate) fn parse() -> Result<Result<Args, HelpPrinted>> { pub(crate) fn parse() -> Result<Args> {
let mut matches = Arguments::from_env(); let mut matches = Arguments::from_env();
if matches.contains("--version") { if matches.contains("--version") {
matches.finish().or_else(handle_extra_flags)?; matches.finish().or_else(handle_extra_flags)?;
return Ok(Ok(Args { verbosity: Verbosity::Normal, command: Command::Version })); return Ok(Args { verbosity: Verbosity::Normal, command: Command::Version });
} }
let verbosity = match ( let verbosity = match (
@ -68,15 +69,16 @@ impl Args {
(false, true, true) => bail!("Invalid flags: -q conflicts with -v"), (false, true, true) => bail!("Invalid flags: -q conflicts with -v"),
}; };
let help = Ok(Args { verbosity, command: Command::Help });
let subcommand = match matches.subcommand()? { let subcommand = match matches.subcommand()? {
Some(it) => it, Some(it) => it,
None => { None => {
if matches.contains(["-h", "--help"]) { if matches.contains(["-h", "--help"]) {
print_subcommands(); print_subcommands();
return Ok(Err(HelpPrinted)); return help;
} }
matches.finish().or_else(handle_extra_flags)?; matches.finish().or_else(handle_extra_flags)?;
return Ok(Ok(Args { verbosity, command: Command::RunServer })); return Ok(Args { verbosity, command: Command::RunServer });
} }
}; };
let command = match subcommand.as_str() { let command = match subcommand.as_str() {
@ -93,7 +95,7 @@ FLAGS:
-h, --help Prints help information -h, --help Prints help information
--no-dump" --no-dump"
); );
return Ok(Err(HelpPrinted)); return help;
} }
let no_dump = matches.contains("--no-dump"); let no_dump = matches.contains("--no-dump");
@ -112,7 +114,7 @@ USAGE:
FLAGS: FLAGS:
-h, --help Prints help inforamtion" -h, --help Prints help inforamtion"
); );
return Ok(Err(HelpPrinted)); return help;
} }
matches.finish().or_else(handle_extra_flags)?; matches.finish().or_else(handle_extra_flags)?;
@ -132,7 +134,7 @@ FLAGS:
-h, --help Prints help information -h, --help Prints help information
-r, --rainbow" -r, --rainbow"
); );
return Ok(Err(HelpPrinted)); return help;
} }
let rainbow = matches.contains(["-r", "--rainbow"]); let rainbow = matches.contains(["-r", "--rainbow"]);
@ -166,7 +168,7 @@ OPTIONS:
ARGS: ARGS:
<PATH>" <PATH>"
); );
return Ok(Err(HelpPrinted)); return help;
} }
let randomize = matches.contains("--randomize"); let randomize = matches.contains("--randomize");
@ -220,7 +222,7 @@ OPTIONS:
ARGS: ARGS:
<PATH> Project to analyse" <PATH> Project to analyse"
); );
return Ok(Err(HelpPrinted)); return help;
} }
let path: PathBuf = matches.opt_value_from_str("--project")?.unwrap_or_default(); let path: PathBuf = matches.opt_value_from_str("--project")?.unwrap_or_default();
@ -266,7 +268,7 @@ FLAGS:
ARGS: ARGS:
<PATH>" <PATH>"
); );
return Ok(Err(HelpPrinted)); return help;
} }
let load_output_dirs = matches.contains("--load-output-dirs"); let load_output_dirs = matches.contains("--load-output-dirs");
@ -302,7 +304,7 @@ FLAGS:
ARGS: ARGS:
<RULE> A structured search replace rule" <RULE> A structured search replace rule"
); );
return Ok(Err(HelpPrinted)); return help;
} }
let mut rules = Vec::new(); let mut rules = Vec::new();
while let Some(rule) = matches.free_from_str()? { while let Some(rule) = matches.free_from_str()? {
@ -329,7 +331,7 @@ FLAGS:
ARGS: ARGS:
<PATTERN> A structured search pattern" <PATTERN> A structured search pattern"
); );
return Ok(Err(HelpPrinted)); return help;
} }
let debug_snippet = matches.opt_value_from_str("--debug")?; let debug_snippet = matches.opt_value_from_str("--debug")?;
let mut patterns = Vec::new(); let mut patterns = Vec::new();
@ -340,10 +342,10 @@ ARGS:
} }
_ => { _ => {
print_subcommands(); print_subcommands();
return Ok(Err(HelpPrinted)); return help;
} }
}; };
Ok(Ok(Args { verbosity, command })) Ok(Args { verbosity, command })
} }
} }
@ -371,8 +373,6 @@ SUBCOMMANDS:
) )
} }
pub(crate) struct HelpPrinted;
fn handle_extra_flags(e: pico_args::Error) -> Result<()> { fn handle_extra_flags(e: pico_args::Error) -> Result<()> {
if let pico_args::Error::UnusedArgsLeft(flags) = e { if let pico_args::Error::UnusedArgsLeft(flags) = e {
let mut invalid_flags = String::new(); let mut invalid_flags = String::new();

View file

@ -3,7 +3,7 @@
//! Based on cli flags, either spawns an LSP server, or runs a batch analysis //! Based on cli flags, either spawns an LSP server, or runs a batch analysis
mod args; mod args;
use std::convert::TryFrom; use std::{convert::TryFrom, process};
use lsp_server::Connection; use lsp_server::Connection;
use ra_project_model::ProjectManifest; use ra_project_model::ProjectManifest;
@ -14,18 +14,20 @@ use rust_analyzer::{
}; };
use vfs::AbsPathBuf; use vfs::AbsPathBuf;
use crate::args::HelpPrinted;
#[cfg(all(feature = "mimalloc"))] #[cfg(all(feature = "mimalloc"))]
#[global_allocator] #[global_allocator]
static ALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc; static ALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc;
fn main() -> Result<()> { fn main() {
if let Err(err) = try_main() {
eprintln!("{}", err);
process::exit(101);
}
}
fn try_main() -> Result<()> {
setup_logging()?; setup_logging()?;
let args = match args::Args::parse()? { let args = args::Args::parse()?;
Ok(it) => it,
Err(HelpPrinted) => return Ok(()),
};
match args.command { match args.command {
args::Command::RunServer => run_server()?, args::Command::RunServer => run_server()?,
args::Command::ProcMacro => ra_proc_macro_srv::cli::run()?, args::Command::ProcMacro => ra_proc_macro_srv::cli::run()?,
@ -45,6 +47,7 @@ fn main() -> Result<()> {
cli::search_for_patterns(patterns, debug_snippet)?; cli::search_for_patterns(patterns, debug_snippet)?;
} }
args::Command::Version => println!("rust-analyzer {}", env!("REV")), args::Command::Version => println!("rust-analyzer {}", env!("REV")),
args::Command::Help => {}
} }
Ok(()) Ok(())
} }