Skip to content

Commit 59d75c2

Browse files
committed
feat: allow unambiguous command shorthands
Allow invoking StGit commands, aliases, and subcommands using any unambiguous prefix (for example, `stg del` for `stg delete`, `stg ser` for `stg series`, or `stg em s` for `stg email send`), matching StGit 1.x behavior. Enable `infer_subcommands(true)` on the base clap Command so clap accepts unambiguous prefixes for top-level and nested subcommands. Because the initial bootstrap CLI parser uses `allow_external_subcommands(true)` to avoid constructing the full command graph up front, also resolve subcommand prefixes across built-in commands, `help`, and configured aliases: - Exact matches on built-in commands, `help`, or aliases always take precedence over prefix matches. - Non-exact prefixes are checked against built-in commands, `help`, and aliases together so that a prefix shared between a built-in command and an alias (such as `res` for `reset` and `resolved`) is rejected as ambiguous. Signed-off-by: Dmitry Torokhov <dtor@google.com>
1 parent faa026a commit 59d75c2

4 files changed

Lines changed: 150 additions & 20 deletions

File tree

‎src/main.rs‎

Lines changed: 115 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ fn get_base_command(color_choice: Option<termcolor::ColorChoice>) -> clap::Comma
6262
],
6363
))
6464
.help_expected(true)
65+
.infer_subcommands(true)
6566
.max_term_width(88)
6667
.disable_version_flag(true)
6768
.arg(
@@ -140,6 +141,44 @@ pub(crate) fn get_full_command(
140141
.subcommands(aliases.values().map(alias::Alias::make))
141142
}
142143

144+
enum Subcommand<'a> {
145+
Command(&'static cmd::StGitCommand),
146+
Alias(&'a alias::Alias),
147+
Help,
148+
}
149+
150+
/// Find a command, alias, or `"help"` matching `sub_name` exactly or as an
151+
/// unambiguous prefix.
152+
fn find_subcommand<'a>(sub_name: &str, aliases: &'a alias::Aliases) -> Option<Subcommand<'a>> {
153+
if let Some(command) = STGIT_COMMANDS
154+
.iter()
155+
.find(|command| command.name == sub_name)
156+
{
157+
return Some(Subcommand::Command(command));
158+
} else if sub_name == "help" {
159+
return Some(Subcommand::Help);
160+
} else if let Some(alias) = aliases.get(sub_name) {
161+
return Some(Subcommand::Alias(alias));
162+
}
163+
164+
let mut candidates = STGIT_COMMANDS
165+
.iter()
166+
.filter(|command| command.name.starts_with(sub_name))
167+
.map(Subcommand::Command)
168+
.chain(
169+
aliases
170+
.values()
171+
.filter(|alias| alias.name.starts_with(sub_name))
172+
.map(Subcommand::Alias),
173+
)
174+
.chain("help".starts_with(sub_name).then_some(Subcommand::Help));
175+
176+
match (candidates.next(), candidates.next()) {
177+
(Some(subcommand), None) => Some(subcommand),
178+
_ => None,
179+
}
180+
}
181+
143182
/// Main entry point for `stg` executable.
144183
///
145184
/// The name of the game is to dispatch to the appropriate subcommand or alias as
@@ -187,16 +226,19 @@ fn main() -> ! {
187226
// If the subcommand name does not match a builtin subcommand, the
188227
// aliases are located, which involves finding the Git repo and parsing
189228
// the various levels of config files. If the subcommand name matches an
190-
// alias, it is executed and the cost of constructing all subcommands'
191-
// Command instances is still avoided.
229+
// alias or an unambiguous prefix of a subcommand or alias, it is
230+
// executed and the cost of constructing all subcommands' Command
231+
// instances is still avoided.
192232
match get_aliases() {
193233
Err(e) => exit_with_result(Err(e), color_choice),
194-
Ok((aliases, maybe_repo)) => {
195-
if let Some(alias) = aliases.get(sub_name) {
234+
Ok((aliases, maybe_repo)) => match find_subcommand(sub_name, &aliases) {
235+
Some(Subcommand::Command(command)) => {
236+
execute_command(command, argv, color_choice)
237+
}
238+
Some(Subcommand::Alias(alias)) => {
196239
let user_args: Vec<OsString> = sub_matches
197240
.get_many::<OsString>("")
198241
.map_or_else(Vec::new, |vals| vals.cloned().collect());
199-
200242
match alias.kind {
201243
alias::AliasKind::Shell => execute_shell_alias(
202244
alias,
@@ -212,7 +254,8 @@ fn main() -> ! {
212254
&aliases,
213255
),
214256
}
215-
} else {
257+
}
258+
Some(Subcommand::Help) | None => {
216259
// If no command or alias matches can be determined from the
217260
// above process, then a complete clap::Command instance is
218261
// constructed with all subcommand Command instances for
@@ -221,7 +264,7 @@ fn main() -> ! {
221264
// expected to terminate with an appropriate help message.
222265
full_app_help(argv, Some(aliases), color_choice)
223266
}
224-
}
267+
},
225268
}
226269
}
227270
} else {
@@ -502,18 +545,13 @@ fn execute_stgit_alias(
502545
.expect("empty aliases are filtered in get_aliases()")
503546
.as_str();
504547

505-
if let Some(command) = STGIT_COMMANDS
506-
.iter()
507-
.find(|command| command.name == resolved_cmd_name)
508-
{
509-
execute_command(command, argv, color_choice)
510-
} else if aliases.contains_key(resolved_cmd_name) {
511-
Err(anyhow!("recursive alias `{}`", alias.name))
512-
} else {
513-
Err(anyhow!(
548+
match find_subcommand(resolved_cmd_name, aliases) {
549+
Some(Subcommand::Command(command)) => execute_command(command, argv, color_choice),
550+
Some(Subcommand::Alias(_)) => Err(anyhow!("recursive alias `{}`", alias.name)),
551+
Some(Subcommand::Help) | None => Err(anyhow!(
514552
"bad alias for `{}`: `{resolved_cmd_name}` is not a stg command",
515553
alias.name,
516-
))
554+
)),
517555
}
518556
}
519557
Err(reason) => Err(anyhow!("bad alias for `{}`: {reason}", alias.name)),
@@ -643,3 +681,63 @@ fn print_merge_conflicts() {
643681
};
644682
stupid.status_short(Some(pathspecs)).unwrap_or_default();
645683
}
684+
685+
#[cfg(test)]
686+
mod tests {
687+
use super::*;
688+
689+
#[test]
690+
fn subcommand_shorthand_resolution() {
691+
let mut aliases = alias::get_default_aliases();
692+
assert!(matches!(
693+
find_subcommand("del", &aliases),
694+
Some(Subcommand::Command(cmd)) if cmd.name == "delete"
695+
));
696+
assert!(matches!(
697+
find_subcommand("de", &aliases),
698+
Some(Subcommand::Command(cmd)) if cmd.name == "delete"
699+
));
700+
assert!(matches!(
701+
find_subcommand("di", &aliases),
702+
Some(Subcommand::Command(cmd)) if cmd.name == "diff"
703+
));
704+
assert!(find_subcommand("d", &aliases).is_none());
705+
assert!(find_subcommand("pu", &aliases).is_none());
706+
assert!(find_subcommand("res", &aliases).is_none());
707+
assert!(matches!(
708+
find_subcommand("rese", &aliases),
709+
Some(Subcommand::Command(cmd)) if cmd.name == "reset"
710+
));
711+
assert!(matches!(
712+
find_subcommand("reso", &aliases),
713+
Some(Subcommand::Alias(alias)) if alias.name == "resolved"
714+
));
715+
assert!(matches!(
716+
find_subcommand("st", &aliases),
717+
Some(Subcommand::Alias(alias)) if alias.name == "status"
718+
));
719+
assert!(find_subcommand("h", &aliases).is_none());
720+
assert!(matches!(
721+
find_subcommand("he", &aliases),
722+
Some(Subcommand::Help)
723+
));
724+
assert!(matches!(
725+
find_subcommand("hi", &aliases),
726+
Some(Subcommand::Command(cmd)) if cmd.name == "hide"
727+
));
728+
729+
aliases.insert(
730+
"show-stat".to_string(),
731+
alias::Alias::new("show-stat", "!git show --stat"),
732+
);
733+
assert!(find_subcommand("sho", &aliases).is_none());
734+
assert!(matches!(
735+
find_subcommand("show", &aliases),
736+
Some(Subcommand::Command(cmd)) if cmd.name == "show"
737+
));
738+
assert!(matches!(
739+
find_subcommand("show-", &aliases),
740+
Some(Subcommand::Alias(alias)) if alias.name == "show-stat"
741+
));
742+
}
743+
}

‎t/t0004-main.sh‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,39 @@ test_expect_success 'Test help on regular command' '
2424
stg help init | grep -e "stg init"
2525
'
2626

27+
test_expect_success 'Test help on command shorthand' '
28+
stg in -h >h-in.txt &&
29+
stg init -h >h-init.txt &&
30+
test_cmp h-init.txt h-in.txt &&
31+
stg he delete >h-del.txt &&
32+
stg delete --help >h-delete.txt &&
33+
test_cmp h-delete.txt h-del.txt
34+
'
35+
36+
test_expect_success 'Test unambiguous command shorthand' '
37+
stg ver >v0.txt &&
38+
stg version >v1.txt &&
39+
test_cmp v1.txt v0.txt &&
40+
stg in &&
41+
stg new -m p0 &&
42+
stg ser --noprefix >s.txt &&
43+
echo p0 >expected.txt &&
44+
test_cmp expected.txt s.txt &&
45+
stg del p0 &&
46+
stg ser --noprefix >s.txt &&
47+
test_must_be_empty s.txt
48+
'
49+
2750
test_expect_success 'Test help on ambiguous command' '
2851
general_error stg pu 2>err &&
2952
grep -e "unrecognized subcommand .pu." err &&
3053
grep -e "some similar subcommands exist: .pull., .push." err &&
3154
general_error stg help pu 2>err &&
32-
grep -e "unrecognized subcommand .pu." err
55+
grep -e "unrecognized subcommand .pu." err &&
56+
general_error stg d 2>err &&
57+
grep -e "unrecognized subcommand .d." err &&
58+
general_error stg h 2>err &&
59+
grep -e "unrecognized subcommand .h." err
3360
'
3461

3562
test_expect_success 'Test version/--version equivalence' '

‎t/t0010-alias.sh‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,13 @@ test_expect_success 'Test help on builtin alias command' '
1212
test_expect_success 'Test ambiguous alias' '
1313
test_config stgit.alias.show-stat "!git show --stat" &&
1414
stg show-stat &&
15+
stg show-s &&
1516
stg init &&
1617
stg show &&
1718
general_error stg sho 2>err &&
18-
grep -e "tip: some similar subcommands exist: .show-stat., .show." err
19+
grep -e "tip: some similar subcommands exist: .show-stat., .show." err &&
20+
general_error stg res 2>err &&
21+
grep -e "unrecognized subcommand .res." err
1922
'
2023

2124
test_expect_success 'Setup top-level and nested aliases' '

‎t/t1901-email.sh‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@ test_expect_success 'Check that email command requires subcommand' '
1111

1212
test_expect_success 'Check email subcommand help' '
1313
stg email help format &&
14-
stg email help send
14+
stg email help send &&
15+
stg em f -h &&
16+
stg em s --help
1517
'
1618

1719
test_done

0 commit comments

Comments
 (0)