Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Include aliases with other commands #9764

Merged
merged 1 commit into from
Aug 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/bin/cargo/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,9 @@ Run with 'cargo -Z [FLAG] [SUBCOMMAND]'",
drop_println!(config, " {}", name);
}
}
CommandInfo::Alias { name, target } => {
drop_println!(config, " {:<20} {}", name, target.iter().join(" "));
}
}
}
return Ok(());
Expand Down
25 changes: 13 additions & 12 deletions src/bin/cargo/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#![warn(clippy::redundant_clone)]

use cargo::core::shell::Shell;
use cargo::util::toml::StringOrVec;
use cargo::util::CliError;
use cargo::util::{self, closest_msg, command_prelude, CargoResult, CliResult, Config};
use cargo_util::{ProcessBuilder, ProcessError};
Expand Down Expand Up @@ -127,15 +128,17 @@ fn list_commands(config: &Config) -> BTreeSet<CommandInfo> {
});
}

commands
}

/// List all runnable aliases
fn list_aliases(config: &Config) -> Vec<String> {
match config.get::<BTreeMap<String, String>>("alias") {
Ok(aliases) => aliases.keys().map(|a| a.to_string()).collect(),
Err(_) => Vec::new(),
// Add the user-defined aliases
if let Ok(aliases) = config.get::<BTreeMap<String, StringOrVec>>("alias") {
for (name, target) in aliases.iter() {
commands.insert(CommandInfo::Alias {
name: name.to_string(),
target: target.clone(),
});
}
}

commands
}

fn execute_external_subcommand(config: &Config, cmd: &str, args: &[&str]) -> CliResult {
Expand All @@ -147,13 +150,11 @@ fn execute_external_subcommand(config: &Config, cmd: &str, args: &[&str]) -> Cli
let command = match path {
Some(command) => command,
None => {
let commands: Vec<String> = list_commands(config)
let suggestions: Vec<_> = list_commands(config)
.iter()
.map(|c| c.name().to_string())
.collect();
let aliases = list_aliases(config);
let suggestions = commands.iter().chain(aliases.iter());
let did_you_mean = closest_msg(cmd, suggestions, |c| c);
let did_you_mean = closest_msg(cmd, suggestions.iter(), |c| c);
let err = anyhow::format_err!("no such subcommand: `{}`{}", cmd, did_you_mean);
return Err(CliError::new(err, 101));
}
Expand Down
7 changes: 5 additions & 2 deletions src/cargo/util/command_prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@ use crate::sources::CRATES_IO_REGISTRY;
use crate::util::important_paths::find_root_manifest_for_wd;
use crate::util::interning::InternedString;
use crate::util::restricted_names::is_glob_pattern;
use crate::util::toml::{StringOrVec, TomlProfile};
use crate::util::validate_package_name;
use crate::util::{
print_available_benches, print_available_binaries, print_available_examples,
print_available_packages, print_available_tests,
};
use crate::util::{toml::TomlProfile, validate_package_name};
use crate::CargoResult;
use anyhow::bail;
use cargo_util::paths;
Expand Down Expand Up @@ -715,17 +716,19 @@ pub fn values_os(args: &ArgMatches<'_>, name: &str) -> Vec<OsString> {
args._values_of_os(name)
}

#[derive(PartialEq, PartialOrd, Eq, Ord)]
#[derive(PartialEq, Eq, PartialOrd, Ord)]
pub enum CommandInfo {
BuiltIn { name: String, about: Option<String> },
External { name: String, path: PathBuf },
Alias { name: String, target: StringOrVec },
}

impl CommandInfo {
pub fn name(&self) -> &str {
match self {
CommandInfo::BuiltIn { name, .. } => name,
CommandInfo::External { name, .. } => name,
CommandInfo::Alias { name, .. } => name,
}
}
}
10 changes: 9 additions & 1 deletion src/cargo/util/toml/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -760,7 +760,9 @@ impl TomlProfile {
}
}

#[derive(Clone, Debug, Serialize, Eq, PartialEq)]
/// A StringOrVec can be parsed from either a TOML string or array,
/// but is always stored as a vector.
#[derive(Clone, Debug, Serialize, Eq, PartialEq, PartialOrd, Ord)]
pub struct StringOrVec(Vec<String>);

impl<'de> de::Deserialize<'de> for StringOrVec {
Expand Down Expand Up @@ -797,6 +799,12 @@ impl<'de> de::Deserialize<'de> for StringOrVec {
}
}

impl StringOrVec {
pub fn iter<'a>(&'a self) -> std::slice::Iter<'a, String> {
self.0.iter()
}
}

#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
#[serde(untagged, expecting = "expected a boolean or a string")]
pub enum StringOrBool {
Expand Down
23 changes: 21 additions & 2 deletions tests/testsuite/cargo_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use std::str;
use cargo_test_support::cargo_process;
use cargo_test_support::paths;
use cargo_test_support::registry::Package;
use cargo_test_support::{basic_bin_manifest, basic_manifest, cargo_exe, project};
use cargo_test_support::{basic_bin_manifest, basic_manifest, cargo_exe, project, project_in_home};

fn path() -> Vec<PathBuf> {
env::split_paths(&env::var_os("PATH").unwrap_or_default()).collect()
Expand All @@ -32,7 +32,7 @@ fn list_commands_with_descriptions() {
}

#[cargo_test]
fn list_aliases_with_descriptions() {
fn list_builtin_aliases_with_descriptions() {
let p = project().build();
p.cargo("--list")
.with_stdout_contains(" b alias: build")
Expand All @@ -42,6 +42,25 @@ fn list_aliases_with_descriptions() {
.run();
}

#[cargo_test]
fn list_custom_aliases_with_descriptions() {
let p = project_in_home("proj")
.file(
&paths::home().join(".cargo").join("config"),
r#"
[alias]
myaliasstr = "foo --bar"
myaliasvec = ["foo", "--bar"]
"#,
)
.build();

p.cargo("--list")
.with_stdout_contains(" myaliasstr foo --bar")
.with_stdout_contains(" myaliasvec foo --bar")
.run();
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice! Lgtm!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you so much! On projects where I am a maintainer I really appreciate other contributors looking at PRs, and I bet the cargo maintainers do too.

#[cargo_test]
fn list_command_looks_at_path() {
let proj = project()
Expand Down