Let an alias end with a flag that takes a value (#19623)

## Description

`alias myfind = find -r` was accepted, but `myfind "txt$"` searched for
the literal text `txt$` and returned an empty list with no error. The
alias kept `-r` without a value, so the next word went to `find`'s other
parameters.

Now the first word after such an alias becomes the flag's value, the way
bash, zsh and fish expand aliases. If no word follows, the parser
reports the missing value at the alias name. `--help` and `-h` still
show help, and tab completion after the alias offers the flag's values.

Names in the alias still resolve where it's defined, so `alias ls = ls
-a` still doesn't call itself.

Examples, main against this branch.

These work now:

| Code | main | this branch |
|---|---|---|
| `alias myfind = find -r; ["file.txt" "x"] \| myfind "txt$"` | empty
list | `[file.txt]` |
| `alias myfind = find -r; ["FILE.TXT" "x"] \| myfind "txt$" -i` | empty
list | `[FILE.TXT]` |
| `alias hex = into int --radix; "ff" \| hex 16` | error: Data cannot be
accessed with a cell path | `255` |
| `alias j = to json -i; {a: 1} \| j 4` | error: Extra positional
argument | JSON indented by 4 spaces |

These don't change:

| Code | main | this branch |
|---|---|---|
| `extern "/bin/echo" [--foo: string, ...rest: string]; alias e =
/bin/echo --foo; e bar` | `--foo bar` | `--foo bar` |
| `alias rep = str replace -a; "aaa" \| rep a b` | `bbb` | `bbb` |
| `alias myfind = find -r; [] \| myfind --help` | help for `find` | help
for `find` |
| `alias myfind = find -r; [] \| myfind -h` | help for `find` | help for
`find` |

These are now an error, the same one you get typing the expansion alone:

| Code | main | this branch |
|---|---|---|
| `alias j = to json -i; {a: 1} \| j` | JSON indented by 2 spaces |
error: Missing flag argument |
| `alias myfind = find -r; ["file.txt"] \| myfind` | error: Missing
parameter: search term or --regex | error: Missing flag argument |
| `extern "/bin/echo" [--foo: string, ...rest: string]; alias e =
/bin/echo --foo; e` | `--foo` | error: Missing flag argument |
| `def cmd [--opt: any] { $opt }; alias c = cmd --opt; c` | `true` |
error: Missing flag argument |

## User-facing changes (Release notes)

- An alias that ends with a flag that takes a value now takes the value
from the first word after it. With `alias myfind = find -r`, `myfind
"txt$"` runs `find -r "txt$"`. Before, the flag got no value and the
alias could return wrong results with no error.
- Breaking change. Using such an alias with nothing after it is now a
"Missing flag argument" error, as typing its expansion alone already
was. This includes aliases of commands declared with `extern`.

### Breaking Changes

**1. Using the alias with nothing after it is now a parse error**

```nushell
alias j = to json -i
{a: 1} | j
```
- **Before:** it runs and ignores `-i`, so you get the default 2-space
indent.
- **After:** `MissingFlagParam`, pointing at `j`.

Because it fails at parse time, a `config.nu` or module that uses such
an alias this way anywhere now fails to load, not just that one line.
The memory note for this branch already records this as the intended
break.

**2. The first word after the alias now goes to the flag instead of to
the positional arguments**

```nushell
def cmd [--opt: string, ...rest] { {opt: $opt, rest: $rest} }
alias c = cmd --opt
c x y
```
- **Before:** `{opt: true, rest: [x, y]}`. A string flag got the boolean
`true`.
- **After:** `{opt: x, rest: [y]}`.

If the flag is typed `int`, the same call used to run with `opt: true`.
Now `x` fails the type check as a parse error.

## Additional notes

- Reported in
https://github.com/nushell/nushell/discussions/19616#discussioncomment-19779865.
- The `--help` and `-h` exception applies only to aliases. `find -r
--help` still searches for `--help`.
This commit is contained in:
Darren Schroeder
2026-11-21 07:15:19 -06:00
committed by GitHub
parent f6e23c4ec6
commit bc405a2232
4 changed files with 175 additions and 2 deletions
+20
View File
@@ -4119,6 +4119,26 @@ fn alias_of_basic_command() {
match_suggestions(&expected_paths, &suggestions)
}
/// An alias that ends with a flag that takes a value completes that flag's values, as typing
/// its expansion would.
#[rstest]
#[case::nothing_typed("a ", vec!["cat", "dog", "eel"])]
#[case::partial("a d", vec!["dog"])]
fn alias_ending_with_flag_completes_flag_value(#[case] input: &str, #[case] expected: Vec<&str>) {
let (_, _, mut engine, mut stack) = new_engine();
let code = "
def animals [] { [cat dog eel] }
def fruits [] { [apple banana] }
def cmd [--opt: string@animals, ...rest: string@fruits] {}
alias a = cmd --opt
";
assert!(support::merge_input(code.as_bytes(), &mut engine, &mut stack).is_ok());
let mut completer = NuCompleter::new(Arc::new(engine), Arc::new(stack));
let suggestions = completer.complete_blocking(input, input.len());
match_suggestions(&expected, &suggestions);
}
#[test]
fn alias_of_another_alias() {
let (_, _, mut engine, mut stack) = new_engine();
+78
View File
@@ -1,3 +1,4 @@
use nu_protocol::Span;
use nu_test_support::prelude::*;
use pretty_assertions::assert_matches;
use rstest::rstest;
@@ -167,3 +168,80 @@ fn export_alias_with_overlay_use_works() -> Result {
fn alias_flag() -> Result {
test().run("alias si = stor import").expect_value_eq(())
}
/// An alias that ends with a flag that takes a value parses like its expansion followed by the
/// words after the alias, so the first of those words is the flag's value.
#[rstest]
#[case::long_flag("alias hex = into int --radix; 'ff' | hex 16", test_value!(255))]
#[case::short_flag("alias hex = into int -r; 'ff' | hex 16", test_value!(255))]
#[case::short_flag_group(
"alias myfind = find -nr; ['file.txt' 'x'] | myfind 'txt$'",
test_value!(["file.txt"])
)]
#[case::more_flags_after(
"alias myfind = find -nr; ['FILE.TXT' 'x'] | myfind 'txt$' -i",
test_value!(["FILE.TXT"])
)]
#[case::alias_of_alias(
"alias hex = into int --radix; alias hex2 = hex; 'ff' | hex2 16",
test_value!(255)
)]
#[case::switch_is_not_filled("alias rep = str replace -a; 'aaa' | rep a b", test_value!("bbb"))]
fn alias_ending_with_flag_takes_value_from_use(
#[case] code: &str,
#[case] expected: Value,
) -> Result {
test().run(code).expect_value_eq(expected)
}
/// `--help` after such an alias still shows help rather than becoming the flag's value.
#[rstest]
#[case::long("alias myfind = find -r; [] | myfind --help")]
#[case::short("alias myfind = find -r; [] | myfind -h")]
fn alias_ending_with_flag_still_shows_help(#[case] code: &str) -> Result {
let help: String = test().run(code)?;
assert_contains("Search for terms in the input data.", help);
Ok(())
}
/// Without a word to fill it, the flag's missing value is reported at the alias's name where it
/// is used, not where it is defined.
#[test]
fn alias_ending_with_flag_reports_missing_value_at_use() -> Result {
let code = "alias hex = into int --radix; 'ff' | hex";
let mut tester = test();
let entry_start = tester.engine_state.next_span_start();
let err = tester.run(code).expect_parse_error()?;
let use_start = entry_start + code.rfind("hex").expect("code uses the alias");
assert_matches!(
err,
ParseError::MissingFlagParam(_, span) if span == Span::new(use_start, use_start + 3)
);
Ok(())
}
/// A runtime error about the filled value points at the value. The flag's name comes from the
/// alias definition, in an earlier entry here, so a span covering both would reach across
/// entries and the error couldn't show its source.
#[test]
fn alias_ending_with_flag_reports_value_error_at_use() -> Result {
let mut tester = test();
let () = tester.run("alias hex = into int --radix")?;
let err = tester.run("'ff' | hex 99").expect_shell_error()?;
let ShellError::TypeMismatch { span, .. } = err else {
panic!("expected a radix TypeMismatch, got {err:?}");
};
assert_eq!(tester.engine_state.get_span_contents(span), b"99");
Ok(())
}
/// An alias defined in one entry, like one from `config.nu`, fills the flag in a later entry.
#[test]
fn alias_ending_with_flag_used_in_later_entry() -> Result {
let mut tester = test();
let () = tester.run("alias hex = into int --radix")?;
tester.run("'ff' | hex 16").expect_value_eq(255)?;
let err = tester.run("'ff' | hex").expect_parse_error()?;
assert_matches!(err, ParseError::MissingFlagParam(..));
Ok(())
}
+3 -2
View File
@@ -349,8 +349,9 @@ fn flatten_expression_into(
flatten_positional_arg_into(working_set, positional, shape, output)
}
Argument::Named(named) => {
if named.0.span.end != 0 {
// Ignore synthetic flags
if !named.0.span.is_empty() {
// Ignore flags with no text: synthetic ones, and a flag an alias
// ends with, whose value was filled in where the alias is used
output.push((named.0.span, FlatShape::Flag));
}
if let Some(expr) = &named.2 {
+74
View File
@@ -1052,6 +1052,67 @@ fn short_spanned(short: char, span: Span) -> Spanned<String> {
}
}
/// Fill in the value of a flag that an alias's expansion ends with.
///
/// `alias myfind = find -r` stores `-r` without its value. `myfind 'txt$'` should parse like
/// `find -r 'txt$'`, so the first word after the alias becomes the value. If there is no word,
/// the missing value is reported at `command_span`, the alias's name. `myfind --help` (or `-h`)
/// still asks for help instead of searching for `--help`. Returns how many of `spans` were used.
fn fill_alias_flag_value(
working_set: &mut StateWorkingSet,
call: &mut Call,
signature: &Signature,
command_span: Span,
spans: &[Span],
allow_null: bool,
) -> usize {
let Some(Argument::Named((long, short, None))) = call.arguments.last() else {
return 0;
};
let flag = match short.as_ref().and_then(|short| short.item.chars().next()) {
Some(short) if long.item.is_empty() => signature.get_short_flag(short),
_ => signature.get_long_flag(&long.item),
};
// A switch has no value to fill.
let Some(shape) = flag.and_then(|flag| flag.arg) else {
return 0;
};
let long_name = long.item.clone();
let Some(&value_span) = spans.first() else {
working_set.error(ParseError::MissingFlagParam(
shape.to_string(),
command_span,
));
return 0;
};
let help_short = signature.get_long_flag("help").and_then(|flag| flag.short);
let asks_for_help = match working_set.get_span_contents(value_span) {
b"--help" => true,
[b'-', short] => help_short == Some(char::from(*short)),
_ => false,
};
if asks_for_help {
return 0;
}
// The flag's name spans come from the alias definition, maybe in another file. With the
// value's span from here, `Argument::span` would run from one to the other, so the name
// gets an empty span where the value starts. It stays clear of the alias name, which
// highlighting colors as a command.
let name_span = Span::new(value_span.start, value_span.start);
let value = parse_flag_value(working_set, value_span, &shape, allow_null);
let (_, value) = ensure_flag_arg_type(working_set, long_name, value, &shape, name_span);
if let Some(Argument::Named((long, short, slot))) = call.arguments.last_mut() {
long.span = name_span;
if let Some(short) = short {
short.span = name_span;
}
*slot = Some(value);
}
1
}
pub fn parse_internal_call(
working_set: &mut StateWorkingSet,
command_span: Span,
@@ -1131,7 +1192,9 @@ pub fn parse_internal_call(
// Starting at the first argument
let mut spans_idx = 0;
let mut is_alias = false;
if let Some(alias) = decl.as_alias() {
is_alias = true;
if let Expression {
expr: Expr::Call(wrapped_call),
..
@@ -1170,6 +1233,17 @@ pub fn parse_internal_call(
let allow_null_flag_value = !working_set.get_decl(call.decl_id).is_known_external();
let mut end_of_options = false;
if is_alias {
spans_idx = fill_alias_flag_value(
working_set,
&mut call,
&signature,
command_span,
spans,
allow_null_flag_value,
);
}
// Commands that pass unknown arguments through (extern, def --wrapped, exec, etc.) forward
// a flag the signature doesn't declare to the program instead of reporting it.
// `extern --strict` reports it, except for the words `strict_extern_forwards` accepts.