4509 Commits
Author SHA1 Message Date
Dmitry Molotkov 35d9ec179b perf(ls, table): eliminate redundant metadata syscalls, double read_dir, and per-row table overhead (#19701)
## Description

Interactive `ls` had two compounding bottlenecks:
1. Bare `ls` checked `read_dir(cwd)` (collecting and sorting every entry
only to test `.next().is_none()` and discard it), then fell back to
`glob_from("*")` — dropping `DirEntry` cached metadata (bypassing #17339
on bare `ls`), double-reading directories on `ls <dir>`, and spawning a
1-thread Rayon pool + `mpsc::channel` even without `--threads` (while
holding the `hidden_dirs` mutex across `dir_entry_dict`, serializing
`--threads` too).
2. `table` re-ran `symlink_metadata`, `SSH_CLIENT` env lookup,
`devicons::icon_for_file` (even when `--icons` was off),
`std::path::absolute`, and `Url::from_file_path` on every row, and
recompiled the ~680-rule `LsColors` Aho-Corasick automatons on every
invocation — even when `path_columns` was empty.

### Design & Trade-offs
- **Bounded `#[serde(skip)]` path-metadata cache on `PipelineMetadata`
vs. `PipelineMetadata::custom` or row-`type` heuristics:**
- A `custom` key would leak onto the plugin wire protocol, show up in
`metadata`, be forgeable via `metadata set`, and silently corrupt
styling across metadata-preserving mutators (`append`, `each`, `str
replace`, `merge`, etc.).
- Trusting `"type"` alone still fails on Unix plain `ls` because default
`LS_COLORS` styles `ex` (`mode & 0o0111`).
- Storing a bounded (`65_536`-entry, ~2 MiB cap), `#[serde(skip)]`,
`PartialEq`-transparent cache on `PipelineMetadata` (keyed by per-cache
128-bit SipHash of display name, hashed outside the mutex) avoids
plugin/API breakage, eliminates redundant `symlink_metadata` on both
Windows and Unix (including plain `ls` executables), and automatically
falls back to disk `symlink_metadata` on any mutated/foreign row, `cwd`
change (`$ans.last`), `ls -s <arg>`, or `ls -Ds`.
- **Direct `read_dir(cwd)` for bare `ls`:** Matches `ls .` and `ls
<dir>` with a single directory read/sort and lazy single-threaded
streaming when `--threads` is off.
- **Process-wide `LsColors` cache (`OnceLock` default + 1-entry custom
cache):** Compiles outside the lock so repeated REPL commands, `grid`,
and completions share the compiled automatons with zero copies.
- **Icons (`--icons`):** Cached directories short-circuit `devicons`'s
internal `is_dir()` via trailing `'/'` and icon hex colors are cached
per `table` call; regular files still incur `devicons 0.6.13`'s internal
`is_dir()` check since its lookup table is private.

### Intentional Behavioral & Test Changes
- **Windows bare `ls` parity with `ls .`:** Bare `ls` now uses
`DirEntry::metadata()` (`WIN32_FIND_DATAW`) like `ls .` and `ls <dir>`
already did since #17339, reporting `0 B` for directories instead of
NTFS `$INDEX_ALLOCATION` sizes (e.g. `4.0 kB`).
- **Linux/FreeBSD non-UTF-8 bare `ls`:** Bare `ls` now lists non-UTF-8
filenames via `read_dir` cleanly like `ls .` rather than printing a
`nu-glob` warning and failing with `No matches found for '*'`;
`list_directory_contains_invalid_utf8` was updated to assert bare `ls`
succeeds while `ls *` continues testing the `nu-glob` warning path.
- **`ls | find <pattern> | table`:** Stripping ANSI escapes before path
resolution fixes a pre-existing bug where highlighted path names failed
`symlink_metadata` and lost OSC 8 links / extension icons.
- **OSC 8 & `--icons` path resolution:** Relative paths now resolve
against Nushell's `$env.PWD` (including Windows same-drive `C:foo` and
rooted `\foo`) rather than the OS process working directory.
- **Lazy streaming in non-threaded `ls`:** Without `--threads`, `ls` now
reads each entry's metadata (and walks globs) lazily as downstream pulls
rows (restoring pre-#13836 behavior instead of relying on a background
Rayon thread racing ahead). Pipelines that mutate other entries in the
same directory while iterating should use `ls | collect | each ...`.

### Benchmarks (`nu -n`, `--release`, Windows x86_64, interleaved A/B
medians vs `993d7fbda`)

| Workload | Before | After | Speedup |
| --- | ---: | ---: | ---: |
| Interactive `ls \| table -e --width 120` (System32, 5,053 rows,
ANSI+OSC8, warm) | 318.34 ms | 37.23 ms | **8.55x** |
| Interactive `ls \| table -e --width 120` (System32, ANSI+OSC8, cold
`OnceLock`) | 333.75 ms | 40.35 ms | **8.27x** |
| Interactive `ls \| table -e --width 120` (System32, ANSI, no OSC8) |
314.73 ms | 34.86 ms | **9.03x** |
| Interactive `ls C:\Windows\System32 \| table -e --width 120`
(ANSI+OSC8) | 316.41 ms | 56.53 ms | **5.60x** |
| Interactive `ls \| table -e --icons --width 120` (System32, ANSI+OSC8)
| 372.79 ms | 194.11 ms | **1.92x** |
| Piped `ls \| table -e --width 120` (System32, `use_ansi_coloring =
false`) | 350.57 ms | 47.13 ms | **7.44x** |
| Pure bare `ls \| ignore` (System32) | 265.87 ms | 9.19 ms | **28.92x**
|
| Pure explicit `ls C:\Windows\System32 \| ignore` | 22.98 ms | 8.76 ms
| **2.62x** |
| Streaming `ls \| first 10 \| ignore` (System32) | 16.16 ms | 6.67 ms |
**2.42x** |
| Small repo dir interactive `ls \| table -e` (50x warm loop) | 165.90
ms | 23.78 ms | **6.98x** |
| Custom `$env.LS_COLORS` interactive `ls \| table -e` (20x warm loop) |
46.53 ms | 10.72 ms | **4.34x** |
| Non-`ls` metadata table (50x empty `path_columns`) | 86.92 ms | 8.30
ms | **10.47x** |

## User-facing changes (Release notes)

- Improved interactive `ls` and `table` rendering performance by up to
**8–9x** in large directories (and **~7x** in everyday directories) by
eliminating duplicate directory scans, redundant per-row metadata
lookups, per-call thread-pool creation, and repeated `LS_COLORS`
parsing.
- Improved bare `ls` pipeline throughput by up to **28x** on large
Windows directories and aligned bare `ls` behavior with `ls .`
(including listing non-UTF-8 filenames cleanly on Linux/FreeBSD).
- Improved `table` performance on non-`ls` tables carrying pipeline
metadata (such as `open` and `from csv` outputs) by skipping
path-coloring setup when `path_columns` is empty.
- Fixed OSC 8 clickable links and `--icons` path resolution in `table`
to resolve relative paths against `$env.PWD` and to handle
ANSI-highlighted paths (e.g., `ls | find ... | table`).
- `ls` without `--threads` now streams entries lazily, reading each
entry's metadata as downstream consumes it (use `ls | collect | each
...` if mutating other entries in the same directory while iterating).

## Additional notes

### Verification Status
- **Ran locally (Windows x86_64):**
- `cargo check -p nu-command --no-default-features` and `cargo check -p
nu-command --no-default-features --target wasm32-unknown-unknown` — pass
- `cargo test -p nu-protocol`, `cargo test -p nu-utils`, `cargo test -p
nu-plugin-core` — pass
- `cargo test -p nu-command --lib -- viewers::table filesystem::ls` —
pass
- `cargo test -p nu-command --test tests --
commands::{ls,table,debug::metadata,reject,find,get}` — pass
  - `cargo test -p nu-cli --test tests -- last_result` — pass
- `cargo fmt --all -- --check`, `cargo nuclippy`, `cargo
nuclippy-tests`, `typos` (all changed files clean on `typos-cli 1.53.0`)
— pass
- Byte-for-byte output equivalence verified against baseline (`ls
C:\Windows\System32 | table -e`, `ls -s`, `ls -Ds`, `ls | select`, `ls |
find`, and candidate bare `ls` vs baseline `ls .`)
2026-12-02 14:27:58 -06:00
Nikhil Gupta 1f884f5920 fix(fill): measure width in terminal columns, not grapheme clusters (#19671)
## Description

`fill` measures its input in grapheme clusters, but a wide character
occupies two
terminal columns. Any string containing CJK text or emoji is therefore
padded two
columns too far per wide character, and columns of filled values do not
line up.

```nu
"abcd"   | fill --character "." --width 8    # abcd....      8 columns  ✔
"日本"   | fill --character "." --width 8    # 日本......    10 columns ✘
"👍"     | fill --character "." --width 8    # 👍.......      9 columns ✘
```

`pad()` already says what it is trying to do — *"Use width instead of
len for
graphical display"* — and the surrounding code agrees: the command's
search terms
are `display`, `render`, `align`, the examples pad with box-drawing
characters,
and #8134 went out of its way to give ANSI escapes zero width.
Zero-width ANSI
only makes sense for terminal rendering, and in a terminal `日` is two
columns.
The cluster count was simply the wrong unit for that goal.

This measures the string with `nu_table::string_width` — the same
function `table`
uses to size a cell. It strips ANSI escape sequences and measures what
is left in
terminal columns, so the zero-width-ANSI behaviour #8134 added is
preserved. The
existing `string_fill_fancy` test covers an ANSI + combining-mark string
and still
passes untouched.

Two consequences are worth naming explicitly:

- **Control characters count as themselves.** A tab is one column, not
zero. An
earlier revision of this PR measured with `strip_ansi_unlikely`, whose
own doc
comment says it "keeps `\n` removes `\r`, `\t` etc.", so tabs and `\r`
came out
as zero columns and received one pad character too many.
`nu_table::string_width`
  strips only escape sequences and fixes that.
- **A multi-line string is measured by its widest line**, not by its
total length,
because `string_width` is `tabled`'s `get_text_width`. So `"ab\ncd" |
fill -c "." -w 6`
  now yields `"ab\ncd...."` where `main` yields `"ab\ncd."`.

Both are covered by the new `string_fill_control_characters` test.

One caveat the comment in `pad()` now records: `fill` and `table` do
**not** agree
on strings containing control characters. `table` runs `clean_charset`
before
measuring, which expands each tab to four spaces and drops `\r`, so a
tab-bearing
value filled to six columns is drawn nine columns wide in a table cell.

`print-positions` was this crate's only user, so the dependency is
dropped from
the workspace.

### On the choice of unit

#8134 framed the unit as "print positions" and described `🧑‍🏫` as one
position
wide. That sequence is one grapheme cluster but renders in two columns,
so under
the current code `fill -w 4 -a c` on it produces five columns of output.
I have
read this as the goal being terminal alignment and the unit being a
means to it,
which is also how #19165 drew the line — it deliberately chose runes for
`to nuon
--pretty` because that is canonicalisation rather than terminal
alignment, and
said so explicitly. `fill` is on the other side of that line. If the
core team
reads it the other way and wants cluster semantics kept, say so and I
will close
this.

## User-facing changes (Release notes)

Fixed `fill` padding strings containing wide characters two columns too
far per
character. `"日本" | fill --character "." --width 8` now produces eight
columns of
output instead of ten, so columns of CJK and emoji values line up. A
multi-line
string is now measured by its widest line rather than by its total
character
count.

## Additional notes

- `cargo test -p nu-command`: 6,706 passed, 0 failed.
- `cargo clippy -p nu-command` and `cargo fmt --check`: clean.
- New test `string_fill_wide_characters` covers CJK, a single emoji, a
ZWJ emoji
  sequence, and a combining mark.
- New test `string_fill_control_characters` covers a tab, a carriage
return, and a
  multi-line string.
- No issue filed for this; found by reading the command.
2026-12-01 07:31:23 -06:00
AWA 12f7273ab4 Fix non-transitive PartialOrd for Value::Record (#19687)
## Description

Fixes a non-transitivity bug in `PartialOrd` for `Value::Record`
(`crates/nu-protocol/src/value/mod.rs`) that can violate Rust's
total-order invariant and panic in `sort` / `sort-by` in both debug and
release builds.

Previously, `Value::Record` compared sorted columns with
`lhs.columns().zip(rhs.columns())`, then compared
`lhs.values().zip(rhs.values())`, and only compared
`lhs.len().partial_cmp(&rhs.len())` at the very end. When one record's
sorted column list was a proper prefix of another's, `zip` stopped early
and fell through to comparing values instead of settling the column
comparison first.

That produces a strict 3-cycle over plain integer records:
- `{a: 3, b: 1} < {a: 1, c: 1}` (columns `["a", "b"] < ["a", "c"]`)
- `{a: 1, c: 1} < {a: 2}` (`"a" == "a"`, `zip` stops, values `1 < 2`)
- `{a: 2} < {a: 3, b: 1}` (`"a" == "a"`, `zip` stops, values `2 < 3`)

Sorting a list containing these records panics inside
`std::slice::sort_by` (`user-provided comparison function does not
correctly implement a total order`):

```nu
1..7 | each { [{k: {a: 3, b: 1}}, {k: {a: 1, c: 1}}, {k: {a: 2}}, {k: {a: 1, c: 1}}] } | flatten | sort-by k
```

### Approach

Compare column iterators lexicographically with
`lhs.columns().cmp(rhs.columns())` before comparing
`lhs.values().partial_cmp(rhs.values())`. Because `Iterator::cmp`
handles prefix lengths directly, values are only compared when both
records have the exact same sorted column names, preserving transitivity
and consistency with `PartialEq` (and keeping `NaN` incomparable when
columns match).

### Verification

- Added `test_record_partial_ord_transitivity` in
`crates/nu-protocol/tests/test_value.rs` and
`sort_records_with_prefix_columns` /
`sort_by_records_with_prefix_columns` in
`crates/nu-command/tests/commands/sort.rs`.
- Verified `sort_by_records_with_prefix_columns` panics before the fix
with `user-provided comparison function does not correctly implement a
total order` and passes after:
  - `cargo test -p nu-protocol`
  - `cargo test -p nu-command --lib sort_utils`
  - `cargo test -p nu-command --test tests -- commands::sort`
- `cargo clippy -p nu-protocol -p nu-command --lib -- -D warnings -D
clippy::unwrap_used -D clippy::unchecked_time_subtraction`
- `cargo clippy -p nu-protocol -p nu-command --tests -- -D warnings -D
clippy::unchecked_time_subtraction`
  - `cargo fmt --all -- --check`

## User-facing changes (Release notes)

Fixed a bug where comparing or sorting records with overlapping prefix
column names (e.g., `{a: 2}`, `{a: 3, b: 1}`, `{a: 1, c: 1}`) violated
comparison transitivity and could panic in `sort` / `sort-by`. Records
now compare their sorted column names (including column count) before
comparing values.

A record whose sorted column names are a prefix of another record's now
sorts before it regardless of values — for example, `{name: zed}` now
sorts before `{name: amy, size: 1}` (matching `jq`), so existing sorts
over lists of records with optional columns can come out in a different
order. `sort` on a homogeneous table of plain values is unchanged
because it compares column by column.
2026-11-29 14:01:47 -06:00
subotac 85a3d9a9ed fix(random): avoid panics when sampling float ranges (#19476)
## Description

`random float 1..<1` and `random float (-1e308)..1e308` currently panic
in rand. Use fallible sampling-range constructors and return the
existing `InvalidRange` error when a range cannot be sampled. Preserve
descending-range validation and valid inclusive, exclusive and unbounded
ranges

Adds regressions for empty ranges, overflowing range widths and negative
values.

## User-facing changes (Release notes)

`random float` reports an error for empty or unrepresentable sampling
ranges instead of panicking

## Additional notes

The actual `random` test sources pass through a local builtin Rust
harness (21 tests). The prescribed custom harness discovers zero tests
on this Windows GNU setup, so that invocation is not counted as
validation. `cargo nuclippy`, workspace formatting and typos pass. Full
workspace tests and hosted CI have not been run1
2026-11-29 07:09:27 -06:00
Raj Aryan 84e126a725 fix(extern): don't recurse when an extern shadows run-external (#19685)
In this PR, I fixed a stack overflow when an extern is named
run-external.
Every external call, including `^cmd` and other extern's, dispatches
through the declaration named `run-external`. An `extern` with that name
therefore called itself. Defining `extern run-external ["ls"]` and then
running `^ls` overflowed the stack.
External calls now skip a known external named `run-external` and use
the built-in runner. A custom `def run-external` still replaces the
built-in. Hiding `run-external` is unchanged: a missing declaration is
still an error.
## User-facing changes (Release notes)
- Fixed a stack overflow when an `extern` command is named
`run-external`. Running another external command, such as `^ls`, now
runs that command instead of crashing. Calling the `extern` itself
reports that the `run-external` program was not found.
## Additional notes
Fixes #11335
2026-11-28 12:30:54 -06:00
Surri757andsu ru b544189760 fix(nuon): escape control characters in strings written by to nuon (#19683)
## Description

`to nuon` writes control characters such as backspace (`\b`), bell
(`\a`) and escape (`\e`) into strings as raw bytes, and does not even
quote them: the quote-forcing check only knows about NUL and whitespace,
so `{a: "x\by"} | to nuon` emits `{a: x<BS>y}`. A raw backspace eats the
character before it and a raw escape starts an ANSI sequence when the
document is printed, so the output is unreadable and unsafe to view.

This makes the NUON writer escape those characters and force quoting for
strings that contain them, mirroring how NUL is already handled and what
`to json` has done since #19443:

```nushell
> {a: "x\by"} | to nuon
{a: "x\by"}
```

Tabs, newlines, carriage returns, vertical tabs and form feeds are still
written verbatim inside quotes, as the NUON specification allows. Round
trips are unchanged: `"a\bb"` still reads back as `a<BS>b`.

This continues the closed #19461, which took the same approach and was
put on hold for PR-load reasons rather than technical ones.

Fixes #6808
Part of #19197 (the NUON half of the control-character escaping work)

## User-facing changes (Release notes)

Fixed an issue where `to nuon` wrote control characters like backspace
or escape into strings as raw bytes, producing output that is corrupted
when displayed. They are now quoted and escaped (`\b`, `\a`, `\e`, or
`\u{..}`), consistent with `to json`. Strings holding ANSI escapes are
now written as `\e[...` text, so colors no longer render when the output
is printed. Run `ansi strip` before `to nuon` if you need it stripped.

## Additional notes

- The change is in `crates/nu-utils/src/quoting.rs`: `needs_quoting` now
forces quoting for C0 controls and DEL, `escape_quote_string` escapes
them, and `as_raw_string` refuses the raw form for values that need
escaping (a raw string cannot carry the `\b` escape). The same helpers
back record keys and table headers, so those are covered too.
- `--raw-strings` is affected the same way; without the raw-form
refusal, a value containing both a quote and a control character would
still emit the raw byte.
- The NUON specification sentence stating that control characters are
written verbatim is updated in the same PR, with a revisions-table
entry. `bugs_to_fix.md` needs no new entry: that file tracks
implementation deviations from the spec, and this updates the spec's
stated behavior.
- Tests: 3 unit tests in `quoting.rs` and 4 integration tests in
`crates/nu-command/tests/format_conversions/nuon.rs`, including the
issue's repro, keys and nested values, the `--raw-strings` path, and a
round trip.
- Drafted with MiniMax Code.

---------

Co-authored-by: su ru <183260426+Surri757@users.noreply.github.com>
2026-11-28 10:47:16 -06:00
Surri757andsu ru 7703d748bd fix(transpose): return an empty record for empty input with --as-record (#19681)
fix(transpose): return an empty record for empty input with --as-record

## Description

`transpose --as-record` only transfers the result to a record when the
result has exactly one row, so an empty table falls through to the list
branch: `[] | transpose --as-record` returns an empty list. The repro
from #17605 still holds on 0.117: `[] | transpose --as-record |
describe` gives `list<any> (stream)`.

With `--as-record` the user asked for a record, so an empty table should
come back as an empty record: `[] | transpose --as-record` now returns
`{}` instead of `[]`.

The inverse of `transpose` for records is `transpose -r -d`, and it
round-trips an empty record: `{} | transpose | transpose -r -d` gives
`{}`.

Root cause: the guard in `crates/nu-command/src/filters/transpose.rs`
checked `result_data.len() == 1`, so the 0-row case fell into the `else`
branch that returns the (empty) list. The guard now accepts 0 rows
(`result_data.len() <= 1`) and produces an empty record for them.
Non-empty inputs take exactly the same code paths as before.

The `--as-record` flag help text mentions the empty case now, so the
generated command docs stay in sync with the behavior.

Fixes #17605

## User-facing changes (Release notes)

`transpose --as-record` (`-d`) now returns an empty record instead of an
empty list when the result has no rows: `[] | transpose -d` gives `{}`
instead of `[]`. This is a behavior change, and scripts that treat an
empty `transpose -d` result as a list will break.

Commands downstream of an empty `transpose -d` result now receive a
record instead of a list:

- `[] | transpose -d | length` now errors with
`only_supports_this_input_type` (input type: record) instead of
returning `0`
- `[] | transpose -d | each {|r| 'ran' } | to nuon` now returns `"ran"`
instead of `[]`
- `[] | transpose -d | append 1 | to nuon` now returns `[{}, 1]` instead
of `[1]`

The empty record can also be produced from inputs that do have rows,
when there is no column left to turn into a row:

- `[{}] | transpose -d | to nuon` now returns `{}` instead of `[]`
- `[[key]; [a] [b]] | transpose -r -d | to nuon` now returns `{}`
instead of `[]`

## Additional notes

Tests: `cargo test --package nu-command --test tests --
commands::transpose`. Before the fix, on `main`, the two new issue-repro
tests fail as expected:

```
test commands::transpose::as_record_on_empty_list_returns_empty_record ... FAILED
test commands::transpose::as_record_round_trips_empty_record ... FAILED

---- commands::transpose::as_record_on_empty_list_returns_empty_record stdout ----
Error: TestError {
    kind: UnexpectedValue {
        expected: String("{}"),
        got: String("[]"),
    },
}

test result: FAILED. 12 passed; 2 failed; 0 ignored; 0 filtered out; across 1 groups, finished in 0.04s
```

With the fix, all 14 tests in the file pass, and the command's example
tests (`cargo test -p nu-command --lib transpose`) pass too:

```
test result: ok. 14 passed; 0 failed; 0 ignored; 0 filtered out; across 1 groups, finished in 0.03s
```

The 4 new tests in `crates/nu-command/tests/commands/transpose.rs` are
the issue's minimal repro (`[] | transpose --as-record`), the
empty-record round trip (`{} | transpose | transpose -r -d`), and two
regression tests pinning the unchanged non-empty paths (a single row
still becomes a record, multiple rows still stay a table).
`cargo fmt --all -- --check` and `cargo clippy -p nu-command
--all-targets -- -D warnings -D clippy::unwrap_used` both pass.

- Drafted with MiniMax Code (AI assistance); the diff has not been
reviewed line by line by a human yet.
- nushell has no AI usage policy, so this disclosure is voluntary.
This PR is submitted as a regular PR rather than a draft. Note that the
workflows on a fork pull request still have to be approved by a
maintainer before they run, so please click "Approve and run workflows"
if you are able to.

---------

Co-authored-by: su ru <183260426+Surri757@users.noreply.github.com>
2026-11-28 09:42:51 -06:00
kiyohara 871078d5b6 docs(tutor): add error handling tutorial (#19678)
## Description

Adds an introductory `tutor error-handling` topic (aliases: `error`,
`errors`, `try`, `catch`, `finally`) covering `try`/`catch`/`finally`
and `error make`.

Links to it from `tutor custom-command` and points readers to `tutor
closures`, `help try`, and `help error make`.

## User-facing changes (Release notes)

- Added a `tutor error-handling` tutorial covering `try`, `catch`,
`finally`, and `error make`.
- Added a link to `tutor error-handling` from `tutor custom-command`.

## Additional notes

- Part of #18895
2026-11-28 06:29:58 -06:00
Darren Schroeder dc352efbc6 Restructure into datetime and reject a bad zone flag up front (#19677)
## Description

It was mentioned in #19669 that "The entire architecture of that command
looks so hard to follow.". This refactor is my attempt to address that
and try to make the code easier to follow. I also fixed 2 flag errors
that were lazy and are not eager. Other than that, functionality should
be unchanged.

## User-facing changes (Release notes)

- `into datetime` now rejects a `--timezone` or `--offset` that names no
zone before reading any input. A datetime, an empty list or a record
with such a flag used to pass through or get a different error. A list
of strings used to turn into a list of error values.
- `into datetime --offset` no longer panics on an offset too large to
negate.

## Additional notes
/cc @cptpiepmatz is this any better?
2026-11-27 14:52:57 -06:00
saudademjj 15356117d8 fix(semver): replace Span::unknown() in semver bump errors (#19675)
## Description

`SemverValue::bump_prerelease` and `SemverValue::set_build_metadata`
constructed `ShellError::Generic` errors using `Span::unknown()`,
causing commands such as `'1.2.3' | semver bump patch --build-metadata
'bad metadata!'` to report an unknown span instead of highlighting the
offending argument.

This PR threads `Spanned` argument spans from `SemverBump::run` into
`bump_prerelease`, `set_build_metadata`, and the invalid bump level
error, eliminating all `Span::unknown()` occurrences in
`crates/nu-command/src/semver/` and adding unit and end-to-end span
tests.

## User-facing changes (Release notes)

Fixed `semver bump` error locations: an invalid `--build-metadata` value
now points at the flag instead of an unrelated snippet, and an invalid
bump level points at the level instead of the command name.

## Additional notes

Related to #7308.
2026-11-27 08:10:52 -06:00
Darren Schroeder 681511d2ae Apply into datetime --timezone and --offset to strings without --format (#19669)
## Description

Without `--format`, `into datetime` ignored `--offset` and `--timezone`
on strings and read them in local time. Timestamps and `--format` input
already used the flags.

Now a date or time without an offset is read in the flag's zone, and
"today" comes from that zone. A string with an offset is converted to
the zone. Relative strings like `tomorrow 10am` are read in the zone
too. With `--format`, a time alone now takes today in the zone as well.

### Before and after

Local zone Europe/Berlin, main at b1c021362, run at 13:39 Berlin time.
It was already the 27th in Kiritimati. Each command ends in `| format
date '%Y-%m-%d %H:%M %:z'`, or `'%H:%M %:z'` for `tomorrow 10am`.

| command | main | branch |
|---|---|---|
| `'26-11-2026 05:00:00' \| into datetime --offset 8` | 2026-11-26 05:00
+01:00 | 2026-11-26 05:00 +08:00 |
| `'26-11-2026 05:00:00' \| into datetime --offset 8 \| date to-timezone
local` | 2026-11-26 05:00 +01:00 | 2026-11-25 22:00 +01:00 |
| `'tomorrow 10am' \| into datetime --timezone Asia/Tokyo` | 10:00
+01:00 | 10:00 +09:00 |
| `'2024-07-01T00:00:00Z' \| into datetime --timezone Asia/Tokyo` |
2024-07-01 00:00 +00:00 | 2024-07-01 09:00 +09:00 |
| `'2024-01-01T00:00:00Z' \| into datetime --offset 15` | 2024-01-01
00:00 +00:00 | error: Invalid timezone or offset |
| `'05:00' \| into datetime --format '%H:%M' --timezone
Pacific/Kiritimati` | 2026-11-26 05:00 +14:00 | 2026-11-27 05:00 +14:00
|

## User-facing changes (Release notes)

- `into datetime --timezone` and `--offset` now work on strings without
`--format`. A date or time without an offset is read in that zone, and
one with an offset is converted to it.
- Breaking change: a string with its own offset now comes back in the
flag's zone. `'2024-07-01T00:00:00Z' | into datetime --timezone
Asia/Tokyo` gave 00:00 +00:00 and now gives 09:00 +09:00. That's the
same instant, so comparisons don't change.
- Breaking change: an invalid `--offset` or `--timezone` is now an error
for these strings, even ones with their own offset.
- With `--format`, a time alone takes today in the `--timezone` zone,
not in local time.

## Additional notes
2026-11-27 07:04:09 -06:00
Abak2006andAbak2006 86b9c8db4b path parse: strip a custom --extension only once (#19670)
## Description
`path parse --extension` used `trim_end_matches`, so it removed every
trailing copy of the extension instead of one. For example
`'notes.txt.txt' | path parse -e txt` gave the stem `notes`. Switched to
`strip_suffix` so only one is removed, and added a test.

## User-facing changes (Release notes)
Fixed `path parse --extension` removing the extension more than once
when a file name ends with it repeated, like `notes.txt.txt`.

Co-authored-by: Abak2006 <250136546+Abak2006@users.noreply.github.com>
2026-11-26 08:32:08 -06:00
Darren Schroeder 9c58ffc960 Run finally when Ctrl-C arrives during the try body (#19667)
## Description

Ctrl-C reaches both Nu and the external it's running. If the external
handles SIGINT itself and exits, Nu's interrupt is still pending when
control reaches `finally`. The first statement there that checks for
interrupts fails with `Operation interrupted`, and the cleanup never
runs.

This broke in 0.116.0, when #19052 replaced the `jump` into `finally`
with `begin-finally`, which doesn't check for interrupts. Now
`begin-finally` and `return` both check. Nu raises the pending interrupt
before `finally` starts, so `finally` runs to completion and the
interrupt comes after it, pointing at `try`, as in 0.115.1.

An external that exits non-zero on Ctrl-C, as `ssh` does with 255, had
the same problem before 0.116.0 too. Its failure carried the pending
interrupt into `finally`. Now the interrupt takes that failure's place.
I left `catch` alone. Doing the same there would let `catch` swallow the
Ctrl-C, and `for h in $hosts { try { ^ssh $h } catch { … } }` would keep
looping.

### Before and after

`repro.nu`, from the issue. Run `nu --no-config-file repro.nu` and press
Ctrl-C. Before is main at a578c6609.

```nushell
try {
  ^sh -c 'trap "exit 0" INT; sleep 5 & wait'
} finally {
  print "cleanup"
}
```

Before:

```nushell
Error: nu::shell::error

  x Operation interrupted
   ,-[repro.nu:4:9]
 3 | } finally {
 4 |   print "cleanup"
   :         ^^^^|^^^^
   :             `-- This operation was interrupted
 5 | }
   `----
```

After:

```nushell
cleanup
Error: nu::shell::error

  x Operation interrupted
   ,-[repro.nu:1:1]
 1 | try {
   : ^|^
   :  `-- This operation was interrupted
 2 |   ^sh -c 'trap "exit 0" INT; sleep 5 & wait'
   `----
```


## User-facing changes (Release notes)

Fixed Ctrl-C skipping the `finally` block of `try { } finally { }` when
the `try` body was running an external that handles SIGINT itself, such
as `ssh`. The `finally` block now runs to completion, then Nu reports
the interrupt.

## Additional notes

closes #19661
2026-11-26 07:49:00 -06:00
Darren Schroeder b1c021362d Fix quadratic parse time in the custom type lookup (#19668)
## Description
#19311 lets signatures name custom value types such as `matrix` or
`polars_dataframe`. The parser asks `StateWorkingSet::find_custom_type`
about every type name that is neither built in nor an alias, and that
function fetched the signature of every declaration on each call. The
working set doesn't cache signatures of commands defined in the current
parse, so each fetch built a whole `Signature` and dropped it.

Predeclaration makes it worse. It hands everything after a `def`'s
parameter list to the signature parser, body included, so each word of
the body (`{ ... }`, `=`, `$x`, `]`) reaches the lookup as a type name.
A file with N commands that declare input/output types made about N
lookups, each over all N declarations.

`find_custom_type` now remembers the names it found and how many
declarations it has read. Each call reads only the declarations added
since the last one.

It reads only built-in and plugin commands and skips `def`, `extern` and
`alias`. A `def`'s input/output annotation only parses if the lookup
already knows the name, so skipping it loses nothing. Parameters are
another story. A parameter with a default value and no annotation gets
its shape from the value's type, never from the lookup. And `parse_def`
replaces a predeclared signature in place, which a lookup that reads
each declaration once would never see. Built-in and plugin signatures
don't change once added, so the remembered names stay right. Skipping
user commands also stops the lookup from building the signature of every
`def` in the file.

The lookup also finds a custom type anywhere in a built-in or plugin
signature: in a parameter's or flag's shape, or inside `list<...>`,
`oneof<...>`, `record<...>`, `table<...>` and closure parameters. It
used to check only top-level input and output types, so a plugin whose
commands only return `list<my_type>` couldn't have `my_type` in a `def`
signature. I couldn't find a real command that shows this. Every custom
type in this repository (`semver`, `matrix`, `SQLiteDatabase`, the
polars and example plugin types) appears as a top-level input or output
type somewhere, and so do the types of the 19 plugins in my config. The
unit tests cover each position instead.

Before and after, main 3870f187e against this branch, release builds on
an Apple silicon Mac.

A generated module of one-line commands, `export def fN [x: int]:
nothing -> string { $x | into string }`, loaded with `nu -n --no-std-lib
-c 'use defs.nu *'` (hyperfine medians of 20, idle CPU):

| commands | main | branch | main instructions | branch instructions |
|---|---|---|---|---|
| 1000 | 100.0 ms | 19.1 ms | 1390M | 177M |
| 2000 | 336.7 ms | 29.4 ms | 4991M | 285M |

## User-facing changes (Release notes)

- Parse time no longer grows with the square of the number of commands
in a file. A config that loads large completion modules starts about 35
ms faster.
- A plugin's custom value type now works in a `def` signature even if
the plugin only uses it inside a `list`, `record`, `table` or `oneof`,
or as a parameter type.

## Additional notes
2026-11-25 18:18:17 -06:00
Darren Schroeder 3870f187e7 Speed up JSON, CSV, YAML and TOML conversion on big inputs (#19666)
## Description

This is the first easy stab at making formats a bit faster. There's
still lots of room for better perf.

Most of the time spent loading and saving big files went into copying
and converting data around the parsers, not into parsing. This PR
removes that work:

- `from json` parsed into a JSON value tree, with a hash map for every
object, and then converted the tree into nushell values. Before that it
copied the whole input once more. It now builds nushell values straight
from the parser, in both default and `--strict` mode. `to json` no
longer copies the value into a JSON tree before writing it.
- `to csv` and `to tsv` built a new CSV writer with an 8 KiB buffer for
every row and handed out one row per chunk, so `save` made one `write`
call per row. For a table that is already in memory, they now fill the
writer's buffer before handing out a chunk. String cells are borrowed
instead of copied.
- `from yaml` ran the int, float and timestamp regexes on every plain
scalar. Each of those patterns starts with a sign, a digit or a dot, so
scalars that start with anything else now skip them. Plain decimal ints
are read without the capture regex. A mapping without `<<` is no longer
merged into an empty record one key at a time. `to yaml` no longer
formats a tag string for values that have no tag.
- `from toml` moves strings and keys out of the parsed TOML instead of
cloning them.

Apart from the fixes below, the output is the same as on main. I
compared 293 cases against main, covering Hjson, duplicate keys, number
edge cases, BOMs, error messages, CSV errors after several chunks, YAML
1.1 and 1

### Before and after

The table has 500k rows and 10 columns of ints, floats, bools, strings
and nulls, which is 139 MB as JSON. Times are from an idle M-series Mac.
"Before" is main. Write times include loading the table from msgpack,
which takes about 0.55 s and 848 MB on both.

| command | before | after |
|---|---|---|
| `open fixture.json` | 1.50 s, 1456 MB | 1.19 s, 979 MB |
| `save fixture.json` | 1.81 s, 1760 MB | 1.00 s, 981 MB |
| `save fixture.csv` | 2.13 s | 1.05 s |
| `save fixture.tsv` | 2.13 s | 1.05 s |
| `open fixture.yaml` | 4.80 s | 3.27 s |
| `save fixture.yaml` | 1.50 s | 1.41 s |
| `open fixture.toml` | 2.20 s, 2902 MB | 2.07 s, 2799 MB |

## User-facing changes (Release notes)

- `from json` and `open` on `.json` files are faster and use a third
less memory on large inputs.
- `to json` and `save` to `.json` are about twice as fast on large
tables and use less memory.
- `to csv`, `to tsv` and `save` to `.csv` or `.tsv` are about twice as
fast on large tables.
- `from yaml` is about a third faster. `to yaml` and `from toml` are a
little faster.
- `from json` reports an error for a `/*` comment with no closing `*/`,
which used to crash nu.
- `from json` without `--strict` reports an error for lists and objects
nested more than 1024 deep, where deeper input used to crash nu with a
stack overflow. Input nested 1025 to about 11,000 levels deep parsed in
a release build before and now gets the error.
- `from yaml` reads -9223372036854775808, the smallest int.

## Additional notes
<!--
Optional.

Examples:
- fixes #123
- closes #456
- related #789

Anything else reviewers should know.
Remove this section if not needed.
-->
2026-11-25 13:12:07 -06:00
Darren Schroeder bf111f1aca Drop 18 crates from Cargo.lock and stop building nu-protocol twice (#19665)
## Description

I'm not sure how helpful this will be since we change things all the
time but it's probably a good practice to look around and see how we can
reduce the amount of crates we use.

This PR removes dependencies nushell can do without. Rewriting `random
pass` without aegis turned up three bugs in it, and moving `get_umask`
turned up a race in `umask`. The PR fixes those too.

- `nu-cmd-extra`'s build script included `theme.rs`, which derives
`nu_protocol::IntoValue`. To read one JSON file, cargo built a second
copy of nu-protocol and everything under it. The build script now has
its own serde struct, and the generated theme list is byte-identical.
- `nu-system` depended on uucore (with clap, fluent and ICU) only for
`get_umask`, and only nu-command calls it. nu-command now has that
function, so every plugin drops 44 crates. `nu_system::get_umask` stays
as a deprecated function that reads the umask through nix.
- `random pass` uses `rand` 0.10 directly instead of
`aegis-password-generator`, which pulled in rand 0.9 and thiserror 1.
- `random uuid -v 3` hashes with the `md-5` 0.11 crate that `hash md5`
already uses, instead of uuid's `v3` feature and its older RustCrypto
stack.
- Hand-written setters with the same signatures replace `derive_setters`
and darling 0.21. `ParseOptions::with_keep_styles` is now deprecated,
like the `keep_styles` field it sets.
- `UniqueString` wraps a `Box<str>` instead of byteyarn's `Yarn`, which
brought zerocopy 0.7.
- parking_lot, lru and nix go back one minor version to match crossterm,
ratatui and uucore, so each one is built once.
- Lockfile bumps of instability and kasuari let ratatui share darling
0.24 and hashbrown 0.17. serde-saphyr stays at 2.1.1 but now resolves
base64 0.23, which its `>=0.21, <0.24` range already allows.
- 31 unused entries are gone from crate manifests, along with the
`dirs-sys` and `webpki-roots` workspace entries that nothing uses.

The `random pass` fixes:

- `--chars` below 4 returned 4 characters, because the password always
took one character from each enabled set. It now returns the requested
length. `--require-each-type` with fewer than 4 characters is an error.
- `--include-ambiguous` and `--include-similar` did nothing, because
aegis ignored them. Passwords now leave out `O 0 l 1 i` by default, as
the help text says, and each flag adds its characters back.
- A negative `--chars` failed with "must be less than or equal to 128".
It now says "greater than 0", and length errors point at the `--chars`
value.

The `umask` fix: reading the umask sets it to 0 for a moment. `umask
<mask>` didn't take the lock that reads take, so a set that landed in
that moment reported `rwxrwxrwx` as the previous mask, and the read then
undid it. Reads and sets now share one lock.

| macOS, default features | main | this PR |
|---|---|---|
| crates in the `nu` build | 582 | 554 |
| crates in a plugin build (`nu_plugin_inc`) | 209 | 150 |
| crates in `nu_plugin_polars` | 481 | 448 |
| packages in `Cargo.lock` | 1029 | 1011 |
| compile units, `cargo build` | 648 | 572 |
| compile units, `cargo build --release` | 740 | 587 |


## User-facing changes (Release notes)

- `random pass --chars` returns exactly the requested length. Below 4 it
used to return 4 characters.
- `random pass` leaves out the look-alike characters `O 0 l 1 i` unless
`--include-ambiguous` or `--include-similar` is given, as its help says.
- `umask <mask>` no longer reports `rwxrwxrwx` as the previous mask, or
loses the new one, when another thread reads the umask at the same time.
- Plugins built on `nu-plugin` compile 59 fewer crates (209 to 150 for
`nu_plugin_inc` on macOS).


## Additional notes
<!--
Optional.

Examples:
- fixes #123
- closes #456
- related #789

Anything else reviewers should know.
Remove this section if not needed.
-->
2026-11-25 13:11:24 -06:00
Darren Schroeder f86116c041 Store parser info in IR as typed values (AST migration phase 6a) (#19652)
## Description

This follows #18808, #18813, #18967, #19351, #19462 and #19638. Since
#19638, commands run only from compiled code. The keyword commands that
read the parser's extra data for a call, and `explain`, still evaluated
parser expressions with the AST evaluator. This PR moves both off it,
deletes the evaluator, and removes the last parser `Expression` from IR.
Each phase is its own commit, and the last commit fixes review findings
in 6a and 6b.

- **Typed parser info (6a).** `Instruction::PushParserInfo` carried a
parser `Expression` that `source`, `source-env` and `run` evaluated to
get back a block id or a path. It now carries a `ParserInfo` value that
the compiler builds once. `source-env` also uses the path the parser
found, instead of looking the file up again when it runs.
- **`explain` runs no code (5a).** A literal, a constant or a bare
variable still shows its value. Any other argument shows its source text
and the type the parser gave it.
- **AST evaluator deleted (5b).** `eval_expression` and its helpers are
gone, 383 of `eval.rs`'s 847 lines. Const evaluation is the only `Eval`
implementation left.
- **Match guards on the arm (6b).** The guard moves from `MatchPattern`,
which every nested pattern carried, to a new `MatchArm { pattern, guard,
body }`. Capture discovery, `$in` handling and highlighting all skipped
guards before. They visit them now.

## User-facing changes (Release notes)

- `explain` no longer evaluates arguments. A literal, a constant or a
bare variable shows its value, and anything else shows its source text,
so `$r.a` shows `$r.a` instead of `1`. Arguments that used to show an
empty name or an error show their source.
- `view ir` shows parser info as values such as `block(305)` or `import
"assert" ["equal"]` instead of a debug dump. `view ir --json` and `ast
--json` change shape for parser info and match arms.
- A closure whose match guard reads an outside variable now captures it.
`$in` works in a guard, and as a bare `=> $in` arm body inside a
closure. All of these used to fail with `Variable not found`.
- A match guard inside a closure can no longer read a `mut` variable
from outside it, the same rule an `if` condition there already follows.
Scripts that did this break. Copy the value into a `let` first.
- The REPL and `nu-highlight` color match guards.
- `source-env` sets `$env.FILE_PWD` and `$env.CURRENT_FILE` from the
file the parser read. They no longer contain `..`, and a `cd` before
`source-env` no longer changes them.

## Additional notes
2026-11-25 13:05:39 -06:00
Darren Schroeder 346ea7027a Destructure values with patterns in let, for, closures and assignment (#19643)
## Description

`let`, `mut`, `const`, `for`, closure parameters and assignment now take
patterns, so a record or list comes apart in one step. They use the
patterns `match` already has, with `$name` for each binding.

A pattern has the same shape as the value. `{...}` takes a record apart
by field name, and `[...]` takes a list apart by position. A table is a
list of records, so its pattern nests one in the other. `[{...}]` takes
apart a table with one row, and `[{...}, ..]` takes its first row. `for`
and `each` get one row at a time, so they take `{...}`. Run `describe`
on the value to see which it needs. `split row` gives a `list<string>`,
which takes `[$key, $value]`. `parse` gives a table even for one match,
which takes `[{$user, $host}]`.

Patterns get three new pieces, which work in `match` too:

- `$y?` binds `null` when the field or item is missing.
- `$port = 8080` gives a default. In a list, this works only in
bindings, because `=` in a `match` list is still a string.
- `{$name, ..$rest}` puts the other fields in `$rest`.

A type annotation can cover a whole pattern, as in `let {$x}: record<x:
int> = $r`.

If a value doesn't fit, the error names the missing field or the item
count. `const` reports it at parse time. A destructuring assignment
checks the whole value before it assigns anything.

`match` changes in four places:

- Quoted keys like `{"a b": $x}` match.
- `{a: $x?}` binds `$x`.
- A range pattern tests the interval between its ends.
- A list pattern matches an int range, and binds the rest as a range.

The language server handles pattern variables for hover, references,
highlights and rename. Renaming `$name` when the shorthand `{$name}`
binds it writes `{name: $new}`, so the pattern still reads the field
`name`.

### Examples

Each line runs on its own and the `# =>` lines under it are what it
prints. Each block also runs top to bottom as a script. On main, every
line in the first block fails to parse. In the second block, a `# main:`
comment shows what main gives when it differs.

```nushell
# Records
let {$name, $age} = {name: "nu", age: 5}; $"($name) is ($age)"
# => nu is 5
let {name: $who} = {name: "nu"}; $who
# => nu
let {server: {$host, $port}} = {server: {host: "localhost", port: 80}}; $"($host):($port)"
# => localhost:80
let {"Content-Type": $ctype} = {"Content-Type": "text/html"}; $ctype
# => text/html
let {$host, $port?} = {host: "localhost"}; $port == null
# => true
let {$host, $port = 8080} = {host: "localhost"}; $port
# => 8080
let {$name, ..$rest} = {name: "a", size: 1, type: "file"}; $rest | to nuon
# => {size: 1, type: file}

# Lists
let [$first, $second] = [1 2]; $first + $second
# => 3
let [$head, ..$tail] = [1 2 3]; $tail | to nuon
# => [2, 3]
let [.., $last] = [1 2 3]; $last
# => 3
let [$a, _, $c] = [1 2 3]; $a + $c
# => 4
let [[$a, $b], [$c, $d]] = [[1 2] [3 4]]; $a + $d
# => 5
let [$x, $y?] = [1]; $y == null
# => true
let [$x, $y = 0] = [1]; $x + $y
# => 1

# Tables are lists of records
let [{$name}, ..] = [[name size]; [a 1] [b 2]]; $name
# => a
[[name size]; [a 1] [b 2]] | each {|{$name, $size}| $"($name)=($size)" } | str join ", "
# => a=1, b=2
mut names = []; for {$name} in [[name size]; [a 1] [b 2]] { $names ++= [$name] }; $names | str join ", "
# => a, b

# Int ranges work like lists, and the rest stays a range
let [$a, $b, ..$rest] = 1..5; $rest | to nuon
# => 3..5
let [$first, ..$rest] = 1..; $rest | to nuon
# => 2..
let [$x, $y, ..] = 0..10..100; $x + $y
# => 10

# Strings, durations, dates and cell paths, through the commands that take them apart
let [$key, $value] = "key=value" | split row "="; $value
# => value
# `split row` returns a list, but `parse` returns a table, a list of records, even for one match
let [{$user, $host}] = "alice@example.com" | parse "{user}@{host}"; $host
# => example.com
let {$hour, $minute} = 90min | into record; $"($hour)h ($minute)m"
# => 1h 30m
let {$year, $month, $day} = 2024-03-15 | into record; $"($year)/($month)/($day)"
# => 2024/3/15
let [{value: $first}, ..] = $.a.b | split cell-path; $first
# => a

# Errors in catch
try { error make {msg: "boom"} } catch {|{$msg}| $msg }
# => boom

# Scalars, globs and closures bind whole
let [$n, $flag] = [1 true]; $flag
# => true
let [$docs] = ["*.md"] | into glob; $docs | describe
# => glob
let [$inc, $double] = [{|x| $x + 1} {|x| $x * 2}]; do $double (do $inc 2)
# => 6

# A type annotation, const, and the pipeline form
let {$x, $y}: record<x: int, y: int> = {x: 1, y: 2}; $x + $y
# => 3
const [$a, $b] = [1 2]; $a + $b
# => 3
{a: 1, b: 2} | let {$a, $b}; $a + $b
# => 3

# Assigning to existing mut variables
mut a = 1; mut b = 2; [$a, $b] = [$b, $a]; $"($a) ($b)"
# => 2 1
mut x = 0; mut y = 0; {$x, $y} = {x: 3, y: 4}; $x * $y
# => 12
```

```nushell
# Range patterns test the interval between their ends
match 3.5 { 1..5 => "in", _ => "out" }  # main: out
# => in
match 2 { 1..3..9 => "in", _ => "out" }  # main: out
# => in
match (-5) { ..0 => "up to 0", _ => "other" }  # main: other
# => up to 0
match 100 { 1.. => "positive", _ => "other" }
# => positive
match 5 { 1..<5 => "in", _ => "out" }
# => out
match 7 { 10..1 => "in", _ => "out" }
# => in

# List patterns match int ranges
match 1..5 { [$a, ..$rest] => ($rest | to nuon), _ => "no match" }  # main: no match
# => 2..5
match 1.. { [$a, $b, ..] => ($a + $b), _ => "no match" }  # main: no match
# => 3
match [1] { [$a, $b?] => ($b == null), _ => "no match" }  # main: error: Variable not found.
# => true

# Record patterns
match {"a b": 1} { {"a b": $x} => $x, _ => "no match" }  # main: no match
# => 1
match {a: 1} { {b: $x?} => ($x == null), _ => "no match" }  # main: error: Variable not found.
# => true
match {a: 1} { {$a, $b = 2} => ($a + $b), _ => "no match" }  # main: error: Parse mismatch: expected record.
# => 3
match {a: 1, b: 2} { {$a, ..$rest} => ($rest | to nuon), _ => "no match" }  # main: error: Parse mismatch: expected record.
# => {b: 2}
```

A value that doesn't fit, on this branch:

```nushell
Error: nu::shell::pattern_mismatch

  × Pattern doesn't fit the value
   ╭─[source:1:13]
 1 │ let {$name, $mtime} = {name: "a", size: 1}
   ·             ───┬──
   ·                ╰── record has no field `mtime`
   ╰────
  help: The record has name, size. Add `?` after the pattern if the field can
        be missing.
```

`let [$a, $b] = [1 2 3]` says `list has 3 items, the pattern takes 2`
and suggests `..`.

When the shape is wrong, the help names the right one. On a table, `let
{$user, $host} = ...` suggests `[{...}]`, and so does `let [$user,
$host] = ...` when the row count doesn't match the pattern. On a record,
`let [{$name}] = ...` suggests `{...}`.

```nushell
Error: nu::shell::pattern_mismatch

  × Pattern doesn't fit the value
   ╭─[source:1:5]
 1 │ let [$user, $host] = "alice@example.com" | parse "{user}@{host}"
   ·     ───────┬──────
   ·            ╰── list has 1 item, the pattern takes 2
   ╰────
  help: The list is a table, so each variable here gets a whole row. Write
        `[{...}]` to take the fields of one row.
```

## User-facing changes (Release notes)

- `let`, `mut`, `const` and `for` take patterns: `let {$name, $size} =
ls | first`, `let [$head, ..$tail] = $list`, `for {$name, $type} in (ls)
{ ... }`.
- Closure parameters take patterns: `ls | each {|{$name, $size}| ... }`,
`catch {|{$msg}| ... }`.
- `[$a, $b] = [$b, $a]` assigns to existing `mut` variables.
- New pattern pieces:
  - `$x?` binds `null` when a field or item is missing.
  - `$port = 8080` sets a default.
  - `{$name, ..$rest}` collects the other fields.
  - `let {$x}: record<x: int> = ...` checks the type.
- When a value doesn't fit a pattern, the error names the missing field
or the item count. If the pattern has the wrong shape for a table or a
record, the help suggests `[{...}]` or `{...}`.
- Breaking change: in `match`, a range pattern tests the interval
between its ends. `1..5` matches 3.5, `1..3..9` matches 2, and `..0`
matches any number up to 0 instead of only 0.
- Breaking change: in `match`, a list pattern matches an int range.
`match 1..5 { [$a, ..] => ... }` used to skip that arm.
- `match` record patterns accept quoted keys like `{"a b": $x}`, and
`{a: $x?}` binds `$x`.
- The language server supports hover, references, highlights and rename
on pattern variables.

## Additional notes

- closes #19591 
- closes #6021
- `def` parameters don't take patterns, on purpose. `help`, completions
and `--help` need a parameter's name and type, and a pattern has
neither. Instead, take a record parameter and destructure it with `let`
in the body.
- Bindings use `$name`, as in `match`. A bare word is still a string, so
`let [a, b] = ...` fails with a hint to write `$a`.
- Without an annotation, pattern variables get their parse-time types
from the value, the same as `$value.field`. With the `cell-path-types`
experimental option turned off, they're `any` until run time.
- Public API changes:
  - `Pattern` gains `Optional` and `Interval`.
  - `Expr` gains `Pattern` and `AssignmentPattern`.
  - `Block` gains `parameter_patterns`.
  - IR gains a `destructure` instruction.
  - `ShellError` and `ParseError` each gain `PatternMismatch`.
- `nu_protocol::engine` gains the help texts
`TABLE_FOR_RECORD_PATTERN_HELP` and `RECORD_FOR_LIST_PATTERN_HELP`.
- Left for later:
  - `++` prefix patterns for strings and binary.
- List patterns on float ranges. Their items can't be counted exactly,
so they don't match.
- `for` ignores a pattern's type annotation, as it does for a plain
variable.
  - `(..0)` in parentheses still means `0..0`.
2026-11-25 11:18:47 -06:00
Mrakorez 6c5aee3872 feat(glob): add --relative-paths (-r) flag (#19056)
## Description

`glob`, while a powerful command for finding files, only returns
absolute paths. This makes searching for files in an interactive session
quite noisy, and scripts using a simple `glob <pattern> | path
relative-to $env.PWD` can run into problems. For example:

```nushell
# returns an empty string
> glob ** | path relative-to $env.PWD | first

# an absolute pattern that doesn't start with PWD causes an error
> glob /some/path/* | path relative-to $env.PWD
```

As a result, users would need to write a shadowing/helper function to
reliably account for this behavior — which feels like overkill just to
display relative paths.

This PR adds a `--relative-paths` (`-r`) switch to `glob` that returns
paths relative to `$env.PWD` when the input pattern is itself relative.
Absolute patterns, `~`-prefixed patterns (`~/...`, `~user/...`), and
Windows drive-relative patterns (e.g., `D:*`) still output absolute
paths regardless of the flag.

## User-facing changes (Release notes)

### `glob` now supports returning relative paths

Added a `--relative-paths` (`-r`) flag to `glob`. When set, and the
pattern given is relative, `glob` returns paths relative to the current
working directory instead of absolute paths. Absolute patterns,
`~`-prefixed patterns (`~/...`, `~user/...`), and Windows drive-relative
patterns (e.g., `D:*`) are unaffected and still output absolute paths.

```nushell
> glob subdir/*.txt
╭───┬─────────────────────────────────────╮
│ 0 │ /home/user/project/subdir/file0.txt │
│ 1 │ /home/user/project/subdir/file1.txt │
│ 2 │ /home/user/project/subdir/file2.txt │
╰───┴─────────────────────────────────────╯

> glob --relative-paths subdir/*.txt
╭───┬──────────────────╮
│ 0 │ subdir/file0.txt │
│ 1 │ subdir/file1.txt │
│ 2 │ subdir/file2.txt │
╰───┴──────────────────╯
```

## Additional notes

Closes #15946
2026-11-25 11:01:48 -06:00
Dixit Sabharwal a578c66091 Make from csv/from tsv keep every field a string; add --infer (#19651)
## Description

Makes type inference in `from csv` and `from tsv` opt-in, as discussed
in #13514. Every field is now a string; `--infer` applies the previous
int-then-float heuristic. `--no-infer` is kept as a deprecated no-op
(first-use parse warning, same mechanism as `du --min-size`) so existing
scripts keep working; passing both flags is an error. `open file.csv`
and `http get` on a `text/csv` response run `from csv`, so they keep
strings too; the help points at `--raw | from csv --infer` for numbers.

Tests that relied on inferred numbers pass `--infer` (or `into int`);
new tests pin the default, `--infer`, the deprecation and the conflict.
The std-rfc `aggregate` examples read their CSV with `--infer`.

## User-facing changes (Release notes)

- **Breaking:** `from csv` and `from tsv` no longer turn numeric-looking
fields into ints and floats; every field is a string, so values like
`007`, `1E5` or `NaN` stay as written. Pass `--infer` for the old
behaviour, or convert columns with `into int` / `into float` / `detect
type`. `open file.csv`, `open file.tsv`, and `http get` on a `text/csv`
response or on a `text/plain` response from a `.csv` or `.tsv` URL
behave the same way; to use `--infer` on them, read the data with
`--raw` first: `open --raw data.csv | from csv --infer`.
- `from csv --no-infer` / `from tsv --no-infer` are deprecated: they are
now the default and warn on first use.

## Additional notes

closes #13514
2026-11-25 05:24:04 -06:00
Darren Schroeder b85aa732b8 Run catch when try is piped into ignore, complete, save or tee (#19647)
## Description


Since 0.114.0, `try` skips `catch` when it's piped into `ignore`,
`complete`, `save` or `tee` and the error comes from the last command in
its block. `finally` still runs, but it gets the raw error as its input
and parameter, so the first command there that reads either one raises
the error again. The case most likely to bite is a custom command that
ends in a `try`. Call it as `my-command | ignore` and its `catch` never
runs.

#18306 made a command return its error as a value when its stderr goes
to a separate pipe. That lets `ignore --stderr` decide what to do with
the error. All four commands above ask for that separate pipe, and the
last command in a `try` block inherits the redirection of whatever
follows the `try`. So the error turned into a value, passed through
`try` without reaching `catch`, and the next command raised it. Up to
0.117.0, a `;` after the pipeline discarded the error. #19467 stopped
that, so on main the error surfaces.

`try` now raises an error value that reaches the end of its block, or
the end of `catch` before `finally`. The handlers run the same as they
do without the pipe. When only `finally` handles the error, `finally`
gets the error record. Then the error goes on to the next command as a
value, the same as without `finally`, so `ignore --stderr` still
consumes it.


## User-facing changes (Release notes)

- Fixed `try` skipping `catch` when it's piped into `ignore`,
`complete`, `save` or `tee`, including through a custom command that
ends in a `try`. In the same case `finally` now gets the error record
instead of the raw error. This was a regression in 0.114.0.
- `try { ... } catch { 'fallback' } | ignore --stderr` now passes on
`fallback` instead of consuming the error, and `try { exit 3 } | ignore
--stderr` now exits.

## Additional notes
2026-11-24 09:44:40 -06:00
Darren Schroeder a349f3257c fix(parser): pass -Zscript and -j8 through to a known external (#19642)
## Description

`generate completions cargo` declares `-Z: string`, and with that extern
loaded, `cargo -Zscript foo.rs` failed with
`only_last_flag_in_batch_can_take_arg`. `^cargo -Zscript` and `cargo -Z
script` both worked. `make -j8` and `git commit -amf` failed the same
way under their externs. `git commit -amf` is the example in #5923,
which #8808 closed by letting the last flag in a batch take the next
word. The attached form never worked.

A known external now reads short flags the way `getopt` does. When a
flag that takes a value comes before the end of the word, the rest of
the word is its value, and the word goes to the program as written.
Nushell still checks that value against the flag's type, so `-jabc` with
`-j: int` fails like `-j abc` does. `extern --strict` accepts the word
when every flag in it is declared. Nushell commands and `def --wrapped`
keep the old rule.

```nushell
> cargo -Zscript fp_asm.rs        # before
Error: nu::parser::only_last_flag_in_batch_can_take_arg

  × Only the last flag in a short flag batch can take an argument.
   ╭─[source:1:37]
 1 │ source cargo_completions.nu; cargo -Zscript fp_asm.rs | complete | reject stdout
   ·                                     ┬
   ·                                     ╰── only the last flag can take args

> cargo -Zscript fp_asm.rs        # after, on stable cargo
error: the `-Z` flag is only accepted on the nightly channel of Cargo, but this is the `stable` channel
```

## User-facing changes (Release notes)

Commands declared with `extern` accept a short flag with its value
attached, such as `cargo -Zscript`, `make -j8` or `git commit -amf`, and
pass it to the program as written.

## Additional notes

closes #19639

- Values that start with `$` or `(` skip the type check. Inside the
word, `-Z$x` stays literal and `-Z(1 + 2)` becomes `-Z3`, so checking
`$x` or `(1 + 2)` alone would test something the program never gets.
- The last-flag check also had a bug. It compared a byte offset with a
character count, so in `-éjm 5` the `-j` took a value without being
last. It now compares spans.
2026-11-24 09:43:13 -06:00
1a76df9156 from xml: add --namespaces to keep namespace prefixes and xmlns (#19649)
## Description

Fixes #11523.

`from xml` kept only local names and dropped `xmlns` declarations, so
`from xml | to xml` lost namespace information:

```nu
'<svg xmlns="http://www.w3.org/2000/svg" width="1"><text xml:space="preserve">a</text></svg>' | from xml | to xml
# before: <svg width="1"><text space="preserve">a</text></svg>
```

This adds a `--namespaces` flag, as suggested in the issue discussion.
With it, names that belong to a prefixed namespace keep their prefix
(`dc:creator`, `xml:space`), and `xmlns` / `xmlns:*` declarations are
added to `attributes` on the element that declares them. Elements in the
default namespace stay unprefixed. The record shape is the same (`tag` /
`attributes` / `content`) and `to xml` needs no change. Without the flag
the output is unchanged.

```nu
'<svg xmlns="http://www.w3.org/2000/svg" width="1"><text xml:space="preserve">a</text></svg>' | from xml --namespaces | to xml
# <svg xmlns="http://www.w3.org/2000/svg" width="1"><text xml:space="preserve">a</text></svg>
```

## User-facing changes (Release notes)

- `from xml` has a new `--namespaces` flag. It keeps namespace prefixes
in tag and attribute names (for example `dc:creator`, `xml:space`) and
adds `xmlns` / `xmlns:<prefix>` keys to `attributes`, so `from xml
--namespaces | to xml` keeps the namespaces of a document. The default
output is unchanged.
- The help text of `from xml` now says `attributes` instead of `attrs`.

## Additional notes

- Tests: unit tests in `crates/nu-command/src/formats/from/xml.rs` and
round-trip tests in `crates/nu-command/tests/format_conversions/xml.rs`.
The flag tests fail on main; the default-output tests pin the unchanged
behaviour. There is also one example for `test_examples`.
- Run on my machine: `cargo fmt --all --check`, `cargo nuclippy`,
`typos`, `cargo test -p nu-command --all-targets` (1016 + 5422 passed)
and the nu-std tests.
- Without the flag the output is byte for byte the same as before on 304
XML files from my system (293 identical, 11 fail to parse the same way
in both).
- Timing (debug build, median of 5, files of 2-3 MB): without the flag
it is within noise of main. With `--namespaces`, a file with a few
namespaces takes about 10-25% longer, and a file with 200 declarations
on the root takes about 3x (0.3 s to 1 s). I did not measure a release
build.
- Known differences with the flag: if several prefixes are bound to the
same namespace, the prefix written back can differ from the original
(same document); declarations are written before the other attributes;
an explicit `xmlns:xml` declaration is not shown because roxmltree does
not expose it.
- I used AI assistance (Claude Code) while writing the code, the tests
and this description. I read the diff, understand how it works, and ran
the checks above myself.

---------

Co-authored-by: Cem Ali Polat <polatcemali58@outlook.com>
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-authored-by: Cem Ali Polat <polatcemali58@gmail.com>
2026-11-24 07:06:09 -06:00
kiyohara 627df5fbb4 docs(tutor): add for/loop tutorial (#19644)
## Description

Adds an introductory `tutor for` topic (aliases: `loop`, `loops`,
`while`, `break`, `continue`). Following `tutor conditional`, it groups
loop constructs into a single topic and focuses on `for` vs `each`
rather than serving as a full reference.

## User-facing changes (Release notes)

Added a `tutor for` tutorial covering `for`, `loop`, `while`, `break`,
and `continue`.

## Additional notes

- Part of #18895
2026-11-23 20:54:46 -06:00
Michał Fox 9d87334710 fix(open): chain the byte streams of several files like cat (#19341)
## Description

`open a.bin b.bin` flattened every file's byte stream into the output,
so each file came out as 8192 byte chunks that had nothing to do with
the content (`[8192, 1808, 8192, 8192, 3616]` for a 10000 and a 20000
byte file), which broke `lines`, `decode` and anything else looking at
the text. when every file stays a byte stream (`--raw` or no `from`
converter) they are now chained into one byte stream like `cat`, read
one after another from a flat list so many files dont nest readers. if
all streams share a type it is kept, otherwise it falls back to
`Unknown`. tables from converters are still flattened together like
before. tests: `open_multiple_files_chains_byte_streams` and
`open_multiple_files_keeps_converter_stream_type`.

## User-facing changes (Release notes)

`open` with several files that stay byte streams now returns one byte
stream, like `cat`, instead of 8 KiB chunks:

- `open a.txt b.txt | str length` gives the combined length, and `|
length` no longer counts chunks
- `open a.txt b.txt | get 0` doesnt work anymore since the result isnt a
list
- like `cat`, a file without a trailing newline runs into the next
file's first line with `lines`

for one value per file use `[a.txt b.txt] | each { open $in }`.

## Additional notes

fixes #10027
2026-11-23 14:49:30 -06:00
iamsiddhesh-dev d0ab0333bf fix running file-associated scripts with ./ paths on Windows (#19584) (#19636)
## Description

Fixes #19584.

On Windows, a script that runs through its file association (for example
a `.nu`, `.py` or `.vbs` file whose extension is in `PATHEXT`) worked as
`.\script.nu` but failed as `./script.nu`:

```
> ./test.nu
'.' is not recognized as an internal or external command,
operable program or batch file.
```

**Cause:** for these scripts `run-external` launches `cmd.exe /D /C
<name>` so Windows applies the file association. The name was passed
exactly as typed, and `cmd.exe` treats `/` as a switch character, so it
read `./test.nu` as the command `.` followed by the switch `/test.nu`.

**Fix:** for file-associated scripts, the name as typed is normalized
before it's handed to `cmd.exe`. The new helper `cmd_script_path`
re-joins the name's path components, which turns every `/` into `\` and
drops redundant `.` components while keeping a leading `.`, e.g.
`./sub/./test.nu` → `.\sub\test.nu`. Only the typed name reaches
cmd.exe, never the cwd or a PATH directory, so spaces or characters like
`&` in those directories can't affect cmd.exe's parsing.

CMD internal commands (`echo`, `assoc`, `start`, …) still receive the
name as typed, so their behaviour is unchanged. `.exe`, `.com`, `.bat`,
`.cmd` and `.ps1` files don't go through this code path.

### Before / after

Tested on Windows 10 Pro 19045 with `.vbs` files, which Windows
associates with WScript by default (`.VBS` is in the default `PATHEXT`).
The test script writes a marker file, so `RAN` means it really executed.

Before (0.116.1 release; `main` at 594dd47c5 behaves the same):

```
.> .\hello.vbs                     => RAN
.> ./hello.vbs                     => FAILED '.' is not recognized as an internal or external command,
.> ./hello                         => FAILED '.' is not recognized as an internal or external command,
.> ./sub/hello.vbs                 => FAILED '.' is not recognized as an internal or external command,
.> ./sub/./hello.vbs               => FAILED '.' is not recognized as an internal or external command,
.> "./sub dir/hello.vbs"           => RAN
John Doe> .\hello.vbs "a b"        => RAN
John Doe> ./hello.vbs "a b"        => FAILED '.' is not recognized as an internal or external command,
R&D> .\hello.vbs                   => RAN
x&whoami&y> .\hello.vbs            => RAN
^echo cmd-builtin-ok               => cmd-builtin-ok
```

After (this PR):

```
.> .\hello.vbs                     => RAN
.> ./hello.vbs                     => RAN
.> ./hello                         => RAN
.> ./sub/hello.vbs                 => RAN
.> ./sub/./hello.vbs               => RAN
.> "./sub dir/hello.vbs"           => RAN
John Doe> .\hello.vbs "a b"        => RAN
John Doe> ./hello.vbs "a b"        => RAN
R&D> .\hello.vbs                   => RAN
x&whoami&y> .\hello.vbs            => RAN
^echo cmd-builtin-ok               => cmd-builtin-ok
```

### Tests

- New Windows integration tests in
`crates/nu-command/tests/commands/run_external.rs` (`mod
file_association`), using `.vbs` (default WScript association, no
registry change). Each prefix (bare, `^`, `run-external`) × script is
its own rstest case:
- `can_run_file_associated_scripts_with_forward_slashes`: `./hello.vbs`,
`./hello`, `./sub/hello.vbs`, `./sub/./hello.vbs`, `.\sub\hello.vbs` (15
cases)
- `can_run_file_associated_scripts_in_dirs_with_cmd_special_chars`: cwd
`John Doe` / `R&D`, with `.\hello.vbs`, `./hello.vbs`, `.\hello.vbs "a
b"` (18 cases)
- Checked that they catch the bugs: against `main` the 18 forward-slash
cases fail, and against the first version of this PR (resolved path) the
special-chars cases fail.
- Windows-only unit test `cmd_script_path_uses_backslashes` (7 rstest
cases) for the normalization itself.
- Ran locally on Windows:
  - `cargo fmt --all -- --check`
- `cargo clippy -p nu-command --all-targets -- -D warnings -D
clippy::unwrap_used -D clippy::unchecked_time_subtraction`
  - `cargo test -p nu-command --lib run_external` (10 passed)
- `cargo test -p nu-command --test tests -- commands::run_external` (124
passed, 3 ignored Linux-only)

## User-facing changes (Release notes)

Fixed an issue on Windows where running a file-associated script with a
forward-slash path such as `./script.nu` failed with `'.' is not
recognized as an internal or external command`, while `.\script.nu`
worked.

## Additional notes

- Fixes #19584
- Related: #6440, #15611 (running scripts through their file
association)
2026-11-23 14:11:12 -06:00
Darren Schroeder 0e0ce1627d Run commands only from compiled code (AST migration phase 4) (#19638)
## Description

This is phase 4 of the AST to IR call migration, after #18808, #18813,
#18967, #19351 and #19462. Commands now run only from compiled IR, so
`engine::Call` loses its AST variants and the code that handled them
goes too.

Plain `cal` was the last runtime code that built an `ast::Call`, to run
`table --index false`. It now runs `table` through `eval_ir_call`, as
`help` does. The rest is deletion: `CallImpl::AstRef`/`AstBox`,
`eval_call`, `eval_external`, `impl CallExt for ast::Call`, and the AST
branches in `get`, `run`, `run-internal`, known externals and plugin
calls.

The AST evaluator stays, because `explain` and the parser info of
`source`, `source-env` and `run` still use it. Its call arms now return
an error, which fixes two `explain` bugs. `explain` evaluates every
argument, and a keyword's argument can be a call. For `else if` that
call is `if`, whose `run` panics. For `alias x = cmd` it ran `cmd`. Both
now show an error value. An argument that holds a subexpression, like
`(1 + 2)`, now shows its source text and parsed type instead of an
internal debug dump. `explain` doesn't run it, because that would run
its commands.

The AST `has_flag` was the only check that a builtin's switch got a
bool. The parser rejects `ls --all=5`, but `ls --all=$x` with `$x` typed
`any` and set to `5` counted as set. Builtins, const calls and custom
commands now give the error `%$cmd` already gave. A builtin checks when
it reads the switch, so one that never reads it still ignores a bad
value.

## User-facing changes (Release notes)

- `explain` no longer crashes on `else if`, and no longer runs the
command an `alias` points to.
- `explain` shows an argument with a subexpression, like `(1 + 2)`, as
its source text and parsed type.
- Breaking change: a switch given a value that isn't a bool, as in `ls
--all=$x` with `$x` set to `5`, is an error. It used to count as set.

## Additional notes
2026-11-23 08:28:07 -06:00
Darren Schroeder 72286fccfd Show parse-time evaluation errors on one line (#19635)
## Description

When evaluation fails at parse time, as in `hide $env.bar` or `const x =
[] | first --strict`, `ShellError::wrap` made a `ParseError` whose
message was the whole rendered report, with box drawing, source snippet
and color codes. Everything that shows an error as one line got that
report. The REPL status line printed it with each line break as a
literal `\n`. The language server, `nu --ide-check`, the debug adapter
and `nu check --debug` passed it on as the message.

`wrap` now builds a new `ParseError::ParseTimeEval`. Its message is
still the report, so printed errors don't change, but it also keeps the
evaluation error. The one-line places show that error's headline and
first label. Editors underline the label's span instead of the whole
value. The MCP server gets the evaluation error's own code, message,
help and labels.

## User-facing changes (Release notes)

- The REPL status line no longer crams a whole error report onto one row
for errors from parse-time evaluation, such as `hide $env.bar`. It shows
`✗ Not a constant: Value is not a parse-time constant`.
- The language server, `nu --ide-check`, the debug adapter and `nu check
--debug` show these errors as one line. Editors underline the part that
failed, such as `into int` in `const d = ('abc' | into int)`.
- The MCP server reports these errors with the evaluation error's own
code, message, help and labels.

## Additional notes
2026-11-23 08:27:31 -06:00
Darren Schroeder 7e1fe77d46 Turn on native-clip and cell-path-types by default (#19634)
## Description

This PR changes two experimental options from opt-in to opt-out, so
they're on by default. Both have been opt-in for more than three months.

- `native-clip` arrived in 0.110.1, tracked in #17665. It adds the
built-in `clip copy` and `clip paste` commands, which use the OS
clipboard API instead of OSC 52.
- `cell-path-types` arrived in 0.111.1, tracked in #17683. It infers the
types of cell paths like `$foo.a.b` at parse time, so the parser reports
a type mismatch before the script runs.

`dc-glob` is old enough too, but it stays opt-in for now.

Since both options are now on for everyone, this PR also fixes three
bugs that were reachable only with an option turned on:

- `cell-path-types` typed an optional path like `$list.5?` as the
element type, `int`, so `let x: nothing = $list.5?` failed to parse. Now
a path with any `?` member is typed `oneof<int, nothing>`.
- On Linux, `clip copy` always used the background clipboard thread,
because `$env.config.clip.resident_mode = false` was ignored. The
setting now works, and the old `plugins.clip.NO_RESIDENT` key still
overrides it when set.
- If the OS refused to start that thread, `clip copy` panicked. Now it
returns an error.


## User-facing changes (Release notes)

- The `native-clip` experimental option is now on by default. `clip
copy` and `clip paste` are built-in commands that use the system
clipboard directly. `use std/clip` still adds the OSC 52 commands `clip
copy52` and `clip paste52`.
- This breaks `"text" | clip` on Windows, which used to run `clip.exe`.
Now `clip` is the built-in command and that line fails to parse. Use
`clip copy`, or `^clip` to run `clip.exe`.
- The `cell-path-types` experimental option is now on by default.
Nushell infers the type of cell paths such as `$record.field` while
parsing, so assigning one to a variable of the wrong type fails before
the script runs. Before, the error appeared only when the line ran.
- On Linux, `$env.config.clip.resident_mode = false` now turns off the
background clipboard thread.
- To get the old behavior, turn either option off with `nu
--experimental-options '[native-clip=false, cell-path-types=false]'`, or
set `NU_EXPERIMENTAL_OPTIONS=native-clip=false,cell-path-types=false`
for sessions that load your config.

## Additional notes
2026-11-23 08:26:54 -06:00
Darren Schroeder aa8bb3fd81 Move dates from chrono to jiff (#19626)
## Description

chrono is unmaintained, so this PR moves nushell's dates to jiff 1.0.
`Value::Date` now holds `nu_protocol::DateTime`, which stores Unix
seconds, nanoseconds and a jiff `Offset`. It is 16 bytes and `Copy`,
like chrono's type, so `Value` stays at 48 bytes. jiff does the
calendar, time zones, parsing and `strftime`. Its range, years -9999 to
9999, is now nushell's.

Output only changes where the release notes say so. `Display`, `Debug`,
RFC 3339, RFC 2822, serde and `format date` print what chrono printed,
localized names included. Input goes through jiff. Date literals, `from
nuon`, `FromStr` and serde use its RFC 3339 reader. `into datetime
--format`, `seq date --input-format` and `from kdl` use its strptime,
plus a small table that keeps chrono's meaning for `%c %x %X %r %v %+
%Z`, nushell's `%J` and `%Q`, and offsets with or without colons. `date
from-human` reads GNU `date` syntax through parse_datetime, after a few
rewrites such as `in 3 days` and `overmorrow`.

chrono-tz, chrono-humanize and human-date-parser leave the dependency
tree, along with the chrono features of rusqlite and calamine. chrono
stays in `Cargo.lock` because rmcp and polars use it. The
chrono-humanize wording and chrono's UTC offset readers are ported under
the MIT license, and each file keeps its notice.

## Before and after

main is 3d8a9cc6e. Both ran with `TZ=America/New_York` on 2026-11-21 at
13:38. Error cells are cut to the reason.

| Command | main | branch |
|---|---|---|
| `2025-04-18T16:04:32.02649+05:30 \| format date '%N'` | `× invalid
format` | `026490000` |
| `'9999-12-31' \| into datetime \| to nuon` |
`9999-12-31T00:00:00-05:00` | `× datetime parsing failed` |
| `2001-02-03T04:05Z \| to nuon` | `× Command 2001-02-03T04:05Z not
found` | `2001-02-03T04:05:00+00:00` |
| `2016-12-31T23:59:60.5Z \| to nuon` | `2016-12-31T23:59:60.500+00:00`
| `2016-12-31T23:59:59.500+00:00` |
| `'Today at 6pm' \| date from-human \| format date '%H:%M'` | `13:38` |
`18:00` |
| `'today at 6pm blah' \| date from-human \| format date '%H:%M'` |
`13:38` | `× Cannot parse as humanized date` |
| `'next hour' \| date from-human \| format date '%H:%M'` | `× Main
thread panicked.` | `14:38` |
| `'6pm tomorrow' \| date from-human \| format date '%a %H:%M'` | `×
Cannot parse as humanized date` | `Sun 18:00` |
| `'TZ="Europe/Paris" 2025-04-18 04:04' \| date from-human \| to nuon` |
`× Cannot parse as humanized date` | `2025-04-18T04:04:00+02:00` |
| `'2025-03-09 02:00' \| into datetime \| to nuon` |
`2025-03-09T02:00:00-05:00` | `2025-03-09T03:00:00-04:00` |
| `'2025-03-09 02:30' \| into datetime --format '%F %H:%M' \| to nuon` |
`× datetime parsing failed` | `2025-03-09T03:30:00-04:00` |
| `2026-07-01T16:00:00Z \| date to-timezone local \| to nuon` |
`2026-07-01T11:00:00-05:00` | `2026-07-01T12:00:00-04:00` |
| `'2021-02-30 10:00' \| into datetime --format '%F %H:%M' \| to nuon` |
`2026-11-21T10:00:00-05:00` | `× … parameter 'day' for 2021-02 is
invalid, must be in range 1..=28 …` |
| `'-5' \| into datetime --format '%s' \| to nuon` | `× can't convert
input contains invalid characters …` | `1969-12-31T23:59:55+00:00` |
| `'07/20/69' \| into datetime --format '%D' \| to nuon` |
`2069-07-20T00:00:00-04:00` | `1969-07-20T00:00:00-04:00` |
| `'Jan 05 2024' \| into datetime --format '%B %d %Y' \| to nuon` |
`2024-01-05T00:00:00-05:00` | `× … %B failed: unrecognized month name …`
|
| `'2021-03-04 10:00 PST' \| into datetime --format '%F %H:%M %Z' \| to
nuon` | `2021-03-04T10:00:00-05:00` | `× can't convert input contains
invalid characters …` |
| `'2021-03-04 10:00:00 -0800 GMT' \| into datetime --format '%F %T %z
%Z' \| to nuon` | `2021-03-04T10:00:00-08:00` | `× can't convert no
possible date and time matching input …` |
| `2100-07-01T12:00:00Z \| date to-timezone America/New_York \| format
date '%:z'` | `-05:00` | `-04:00` |

## Release notes

- Dates run from year -9999 to 9999, where main reached 262142.
9999-12-31 at UTC is past jiff's last instant, so `'9999-12-31' | into
datetime` is an error, and `from toml` and `from msgpack` keep such a
date as text.
- Date literals and `from nuon` read `2001-02-03T04:05Z`,
`[2024-01-15T10:00]` and offsets like `+0530` and `-08` as dates.
`2024-01-15T1030` is still a string, and a fraction longer than 9 digits
no longer reads.
- Second 60 reads as second 59 everywhere.
- `into datetime --format`, `seq date --input-format` and `from kdl`
follow jiff's strptime. A date that doesn't exist or a weekday that
doesn't match is an error, where main gave today at that time. `%B` and
`%A` take only full names, and `%b` and `%a` only abbreviations.
Two-digit years run from 1969 to 2068. `%s` can be negative, and it wins
over a date in the same text.
- `%Z` reads `UTC`, `GMT` and offsets. Other names such as `PST` are an
error, unless `%z` gives the offset, so `+0900 JST` reads. `UTC` or
`GMT` next to a different offset, as in `-0800 GMT`, is an error.
- `format date` and `$env.config.datetime_format` accept `%N`, `%#z` and
the `^` flag, and `datetime_format` drops `%E` and `%O` the way `format
date` does. `seq date --output-format` prints `+0000` for `%z` instead
of failing.
- `date from-human` reads GNU `date` syntax: `6pm tomorrow`, `today
1430`, `@1744972472`, and a leading `TZ="Europe/Paris"`. `next month`,
`next hour` and `today at 6pm` give the right date, where main misread
them or panicked. Text after a date is an error.
- A local time in a DST gap moves forward by the jump, with or without
`--format`. Wall-clock times get the offset of their own date, not
today's, in records, `date to-timezone local`, `date from-human`, `from
xlsx` and `from ods`.
- Time zones come from the system's tzdata, with a bundled 2026f copy as
the fallback, instead of chrono-tz's 2025b. 13 zones have a different
offset today than on main, and DST rules continue past 2099.
- RFC 3339, RFC 2822 and TOML text round a local mean time offset to the
minute and move the clock with it, so the text names the same instant. A
record's `timezone` keeps its seconds.
- polars rejects a date outside 1677-09-21 to 2262-04-11, where main
stored 1970-01-01 or null. A record `year` too large for 32 bits is an
error, and `to plist` rejects years before 0 instead of crashing.
- For plugin authors, `Value::date` and `Value::as_date` take
`nu_protocol::DateTime`. nu-protocol's `chrono` feature converts to and
from `chrono::DateTime<FixedOffset>`. Older plugins keep working, since
dates cross the wire as the same text.
2026-11-23 08:26:13 -06:00
Darren Schroeder 43661e3c9a fix(rm): retry rm -r when a directory is left not empty (#19637)
## Description

On macOS, `rm -rf node_modules` can fail with `Directory not empty (os
error 66)` and leave part of the tree behind, while a second `rm -rf`
removes the rest (#19599).

`rm -r` hands each directory to `std::fs::remove_dir_all`. That function
deletes each directory's entries while it reads them, and it stops at
the first error. When one nested directory still has an entry at the
end, the whole removal stops. In the report, 12,399 of 41,026 entries
survived the first run. The path in the error is the argument `rm` was
given, not the directory that was still not empty. `^rm -rf` removes the
same tree on the first run, and zsh's builtin `rm` reads every name in a
directory before deleting any of them.

`rm` now calls `remove_dir_all` again, up to 3 times in all, when it
fails with "Directory not empty". Each call opens every directory again
and continues from what is left. Other errors are returned right away.
Ctrl-C is checked before each retry, so a long retry can be stopped.
`remove_dir_all` keeps its no-follow, fd-relative traversal, so the
retry doesn't reopen the symlink race.

## User-facing changes (Release notes)

Fixed `rm -r` on macOS sometimes stopping partway through a large
directory with "Directory not empty". `rm` now retries the removal
before it reports that error.

## Additional notes

closes #19599
- I couldn't reproduce the failure locally, so there is no before/after
output. The reporter sees it only in their original project, never in a
fresh install from the same lockfile. The unit tests pass a fake removal
function to the retry loop and check it retries on "Directory not
empty", gives up after the last try, returns other errors without
retrying, and stops on Ctrl-C before a retry.
- If the tree is already gone on a retry, that counts as success,
because an earlier call removed part of it.
- The retry isn't gated to macOS. Elsewhere it only runs after a removal
that would have failed anyway.
2026-11-23 06:28:37 -06:00
Ted LukinandDarren Schroeder 3dbf050604 make string hooks behave like closure ones (#19600)
<!--
Thanks for contributing to Nushell!

Before submitting, please read the contributing guide:
https://github.com/nushell/nushell/blob/main/CONTRIBUTING.md

This template helps reviewers understand your changes and allows us to
generate high-quality release notes.
-->

## Description
<!--
Explain what this PR does and why.

This section is intentionally flexible:
- Describe the problem
- Explain your approach
- Include technical details if relevant

Good examples:
- "In this PR, I fixed..."
- "In this PR, I added support for..."
- "This change improves X by..."

Write as much or as little as needed for reviewers to understand your
changes.
-->
~~pure refactor, semantically everything (i hope) should be the same.~~
removed like 50 lines of code duplication (`eval_string_hook`), also
changed `let mut output; match { x => output = ... }` to just `let
output = match { ... } and eventually went to also fix some stuff, see
release notes

## User-facing changes (Release notes)
<!--
This section is used (mostly as-is) for https://www.nushell.sh/blog/

Describe how Nushell behavior changes from a user's perspective.
Do NOT describe internal Rust changes here.

Write in a release note style, for example:
- "Added support for..."
- "Fixed an issue where..."
- "Nushell now supports..."
- "Improved performance of..."

If your changes do NOT affect users (internal refactors, cleanup, etc.),
just write:
- "n/a"
- "nan"
- or similar

This tells us the change should not appear in the changelog.

Tips:
- Focus on observable behavior
- Include examples if helpful
- Keep it concise

You can:
- Write a short paragraph (will appear as a bullet point), OR
- Use headings (###) if your change needs more structure

Avoid writing things like:
- "In this PR, I refactored..."
- "This updates internal code..."

You may leave this blank until the PR is ready.
-->
Did you know that you could cause internal panic with
`$env.config.hooks.command_not_found = "hello"; try { world }`? Well now
you can't. String hooks should now match the behavior of closure ones,
for example they no longer are just printed and then swallowed, so you
can correctly catch them.
The only difference remaining is formatting of errors happening inside
the hook itself - string hooks can only point at their source string in
general, whereas closure hooks point at the exact place the error
occurred.
<!--
## Additional notes
Optional.

Examples:
- fixes #123
- closes #456
- related #789

Anything else reviewers should know.
Remove this section if not needed.
-->

---------

Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com>
2026-11-22 18:23:07 -06:00
Stuart Carnie 86d3396635 Add striped rows to table and explore (#19575)
## Description

In this PR, I added striped rows to `table` and `explore`: every other
data row gets a different background, which makes wide tables easier to
read across.

<img
src="https://cdn.discordapp.com/attachments/615329862395101194/1572010038610894980/CleanShot_2026-11-17_at_09.06.242x.png?ex=6afccfef&is=6afb7e6f&hm=b78f4a5e3bd4c1655bf3f5023dd237c751d711492569690a0b1dc0b7834fe854"
/>

Striping is turned on with `$env.config.table.striped`, and its colors
come from `color_config`, as plain colors like the rest of it:
`row_stripe_bg` for the first row and every other one, `row_stripe_alt`
for the rows between them. When only `row_stripe_bg` is given, as
`"#rrggbb"`, the alternate color is worked out from it: its WCAG 2
relative luminance[^luminance] decides whether white or black is laid
over it, composited at `$env.config.table.stripe_blend` (default
`0.08`), so stripes are slightly lighter on a dark background and
slightly darker on a light one. With neither color set there are no
stripes.

For stripes that follow the terminal, `std/config` gets two commands,
`terminal-background` and `terminal-foreground`, in the way of `std/clip
paste52`: they ask the terminal with `term query` and return the color
as `"#rrggbb"`, or nothing from a terminal that does not report its
colors, or when stdin or stdout is not a terminal. The cursor position
is asked for after the color, so a terminal that does not report its
colors still answers and nothing waits. They are for `config.nu`, once,
when nushell starts; `doc_config.nu` has the lines for it.

In `table`, stripes are painted onto the rendered text between the outer
borders, which leaves the existing color logic untouched, and the
background is put back after any escape sequence in a cell that resets
it. With `table --expand`, only the rows of the outer table are striped.
In `explore`, the row backgrounds are set on the ratatui buffer, under
cells that have no background of their own, and follow the rows while
scrolling.

[^luminance]: The brightness of a color as the eye perceives it, from 0
(black) to 1 (white): each sRGB channel is made linear, then they are
summed as `0.2126 R + 0.7152 G + 0.0722 B`, green counting most. Defined
in [WCAG 2.2](https://www.w3.org/TR/WCAG22/#dfn-relative-luminance). A
background above 0.179, where black and white contrast with it equally,
counts as light.

## User-facing changes (Release notes)

### Striped table rows

`table` and `explore` can now draw every other row on a different
background. It is off by default, and takes a color to make the stripes
from:

```nu
$env.config.table.striped = true
$env.config.color_config.row_stripe_bg = "#282c34"   # the background of your terminal
```

The stripe is a little lighter than a dark `row_stripe_bg` and a little
darker than a light one. `$env.config.table.stripe_blend` sets how
strong it is, from `0.0` to `1.0` (default `0.08`), or set its color
yourself:

```nu
$env.config.color_config.row_stripe_alt = "#393d44"  # the rows between
```

To take `row_stripe_bg` from the terminal when nushell starts:

```nu
use std/config terminal-background
if $nu.is-interactive and $env.config.table.striped {
    let background = terminal-background
    if $background != null { $env.config.color_config.row_stripe_bg = $background }
}
```

`terminal-background` returns nothing from a terminal that does not
report its background, which leaves tables without stripes. Keys typed
before the terminal answers are lost, so this belongs where nushell
starts, not at each prompt. `terminal-foreground` gives the color of the
text the same way.

## Additional notes

- No new dependency, and nothing that differs between platforms: the PR
touches `nu-table`, `nu-explore`, the config and its documentation, and
`std/config`.
- `row_stripe_bg` is painted on its rows, so setting it to the
terminal's background shows on a terminal with a transparent background
or a background image. `row_stripe_alt` alone leaves those rows as they
are.
- Not striped: tables nested in a `table --expand` cell, the markdown
and reStructuredText themes, `table --collapse`, and the transposed
layout of `explore`.
- `terminal-background` and `terminal-foreground` have no automated
test, as they need a terminal. They were tried against a fake terminal
(one that reports colors, as `rgb:` or `rgba:`, with channels of one,
two and four digits and either string terminator; one that does not;
stdout sent to a file; and no terminal at all), not in a real one.
- `term query` has no timeout: where nothing answers either query, as in
a pty with no terminal behind it, the commands wait until Ctrl+C. Over
ssh to Windows they return nothing, as the terminal's color reply does
not get through. `explore` is covered by widget tests, not run on a live
terminal. `typos` was not run locally.
2026-11-22 17:18:52 -06:00
Darren Schroeder 933b486fff Speed up the IR evaluator and build releases with opt-level 3 (#19628)
## Description

Scripts that loop, do arithmetic or call custom commands spent most of
their time on evaluator bookkeeping. This PR cuts most of it:

- Register writes no longer allocate. `PipelineExecutionData` filled its
exit-status list with `vec![None]` for every value. Now only an
external's output adds an entry.
- `binary_op` runs on the operands in their registers and writes the
result in place. Literal loads, variable loads, `span` and `collect_reg`
also write in place.
- The compiler drops the `load-literal` + `drain` pair after an
assignment or `let` used as a statement, since neither instruction did
anything. The drain stays when a jump lands on it, because a value from
another branch still needs draining there.
- The callee's parent stack, which `scope variables` reads, was a clone
of the whole caller stack on every call. Custom command calls now lend
the caller's variables to it and take them back afterwards. Closure
calls copy only the variables. Argument normalization and the
`NU_BACKTRACE` lookup are skipped when they have nothing to do.
- Release builds use `opt-level = 3` instead of `"s"`.

### Before and after

`main` is bc405a223 with its release profile. The scripts come from
[shellarena](https://github.com/navid-m/shellarena), and the 100x rows
run 100 times the iterations. Measured on macOS arm64. Wall time is from
hyperfine with the load average under 3, and instructions retired are
the median of 3 runs.

| script | wall, main | wall, this PR | instructions, main |
instructions, this PR |
|---|---|---|---|---|
| empty script | 11.7 ms | 11.6 ms | 85.7M | 82.6M |
| arith (10k iterations) | 29.6 ms | 18.8 ms | 300.2M | 169.6M |
| strings (10k appends) | 37.8 ms | 25.0 ms | 393.3M | 241.7M |
| func (5k custom command calls) | 27.2 ms | 18.0 ms | 277.0M | 163.5M |
| arith 100x | 1.77 s | 0.73 s | 21,193M | 8,691M |
| strings 100x | 2.54 s | 1.29 s | 29,987M | 15,567M |
| func 100x | 1.47 s | 0.63 s | 17,590M | 7,675M |
| 40k command and closure calls, caller holds three 100 KB strings | 341
ms | 175 ms | 3,687M | 1,868M |

Startup didn't change, so short scripts gain less. `opt-level = 3` alone
cuts instructions by 6-8%, and it grows `nu` from 81.1 MB to 89.9 MB.
Plugins use the same profile, so they grow too. I didn't measure them.

`view ir` for the arith script drops from 58 to 46 instructions. The
first `mut` and the end of the loop:

```
main                                      this PR
 1: store-variable  var 74, %0  # let      1: store-variable  var 74, %0  # let
 2: load-literal    %0, empty              2: load-literal    %0, empty
 3: drain           %0                     3: load-literal    %0, empty
 4: load-literal    %0, empty              4: load-literal    %0, int(1)
 5: load-literal    %0, empty             ...
 6: load-literal    %0, int(1)            42: store-variable  var 74, %0
...                                       43: jump            12  # while
52: store-variable  var 74, %0
53: load-literal    %0, nothing
54: drain           %0
55: jump            18  # while
```

## User-facing changes (Release notes)

- Loops, arithmetic and custom command calls run about twice as fast in
longer scripts.
- `view ir` no longer shows a `load-literal` + `drain` pair after an
assignment or `let` used as a statement.
- Release builds are optimized for speed instead of size, so `nu` is
about 11% larger.

## Additional notes
2026-11-22 13:59:43 -06:00
Martin Kronberger 3b036537d2 fix(config): let the prompt indicators take a closure again (#19612)
## Description

#18734 moved the prompt into `$env.config.prompt`, but the indicator
keys only took a string.
`$env.PROMPT_INDICATOR` and the other indicator variables always took a
closure too, thus migrating an indicator that changes with
`$env.LAST_EXIT_CODE` to the new keys was not possible.

This was never a decision.
The indicators moved first, typed as `String`, before `left` and `right`
joined the PR.
When those followed it turned out config can hold closures after all
(`Hooks` already does), but the indicator keys were never widened.

The indicators now go through the same path as `left` and `right`:
- **config**: the transient keys parse with `update_prompt_source`, the
live keys with an `update_indicator` that differs only by rejecting
`null`, since every edit mode draws an indicator.
- **resolution**: every segment resolves through
`resolve_prompt_source`, `vi_visual` (no variable) through `render`
directly.
- **removed**: `update_optional_string`, `resolve_indicator` and
`resolve_transient_indicator`, which only existed to carry the narrower
type.

A closure that fails to render reports its error and falls back to the
built-in indicator.
`input --reedline` renders the keys the same way.

**Scrutinize**: `crates/nu-cli/src/prompt_update.rs`, the evaluation
order of the segments is kept since any of them may have side effects
now.
**Skim**: the test updates in `crates/nu-protocol/src/config/prompt.rs`,
mostly `"x".into()` to `Value::test_string("x")`.

Tests: `nu-protocol` `config::prompt` 15/15, `nu-cli` `prompt` 28/28
including a new `configured_indicators_accept_closures` that parses and
renders real closures, `nu-command` `reedline_prompt` 1/1.
Clippy with CI flags clean on the touched crates.

## User-facing changes (Release notes)

`$env.config.prompt.indicator`, `vi_insert`, `vi_normal`, `vi_visual`
and `multiline`, plus their `transient` counterparts, now accept a
closure as well as a string, the same as `$env.PROMPT_INDICATOR` and
friends always did.

```nu
$env.config.prompt.indicator = {||
    if $env.LAST_EXIT_CODE == 0 { "> " } else { $"(ansi red)> (ansi reset)" }
}
```

## Additional notes

Follow-up to #18734.

[![AI:W
WRITE](https://img.shields.io/badge/AI-WRITE-grey?style=flat&logoSize=auto&labelColor=13171f)](https://0rwx.com)
2026-11-22 11:31:41 +01:00
Manav Kumar Dubey d5b8ab039e fix(glob): prevent directory symlink cycles during traversal (#19622)
## Description

Fixes #8736. Related to #15218.

Recursive globbing could follow a directory symlink back to an ancestor
and walk the same subtree repeatedly. For example, `ls **/sources.list`
could return the same file through progressively longer paths.

Both glob backends now skip descent when a directory link leads back to
an ancestor and continue searching sibling directories. The link itself
can still match, and separate aliases to the same target still produce
their own paths.

The review follow-up limits cycle checks to patterns containing `**`,
preserving fixed-depth matches such as `ls */up/*.txt`. Both walkers
defer directory identity lookups until they follow a directory link.
Sibling links share the parent lookup and extend the ancestor chain
independently. The `ls` cycle tests for both backends and the `glob`
alias test now run on Windows as well as Unix.

## User-facing changes (Release notes)

Recursive globbing now skips directory symlink cycles and continues
searching other directories.

## Additional notes

### Release benchmarks

I compared Cargo release builds on macOS arm64. The timings are median
wall times and include Nushell startup.

- **One symlink loop.** `ls -a **/sources.list | length` went from 33
matches to one. Legacy glob went from 15.0 to 10.1 ms, and dc-glob went
from 12.5 to 9.3 ms.
- **Two symlink loops.** Both patched backends returned all seven
expected entries in about 10 ms. The upstream runs hit the wall-time or
CPU limit before returning a count.
- **256 links sharing a parent.** Legacy glob took 21.6 ms on upstream,
25.9 ms on the earlier local revision, and 22.1 ms with the shared
lookup. The siblings now reuse one parent chain. Each link still checks
its target against that chain so cycles are pruned and valid aliases can
be traversed independently.
- **256 links under separate parents.** Legacy glob took 20.0 ms on
upstream, 20.1 ms on the previously published PR, and 27.7 ms with this
follow-up. For dc-glob, the times were 15.9, 18.1, and 24.0 ms. All
builds returned 257 matches. Deferring identity lookups avoids opening
an extra identity handle for each directory on link-free Windows walks.
In this fixture, each link has a separate parent, so the walkers
repeatedly resolve the common ancestors. The slowdown was measured on
macOS. The Windows timing impact still needs measurement.
- **Ordinary tree with 4,680 files.** The two-thread `ls` medians were
within about 1.4 ms of upstream. With one Rayon thread, dc-glob took
about 1–2 ms longer across the two patterns tested. The result sets
matched. The source of that smaller timing difference is still
uncertain.

### Compatibility and validation

One mixed-pattern case remains open. With `target/up` pointing back to
`target`, `ls -a */up/**/marker.txt` can lose `target/up/marker.txt`.
This reproduces on both the previously published PR revision and the
follow-up. I'd appreciate your take on whether to handle that case here
or in a separate matcher change.

On macOS, 13,319 workspace tests and 242 doctests passed, along with
formatting, both Clippy checks, Typos, and the WASM check and build.
Native Windows and Linux verification of the follow-up is pending.
2026-11-21 14:17:14 -06:00
CemandCem Ali Polat a661e23013 compact: accept cell paths for column arguments (#19624)
## Description

Fixes #4274.

`compact` read its column arguments as plain strings, so a nested path
was looked up as one literal key and every row was dropped:

```nu
[{labels: {c: 1}} {labels: {c: null}}] | compact labels.c
# before: []
# after:  [{labels: {c: 1}}]
```

The column arguments are now cell paths, the same change `default` got
in #19058, so `compact` and `default` read columns the same way:

- `compact a.b` follows the nested path; `--empty` applies to the nested
value too (`[{a: {b: ""}} {a: {b: x}}] | compact -e a.b` keeps only the
second row; main dropped both).
- Optional members work: `compact a?.b` drops rows where `a` or `b` is
missing or null.
- A missing column or path still drops the row, as before. Record input
and lists of non-records behave as before.
- A path that starts with a number, like `compact 2024` or `compact 0`,
is an error that asks for a quoted name (`compact "2024"`). Main also
errored on these, with "can't convert int to string"; without the check
a number would parse as a row index and silently drop every record row.
A number later in the path (`compact a.0`) works.
- A plain column name still takes a single record lookup, so there is no
slowdown for the common case (see below).

## User-facing changes (Release notes)

- `compact` accepts cell paths: `compact labels.c` checks the nested
field `c` inside `labels` instead of a column literally named
`labels.c`. To match a column whose name contains a `.` or ends in `?`
or `!`, quote it: `compact "a.b"`, `compact "a?"` (a quoted name or a
string variable still matches the literal key). Unquoted, `a?` is an
optional member and `a!` a case-insensitive one.
- Passing a non-path argument such as a list or record now gives a
parse/type error ("expected cell-path") instead of "Can't convert to
string." A bare number gives "compact needs a column name; quote a
number to match a column, like "2024"".

## Additional notes

- Tests: 11 new tests in `crates/nu-command/tests/commands/compact.rs`
(nested path, nested with `--empty`, missing nested path, several paths,
plain top-level column, quoted dotted name, optional path, a number as
the first member rejected on list rows and on record rows, quoted number
column, number later in the path) and an `examples()` entry. The nested
ones fail on main; the plain-column and quoted-name ones pin behaviour
that did not change. The two rejection tests fail with the new check
commented out.
- Run on my machine: `cargo test -p nu-command --test tests --
commands::compact` (18 passed), `cargo test -p nu-command --lib --
compact` (5 passed), `cargo fmt --all --check` and `cargo clippy -p
nu-command --all-targets -- -D warnings -D clippy::unwrap_used` are
clean.
- Performance (debug builds, 200k rows, median of 7 `timeit` runs):
`compact a` 131 ms on main, 133 ms here; `compact a id s` 178 ms on
main, 181 ms here. The first version of this change walked every column
with `follow_cell_path` and was about 1.5-2x slower, so a single plain
name now goes straight to `record.get` and only real paths walk.
- I used AI assistance (Claude Code) while writing the code, the tests
and this description. I read the diff, understand how it works, and
checked the before/after outputs above myself; the tests listed above
ran on my machine.

---------

Co-authored-by: Cem Ali Polat <polatcemali58@outlook.com>
2026-11-21 09:47:23 -06:00
Darren Schroeder bc405a2232 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`.
2026-11-21 07:15:19 -06:00
Manav Kumar Dubey f6e23c4ec6 fix(rename): clarify missing column errors (#19609)
## Description

Follow-up to #18108 for #17448.

`rename --column` could report that a column was missing from the entire
input when only a later record lacked it.

```nu
[{name: Alice} {age: 30}] | rename -c {name: n}
```

The error now labels `rename` with `cannot rename column 'name'`. The
existing highlight on `{age: 30}` now says `row 1 is missing column
'name'`. The error code is `nu::shell::unsupported_input`.

## User-facing changes (Release notes)

`rename --column` now reports the zero-based index of the input row that
is missing a requested column.

## Additional notes

- Added regression coverage for a missing column in a later record and
in a single record, the highlighted record span, and a successful mapped
rename.
- On macOS, seven rename integration tests and three rename unit tests
passed. Formatting, both Clippy checks, Typos, and `git diff --check`
also passed.
2026-11-20 10:14:20 -06:00
Chen Jiajie 0b6b84fbfd feat(cp): add -l/--link flag to create hard links (#19583)
## Description

Implements #14306: `cp` gains a `-l`/`--link` flag matching GNU `cp -l`,
which creates hard links to regular files instead of copying them.
Combined with `-r` it can hard-link a whole directory tree
(`cp -lr source dest`), the use case in the issue.

The flag just exposes `uu_cp`'s existing `CopyMode::Link`.

- `-l` cannot be combined with `-u`: uu_cp ignores `UpdateMode` in
  `CopyMode::Link`, so the combination is rejected with
  `IncompatibleParameters` rather than silently misbehaving.
- When linking, symlinks are followed and their targets are linked,
  matching uutils' `resolve_dereference` (`!recursive || is_link`).
  `-P`/`--no-dereference` links the links themselves, as noted in the
  flag's help text.

Fresh take on #14359, which went stale.

## User-facing changes (Release notes)

`cp` now supports `-l`/`--link` to create hard links to regular files
instead of copying, e.g. `cp -l a.txt b.txt`, or `cp -lr dir_a dir_b` to
recursively link a directory tree (symlinks inside the tree are followed
unless `-P` is given). `-l` cannot be combined with `-u`.

## Additional notes

- closes #14306
- supersedes #14359
- Tests in `crates/nu-command/tests/commands/ucp.rs` check hard-link
  semantics portably (write-through, no inode APIs): `cp -l` on a single
  file, `cp -lr` on a tree with a symlink, `cp -l` over an existing
  destination, `cp -lf` replacing it, and `cp -lu` erroring.
- `linking_does_not_change_source_mode` is a regression test for
  uutils/coreutils#15087 (chmod after hard link used to mutate the
  source's mode); uu_cp 0.13.0 on main has the fix.
- `commands::ucp::test_cp_debug_default` fails on macOS on unmodified
  `main` (uu_cp reports `reflink: yes` on APFS); unrelated to this
  change.
2026-11-20 09:13:01 -06:00
Aradhya Jain ca706392de to csv/tsv: add --quote and --escape, matching from csv/tsv (#19328)
## Description

`from csv`/`from tsv` already expose `--quote`/`-q` and `--escape`/`-e`
flags, wired straight into `csv::ReaderBuilder::quote()`/`.escape()`.
The
write-side siblings `to csv`/`to tsv` only ever exposed
`--separator`/`--noheaders`/`--columns` -- the shared writer helper
never
touched `csv::WriterBuilder::quote()`/`.escape()` at all, even though
the
same `csv` crate's `WriterBuilder` supports both symmetrically to
`ReaderBuilder`. Net effect: you could parse CSV/TSV written with a
custom
quote or escape character, but never produce it, so round-tripping
non-default-quoted data was impossible.

This adds the same `--quote`/`--escape` flags to `to csv` and `to tsv`,
threaded through the shared `to_delimited_data` helper's two
`WriterBuilder` construction sites (the materialized-input and
streaming-
input paths both build a writer independently).

One thing worth calling out for reviewers: `WriterBuilder::escape`
(unlike
`ReaderBuilder`'s) only has an effect once `double_quote` is turned off
--
by default `csv` escapes embedded quotes by doubling them, and the
idiosyncratic single-escape-character style is an alternative to that,
not
an addition on top of it. So `--escape` also disables the default
doubled-quote escaping when set, matching the `csv` crate's own
documented
behavior.

## User-facing changes (Release notes)

- Added `--quote`/`-q` and `--escape`/`-e` flags to `to csv` and `to
tsv`,
matching the existing flags on `from csv`/`from tsv`, so CSV/TSV output
  can use a custom quote or escape character instead of the default `"`
  and doubled-quote escaping.

## Additional notes

n/a
2026-11-20 08:32:18 -06:00
Darren Schroeder 75ead0b200 Keep failures in $env.LAST_EXIT_CODE until something resets them (#19607)
## Description

A failure now stays in `$env.LAST_EXIT_CODE` until another command sets
a code or you reset it with `$env.LAST_EXIT_CODE = 0`. Three places
dropped it. `try` without `catch` kept the old code. The REPL set 0
after every line that didn't error, so a failure the line handled never
reached the prompt. A hook that failed without catching it left the code
alone, and so did one ending in a failing external.

This works like PowerShell's `$LASTEXITCODE`, which error handling never
resets. `catch` can keep or reset the code, `finally` sees it, and `nu
-c 'try { error make {msg: x} }'` still exits 0.

A record hook with a string `code` (`{code: "..."}`) now runs like a
plain string hook. It gets the hook's input and doesn't inherit the
caller's output redirection.

Tables compare main with this branch.

| `$env.LAST_EXIT_CODE = 5`, then | main | this branch |
|---|---|---|
| `try { ^sh -c "exit 7" }` | 5 | 7 |
| `try { error make {msg: x} }` | 5 | 1 |
| `try { ^sh -c "exit 7" } catch { }` | 7 | 7 |
| `try { ^sh -c "exit 7" } catch { $env.LAST_EXIT_CODE = 0 }` | 0 | 0 |
| `try { "fine" }` | 5 | 5 |

| Line typed at the prompt | main | this branch |
|---|---|---|
| `try { ^sh -c "exit 7" }` | 0 | 7 |
| `try { ^sh -c "exit 7" } catch { }` | 0 | 7 |
| `try { ^sh -c "exit 7" } catch { $env.LAST_EXIT_CODE = 0 }` | 0 | 0 |
| `try { ^sh -c "exit 7" }; ^true` | 0 | 0 |
| `$env.LAST_EXIT_CODE = 4` | 0 | 4 |
| `ls \| ignore` | 0 | 0 |

| Hook, code at the next prompt | main | this branch |
|---|---|---|
| `pre_prompt = [{\|\| ^sh -c "exit 9"; null }]` | 0 | 9 |
| `pre_prompt = [{\|\| ^sh -c "exit 8" }]` | 0 | 8 |
| `env_change.FOO = [{\|\| ^sh -c "exit 8" }]`, then `$env.FOO = 1` | 0
| 8 |
| `display_output = [{\|\| try { ^sh -c "exit 7" } catch { } } {\|\|
table }]`, then `1` | 0 | 7 |

| Record hook with a string `code` | main | this branch |
|---|---|---|
| `display_output = {code: "$in \| describe"}`, then `[1 2 3]` |
`nothing` | `list<int>` |
| `pre_prompt = [{code: 'try { "x" }'}]` | prints `x` before each prompt
| prints nothing, like the plain string |
| `command_not_found = {code: "^echo from-hook"}`, then `try { nosuch }
catch { "caught" }` | `caught` | `from-hook`, `caught` |


## User-facing changes (Release notes)

- `try` without `catch` sets `$env.LAST_EXIT_CODE` to the code of the
failure it handles, or 1 if the error has none.
- At the prompt, `$env.LAST_EXIT_CODE` keeps a code the line set, so
`try { ^false }` shows 1 instead of 0.
- A failing `pre_prompt`, `pre_execution` or `env_change` hook sets
`$env.LAST_EXIT_CODE`, also when the failure is an external at the end
of the hook. A failing `env_change` hook runs once per change instead of
before every prompt.
- A record hook with a string `code` gets the hook's input, so
`display_output = {code: "table -e"}` prints the table. In `pre_prompt`
and `env_change` it no longer prints a value it ends with, and in
`command_not_found` an external it runs writes to the terminal.

## Additional notes

- `do -i` still sets 0 for a failing external. Eating errors is its job.
- An external at the end of a `command_not_found` or `display_output`
list hook still isn't checked. In `command_not_found`, checking it would
replace the "command not found" error with, say, `pkgfile`'s exit
status.
- After a `command_not_found` hook runs, env vars set earlier in the
same line or script are gone, `$env.LAST_EXIT_CODE` included. Main does
the same.
2026-11-20 07:58:15 -06:00
Darren Schroeder a6416ebf3c Report an error for a spread in use members (#19598)
## Description

`use m ...$names` parsed without an error and imported none of the names
([#19514](https://github.com/nushell/nushell/issues/19514)). `use`
declares `members` as a rest parameter, so the call parser accepted the
spread, but `parse_use` reads its members with `positional_iter()`,
which stops at the first spread. So `parse_use` dropped the spread and
everything after it, and `use m ...$names` behaved like `use m`.

`use` resolves imports at parse time, so a `let` list can never be
spread there. The parser already rejects a spread inside a member list,
`use m [...$names]`, with "cannot spread in an import pattern". This PR
reports the same error for a spread member, in `use` and `export use`.
`hide` and `overlay use` have no rest parameter. `hide m ...$names` is
already a parse error, and `overlay use m ...$names` fails at run time.

## User-facing changes (Release notes)

`use` now reports a parse error for a spread member (`use m ...$names`).
It used to be accepted and import none of the listed names.

## Additional notes

closes #19514
2026-11-20 07:57:42 -06:00
CemandCem Ali Polat 18424af6f9 headers: rename repeated column names instead of creating duplicates (#19619)
## Description

Fixes #11020.

If the first row repeats a value, `headers` built a record with two
columns of the same name. A name-based lookup then sees only one of
them, so the other value is silently lost:

```nu
[[a b]; [x x] [1 2]] | headers | get x_1
# before: Error: nu::shell::column_not_found
# after:  [2]
```

With non-string headers the old build even drops a column:

```nu
[[a b c]; [1 1.0 1] [1 2 3]] | headers | columns
# before: ["1", "1.0"]
# after:  ["1", "1.0", "1_1"]
```

`headers` now renames repeats with a `_N` suffix (`x`, `x_1`, `x_2`),
the same way `from csv` / `from tsv` do since #19595. I reused the
`dedupe_headers` helper from that PR (made `pub(crate)`, no new
algorithm), so the two commands behave the same:

- A name the header row already uses keeps it: `[x x x_1]` gives `x,
x_2, x_1`.
- Blank and null cells are still named by position (`column0`, ...)
first, then deduped, so a literal `column0` next to a blank becomes
`column0_1`.
- The names are computed once for the header row. Rows with reordered or
missing columns still map by name: `[{a: x, b: x}, {b: 2, a: 1}, {a: 5}]
| headers` gives `[{x_1: 2, x: 1}, {x: 5}]`.

`rename` is unchanged on purpose: there the user types the names, so a
repeat is most likely a mistake and an error is the right answer. The
`rename` part of #11020 was already handled in #19196; this PR covers
the remaining `headers` part.

## User-facing changes (Release notes)

- `headers` no longer creates duplicate column names. Repeated names in
the first row get a `_N` suffix (`x`, `x_1`, ...), so column names can
change from `x, x` to `x, x_1`. This matches `from csv` and `from tsv`.
- When a name repeats, `x` now holds the first column's value and the
later ones become `x_1`, `x_2`. Before, `get x` returned the last one,
so a script that reads `headers | get x` on such a table now gets a
different value without an error. A blank cell named by position flips
the same way: `[[a b]; [column1 ''] [1 2]] | headers | get column1` gave
`[2]` and now gives `[1]`.

## Additional notes

- Tests: 8 new `nu!` tests in
`crates/nu-command/tests/commands/headers.rs` (repeats, existing `_1`
suffix, blank and null names colliding with `column0`, int/float names,
reordered and missing columns, reaching the renamed column by name) and
an `examples()` entry. I checked every expected output against a build
of main, and main gives the wrong result for each.
- Run on my machine: `cargo test -p nu-command --test tests -- headers`
gives `60 passed; 0 failed`; `cargo test -p nu-command --lib -- headers
from::csv from::tsv` passes; `cargo fmt --all --check` and `cargo clippy
-p nu-command --all-targets -- -D warnings -D clippy::unwrap_used` are
clean.
- Performance (debug builds, 20000 rows x 200 columns with 50 distinct
header names, `headers | length` in `timeit`): main 5.81 s / 5.76 s /
5.71 s, this PR 5.73 s / 6.02 s. Within noise; the dedupe runs once per
call. Most of that time is the existing per-cell `position()` lookup in
`replace_headers`, which I left alone.
- I used AI assistance (Claude Code) while writing the code, the tests
and this description. I read the diff, understand how it works, and
checked the before/after outputs above myself; the tests listed above
ran on my machine.

---------

Co-authored-by: Cem Ali Polat <polatcemali58@outlook.com>
2026-11-20 07:55:45 -06:00
Darren Schroeder d2071ef150 bump uu_* crates to 0.13.0 (#19620)
<!--
Thanks for contributing to Nushell!

Before submitting, please read the contributing guide:
https://github.com/nushell/nushell/blob/main/CONTRIBUTING.md

This template helps reviewers understand your changes and allows us to
generate high-quality release notes.
-->

## Description

This PR bumps the uutils/coreutils crates (`uucore`, `uu_cp`,
`uu_mkdir`, `uu_mktemp`, `uu_mv`, `uu_touch`, `uu_uname`, `uu_whoami`)
from 0.12.0 to 0.13.0. None of the uutils APIs nushell calls changed, so
only the versions and the lock move.

<!--
Explain what this PR does and why.

This section is intentionally flexible:
- Describe the problem
- Explain your approach
- Include technical details if relevant

Good examples:
- "In this PR, I fixed..."
- "In this PR, I added support for..."
- "This change improves X by..."

Write as much or as little as needed for reviewers to understand your
changes.
-->

## User-facing changes (Release notes)

- `cp -rn` now copies the rest of a directory after skipping a file that
already exists. Before, it stopped at the first skipped file and
reported success.
- `cp -r` now applies the umask to the directories it creates, as it
already did for files.

<!--
This section is used (mostly as-is) for https://www.nushell.sh/blog/

Describe how Nushell behavior changes from a user's perspective.
Do NOT describe internal Rust changes here.

Write in a release note style, for example:
- "Added support for..."
- "Fixed an issue where..."
- "Nushell now supports..."
- "Improved performance of..."

If your changes do NOT affect users (internal refactors, cleanup, etc.),
just write:
- "n/a"
- "nan"
- or similar

This tells us the change should not appear in the changelog.

Tips:
- Focus on observable behavior
- Include examples if helpful
- Keep it concise

You can:
- Write a short paragraph (will appear as a bullet point), OR
- Use headings (###) if your change needs more structure

Avoid writing things like:
- "In this PR, I refactored..."
- "This updates internal code..."

You may leave this blank until the PR is ready.
-->

## Additional notes
<!--
Optional.

Examples:
- fixes #123
- closes #456
- related #789

Anything else reviewers should know.
Remove this section if not needed.
-->
2026-11-20 07:17:51 -06:00
Abdul karim mia 3d8a9cc6e0 fix(filters): honor --strict when rows parameter is provided to first (#19521)
# Description

In `first_helper`, when a `rows` parameter was provided
(`return_single_element == false`), the `--strict` switch (`-s`) was
previously ignored across all input variants (`Value::List`,
`Value::Binary`, `Value::Range`, `QueryPlan`,
`PipelineData::ListStream`, and `PipelineData::ByteStream`), as well as
when `rows == 0`.

This PR updates `first_helper` so that when `--strict` is enabled and
the input is empty, `first` consistently raises
`ShellError::AccessEmptyContent` even if a `rows` count was passed (such
as `[1] | where name == 123 | first -s 1`, `[] | first -s 1`, `0x[] |
first -s 1`, etc.).

# User-facing changes (Release notes)

Fixed an issue where `first --strict` (`-s`) ignored the `--strict` flag
when a `rows` count argument was provided on empty inputs.

# Additional notes

fixes #19506

Signed-off-by: Abdul karim mia <akmia51@gmail.com>
2026-11-19 13:11:39 -06:00
Darren Schroeder 8d30d9faa2 Deprecate du --min-size in favor of where (#19608)
## Description

`du --min-size` doesn't do what people expect (#19605). It only leaves
small files out of each directory's total. It never removes rows, so
directories always show up, and top-level files ignore the flag
completely. A user who wants "only entries of at least N" gets a table
that looks unfiltered.

Filtering rows is already what `where` does, and it does it on every
row: `du | where apparent >= 1MB`. So this PR deprecates `--min-size`
and doesn't fix its semantics. The flag still works as before and now
gives a parse-time deprecation warning that points to `where`. `du` also
gets a `where` example.

```nushell
Warning: nu::parser::deprecated

  ⚠ Flag deprecated.
   ╭─[source:1:4]
 1 │ du -m 1000 | ...
   ·    ─┬
   ·     ╰── du --min-size was deprecated in 0.118.0 and will be removed in a future release.
   ╰────
  help: To hide small entries, filter the rows: `du | where apparent >= 1MB`.
        Directory totals still include every file.
```

## User-facing changes (Release notes)

du --min-size` is deprecated. To show only large entries, filter the
rows with `where`: `du | where apparent >= 1MB`.

## Additional notes

Closes #19605.
This makes #19601 (`--min-size` accepts a filesize) unnecessary.
2026-11-19 11:35:33 -06:00
Martin Kronberger 08b96a7933 test(repl): read the raw-mode pty until all output arrives (#19571)
## Description

`kept_output_processing_writes_a_newline_as_crlf` from #19542 flakes in
CI.
It failed the Linux `root` job on #19557 with `left: "a\r\n"`, `right:
"a\r\nb"`, and fail-fast then cancelled macOS and Windows.

The helper wrote `a\nb` to the pty slave and did a single `read()` on
the master.
A pty master hands over whatever the line discipline has processed so
far, so with `ONLCR` on the `\r\n` and the `b` can land in separate
reads.

The helper now reads until the last written byte `b` shows up.
Every expected output ends in `b`, so a broken result still fails the
assert instead of hanging the test.
I went with this over `read_exact` for that reason: a short output would
block `read_exact` forever.

Both `platform::raw_mode` tests pass locally, 50 runs in a row.

## User-facing changes (Release notes)

n/a

## Additional notes

related #19542, #19557

[![AI:W
WRITE](https://img.shields.io/badge/AI-WRITE-grey?style=flat&logoSize=auto&labelColor=13171f)](https://0rwx.com)
2026-11-19 15:09:28 +01:00
Piepmatz b9d514df7b Replace old Playground usages with the new one (#18915)
## Description

This PR replaces all the `Playground::setup` calls with the new injected
`Playground`.

Most of the changes are done via [this
script](https://tangled.org/cptpiepmatz.de/nushell_playground_asr) which
uses the rust-analyzer internals to replace code via the AST.

All the test should behave exactly the same as before but they don't
need to manually set up a playground anymore. Also this removes quite a
lot of lines, which is nice.

## User-facing changes (Release notes)

n/a

---

<sub>Stack created with <a
href="https://github.com/github/gh-stack">GitHub Stacks CLI</a> • <a
href="https://gh.io/stacks-feedback">Give Feedback 💬</a></sub>
2026-11-19 14:29:12 +01:00
Piepmatz 2402590b86 Add new Playground API (#18913)
## Description

This PR implements a new `Playground` API which should be a lot simpler
to use than the old `Playground` API. It also moves the old `Playground`
to a `deprecated` module. That will be removed in the future.

Instead of the confusing `within` structure of the playground, all
methods simply run from the root of the playground if not used with `at`
which allows nesting to be more obvious. Most calls to the playground
already only created a single file, so this should make the API a lot
nicer and easier to use.

## User-facing changes (Release notes)

n/a

---

<sub>Stack created with <a
href="https://github.com/github/gh-stack">GitHub Stacks CLI</a> • <a
href="https://gh.io/stacks-feedback">Give Feedback 💬</a></sub>
2026-11-19 14:29:11 +01:00