Skip to content

Commit 8ccf90f

Browse files
committed
refactor(cli): Make help behave like other subcommands
Before, we had hacks to intercept raw arguments and to intercept clap errors and assume what their intention was to be able to implement our help system. This flips it around and makes help like any other subcommand, simplifying cargo initialization.
1 parent 4ed54ce commit 8ccf90f

File tree

4 files changed

+25
-64
lines changed

4 files changed

+25
-64
lines changed

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ toml_edit = { version = "0.14.3", features = ["serde", "easy", "perf"] }
6161
unicode-xid = "0.2.0"
6262
url = "2.2.2"
6363
walkdir = "2.2"
64-
clap = "3.2.1"
64+
clap = "3.2.18"
6565
unicode-width = "0.1.5"
6666
openssl = { version = '0.10.11', optional = true }
6767
im-rc = "15.0.0"

src/bin/cargo/cli.rs

Lines changed: 5 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,7 @@
11
use anyhow::anyhow;
22
use cargo::core::{features, CliUnstable};
33
use cargo::{self, drop_print, drop_println, CliResult, Config};
4-
use clap::{
5-
error::{ContextKind, ContextValue},
6-
AppSettings, Arg, ArgMatches,
7-
};
4+
use clap::{AppSettings, Arg, ArgMatches};
85
use itertools::Itertools;
96
use std::collections::HashMap;
107
use std::fmt::Write;
@@ -29,31 +26,7 @@ pub fn main(config: &mut Config) -> CliResult {
2926
// In general, try to avoid loading config values unless necessary (like
3027
// the [alias] table).
3128

32-
if commands::help::handle_embedded_help(config) {
33-
return Ok(());
34-
}
35-
36-
let args = match cli().try_get_matches() {
37-
Ok(args) => args,
38-
Err(e) => {
39-
if e.kind() == clap::ErrorKind::UnrecognizedSubcommand {
40-
// An unrecognized subcommand might be an external subcommand.
41-
let cmd = e
42-
.context()
43-
.find_map(|c| match c {
44-
(ContextKind::InvalidSubcommand, &ContextValue::String(ref cmd)) => {
45-
Some(cmd)
46-
}
47-
_ => None,
48-
})
49-
.expect("UnrecognizedSubcommand implies the presence of InvalidSubcommand");
50-
return super::execute_external_subcommand(config, cmd, &[cmd, "--help"])
51-
.map_err(|_| e.into());
52-
} else {
53-
return Err(e.into());
54-
}
55-
}
56-
};
29+
let args = cli().try_get_matches()?;
5730

5831
// Global args need to be extracted before expanding aliases because the
5932
// clap code for extracting a subcommand discards global options
@@ -412,7 +385,7 @@ impl GlobalArgs {
412385
}
413386
}
414387

415-
fn cli() -> App {
388+
pub fn cli() -> App {
416389
let is_rustup = std::env::var_os("RUSTUP_HOME").is_some();
417390
let usage = if is_rustup {
418391
"cargo [+toolchain] [OPTIONS] [SUBCOMMAND]"
@@ -425,6 +398,8 @@ fn cli() -> App {
425398
// Doesn't mix well with our list of common cargo commands. See clap-rs/clap#3108 for
426399
// opening clap up to allow us to style our help template
427400
.disable_colored_help(true)
401+
// Provide a custom help subcommand for calling into man pages
402+
.disable_help_subcommand(true)
428403
.override_usage(usage)
429404
.help_template(
430405
"\

src/bin/cargo/commands/help.rs

Lines changed: 17 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use crate::aliased_command;
2+
use crate::command_prelude::*;
23
use cargo::util::errors::CargoResult;
34
use cargo::{drop_println, Config};
45
use cargo_util::paths::resolve_executable;
@@ -10,43 +11,26 @@ use std::path::Path;
1011

1112
const COMPRESSED_MAN: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/man.tgz"));
1213

13-
/// Checks if the `help` command is being issued.
14-
///
15-
/// This runs before clap processing, because it needs to intercept the `help`
16-
/// command if a man page is available.
17-
///
18-
/// Returns `true` if help information was successfully displayed to the user.
19-
/// In this case, Cargo should exit.
20-
pub fn handle_embedded_help(config: &Config) -> bool {
21-
match try_help(config) {
22-
Ok(true) => true,
23-
Ok(false) => false,
24-
Err(e) => {
25-
log::warn!("help failed: {:?}", e);
26-
false
27-
}
28-
}
14+
pub fn cli() -> App {
15+
subcommand("help")
16+
.about("Displays help for a cargo subcommand")
17+
.arg(Arg::new("SUBCOMMAND"))
2918
}
3019

31-
fn try_help(config: &Config) -> CargoResult<bool> {
32-
let mut args = std::env::args_os()
33-
.skip(1)
34-
.skip_while(|arg| arg.to_str().map_or(false, |s| s.starts_with('-')));
35-
if !args
36-
.next()
37-
.map_or(false, |arg| arg.to_str() == Some("help"))
38-
{
39-
return Ok(false);
20+
pub fn exec(config: &mut Config, args: &ArgMatches) -> CliResult {
21+
let subcommand = args.get_one::<String>("SUBCOMMAND");
22+
if let Some(subcommand) = subcommand {
23+
if !try_help(config, subcommand)? {
24+
crate::execute_external_subcommand(config, subcommand, &[subcommand, "--help"])?;
25+
}
26+
} else {
27+
let mut cmd = crate::cli::cli();
28+
let _ = cmd.print_help();
4029
}
41-
let subcommand = match args.next() {
42-
Some(arg) => arg,
43-
None => return Ok(false),
44-
};
45-
let subcommand = match subcommand.to_str() {
46-
Some(s) => s,
47-
None => return Ok(false),
48-
};
30+
Ok(())
31+
}
4932

33+
fn try_help(config: &Config, subcommand: &str) -> CargoResult<bool> {
5034
let subcommand = match check_alias(config, subcommand) {
5135
// If this alias is more than a simple subcommand pass-through, show the alias.
5236
Some(argv) if argv.len() > 1 => {

src/bin/cargo/commands/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ pub fn builtin() -> Vec<App> {
1111
doc::cli(),
1212
fetch::cli(),
1313
fix::cli(),
14+
help::cli(),
1415
generate_lockfile::cli(),
1516
git_checkout::cli(),
1617
init::cli(),
@@ -52,6 +53,7 @@ pub fn builtin_exec(cmd: &str) -> Option<fn(&mut Config, &ArgMatches) -> CliResu
5253
"doc" => doc::exec,
5354
"fetch" => fetch::exec,
5455
"fix" => fix::exec,
56+
"help" => help::exec,
5557
"generate-lockfile" => generate_lockfile::exec,
5658
"git-checkout" => git_checkout::exec,
5759
"init" => init::exec,

0 commit comments

Comments
 (0)