Commit Graph
314 Commits
Author SHA1 Message Date
Darren Schroeder 15268e32db allow parameters with # to be passed (#18782)
## Description

This PR fixes a bug where `"#00abcd"` couldn't be passed as a parameter
because `#` indicates to nushell that a comment is following.

## User-facing changes (Release notes)

Quotes strings with `"#"` in them like `"#00abcd"` are now allowed to be
passed as parameters.

### Example
A script named test.nu
```nushell
def main [color: string] {
  $"Your color is ($color)"
}
```
Then pass a hex color as a parameter.
```nushell
❯ let myColor = "#000000"
❯ nu test.nu $myColor
Your color is #000000
❯ nu test.nu "#abcdef"
Your color is #abcdef
```

## Additional notes

closes https://github.com/nushell/nushell/issues/18778
2026-08-07 07:02:03 -05:00
Piepmatz e08c27a424 More updated tests (#18768)
<!--
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.
-->
Well, another batch of updated tests.

## 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.
-->
n/a
2026-08-02 03:52:40 +02:00
Darren Schroeder 30cf02c8e3 The source command no longer breaks variable visibility (#18538)
## Description
This PR fixes a problem when a script or REPL input used `source` to run
a `.nu` file, variables defined before the `source` call could become
invisible inside the sourced file, producing a "variable not found"
error.

Two distinct mechanisms contributed to the bug:

1. Double-parse in `evaluate_file`. The first parse stored blocks from
`source` with one set of `VarId`s. The second prase created _new_
`VarId`s for `let`/`mut` declarations. The `source` results were cached
but referenced the old `VarId`s.

2. Cross-session block caching in the parser -
`find_block_by_span(new_span)` in `parse_captures_compile` was called to
avoid re-parsing files that had already been parsed. This cached data
was stored in the permanent state. In the repl, if `let xxx` was
redeclared (getting a new varid), the cached block was used referencing
the old varid.

## User-facing changes (Release notes)
Fixes the bugs found when a script or REPL input used `source` to run a
`.nu` file, variables defined before the `source` call could become
invisible inside the sourced file, producing a "variable not found"
error.

**Example reproducing the bug** — script file `lll.nu`:

```nushell
let xxx = 'let in script'
source sss.nu
```

Where `sss.nu` contains:

```nushell
print $xxx
```

Running `nu lll.nu` would fail with:

```nushell
Error: nu::shell::variable_not_found

  × Variable not found
   ╭─[sss.nu:1:7]
 1 │ print $xxx
   ·       ──┬─
   ·         ╰── variable not found
   ╰────
```

The same error could also appear in the REPL after re-declaring a
variable:

```nushell
❯ let xxx = 'value 1'
❯ source sss.nu    # OK: prints "value 1"
❯ let xxx = 'value 2'
❯ source sss.nu    # Error: variable not found
```
After this change the last statement above would print `value 2`. See
the tests and the issue to see more variations.

## Additional notes

closes https://github.com/nushell/nushell/issues/18515
2026-07-29 16:53:32 -05:00
Piepmatz c70ebfe228 Update internal commands tests (#18718)
<!--

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.

-->
This PR updates the internal commands tests. This is, next to #18717,
also a very large file. So it got separated into its own PR too.


## 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.

-->
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-07-26 20:08:40 +02:00
Piepmatz 69d6beb8bf Update external commands tests (#18717)
<!--

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.

-->
This PR updates the external commands tests. This file is pretty large
and therefore separated into its own PR.


## 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.

-->
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-07-26 20:08:39 +02:00
Piepmatz 94d06fa302 Refactor most test files that used nu --testbin (#18713)
<!--

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.

-->
`nu --testbin` is going to be removed by #18719, so this PR starts by
refactoring all tests that call `nu --testbin` in some way. Not only are
these tests refactored but then the whole file. Instead of calling `nu
--testbin`, the relevant `#[deps(TESTBIN_x)]` is annotated on the test
and the test binary is called directly.

The files in this PR are the smaller ones, the larges ones are in
seperate PRs up the stack.


## 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.

-->
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-07-26 20:08:38 +02:00
Piepmatz 189141a2b2 Update some more tests that used nu_repl_code (#18649)
<!--

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.

-->
This PR updates some more test to the new harness by replacing
`nu_repl_code` and `nu!`.

This set of tests is grouped together, as they did use `nu_repl_code` in
some capacity. After this PR no more `nu_repl_code` should be used
anywhere.


## 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.

-->
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-07-26 20:08:37 +02:00
BahexandTim 'Piepmatz' Hesse f852cac740 Update some tests to use the new test infra (#18651)
## Description

- Enabled `pretty_assertions`'s `unstable` feature to get
`assert_matches!` (the stdlib version is available in 1.96)
- Tried to keep most tests 1:1, though I made some significant changes
here and there.

## User-facing changes (Release notes)
N/A

---------

Co-authored-by: Tim 'Piepmatz' Hesse <git+github@cptpiepmatz.de>
2026-07-18 21:58:58 +03:00
Piepmatz 8c4aeb7349 Add test dependencies via test attribute #[deps(...)] (#18570) 2026-07-11 23:10:41 +02:00
Bahex 8560eef575 fix: assigment errors point to the assigment (#18531)
## Description

- #16832

Errors raised for assignment errors did not point to the relevant
assignment, just pointed to the values origin.

## User-facing changes (Release notes)

### More helpful errors for failed assignments with
`enforce-runtime-annotations`

With `enforce-runtime-annotations` enabled, assignments with incorrect
types raise errors.

Previously this error was `nu::shell::cant_convert` originally used for
unsuccessful type coercions of command arguments. Unfortunately, this
error only pointed at the assigned values *origin* and not at the failed
assignment.

This error has been switched to `nu::shell::type_mismatch` and now
points to the failed assignment in addition to the value's origin.

##### example 1
<table>
<tr>
<td>Code</td>
<td width="1000">

```nushell
mut execution_time = -1
$execution_time = $env.CMD_DURATION_MS
```

</td>
</tr>

<tr>
<td>Before</td>
<td>

```
Error: nu::shell::cant_convert

  × Can't convert to int.
   ╭─[Host Environment Variables:1:1]
 1 │ "LANG"="en_US.UTF-8"
   · ▲
   · ╰── can't convert string to int
 2 │ "LC_TIME"="en_DK.UTF-8"
   ╰────
```

</td>
</tr>

<tr>
<td>After</td>
<td>

```
Error: nu::shell::type_mismatch

  × Type mismatch.
   ╭─[repl_entry #3:2:17]
 1 │ mut execution_time = -1
 2 │ $execution_time = $env.CMD_DURATION_MS
   ·                 ┬
   ·                 ╰── expected int, got string
   ╰────
```

</td>
</tr>
</table>

##### example 2
<table>
<tr>
<td>Code</td>
<td width="1000">

```nushell
# delibarete type erasure
# we need to bypass parse-time
# type checking for this example
let stuff: any = {
	foo: "bar"
}

mut x = 1

$x = $stuff.foo
```

</td>
</tr>

<tr>
<td>Before</td>
<td>

```
Error: nu::shell::cant_convert

  × Can't convert to int.
   ╭─[repl_entry #7:5:7]
 4 │ let stuff: any = {
 5 │     foo: "bar"
   ·          ──┬──
   ·            ╰── can't convert string to int
 6 │ }
   ╰────
```

</td>
</tr>

<tr>
<td>After</td>
<td>

```
Error: nu::shell::type_mismatch

  × Type mismatch.
    ╭─[repl_entry #1:5:7]
  4 │ let stuff: any = {
  5 │     foo: "bar"
    ·          ──┬──
    ·            ╰── the value is a string
  6 │ }
  7 │ 
  8 │ mut x = 1
  9 │ 
 10 │ $x = $stuff.foo
    ·    ┬
    ·    ╰── expected int, got string
    ╰────
```

</td>
</tr>
</table>

## Additional notes

- This should make it much easier to diagnose problems described in
#18528
2026-07-07 01:37:52 +03:00
Tyarel8 7c3be8c4ac delete deprecated stdlib copy and paste (#18403)
## Description
Removed the copy/paste command from stdlib that were deprecated in
`0.111.0`. I think it makes sense to remove these sooner rather than
later since it can be confusing that they have the exact same name as
the ones in the "new" `native-clip` experimental option.

## 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.
-->
Removed the deprecated `use std/clip` `copy` and `paste` commands, they
are now called `copy52` and `paste52` for the ones that use the terminal
`OSC 52`, or you can use `clip copy` and `clip paste` from the
experimental option `native-clip` that access the system clipboard
directly.

<!--
Optional.

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

Anything else reviewers should know.
Remove this section if not needed.
-->
2026-06-13 07:49:11 -05:00
Bahex 802eb44d90 test: stderr/stdout full tests should not read user config (#18253)
## Description

Reading my config (which had some elaborate startup code) caused these
tests to fail. Likely because of `term query` calls.

## User-facing changes (Release notes)
N/A

## Additional notes

Tests being affected by user config is unfortunately a reoccurring
issue.

We should consider setting `XDG_{CONFIG,DATA,CACHE}_HOME` and
`XDG_DATA_DIRS` to empty directories during tests to avoid this problem
all together rather than patching it on a test by test basis.
2026-05-20 12:24:12 +03:00
Piepmatz 462ffde0f8 Fix CI not executing all tests on Windows (#18211) 2026-05-16 15:54:00 +02:00
Darren Schroeder fbe85c70c2 fix(repl): improve error handling and cleanup on unexpected errors (#18210)
<!--
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 improves repl error handling when being redirected.
<!--
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)
Improve repl error handling when redirected like `nu > /dev/full` or `nu
2>/dev/full`.

<!--
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
closes https://github.com/nushell/nushell/issues/18208
closes https://github.com/nushell/nushell/issues/18209
<!--
Optional.

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

Anything else reviewers should know.
Remove this section if not needed.
-->
2026-05-15 09:10:57 -05:00
Darren SchroederandTim 'Piepmatz' Hesse 4b1aca5239 feat: enhance script argument parsing to handle newlines and whitespace correctly (#17826)
Co-authored-by: Tim 'Piepmatz' Hesse <git+github@cptpiepmatz.de>
2026-03-27 10:56:35 +01:00
Piepmatz b36b7eea26 Warn on clippy::needless_raw_strings (#17822)
<!--
Thank you for improving Nushell!
Please, read our contributing guide:
https://github.com/nushell/nushell/blob/main/CONTRIBUTING.md
-->

This PR enables the clippy lint `needless_raw_strings` to avoid raw
strings where they aren't needed. We have a lot of them and I don't
think that's that nice tbh.

## Release notes summary - What our users need to know
<!--
This section will be included as part of our release notes. See the
contributing guide for more details.
Please include only details relevant for users here. Motivation and
technical details can be added above or below this section.

You may leave this section blank until your PR is finalized. Ask a core
team member if you need help filling this section.
-->
n/a
2026-03-17 01:42:03 +01:00
Piepmatz b6a7a2f2d3 Enable env_shlvl_in_repl and env_shlvl_in_exec_repl tests (#17803) 2026-03-15 00:45:22 +01:00
Darren Schroeder 403ec4ee8a fix duplicate custom commands from showing up (#17727) 2026-03-05 13:28:17 -06:00
Chris Denton 03f0cc21a4 Prefer PWD over current_dir if they're the same directory (#17720) 2026-03-05 10:55:29 -06:00
Piepmatz 8a5bf67592 Move native clip commands behind an experimental option (#17664) 2026-02-27 16:59:57 +01:00
2bc9c4b4ac Custom subcommand help (#17610)
Co-authored-by: Motalleb Fallahnezhad <fmotalleb@dornica.net>
Co-authored-by: Motalleb Fallahnezhad <fmotalleb@gmail.com>
2026-02-24 10:25:20 -06:00
Darren Schroeder 28cd326ec3 abstract env var names so they're insensitive on windows and sensitive on other operating systems (#17558)
There are some edge cases when working with environment variables. So, I
took the opportunity in this PR to refactor how nushell handles env
vars. All environment variables across all operating systems and
case-insensitive for lookups and case-preserving for storage.

This is how it now works. All environment variable access goes through
EnvName in env_names.rs now, except for a few places that still need to
use `std::env::var()` type calls for initial nushell setup.

```
//! ## Case Sensitivity Rules
//!
//! - **All platforms**: All environment variable names are case-insensitive but case-preserving.
//!   This means `PATH`, `Path`, and `path` refer to the same variable, and so do `HOME` and `home`.
//!
//! This ensures that:
//! - `$env.PATH`, `$env.path`, `$env.Path` all work on any platform
//! - `$env.HOME`, `$env.home` all refer to the same variable
//! - Case is preserved when storing the variable name
//! - Existing scripts may need updates if they relied on case sensitivity
```

## Release notes summary - What our users need to know
All environment variables across all operating systems and
case-insensitive for lookups and case-preserving for storage.

## Tasks after submitting
<!-- Remove any tasks which aren't relevant for your PR, or add your own
-->
- [ ] Update the
[documentation](https://github.com/nushell/nushell.github.io)
2026-02-17 19:11:40 -06:00
Wind 7816ba9b7f pipefail: enable by default (#17449)
As title
It reveals somes issues, like breaking `do -i`. So this pr fixes it as
well.

I introduce a new type `ExitStatusGuard` which wraps both
`exit_stauts_future` and `ignore_error`. So we can check the status
easier.

## Release notes summary - What our users need to know
nushell will use `pipefail` by default, so something like `^false |
lines` returns an empty list, with a failure exit status code

## Tasks after submitting
NaN
2026-02-04 09:51:28 +08:00
Kai Sforza ddf80f3107 error_make: Another rewrite of error make (#17070)
## User-facing Changes

* New arguments! (`error make "hello"`)
* New parts for `error_struct`! (`error make {inner: [] labels: []
...}`)
* Pipeline inputs for chained errors! (`try {error make foo} catch
{error make bar}`)
* Pipeline inputs for normal errors! (`"help" | error make`)
* External errors! (`error make {src: {path: $nu.cofig-path} ...}`)
* Backwards compatibility!

### Arguments and Inputs

The main changes are in how the arguments are passed. Everything is
still backwards compatible with the old `error make` commands, there's
just a nice extra layer we get from the pipeline and a few new args
(that were already added in #17037). There are some new ways to
(hopefully intentionally) cause an error, such as using a naked `error
make`, pipelines from records and simple string input!

#### Inputs

Because `error make` will just make an error anyway, it can technically
take any input to make an error, but only properly formatted record
input will create a chain. the `x | f $in` pattern can be used for
string input, if that is more comfortable.

#### With no arguments

This is a completely new way to do this, with no arguments the `error
make` invocation is highlighted, along with a simple `originates from
here` message. This makes normal errors very easy to create without any
special message setup.

```
> error make
Error: nu::shell::error

  × originates from here
   ╭─[entry #4:1:1]
 1 │ error make
   · ──────────
   ╰────
```

#### Create a single argument

* With pipeline input: `{msg: foo} | error make`
* With an argument: `error make {msg: foo}`
* With a string argument: `error make foo`
```
Error: nu::shell::error

  × foo
   ╭─[entry #2:1:12]
 1 │ error make {msg: foo}
   ·            ──────────
   ╰────
```
#### Chaining errors together

These will automatically create a chain of errors, placing the pipeline
as an `inner` to the argument. This can very easily be used to get a bit
more detail in a try loop using the naked `error make`:

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

  × originates from here
   ╭─[source:1:31]
 1 │ try {error make "foo"} catch {error make}
   ·                               ──────────
   ╰────

Error: nu::shell::error

  × foo
   ╭─[source:1:6]
 1 │ try {error make "foo"} catch {error make}
   ·      ──────────
   ╰────
```

Or with more complex errors:

* With both, combining the errors: `{msg: foo} | error make bar`
* With the raw error from try: `try {error make foo} catch {error make
bar}`

Both are equivalent to:
* `error make {msg: bar inner: [{msg: foo}]}`

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

  × bar
   ╭─[entry #1:1:29]
 1 │ try {error make foo} catch {error make bar}
   ·                             ──────────
   ╰────

Error: nu::shell::error

  × foo
   ╭─[entry #1:1:6]
 1 │ try {error make foo} catch {error make bar}
   ·      ──────────
   ╰────
```

### Labels

As is noticeable in the examples above, simple errors no longer use an
extra line for the label. If no label is present, `error make` will
place a bar under the span of itself or the argument to `error make`.
Labels have also gotten a bit of a rewrite, but they're pretty much the
same as those in #17037, except for `label`, which is now only a single
label (not `oneof<list, label>`).
#### Simple Labels

`label.text` and `labels.*.text` is no longer required for a span to
show up, an empty text will simply underline. This example can either
use `label: $record` or be written as `labels: [$record]`:

```
> def f [x] {
  error make {msg: here label: {span: (metadata $x).span}}
}
f abcd
Error: nu::shell::error

  × here
   ╭─[entry #7:4:3]
 3 │ }
 4 │ f abcd
   ·   ────
   ╰────
```

#### Multiple labels
Any number of labels can be added in the `labels` column, allowing for
more detailed error messages, especially for functions:

```
> def f [x y z] {
  error make {msg: here labels: [
    {text: "there" span: (metadata $x).span}
    {text: "everywhere" span: (metadata $y).span}
    {text: "somewhere" span: (metadata $z).span}
  ]
  }
}
f abcd [x y z] {d: a}

Error: nu::shell::error

  × here
   ╭─[entry #11:9:3]
 8 │ }
 9 │ f abcd [x y z] {d: a}
   ·   ──┬─ ───┬─── ───┬──
   ·     │     │       ╰── somewhere
   ·     │     ╰── everywhere
   ·     ╰── there
   ╰────
```

#### External sources

There is a `ShellError::OutsideSpannedLabeledError` that can be used to
refer to external sources, not just the internal nushell spanns. This
has been expanded to allow the multi-label stuff to work using the new
`src` column:

```
> "foo\nbar\nbaz" | save -f /tmp/foo.bar
error make {
  msg: 'error here'
  src: {path: /tmp/foo.bar}
  labels: [
    {text: "this" span: {start: 4 end: 7}}
  ]
}
Error: nu::shell::outside

  × error here
   ╭─[/tmp/foo.bar:2:1]
 1 │ foo
 2 │ bar
   · ─┬─
   ·  ╰── this
 3 │ baz
   ╰────
```

### Errors That Can't be Caught

These will not work since `try` will never get parsed:

- `try {1 + ""} catch {error make badmath}`
- (TODO: Add more examples)

## Internal Changes

Most of the parsing from an error record to an actual error is now moved
into `nu-protocol`, using `FromValue` to turn it into a useful internal
type.

### `nu-protocol::LabeledError`

This struct has a few changes, the main one being the type of
`LabeledError.inner`. It is now a `ShellError`, not another
`LabeledError`. It should be trivial to do a `.into()` for things that
already use `LabeledError.with_inner(x)`.

### `nu-protocol::ShellError::into_value`

I renamed the old `into_value` to `into_full_value` to better say what
it is, since it doesn't just do the `IntoValue::into_value` method, it
also requires some context to create the `Value`. Now `ShellError` has
an `IntoValue` implementation matching other types.

### `nu-protocol::ShellError::{OutsideSource, OutsideSourceNoUrl}`

Miette's derived types don't have a nice way to maybe include a url, so
there are now two types! These allow using multiple labels on outside
sources. They are used internally for the new `{src: {}}` part of the
`error_struct`, and they look a lot more like the `LabeledError`, but
without the need for a separate type and all the fun `impl`s that would
require for the `Diagnostic::source_code` method.

### Misc

* Spelling fix: `into_chainned` => `into_chained`

## Current bugs:
- [x] `OutsideSpannedLabeledError`  
The inner most error of `try {']' from nuon} catch {error make}` will
reference `span: {start: 0, end: 1}`, which in `']' from nuon` will
point to the `]` character, but when it does this in `error make` as an
input it will point to the very first character (probably the `n` in
`nu`).

## Release notes summary - What our users need to know

### New `error make` functionality!
* New arguments! (`error make "hello"`)
* New parts for `error_struct`! (`error make {inner: [] labels: []
...}`)
* Pipeline inputs for chained errors! (`try {error make foo} catch
{error make bar}`)
* Pipeline inputs for normal errors! (`"help" | error make`)
* External errors! (`error make {src: {path: $nu.cofig-path} ...}`)
* Backwards compatibility!


## Tasks after submitting
<!-- Remove any tasks which aren't relevant for your PR, or add your own
-->
- [ ] Update the
[documentation](https://github.com/nushell/nushell.github.io)
2025-12-18 07:34:08 -06:00
Wind 65e710b02c Making --env-config and --config errors lead to error status code when running nu scripts or commands. (#17103)
Fixes: #14745

## Release notes summary - What our users need to know
If user runs script or command with a bad config file, the script or
command won't run.
```
echo 'errnocmd' | save config.nu
nu --config config.nu -c 'echo $env.NU_VERSION'
```

won't show nushell version and exits with status code 1.
2025-12-05 09:12:20 +08:00
Kai Sforza a1f54c5637 Fix up the env.rs tests (#17085)
Just uses `ends-with` and a prefix to skip the control characters at the
start of the strings

This fixes the issues that came up in #17038 for being run in terminals.
This doesn't fix the underlying issue, however it does allow tests to be
run in certain terminals and still pass.

This also fixes a problem with some of the tests that load `std/log`. If
`$env.NU_LOG_FORMAT` is set in the parent shell, then these tests will
incorrectly fail. Clearing the env out before running makes these work.

<!--
Thank you for improving Nushell!
Please, read our contributing guide:
https://github.com/nushell/nushell/blob/main/CONTRIBUTING.md
-->

## Release notes summary - What our users need to know
<!--
This section will be included as part of our release notes. See the
contributing guide for more details.
Please include only details relevant for users here. Motivation and
technical details can be added above or below this section.

You may leave this section blank until your PR is finalized. Ask a core
team member if you need help filling this section.
-->

## Tasks after submitting
<!-- Remove any tasks which aren't relevant for your PR, or add your own
-->
- [ ] Update the
[documentation](https://github.com/nushell/nushell.github.io)
2025-12-04 11:12:28 -06:00
Wind 1025ddb322 make pipefail works with let (#16879)
This pr address comment by @132ikl :
https://github.com/nushell/nushell/issues/16760#issuecomment-3344409581

After visiting IR of `let x = ^false | into int`:
```
# 2 registers, 8 instructions, 5 bytes of data
   0: load-literal           %1, glob-pattern("false", no_expand = false)
   1: push-positional        %1
   2: redirect-out           pipe
   3: call                   decl 142 "run-external", %0
   4: redirect-out           value
   5: call                   decl 299 "into int", %0
   6: store-variable         var 320, %0 # let
   7: return                 %0
```
Nushell runs `store-variable` instruction, which collect values from
registry through `collect_reg`. This pr adds `check_exit_status_future`
logic inside `collect_reg` to make pipefail works with `let`.

## Release notes summary - What our users need to know
### pipefail works well with `let`
```
let x = bash -c "echo 123; exit 1" | into int; $x
Error: nu::shell::non_zero_exit_code

  × External command had a non-zero exit code
   ╭─[entry #28:1:9]
 1 │ let x = bash -c "echo 123; exit 1" | into int; $x
   ·         ──┬─
   ·           ╰── exited with code 1
   ╰────
```
2025-10-17 10:51:45 -04:00
Bahex f21fd3b109 big testing refactor (#16802)
- refactored how `nu!` executes commands
- commands are no longer split into lines and joined with semicolons,
they are passed verbatim to nu
  - removes the need for `pipeline()` 
- **Removed built-in string formatting from `nu!`**. Going through almost
all uses of `nu!` across the code base it became clear that:
  - built-in formatting is rarely used
  - most people are not aware of it and use `format!` anyway
- it can't be used with `"{inline}"` arguments because it's only
activated if there are extra arguments after the nu code string

## Release notes summary - What our users need to know
N/A

## Tasks after submitting
N/A
2025-10-09 13:31:53 +03:00
Windandrose f712c37009 Try to implement pipefail feature (#16449)
Closes: #13817

The core requirement here is to have a way to track all exit status in a
pipeline. To achieve this without affecting command itself.

I created a new struct in `pipeline_data.rs`:
```rust
pub struct PipelineExecutionData {
    pub body: PipelineData,
    /// This field is using to track all exit status in a pipeline.
    pub exit: Vec<Option<(Arc<Mutex<ExitStatusFuture>>, Span)>>,
}
```

Then I changed registers in `EvalContext` from `&'a mut [PipelineData]`
to `&'a mut [PipelineExecutionData]`. So the eval engine itself can
track exit status.
Then during evaluation, when nushell is going to execute
`Instruction::Call`. It takes `input.exit` first, then attach this into
`results.exit`. This is similar to the way nushell implements backtrace
feature.

After all of this, when nushell executes `Instruction::Drain`, or
printing pipeline. It iterates through *exit_futures* reversely. To see
if a command exits with non-zero status.

## Release notes summary - What our users need to know
This release will be add an experimental option for `pipefail`. This can
be set using `nu --experimental-options=['pipefail']`
> If set, the LAST_EXIT_CODE will be set to any command which exit with
a non-zero status, or zero if all commands in the pipeline exit
successfully.
```nushell
> ^false | print aa
aa
> $env.LAST_EXIT_CODE
1
```
It'd be more interesting if using it with
`$env.config.display_errors.exit_code = true`. Show users are able to
see which command is failed.
```nushell
> $env.config.display_errors.exit_code = true
> ^ls | ^false | print aa
aa
Error: nu::shell::non_zero_exit_code

  × External command had a non-zero exit code
   ╭─[entry #5:1:8]
 1 │ ^ls | ^false | print aa
   ·        ──┬──
   ·          ╰── exited with code 1
   ╰────
```

## Tasks after submitting
- [ ] Update the
[documentation](https://github.com/nushell/nushell.github.io)

---------

Co-authored-by: rose <132@ikl.sh>
2025-09-07 21:21:13 -04:00
Bahex f7c131443f fix(nu): script file not found error should point to commandline, not rust code (#16273) 2025-08-21 16:23:56 +03:00
Bahex 2df00ff498 Revert "Add extern for nu command" (#16180)
Reverts nushell/nushell#16119
2025-07-15 19:18:44 +03:00
132ikl 316d2d6af2 Add extern for nu command (#16119)
# Description
Adds an `extern` definition (`KnownExternal`) for the `nu` command. This
way you can do `help nu` and get tab completions for flags on the `nu`
executable

# User-Facing Changes
* You can now view the flags for Nushell itself with `help nu`, and tab
completion for flags on `nu` works
2025-07-15 02:26:40 +03:00
Wind 288f419f7b print to a value should be a SIGPIPE (#16171)
# Description
Partially handles #14799 
It's difficult to fix all cases there, but I think it's good to improve
one of this with a small step

# User-Facing Changes
Given the following code in c:
```C
// write.c
#include <stdio.h>

int main() {
  while (1) {
    printf("a\n");
  }
}
```
After this pr, `./write | 0` will exit immediately, in that case,
`./write` will receive `SIGPIPE` in unix. Before this pr, `./write | 0`
runs indefinitely.

-----------------------

Maybe it's easier to see what happened internally by the different
output of `view ir { ./write | 0 }` command.
### Before
```
# 2 registers, 6 instructions, 7 bytes of data
   0: load-literal           %1, glob-pattern("./write", no_expand = false)
   1: push-positional        %1
   2: redirect-out           null
   3: call                   decl 135 "run-external", %0
   4: load-literal           %0, int(0)
   5: return                 %0
```

### After
```
# 2 registers, 6 instructions, 7 bytes of data
   0: load-literal           %1, glob-pattern("./write", no_expand = false)
   1: push-positional        %1
   2: redirect-out           pipe      # changed, the command's output is a pipe rather than null
   3: call                   decl 136 "run-external", %0
   4: load-literal           %0, int(0)
   5: return                 %0
```
# Tests + Formatting
Added 1 test.

# After Submitting
NaN
2025-07-14 13:26:51 -04:00
BahexandBahex 5478ec44bb to <format>: preserve round float numbers' type (#16016)
- fixes #16011

# Description
`Display` implementation for `f64` omits the decimal part for round
numbers, and by using it we did the same.
This affected:
- conversions to delimited formats: `csv`, `tsv`
- textual formats: `html`, `md`, `text`
- pretty printed `json` (`--raw` was unaffected)
- how single float values are displayed in the REPL

> [!TIP]
> This PR fixes our existing json pretty printing implementation.
> We can likely switch to using serde_json's impl using its
PrettyFormatter which allows arbitrary indent strings.

# User-Facing Changes
- Round trips through `csv`, `tsv`, and `json` preserve the type of
round floats.
- It's always clear whether a number is an integer or a float in the
REPL
  ```nushell
  4 / 2
  # => 2  # before: is this an int or a float?

  4 / 2
  # => 2.0  # after: clearly a float
  ``` 

# Tests + Formatting
Adjusted tests for the new behavior.

- 🟢 toolkit fmt
- 🟢 toolkit clippy
- 🟢 toolkit test
- 🟢 toolkit test stdlib

# After Submitting
N/A

---------

Co-authored-by: Bahex <17417311+Bahex@users.noreply.github.com>
2025-06-26 15:15:19 -05:00
Jack Wright c2ac8f730e Rust 1.85, edition=2024 (#15741) 2025-05-13 16:49:30 +02:00
WindandStefan Holderbach 11cdb94699 IR: rasing reasonable error when using subexpression with and operator (#15623)
# Description
Fixes: #15510
I think it's introduced by #14653, which changes `and/or` to `match`
expression.

After looking into `compile_match`, it's important to collect the value
before matching this.
```rust
    // Important to collect it first
    builder.push(Instruction::Collect { src_dst: match_reg }.into_spanned(match_expr.span))?;
```
This pr is going to apply the logic while compiling `and/or` operation.

# User-Facing Changes
The following will raise a reasonable error:
```nushell
> (nu --testbin cococo false) and true
Error: nu::shell::operator_unsupported_type

  × The 'and' operator does not work on values of type 'string'.
   ╭─[entry #7:1:2]
 1 │ (nu --testbin cococo false) and true
   ·  ─┬                         ─┬─
   ·   │                          ╰── does not support 'string'
   ·   ╰── string
   ╰────
```

# Tests + Formatting
Added 1 test.

# After Submitting
Maybe need to update doc
https://github.com/nushell/nushell.github.io/pull/1876

---------

Co-authored-by: Stefan Holderbach <sholderbach@users.noreply.github.com>
2025-04-25 22:00:20 +08:00
Douglas 3030608de0 Ignore problematic overlapping tests for SHLVL (#15430)
The `$env.SHLVL` tests, while improved, still cause CI (usually local)
an irritating percentage of the time. Until we can come with a better
way of testing, we're going to ignore them.
2025-03-27 14:47:43 -04:00
Ian Manske 62e56d3581 Rework operator type errors (#14429)
# Description

This PR adds two new `ParseError` and `ShellError` cases for type errors
relating to operators.
- `OperatorUnsupportedType` is used when a type is not supported by an
operator in any way, shape, or form. E.g., `+` does not support `bool`.
- `OperatorIncompatibleTypes` is used when a operator is used with types
it supports, but the combination of types provided cannot be used
together. E.g., `filesize + duration` is not a valid combination.

The other preexisting error cases related to operators have been removed
and replaced with the new ones above. Namely:

- `ShellError::OperatorMismatch`
- `ShellError::UnsupportedOperator`
- `ParseError::UnsupportedOperationLHS`
- `ParseError::UnsupportedOperationRHS`
- `ParseError::UnsupportedOperationTernary`

# User-Facing Changes

- `help operators` now lists the precedence of `not` as 55 instead of 0
(above the other boolean operators). Fixes #13675.
- `math median` and `math mode` now ignore NaN values so that `[NaN NaN]
| math median` and `[NaN NaN] | math mode` no longer trigger a type
error. Instead, it's now an empty input error. Fixing this in earnest
can be left for a future PR.
- Comparisons with `nan` now return false instead of causing an error.
E.g., `1 == nan` is now `false`.
- All the operator type errors have been standardized and reworked. In
particular, they can now have a help message, which is currently used
for types errors relating to `++`.

```nu
[1] ++ 2
```
```
Error: nu::parser::operator_unsupported_type

  × The '++' operator does not work on values of type 'int'.
   ╭─[entry #1:1:5]
 1 │ [1] ++ 2
   ·     ─┬ ┬
   ·      │ ╰── int
   ·      ╰── does not support 'int'
   ╰────
  help: if you meant to append a value to a list or a record to a table, use the `append` command or wrap the value in a list. For example: `$list ++ $value` should be
        `$list ++ [$value]` or `$list | append $value`.
```
2025-02-12 20:03:40 -08:00
Wind 2f18b9c856 Enable nushell error with backtrace (#14945)
# Description
After this pr, nushell is able to raise errors with a backtrace, which
should make users easier to debug. To enable the feature, users need to
set env variable via `$env.NU_BACKTRACE = 1`. But yeah it might not work
perfectly, there are some corner cases which might not be handled.

I think it should close #13379 in another way.

### About the change

The implementation mostly contained with 2 parts:
1. introduce a new `ChainedError` struct as well as a new
`ShellError::ChainedError` variant. If `eval_instruction` returned an
error, it converts the error to `ShellError::ChainedError`.
`ChainedError` struct is responsable to display errors properly. It
needs to handle the following 2 cases:
- if we run a function which runs `error make` internally, it needs to
display the error itself along with caller span.
- if we run a `error make` directly, or some commands directly returns
an error, we just want nushell raise an error about `error make`.

2. Attach caller spans to `ListStream` and `ByteStream`, because they
are lazy streams, and *only* contains the span that runs it
directly(like `^false`, for example), so nushell needs to add all caller
spans to the stream.
For example: in `def a [] { ^false }; def b [] { a; 33 }; b`, when we
run `b`, which runs `a`, which runs `^false`, the `ByteStream` only
contains the span of `^false`, we need to make it contains the span of
`a`, so nushell is able to get all spans if something bad happened.
This behavior is happened after running `Instruction::Call`, if it
returns a `ByteStream` and `ListStream`, it will call `push_caller_span`
method to attach call spans.

# User-Facing Changes
It's better to demostrate how it works by examples, given the following
definition:
```nushell
> $env.NU_BACKTRACE = 1
> def a [x] { if $x == 3 { error make {msg: 'a custom error'}}}
> def a_2 [x] { if $x == 3 { ^false } else { $x } }
> def a_3 [x] { if $x == 3 { [1 2 3] | each {error make {msg: 'a custom error inside list stream'} } } }
> def b [--list-stream --external] {
    if $external == true {
        # error with non-zero exit code, which is generated from external command.
        a_2 1; a_2 3; a_2 2
    } else if $list_stream == true {
        # error generated by list-stream
        a_3 1; a_3 3; a_3 2
    } else {
        # error generated by command directly
        a 1; a 2; a 3
    }
}
```

Run `b` directly shows the following error:

<details>

```nushell
Error: chained_error

  × oops
   ╭─[entry #27:1:1]
 1 │ b
   · ┬
   · ╰── error happened when running this
   ╰────

Error: chained_error

  × oops
    ╭─[entry #26:10:19]
  9 │         # error generated by command directly
 10 │         a 1; a 2; a 3
    ·                   ┬
    ·                   ╰── error happened when running this
 11 │     }
    ╰────

Error:
  × a custom error
   ╭─[entry #6:1:26]
 1 │ def a [x] { if $x == 3 { error make {msg: 'a custom error'}}}
   ·                          ─────┬────
   ·                               ╰── originates from here
   ╰────
```

</details>

Run `b --list-stream` shows the following error

<details>

```nushell
Error: chained_error

  × oops
   ╭─[entry #28:1:1]
 1 │ b --list-stream
   · ┬
   · ╰── error happened when running this
   ╰────

Error: nu::shell::eval_block_with_input

  × Eval block failed with pipeline input
   ╭─[entry #26:7:16]
 6 │         # error generated by list-stream
 7 │         a_3 1; a_3 3; a_3 2
   ·                ─┬─
   ·                 ╰── source value
 8 │     } else {
   ╰────

Error: nu::shell::eval_block_with_input

  × Eval block failed with pipeline input
   ╭─[entry #23:1:29]
 1 │ def a_3 [x] { if $x == 3 { [1 2 3] | each {error make {msg: 'a custom error inside list stream'} } } }
   ·                             ┬
   ·                             ╰── source value
   ╰────

Error:
  × a custom error inside list stream
   ╭─[entry #23:1:44]
 1 │ def a_3 [x] { if $x == 3 { [1 2 3] | each {error make {msg: 'a custom error inside list stream'} } } }
   ·                                            ─────┬────
   ·                                                 ╰── originates from here
   ╰────
```

</details>

Run `b --external` shows the following error:

<details>

```nushell
Error: chained_error

  × oops
   ╭─[entry #29:1:1]
 1 │ b --external
   · ┬
   · ╰── error happened when running this
   ╰────

Error: nu::shell::eval_block_with_input

  × Eval block failed with pipeline input
   ╭─[entry #26:4:16]
 3 │         # error with non-zero exit code, which is generated from external command.
 4 │         a_2 1; a_2 3; a_2 2
   ·                ─┬─
   ·                 ╰── source value
 5 │     } else if $list_stream == true {
   ╰────

Error: nu::shell::non_zero_exit_code

  × External command had a non-zero exit code
   ╭─[entry #7:1:29]
 1 │ def a_2 [x] { if $x == 3 { ^false } else { $x } }
   ·                             ──┬──
   ·                               ╰── exited with code 1
   ╰────
```

</details>

It also added a message to guide the usage of NU_BACKTRACE, see the last
line in the following example:
```shell
 ls asdfasd
Error: nu::shell::io::not_found

  × I/O error
  ╰─▶   × Entity not found

   ╭─[entry #17:1:4]
 1 │ ls asdfasd
   ·    ───┬───
   ·       ╰── Entity not found
   ╰────
  help: The error occurred at '/home/windsoilder/projects/nushell/asdfasd'

set the `NU_BACKTRACE=1` environment variable to display a backtrace.
```
# Tests + Formatting
Added some tests for the behavior.

# After Submitting
2025-02-06 22:05:58 +08:00
Wind f4205132c7 add tests with display_error=True (#14939)
# Description
This is a follow up for pr:
https://github.com/nushell/nushell/pull/13873

In that pr, I left 2 TODOs about tests, this pr is going to resolve
them.

# User-Facing Changes
NaN
# Tests + Formatting
Added 2 tests
2025-01-30 06:34:56 -06:00
Ian Manske 93e121782c Improve and fix filesize formatting/display (#14397)
# Description

This PR cleans up the code surrounding formatting and displaying file
sizes.
- The `byte_unit` crate we use for file size units displays kilobytes as
`KB`, which is not the SI or ISO/IEC standard. Rather it should be `kB`,
so this fixes #8872. On some systems, `KB` actually means `KiB`, so this
avoids any potential confusion.
- The `byte_unit` crate, when displaying file sizes, casts integers to
floats which will lose precision for large file sizes. This PR adds a
custom `Display` implementation for `Filesize` that can give an exact
string representation of a `Filesize` for metric/SI units.
- This PR also removes the dependency on the `byte_unit` crate which
brought in several other dependencies.

Additionally, this PR makes some changes to the config for filesize
formatting (`$env.config.filesize`).
- The previous filesize config had the `metric` and `format` options. If
a metric (SI) unit was set in `format`, but `metric` was set to false,
then the `metric` option would take precedence and convert `format` to
the corresponding binary unit (or vice versa). E.g., `{ format: kB,
metric: false }` => `KiB`. Instead, this PR adds the `unit` option to
replace the `format` and `metric` options. `unit` can be set to a fixed
file size unit like `kB` or `KiB`, or it can be set to one of the
special options: `binary` or `metric`. These options tells nushell to
format file sizes using an appropriately scaled metric or binary unit
(examples below).
  ```nushell
  # precision = null

  # unit = kB
  1kB  # 1 kB
  1KiB # 1.024 kB
  
  # unit = KiB
  1kB  # 0.9765625 KiB
  1KiB # 1 KiB
  
  # unit = metric
  1000B     # 1 kB
  1024B     # 1.024 kB
  10_000MB  # 10 GB
  10_240MiB # 10.73741824 GB

  # unit = binary
  1000B     # 1000 B
  1024B     # 1 KiB
  10_000MB  # 9.313225746154785 GiB
  10_240MiB # 10 GiB
  ```
- In addition, this PR also adds the `precision` option to the filesize
config. It determines how many digits to show after the decimal point.
If set to null, then everything after the decimal point is shown.
- The default filesize config is `{ unit: metric, precision: 1 }`.

# User-Facing Changes

- Commands that use the config to format file sizes will follow the
changes described above (e.g., `table`, `into string`, `to text`, etc.).
- The file size unit/format passed to `format filesize` is now case
sensitive. An error with the valid units is shown if the case does not
match.
- `$env.config.filesize.format` and `$env.config.filesize.metric` are
deprecated and replaced by `$env.config.filesize.unit`.
- A new `$env.config.filesize.precision` option was added.

# Tests + Formatting

Mostly updated test expected outputs.

# After Submitting

This PR does not change the way NUON serializes file sizes, because that
would require changing the nu parser to be able to losslessly decode the
new, exact string representation introduced in this PR.

Similarly, this PR also does not change the file size parsing in any
way. Although the file size units provided to `format filesize` or the
filesize config are now case-sensitive, the same is not yet true for
file size literals in nushell code.
2025-01-22 22:24:51 -08:00
Douglas 72d50cf8b7 Convert Path to list in main and preserve case (#14764)
# Description

Fixes multiple issues related to `ENV_CONVERSION` and
path-conversion-to-list.

* #14681 removed some calls to `convert_env_values()`, but we found that
this caused `nu -n` to no longer convert the path properly.
* `ENV_CONVERSIONS` have apparently never preserved case, meaning a
conversion with a key of `foo` would not update `$env.FOO` but rather
create a new environment variable with a different case.
* There was a partial code-path that attempted to solve this for `PATH`,
but it only worked for `PATH` and `Path`.
* `convert_env_values()`, which handled `ENV_CONVERSIONS` was called in
multiple places in the startup depending on flags.

This PR:

* Refactors the startup to handle the conversion in `main()` rather than
in each potential startup path
* Updates `get_env_var_insensitive()` functions added in #14390 to
return the name of the environment variable with its original case. This
allows code that updates environment variables to preserve the case.
* Makes use of the updated function in `ENV_CONVERSIONS` to preserve the
case of any updated environment variables. The `ENV_CONVERSION` key
itself is still case **insensitive**.
* Makes use of the updated function to preserve the case of the `PATH`
environment variable (normally handled separately, regardless of whether
or not there was an `ENV_CONVERSION` for it).

## Before

`env_convert_values` was run:

* Before the user `env.nu` ran, which included `nu -c <commandstring>`
and `nu <script.nu>`
* Before the REPL loaded, which included `nu -n`

## After

`env_convert_values` always runs once in `main()` before any config file
is processed or the REPL is started

# User-Facing Changes

Bug fixes

# Tests + Formatting

- 🟢 `toolkit fmt`
- 🟢 `toolkit clippy`
- 🟢 `toolkit test`
- 🟢 `toolkit test stdlib`

Added additional tests to prevent future regression.

# After Submitting

There is additional cleanup that should probably be done in
`convert_env_values()`. This function previously handled
`ENV_CONVERSIONS`, but there is no longer any need for this since
`convert_env_vars()` runs whenever `$env.ENV_CONVERSIONS` changes now.

This means that the only relevant task in the old `convert_env_values()`
is to convert the `PATH` to a list, and ensure that it is a list of
strings. It's still calling the `from_string` conversion on every
variable (just once) even though there are no `ENV_CONVERSIONS` at this
point.

Leaving that to another PR though, while we get the core issue fixed
with this one.
2025-01-10 10:18:44 -06:00
Bahex 79f19f2fc7 Enable conditional source and use patterns by allowing null as a no-op module (#14773)
Related:
- #14329
- #13872
- #8214

# Description & User-Facing Changes

This PR allows enables the following uses, which are all no-op.
```nushell
source null
source-env null
use null
overlay use null
```

The motivation for this change is conditional sourcing of files. For
example, with this change `login.nu` may be deprecated and replaced with
the following code in `config.nu`
```nushell
const login_module = if $nu.is-login { "login.nu" } else { null }
source $login_module
```

# Tests + Formatting
I'm hoping for CI to pass 😄

# After Submitting
Add a part about the conditional sourcing pattern to the website.
2025-01-09 06:37:27 -06:00
Douglas d702c4605a Increment SHLVL before run_repl() (#14732)
# Description

A follow-on to #14727:

* Instead of using `is-interactive` as the trigger for incrementing
`SHLVL`, this change puts the increment logic just before `run_repl()`
is called.
* Tests are changed to use `-e`
* Moves the `confirm_stdin_is_terminal()` call immediately **after** the
`prerun_cmd` (which executes `--execute (-e) <commandstring>`. The fact
that it was **before** that call seems to be a bug, since the error
message says *"or provide arguments to invoke a script"* even if
`--execute` was used. This change enables REPL testing using `--execute
(-e)`.
* Added a test to ensure `-c` does *not* increment SHLVL.

# User-Facing Changes

`$env.SHLVL` runs before the REPL is started, rather than when
`is-interactive`

# Tests + Formatting

- 🟢 `toolkit fmt`
- 🟢 `toolkit clippy`
- 🟢 `toolkit test`
- 🟢 `toolkit test stdlib`

# After Submitting

N/A
2025-01-03 15:16:57 -06:00
Douglas 86f7f53f85 Run SHLVL tests sequentially (#14727)
Tests for #14707 are causing hangs which are preventing `toolkit test`
from completing on some systems. This appears to be due to the use of
`-i` to force interactive mode, which is required in order to update the
`SHLVL`. Both tests are likely attempting to acquire the terminal at the
same time, and one is hanging as a result.

This is a temporary fix which runs both of these tests sequentially.
It's temporary because we need to find a solution which doesn't use
`-i`, since any other future `-it` test will cause the same situation
again.
2025-01-02 23:22:04 -05:00
Rikuki IX 4884894ddb make exec command decrement SHLVL correctly & SHLVL related test (#14707)
# Description

Rework of #14570, fixing #14567.

`exec` will decrement `SHLVL` env value before passing it to target
executable (in interactive mode).

(Same as last pr, but this time there's no wrong change to current
working code)

Two `SHLVL` related tests were also added this time.
2024-12-31 16:35:49 +01:00
Bahex 1b01598840 Run ENV_CONVERSIONS whenever it's modified (#14591)
- this PR should close #14514

# Description
Makes updates to `$env.ENV_CONVERSIONS` take effect immediately.

# User-Facing Changes
No breaking change, `$env.ENV_CONVERSIONS` can be set and its effect
used in the same file.

# Tests + Formatting

- 🟢 toolkit fmt
- 🟢 toolkit clippy
- 🟢 toolkit test
- 🟢 toolkit test stdlib

# After Submitting
N/A
2024-12-25 21:37:24 +08:00
Devyn Cairns d99905b604 Make the --no-newline test use --no-config-file as well (#14654)
Just a quick change: the test I made for `--no-newline` was missing
`--no-config-file`, so it could false-negative if you have problems with
your config.
2024-12-22 13:55:03 +01:00
Douglas ac75562296 Remove long-unused autoenv tests (#14436)
# Description

The `.nu-env` file feature was removed some time ago (probably in the
engine-q upgrade?). The tests, however, still remained as dead-code, so
this is just some basic clean-up.

If this feature was ever implemented again, the tests would need to be
rewritten anyway due to the changes in the way config is handled.

# User-Facing Changes

None

# Tests + Formatting

- 🟢 `toolkit fmt`
- 🟢 `toolkit clippy`
- 🟢 `toolkit test`
- 🟢 `toolkit test stdlib`
- 
# After Submitting

N/A
2024-11-26 10:22:18 +08:00
Douglas 8c1ab7e0a3 Add proper config defaults for hooks (#14341)
# Release Notes Excerpt

* Hooks now default to an empty value of the proper type (e.g., `[]` or
`{}`) when not otherwise specified

# Description

```nushell
# Start with no config
nu -n
# Populate with defaults
$env.config = {}
$env.config.hooks
```

* Before: All hooks other than `display_output` were set to `null`.
Attempting to append a hook using `++=` would fail unless it had already
been assigned.
* After:
* `pre_prompt`, `pre_execution`, and `command_not_found` are set to
empty lists. This allows the user to simply append new hooks using
`++=`.
* `env_change` is set to an empty record. This allows the user to add
new hooks using `merge`, although a "helper" command would still be
useful (TODO: stdlib).

Also fixed a typo in an error message.

# User-Facing Changes

There shouldn't be any breaking changes since (before) there were no
guarantees of the hook's value/type. Previously, users would have to
check for `null` and `default` to an empty list before appending. Any
user-strategies for dealing with the problem should continue to work
after this change.

# Tests + Formatting

- 🟢 `toolkit fmt`
- 🟢 `toolkit clippy`
- 🟢 `toolkit test`
- 🟢 `toolkit test stdlib`

Note that, for reasons I cannot ascertain, this PR appears to have
*fixed* the `command_not_found_error_recognizes_non_executable_file`
test that was previously broken by #12953. That PR essentially rewrote
the test to match the new behavior, but it no longer tested what it was
intended to test.

Now, the test is working again as designed (and as it works in the
REPL).

# After Submitting

This will be covered in the Configuration update for #14249. This PR
will simplify several examples in the doc.
2024-11-14 20:27:26 -08:00