mirror of
https://github.com/nushell/nushell.git
synced 2026-11-23 01:48:49 +08:00
## Description
This PR makes it much easier to **shadow builtins and forward optional
named flags**, especially cases where “flag absent” and “flag present
with a value” mean different things (the current example is `cp
--preserve`).
When shadowing a builtin, people write:
```nushell
def cp [
--preserve: list<string>
--recursive (-r)
...rest
] {
%cp --preserve=$preserve --recursive=$recursive ...$rest
}
```
If the user does not pass `--preserve`, `$preserve` is `null`. Passing
`--preserve=$preserve` used to **attach** the named flag with a null
value. Builtins then rejected it (e.g. `--preserve` expects
`list<string>`), even though omitting the flag would have used the
builtin’s normal default path.
There was also no good way to build a dynamic set of flags the way
people build rest args with `...$list`.
## User-facing changes (Release notes)
### Named flags: null can omit or pass through based on type
When a named flag is given `null`, Nushell now:
- **Omits** the flag if its type does not accept `nothing` (e.g. `--x:
int`, `--preserve: list<string>`), so defaults and “flag not passed”
behavior work—especially useful when shadowing builtins with `%cp` /
`%ls` and writing `--flag=$maybe_null`
- **Passes `null` through** if the type accepts `nothing` (e.g. `--x:
any`, `--x: oneof<int, nothing>`), so callers can still express an
explicit null when they opt into that in the signature
```nushell
def f [--x: oneof<int, nothing> = 5] { $x }
f # 5
f --x=null # null
def g [--x: int = 5] { $x }
g --x=(null) # 5 (omitted → default) note: in this example null is wrapped in parens because this syntax would fail with `g --x=null` as you're typing due to parse checking.
```
### Record spread into named flags
Internal and custom commands accept spreading a record as named flags:
```nushell
def wrap [--preserve: list<string>, --recursive, ...rest] {
%cp ...{ preserve: $preserve, recursive: $recursive } ...$rest
}
let flags = {preserve: [mode], recursive: true}
wrap ...$flags src dest
```
- Null fields follow the same type rule as named flags above
- Switch fields: `true` sets the flag; `false` / `null` omit
- Field values are type-checked against the flag signature
- Unknown flag names in the record error at runtime
- Spreading a **list** into a command with no `...rest` errors clearly
(it is not treated as named flags)
## Additional notes
closes https://github.com/nushell/nushell/issues/18790