Compare commits

...

138 Commits

Author SHA1 Message Date
4f67310681 Revert "Allow polars schema --datatype-list to be used without pipeline inp…"
This reverts commit fb691c0da5.
2025-06-13 12:38:53 -07:00
fb691c0da5 Allow polars schema --datatype-list to be used without pipeline input (#15964)
# Description
Fixes the issue of listing allowed datatypes when not being used with
dataframe pipeline input.

Co-authored-by: Jack Wright <jack.wright@nike.com>
2025-06-13 12:38:50 -07:00
7972aea530 Make polars last consistent with polars first (#15963)
# Description
`polars last` will only return one row by default making it consistent
with `polars first`

# User-Facing Changes
- `polars last` will only return one row by default making it consistent
with `polars first`

Co-authored-by: Jack Wright <jack.wright@nike.com>
2025-06-13 12:35:26 -07:00
aa710eeb9a Add groupby support for polars last (#15953)
# Description
Allows `polars last` to be used with group-by
```nu
> ❯ : [[a b c d]; [1 0.5 true Apple] [2 0.5 true Orange] [2 4 true Apple] [3 10 false Apple] [4 13 false Banana] [5 14 true Banana]] | polars into-df -s {a: u8, b: f32, c: bool, d: str} | polars group-by d | polars last | polars sort-by [a] | polars collect
╭───┬────────┬───┬───────┬───────╮
│ # │   d    │ a │   b   │   c   │
├───┼────────┼───┼───────┼───────┤
│ 0 │ Orange │ 2 │  0.50 │ true  │
│ 1 │ Apple  │ 3 │ 10.00 │ false │
│ 2 │ Banana │ 5 │ 14.00 │ true  │
╰───┴────────┴───┴───────┴───────╯
```

# User-Facing Changes
- `polars last` can now be used with group-by expressions

Co-authored-by: Jack Wright <jack.wright@nike.com>
2025-06-13 12:10:29 -07:00
91e843a6d4 add like, not-like to help operators (#15959)
# Description

This PR adds `like` and `not-like` to the `help operators` command. Now
it at least lists them. I wasn't sure if I should say `=~ or like` so I
just separated them with a comma.

![image](https://github.com/user-attachments/assets/1165d900-80a2-4633-9b75-109fcb617c75)


# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use toolkit.nu; toolkit test stdlib"` to run the
tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
2025-06-13 08:59:37 -05:00
ebcb26f9d5 Promote clip from std-rfc to std (#15877)
# Description
Promotes the clip module from `std-rfc` to `std`. Whether we want to
promote other modules as well (probably?) is up for discussion but I
thought I would get the ball rolling with this one.

# User-Facing Changes
* The `clip` module has been promoted from `std-rfc` to `std`. Using the
`std-rfc` version of clip modules will give a deprecation warning
instructing you to switch to the `std` version.

# Tests + Formatting
N/A

# After Submitting
N/A
2025-06-13 07:26:48 +08:00
f8b0af70ff Don't make unquoted file/dir paths absolute (#15878)
# Description

Closes #15848. Currently, we expand unquoted strings to absolute paths
if they are of type `path` or `directory`. This PR makes this no longer
happen. `~`, `.`, and `..+` are still expanded, but a path like
`.../foo/bar/..` will only be turned into `../../foo`, rather than a
full absolute path.

This is mostly so that paths don't get modified before being sent to
known external commands (as in the linked issue). But also, it seems
unnecessary to make all unquoted paths absolute.

After feedback from @132ikl, this PR also makes it so that unquoted
paths are expanded at parse time, so that it matches the runtime
behavior. Previously, `path` expressions were turned into strings
verbatim, while `directory` expressions were treated as not being const.

API change: `nu_path::expansions::expand_path` is now exposed as
`nu_path::expand_path`.

# User-Facing Changes

This has the potential to silently break a lot of scripts. For example,
if someone has a command that expects an already-expanded absolute path,
changes the current working directory, and then passes the path
somewhere, they will now need to use `path expand` to expand the path
themselves before changing the current working directory.

# Tests + Formatting

Just added one test to make sure unquoted `path` arguments aren't made
absolute.

# After Submitting

This is a breaking change, so will need to be mentioned in the release
notes.
2025-06-13 07:26:01 +08:00
12465193a4 cli: Use latest specified flag value when repeated (#15919)
# Description

This PR makes the last specified CLI arguments take precedence over the
earlier ones.

Existing command line tools that align with the new behaviour include:
- `neovim`: `nvim -u a.lua -u b.lua` will use `b.lua`
- `ripgrep`: you can have `--smart-case` in your user config but
override it later with `--case-sensitive` or `--ignore-case` (not
exactly the same flag override as the one I'm talking about but I think
it's still a valid example of latter flags taking precedence over the
first ones)

I think a flag defined last can be considered an override. This allows
having a `nu` alias that includes some default config (`alias nu="nu
--config something.nu"`) but being able to override that default config
as if using `nu` normally.
 
## Example

```sh
nu --config config1.nu --config config2.nu -c '$nu.config-path'
```
The current behavior would print `config1.nu`, and the new one would
print `config2.nu`

## Implementation

Just `.rev()` the iterator to search for arguments starting from the end
of the list. To support that I had to modify the return type of
`named_iter` (I couldn't find a more generic way than
`DoubleEndedIterator`).

# User-Facing Changes

- Users passing repeated flags and relying in nushell using the first
value will experience breakage. Given that right now there's no point in
passing a flag multiple times I guess not many users will be affected

# Tests + Formatting

I added a test that checks the new behavior with `--config` and
`--env-config`. I'm happy to add more cases if needed

# After Submitting
2025-06-13 07:23:38 +08:00
bd3930d00d Better error on spawn failure caused by null bytes (#15911)
# Description

When attempting to pass a null byte in a commandline argument, Nu
currently fails with:

```
> ^echo (char -i 0)
Error: nu:🐚:io::invalid_input

  × I/O error
  ╰─▶   × Could not spawn foreground child

   ╭────
 1 │ crates/nu-command/src/system/run_external.rs:284:17
   · ─────────────────────────┬─────────────────────────
   ·                          ╰── Invalid input parameter
   ╰────
```

This does not explain which input parameter is invalid, or why. Since Nu
does not typically seem to escape null bytes when printing values
containing them, this can make it a bit tricky to track down the
problem.

After this change, it fails with:

```
> ^echo (char -i 0)
Error: nu:🐚:io::invalid_input

  × I/O error
  ╰─▶   × Could not spawn foreground child: nul byte found in provided data

   ╭────
 1 │ crates/nu-command/src/system/run_external.rs:282:17
   · ─────────────────────────┬─────────────────────────
   ·                          ╰── Invalid input parameter
   ╰────

```

which is more useful. This could be improved further but this is niche
enough that is probably not necessary.

This might make some other errors unnecessarily verbose but seems like
the better default. I did check that attempting to execute a
non-executable file still has a reasonable error: the error message for
that failure is not affected by this change.

It is still an "internal" error (referencing the Nu code triggering it,
not the user's input) because the `call.head` span available to this
code is for the command, not its arguments. Using it would result in

```
  × I/O error
  ╰─▶   × Could not spawn foreground child: nul byte found in provided data

   ╭─[entry #1:1:2]
 1 │ ^echo (char -i 0)
   ·  ──┬─
   ·    ╰── Invalid input parameter
   ╰────
```

which is actively misleading because "echo" does not contain the nul
byte.

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use toolkit.nu; toolkit test stdlib"` to run the
tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

Haven't tried to write a test yet: it's tricky because the better error
message comes from the Rust stdlib (so a straightforward integration
test checking for the specific message would be brittle)...

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
2025-06-13 07:22:37 +08:00
81e86c40e1 Try to make hide-env respects overlays (#15904)
# Description
Closes: #15755
I think it's a good feature, to achieve this, we need to get all hidden
envs(it's defined in `get_hidden_env_vars`, and then restore these envs
back to stack)

# User-Facing Changes
### Before
```nushell
> $env.foo = 'bar'
> overlay new xxx
> hide-env foo
> overlay hide xxx
> $env.foo
Error: nu:🐚:column_not_found

  × Cannot find column 'foo'
   ╭─[entry #21:5:1]
 4 │ overlay hide xxx
 5 │ $env.foo
   · ────┬───┬
   ·     │   ╰── value originates here
   ·     ╰── cannot find column 'foo'
   ╰────
```

### After
```nushell
> $env.foo = 'bar'
> overlay new xxx
> hide-env foo
> overlay hide xxx
> $env.foo
bar
```

## Note
But it doesn't work if it runs the example code in script:
`nu -c "$env.foo = 'bar'; overlay new xxx; hide-env foo; overlay hide
xxx; $env.foo"`
still raises an error says `foo` doesn't found. That's because if we run
the script at once, the envs in stack doesn't have a chance to merge
back into `engine_state`, which is only called in `repl`.

It introduces some sort of inconsistency, but I think users use overlays
mostly in repl, so it's good to have such feature first.

# Tests + Formatting
Added 2 tests

# After Submitting
NaN
2025-06-13 07:22:23 +08:00
2fe25d6299 nu-table: (table -e) Reuse NuRecordsValue::width in some cases (#15902)
Just remove a few calculations of width for values which will be
inserted anyhow.
So it must be just a bit faster (in base case).
2025-06-13 07:22:10 +08:00
4aeede2dd5 nu-table: Remove safety-net width check (#15901)
I think we must be relatively confident to say at the check point we
build correct table.
There must be no point endlessly recheck stuff.
2025-06-13 07:22:02 +08:00
0e46ef9769 build(deps): bump which from 7.0.0 to 7.0.3 (#15937)
Bumps [which](https://github.com/harryfei/which-rs) from 7.0.0 to 7.0.3.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/harryfei/which-rs/releases">which's
releases</a>.</em></p>
<blockquote>
<h2>7.0.3</h2>
<ul>
<li>Update rustix to version 1.0. Congrats to rustix on this milestone,
and thanks <a href="https://github.com/mhils"><code>@​mhils</code></a>
for this contribution to which!</li>
</ul>
<h2>7.0.2</h2>
<ul>
<li>Don't return paths containing the single dot <code>.</code>
reference to the current directory, even if the original request was
given in terms of the current directory. Thanks <a
href="https://github.com/jakobhellermann"><code>@​jakobhellermann</code></a>
for this contribution!</li>
</ul>
<h2>7.0.1</h2>
<h2>What's Changed</h2>
<ul>
<li>Switch to <code>env_home</code> crate by <a
href="https://github.com/micolous"><code>@​micolous</code></a> in <a
href="https://redirect.github.com/harryfei/which-rs/pull/105">harryfei/which-rs#105</a></li>
<li>fixes <a
href="https://redirect.github.com/harryfei/which-rs/issues/106">#106</a>,
bump patch version by <a
href="https://github.com/Xaeroxe"><code>@​Xaeroxe</code></a> in <a
href="https://redirect.github.com/harryfei/which-rs/pull/107">harryfei/which-rs#107</a></li>
</ul>
<h2>New Contributors</h2>
<ul>
<li><a href="https://github.com/micolous"><code>@​micolous</code></a>
made their first contribution in <a
href="https://redirect.github.com/harryfei/which-rs/pull/105">harryfei/which-rs#105</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/harryfei/which-rs/compare/7.0.0...7.0.1">https://github.com/harryfei/which-rs/compare/7.0.0...7.0.1</a></p>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/harryfei/which-rs/blob/master/CHANGELOG.md">which's
changelog</a>.</em></p>
<blockquote>
<h2>7.0.3</h2>
<ul>
<li>Update rustix to version 1.0. Congrats to rustix on this milestone,
and thanks <a href="https://github.com/mhils"><code>@​mhils</code></a>
for this contribution to which!</li>
</ul>
<h2>7.0.2</h2>
<ul>
<li>Don't return paths containing the single dot <code>.</code>
reference to the current directory, even if the original request was
given in
terms of the current directory. Thanks <a
href="https://github.com/jakobhellermann"><code>@​jakobhellermann</code></a>
for this contribution!</li>
</ul>
<h2>7.0.1</h2>
<ul>
<li>Get user home directory from <code>env_home</code> instead of
<code>home</code>. Thanks <a
href="https://github.com/micolous"><code>@​micolous</code></a> for this
contribution!</li>
<li>If home directory is unavailable, do not expand the tilde to an
empty string. Leave it as is.</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="1d145deef8"><code>1d145de</code></a>
release version 7.0.3</li>
<li><a
href="f5e5292234"><code>f5e5292</code></a>
fix unrelated lint error</li>
<li><a
href="4dcefa6fe9"><code>4dcefa6</code></a>
bump rustix</li>
<li><a
href="bd868818bd"><code>bd86881</code></a>
bump version, add to changelog</li>
<li><a
href="cf37760ea1"><code>cf37760</code></a>
don't run relative dot test on macos</li>
<li><a
href="f2c4bd6e8b"><code>f2c4bd6</code></a>
update target to new name for wasm32-wasip1</li>
<li><a
href="87acc088c1"><code>87acc08</code></a>
When searching for <code>./script.sh</code>, don't return
<code>/path/to/./script.sh</code></li>
<li><a
href="68acf2c456"><code>68acf2c</code></a>
Fix changelog to link to GitHub profile</li>
<li><a
href="b6754b2a56"><code>b6754b2</code></a>
Update CHANGELOG.md</li>
<li><a
href="0c63719129"><code>0c63719</code></a>
fixes <a
href="https://redirect.github.com/harryfei/which-rs/issues/106">#106</a>,
bump patch version</li>
<li>Additional commits viewable in <a
href="https://github.com/harryfei/which-rs/compare/7.0.0...7.0.3">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=which&package-manager=cargo&previous-version=7.0.0&new-version=7.0.3)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-06-13 07:21:37 +08:00
962467fdfd build(deps): bump titlecase from 3.5.0 to 3.6.0 (#15936)
Bumps [titlecase](https://github.com/wezm/titlecase) from 3.5.0 to
3.6.0.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/wezm/titlecase/releases">titlecase's
releases</a>.</em></p>
<blockquote>
<h2>Version 3.6.0</h2>
<ul>
<li>Support hyphenated words by <a
href="https://github.com/carlocorradini"><code>@​carlocorradini</code></a>
in <a
href="https://redirect.github.com/wezm/titlecase/pull/37">#37</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/wezm/titlecase/compare/v3.5.0...v3.6.0">https://github.com/wezm/titlecase/compare/v3.5.0...v3.6.0</a></p>
<h2>Binaries</h2>
<ul>
<li><a
href="https://releases.wezm.net/titlecase/v3.6.0/titlecase-v3.6.0-amd64-unknown-freebsd.tar.gz">FreeBSD
13+ amd64</a></li>
<li><a
href="https://releases.wezm.net/titlecase/v3.6.0/titlecase-v3.6.0-x86_64-unknown-linux-musl.tar.gz">Linux
x86_64</a></li>
<li><a
href="https://releases.wezm.net/titlecase/v3.6.0/titlecase-v3.6.0-universal-apple-darwin.tar.gz">MacOS
Universal</a></li>
<li><a
href="https://releases.wezm.net/titlecase/v3.6.0/titlecase-v3.6.0-x86_64-pc-windows-msvc.zip">Windows
x86_64</a></li>
</ul>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/wezm/titlecase/blob/master/Changelog.md">titlecase's
changelog</a>.</em></p>
<blockquote>
<h2><a
href="https://github.com/wezm/titlecase/releases/tag/v3.6.0">3.6.0</a></h2>
<ul>
<li>Support hypendated words <a
href="https://redirect.github.com/wezm/titlecase/pull/37">#37</a>.
Thanks <a
href="https://github.com/carlocorradini"><code>@​carlocorradini</code></a></li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="83265b43ba"><code>83265b4</code></a>
Version 3.6.0</li>
<li><a
href="e49b32b262"><code>e49b32b</code></a>
Use 'contains' to check for internal characters</li>
<li><a
href="736be39991"><code>736be39</code></a>
feat: hyphen</li>
<li>See full diff in <a
href="https://github.com/wezm/titlecase/compare/v3.5.0...v3.6.0">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=titlecase&package-manager=cargo&previous-version=3.5.0&new-version=3.6.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-06-13 07:21:09 +08:00
d27232df6e build(deps): bump ansi-str from 0.8.0 to 0.9.0 (#15935)
Bumps [ansi-str](https://github.com/zhiburt/ansi-str) from 0.8.0 to
0.9.0.
<details>
<summary>Commits</summary>
<ul>
<li>See full diff in <a
href="https://github.com/zhiburt/ansi-str/commits">compare view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=ansi-str&package-manager=cargo&previous-version=0.8.0&new-version=0.9.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-06-13 07:19:47 +08:00
d7cec2088a Fix docs typo referring to non-existant Value::CustomValue (#15954)
# Description

I was messing around with custom types and noticed `nu-protocol`
referring to a `Value::CustomValue` variant that doesn't exist. Fixed it
to say `Value::Custom` instead.

# User-Facing Changes

Documentation mentions the correct variant of `Value`

# Tests + Formatting

No new tests necessary

# After Submitting
2025-06-12 13:34:52 -05:00
22d1fdcdf6 Improve precision in parsing of filesize values (#15950)
- improves rounding error reported in #15851
- my ~~discussion~~ monologue on how filesizes are parsed currently:
#15944

# Description

The issue linked above reported rounding errors when converting MiB to
GiB, which is mainly caused by parsing of the literal.

Nushell tries to convert all filesize values to bytes, but currently
does so in 2 steps:
- first converting it to the next smaller unit in `nu-parser` (so `MiB`
to `KiB`, in this case), and truncating to an `i64` here
- then converting that to bytes in `nu-engine`, again truncating to
`i64`

In the specific example above (`95307.27MiB`), this causes 419 bytes of
rounding error. By instead directly converting to bytes while parsing,
the value is accurate (truncating those 0.52 bytes, or 4.12 bits).
Rounding error in the conversion to GiB is also multiple magnitudes
lower.

(Note that I haven't thoroughly tested this, so I can't say with
confidence that all values would be parsed accurate to the byte.)

# User-Facing Changes

More accurate filesize values, and lower accumulated rounding error in
calculations.

# Tests + Formatting

new test: `parse_filesize` in `nu-parser` - verifies that `95307.27MiB`
is parsed correctly as `99_936_915_947B`

# After Submitting
2025-06-12 07:58:21 -05:00
ba59f71f20 bump to dev version 0.105.2 (#15952)
# Description

Bump nushell to development version.

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use toolkit.nu; toolkit test stdlib"` to run the
tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
2025-06-12 07:57:01 -05:00
2352548467 Use NUSHELL_PAT for winget publish (#15934)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->
Use NUSHELL_PAT for winget publish
2025-06-11 06:48:54 +08:00
3efbda63b8 Try to fix winget publish error (#15933)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->

Try to fix winget publish error here:
https://github.com/nushell/nushell/actions/runs/15567694761/job/43835718254#step:2:208
2025-06-11 05:27:27 +08:00
1fe62ee613 bump patch version 2025-06-10 21:42:41 +02:00
126d11fcb7 Revert "update nushell to use coreutils v0.1.0 crates (#15896)" (#15932) 2025-06-10 21:37:28 +02:00
ea4f8ff400 Use stable reedline version for the release (#15931) 2025-06-10 18:45:52 +02:00
ebcdf5a8b1 Bump to 0.105.0 (#15930)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# Description
Bump to 0.105.0
2025-06-10 23:37:00 +08:00
440b9c8e1f Fix typo in examples of the table command (#15925)
# Description

Currently, the examples for `table` have a small typo (notice row 1,
column a):
```
  Render data in table view
  > [[a b]; [1 2] [3 4]] | table
  ╭───┬───┬───╮
  │ # │ a │ b │
  ├───┼───┼───┤
  │ 0 │ 1 │ 2 │
  │ 1 │ 3 │ 4 │
  ╰───┴───┴───╯

  Render data in table view (expanded)
  > [[a b]; [1 2] [2 [4 4]]] | table --expand
  ╭───┬───┬───────────╮
  │ # │ a │     b     │
  ├───┼───┼───────────┤
  │ 0 │ 1 │         2 │
  │ 1 │ 3 │ ╭───┬───╮ │
  │   │   │ │ 0 │ 4 │ │
  │   │   │ │ 1 │ 4 │ │
  │   │   │ ╰───┴───╯ │
  ╰───┴───┴───────────╯

  Render data in table view (collapsed)
  > [[a b]; [1 2] [2 [4 4]]] | table --collapse
  ╭───┬───╮
  │ a │ b │
  ├───┼───┤
  │ 1 │ 2 │
  ├───┼───┤
  │ 3 │ 4 │
  │   ├───┤
  │   │ 4 │
  ╰───┴───╯
  ```

I changed the example commands to match their outputs, and swapped the 2 for a 3 in all the following examples too, for consistency.

# User-Facing Changes

More accurate examples for the `table` command.

# Tests + Formatting

No changes

# After Submitting
2025-06-09 13:20:34 -05:00
96a886eb84 feat(to-md): add support for centering columns via CellPaths (#14552) (#15861)
Closes #14552 

# Description

Implemented a new flag to the ```to md``` command to center specific
columns in Markdown table output using a list of CellPaths.
This enhances formatting control for users exporting tables to markdown.

## Example

For the table:

```shell
let t = version | select version build_time | transpose k v
```

```
╭───┬────────────┬────────────────────────────╮
│ # │     k      │             v              │
├───┼────────────┼────────────────────────────┤
│ 0 │ version    │ 0.104.1                    │
│ 1 │ build_time │ 2025-05-21 11:15:45 +01:00 │
╰───┴────────────┴────────────────────────────╯
```

Running ```$t | to md``` or ```$t | to md --pretty``` gives us,
respectively:

```
|k|v|
|-|-|
|version|0.104.1|
|build_time|2025-05-21 11:15:45 +01:00|
```

|k|v|
|-|-|
|version|0.104.1|
|build_time|2025-05-21 11:15:45 +01:00|

and

```
| k          | v                          |
| ---------- | -------------------------- |
| version    | 0.104.1                    |
| build_time | 2025-05-21 11:15:45 +01:00 |
```

| k          | v                          |
| ---------- | -------------------------- |
| version    | 0.104.1                    |
| build_time | 2025-05-21 11:15:45 +01:00 |

With the new ```center``` flag, when adding ```--center [v]``` to the
previous commands, we obtain, respectively:

```
|k|v|
|-|:-:|
|version|0.104.1|
|build_time|2025-05-21 11:15:45 +01:00|
```

|k|v|
|-|:-:|
|version|0.104.1|
|build_time|2025-05-21 11:15:45 +01:00|

and

```
| k          |             v              |
| ---------- |:--------------------------:|
| version    |          0.104.1           |
| build_time | 2025-05-21 11:15:45 +01:00 |
```

| k          |             v              |
| ---------- |:--------------------------:|
| version    |          0.104.1           |
| build_time | 2025-05-21 11:15:45 +01:00 |

The new ```center``` option, as demonstrated in the example, not only
formats the Markdown table to center columns but also, when paired with
```pretty```, it also centers the string values within those columns.

The logic works by extracting the column from the CellPath and applying
centering. So, ```--center [1.v]``` is also valid and centers the
```v``` column.
You can also specify multiple columns, for instance, ```--center [v
k]``` will center both columns in the example above.

# User-Facing Changes

The ```to md``` command will support column centering with the new
```center``` flag.

# Tests + Formatting

Added test cases to ensure correct behaviour.
fmt + clippy OK.

# After Submitting

The command documentation needs to be updated with the new ```center```
flag and an example.


Co-authored-by: Marco Cunha <marcomarquesdacunha@tecnico.ulisboa.pt>

Co-authored-by: Marco Cunha <marcomarquesdacunha@tecnico.ulisboa.pt>
2025-06-09 06:07:09 -05:00
61d59f13fa Try to fix PAT issue of winget publish account (#15922)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->

Try to fix PAT issue of `winget` publish account, this change may make
publish with `nushell` account work
2025-06-09 09:33:12 +08:00
5da7dcdbdb make date humanize use human_time_from_now() (#15918)
# Description

This PR fixes a `date humanize` bug and makes it use @LoicRiegel's newer
function `human_time_from_now()`.

### Before
```nushell
❯ (date now) + 3day
Wed, 11 Jun 2025 07:15:48 -0500 (in 3 days)
❯ (date now) + 3day | date humanize
in 2 days
```

### After
```nushell
❯ (date now) + 3day
Wed, 11 Jun 2025 07:23:10 -0500 (in 3 days)
❯ (date now) + 3day | date humanize
in 3 days
```

Closes #15916


# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use toolkit.nu; toolkit test stdlib"` to run the
tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
2025-06-08 16:09:57 -05:00
f92f11c0cf Enable shell_integration.osc9_9 by default on Windows (#15914)
# Description

This sets the value to true by default only on Windows. This is not a
legacy code and is used by the Windows Terminal to detect the current
directory (explicitly enabling osc7 did not work). Here are the official
docs:
https://learn.microsoft.com/en-us/windows/terminal/tutorials/new-tab-same-directory

# User-Facing Changes

Windows users will by default have their terminals properly detect the
current working directory without extra configuration/troubleshooting.
2025-06-08 07:29:49 -05:00
3bf96523a4 Pull reedline development version (#15912)
To check https://github.com/nushell/reedline/pull/916

As this is the only commit since the last release, if problems are
encountered for Nushell we can revert this and forgo a reedline release

---------

Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com>
2025-06-07 15:19:25 -05:00
8d46398e13 fix(polars): swap out pivot for pivot_stable to suppress warning message (#15913)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->
The current implementation of `polars pivot` calls an unsupported
version of pivot that throws a warning message in stdout (using
println!) stating that "unstable pivot not yet unsupported, using stable
pivot." This PR swaps out the call to `pivot` with a call to
`pivot_stable`, which is being done in the underlying polars anyways.

```nushell
#  Current Implementation
> [[a b c]; [1 x 10] [1 y 10] [2 x 11] [2 y 11]] | polars into-df | polars pivot -i [a] -o [b] -v [c]
unstable pivot not yet supported, using stable pivot
╭───┬───┬────┬────╮
│ # │ a │ x  │ y  │
├───┼───┼────┼────┤
│ 0 │ 1 │ 10 │ 10 │
│ 1 │ 2 │ 11 │ 11 │

#  Proposed Implementation (no println! statement)
> [[a b c]; [1 x 10] [1 y 10] [2 x 11] [2 y 11]] | polars into-df | polars pivot -i [a] -o [b] -v [c]
╭───┬───┬────┬────╮
│ # │ a │ x  │ y  │
├───┼───┼────┼────┤
│ 0 │ 1 │ 10 │ 10 │
│ 1 │ 2 │ 11 │ 11 │
╰───┴───┴────┴────╯
```

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->
None

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use toolkit.nu; toolkit test stdlib"` to run the
tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->
Current suite of tests were sufficient

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
2025-06-07 11:46:02 -05:00
461d558983 Fix: Downgrade calamine to 0.26 to fix build without --locked (#15908)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

- basically reverts #15657
- still fixes #15584
- fixes #15784
- related https://github.com/tafia/calamine/pull/506

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->

The `zip` crate had some issues properly upgrading their repo and did
some yanking shenanigans. Since their yanking took so long `calamine`
tried to fix it but right now pinned to a yanked version of `zip`. This
breaks `cargo update`, `cargo add nu_command` and forces installs to use
`--locked`. For `calamine` exists [a
PR](https://github.com/tafia/calamine/pull/506) that would fix this but
right now that is not merged and we don't know when. Since we only
bumped `calamine` to fix #15584 and with the correctly yanked
`zip@2.5.0` we don't have that issue anymore. So I'm basically reverting
our `calamine` version. As soon as `calamine` updates with the new
version of `zip`, we can bump it again.

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->

Should be none.

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use toolkit.nu; toolkit test stdlib"` to run the
tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

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

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->

If dependabot tries to bump `calamine` to `0.27.0`, we have to closed
that PR.
2025-06-07 12:42:43 +02:00
65c9160170 Fix typo in example config.nu (#15910) 2025-06-07 13:51:07 +08:00
e3124d3561 reorder cals input_output_types (#15909)
This PR should close #15906

# User-Facing Changes
reorder `cal`s `input_output_types`, so that `String` is first in order.
2025-06-06 16:28:12 -04:00
b886fd364c update nushell to use coreutils v0.1.0 crates (#15896) 2025-06-05 15:59:34 -05:00
21d949207f Add regex documentation/examples to polars col (#15898)
# Description
Include regular expression example and help documentation to `polars
col`

Co-authored-by: Jack Wright <jack.wright@nike.com>
2025-06-05 15:53:22 -05:00
4a9e2ac37b Creates col and nth expressions when using paths on lazy frames. (#15891)
# Description
Instead of collecting the frame and returning the columns of the
collected frame when using paths $df.column_name or $df.0 this creates
expressions:

```nu
> ❯ : let df = polars open /tmp/foo.parquet
> ❯ : $df | polars select $df.pid | polars first 5 | polars collect
╭───┬───────╮
│ # │  pid  │
├───┼───────┤
│ 0 │ 45280 │
│ 1 │ 45252 │
│ 2 │ 45242 │
│ 3 │ 45241 │
│ 4 │ 45207 │
╰───┴───────╯

> ❯ : $df | polars select $df.0 | polars first 5 | polars collect
╭───┬───────╮
│ # │  pid  │
├───┼───────┤
│ 0 │ 45280 │
│ 1 │ 45252 │
│ 2 │ 45242 │
│ 3 │ 45241 │
│ 4 │ 45207 │
╰───┴───────╯
```

---------

Co-authored-by: Jack Wright <jack.wright@nike.com>
2025-06-05 12:42:27 -07:00
9cc74e7a9f Update where documentation (#15467)
# Description

Updates `help where` to better explain row conditions, and provide more
examples. Also, the syntax shape is changed to `one_of(condition,
closure())>`. I don't think this should affect parsing at all because it
should still always be parsed as `SyntaxShape::RowCondition`, but it
should be more clear that you can use a row condition _or_ a closure
here, even if technically we consider closures to be row conditions
internally. In a similar vein, the help text makes this distinction
explicitly to make it more clear to users that closures are supported.

# User-Facing Changes

* Updated `where` help text



---------

Co-authored-by: Bahex <Bahex@users.noreply.github.com>
Co-authored-by: Douglas <32344964+NotTheDr01ds@users.noreply.github.com>
Co-authored-by: Stefan Holderbach <sholderbach@users.noreply.github.com>
2025-06-05 21:31:22 +02:00
4adcf079e2 fix(std/iter): align example descriptions with closure logic for find and find-index (#15895)
- Updated the second @example for `find` to "Try to find an even
element" to match the closure logic.
- Updated the second @example for `find-index` to "Try to find the index
of an even element" for consistency.
2025-06-05 07:37:09 -05:00
81cec2e50f Fix table wrap emojie (#15138)
I did a naive fix; which is probably all right.
But I want to spend some time to refactor a neighboring stuff.
And it's yet not to be released I guess;
I hope to add a few things beforehand.

I've just opened it so you can verify that it must be addressed.

close #15104, #14910, #15256
2025-06-05 06:45:05 -05:00
ed7b2615c1 fix(glob): Fix drive-letter glob expansion on Windows (#15871)
# Description
This PR fixes drive-letter glob expansion on Windows. It adds a bit of
pre-processing to play better with the wax crate.
This change is following suggestions from this thread on the wax repo:
https://github.com/olson-sean-k/wax/issues/34

fixes #15707 #7125
2025-06-04 17:28:49 -05:00
74e0e4f092 (gstat): add config option to disable tag calculation (#15893)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->
Fixes #15884.
Adds `--disable-tag` flag to the `gstat` plugin that disables expensive
calculations. Instead `gstat` reports `no_tag`.

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->
There is no change in behaviour if the flag is not provided.

If the flag is provided, it will behave like there is no tags in the
repo, so no existing config will break.
2025-06-04 17:28:02 -05:00
42fc9f52a1 Partial workaround and deprecation warning for breaking change usage of #15654 (#15806)
# Description
Adds a temporary workaround to prevent #15654 from being a breaking
change when using a closure stored in a variable, and issues a warning.
Also has a special case related to
https://github.com/carapace-sh/carapace-bin/pull/2796 which suggests
re-running `carapace init`


![image](https://github.com/user-attachments/assets/783f3dbf-2a85-4aa5-ac66-efc584ac77fd)


![image](https://github.com/user-attachments/assets/c8fb5ae1-66a8-474c-8244-a22600f4da43)

# After Submitting
Remove variable name detection after grace period
2025-06-04 10:19:25 +02:00
c563e0cfb0 build(deps): bump itertools from 0.13.0 to 0.14.0 (#15886) 2025-06-04 08:10:21 +00:00
8671a3dbbd Fixup: Fix regression caused by #15881 (#15889)
# Description

This PR fixes regressions introduced by #15881.

# User-Facing Changes

None.

# Tests + Formatting

See nushell/integrations#57.

# After Submitting

None.
2025-06-04 10:08:02 +02:00
fc813af4c8 Better error handling for negative integer exponents in ** operator (#15882)
**Title**: Better error handling for negative integer exponents in `**`
operator

---

### Bug Fix

This PR addresses an issue where attempting to raise an integer to a
negative power (e.g. `10 ** -1`) incorrectly triggered an
`OperatorOverflow` error. This behavior was misleading since the
overflow isn't actually the root problem — it's the unsupported
operation of raising integers to negative powers.

---

###  Fix Summary

* Updated `Value::pow` to:

  * Check for negative exponents when both operands are integers.
* Return a `ShellError::IncorrectValue` with a helpful message guiding
users to use floating point values instead.

#### Example:

```bash
> 10 ** -1
Error: nu:🐚:incorrect_value

  × Incorrect value.
   ╝─[entry #2:1:4]
 1 │ 10 ** -1
   ·    ─┬┬
   ·     │╰── encountered here
   ·     ╰── Negative exponent for integer power is unsupported; use floats instead.
```

---

### Testing

Manual testing:

* `10 ** -1` → now returns a clear and appropriate `IncorrectValue`
error.
* `10.0 ** -1`, `10 ** -1.0`, etc. continue to work as expected.

---

### Related

Fixes #15860



---------

Co-authored-by: Kumar Ujjawal <kumar.ujjawal@greenpista.com>
2025-06-04 10:06:41 +02:00
b83aa17c96 build(deps): bump crate-ci/typos from 1.32.0 to 1.33.1 (#15885) 2025-06-04 08:48:39 +08:00
c7e10c3c57 Correctly quote nu.exe and nu.ico path containing spaces in WiX (#15881)
# Description

This PR improves the installation process of Nushell's Windows Terminal
Profile by adding proper quoting when refilling the path to `nu.exe` and
`nu.ico`.

**Crossref:**
https://github.com/microsoft/terminal/issues/6082#issuecomment-1001226003

**Affected lines:**


222c307648/wix/main.wxs (L278-L282)

Currently, when any part of the installation path of `nu.exe` contains
spaces, the auto-generated profile would contain a truncated path due to
improper quoting. At best, this would cause failures when launching the
profile. At worst, this could lead to executable hijacks.

Assume this default-generated profile with the username "Mantle Bao":

```json
{
  "profiles": [
    {
      "guid": "{47302f9c-1ac4-566c-aa3e-8cf29889d6ab}",
      "name": "Nushell",
      "commandline": "C:\\Users\\Mantle Bao\\AppData\\Local\\Programs\\nu\\bin\\nu.exe",
      "icon": "C:\\Users\\Mantle Bao\\AppData\\Local\\Programs\\nu\\nu.ico",
      "startingDirectory": "%USERPROFILE%"
    }
  ]
}
```

And a file named "Mantle" exists under `C:\Users\`:

```nushell
> sudo nu -c `touch C:\Users\Mantle`
> ls `C:\Users\` | find "Mantle" | select name type
╭───┬─────────────────────────────────────────────────┬──────╮
│ # │                      name                       │ type │
├───┼─────────────────────────────────────────────────┼──────┤
│ 0 │ C:\Users\Mantle                                 │ file │
│ 1 │ C:\Users\Mantle Bao                             │ dir  │
╰───┴─────────────────────────────────────────────────┴──────╯
>
```

Launching this profile produces this error in Windows Terminal
1.22.11141.0:

```plain-text
[error 2147942593 (0x800700c1) when launching `C:\Users\Mantle Bao\AppData\Local\Programs\nu\bin\nu.exe']
```

![Error 0x800700c1 pops up when launching the
profile](https://github.com/user-attachments/assets/7cb0d175-299c-4fb0-aa43-2185675e12ae)

[Looking
up](https://learn.microsoft.com/en-us/windows/win32/debug/system-error-code-lookup-tool)
this error code would yield its name as `ERROR_BAD_EXE_FORMAT`, since
the Windows shell will try to execute `C:\\Users\\Mantle` but not the
actual `nu.exe`.

## Hijacking PoC

![Running
Calc](https://github.com/user-attachments/assets/a7ab9ea4-680b-441f-8a7f-26eaad1b7942)

# User-Facing Changes

None. It should only affect the installation phase without any
user-facing changes.

# Tests + Formatting

This PR does not modify Rust or Nu code, and all its improvements belong
to the packaging system. Thus, no conventional tests or formatting
apply. But in case there exists preferred ways to test the packaging
process, please inform me of those, and I would make appropriate
changes.

# After Submitting

None. It should only affect the installation phase without any
post-submission edits.
2025-06-03 21:38:42 +02:00
e7d2717424 feat(std-rfc): add iter module and recurse command (#15840)
# Description
`recurse` command is similar to `jq`'s `recurse`/`..` command. Along
with values, it also returns their cell-paths relative to the "root"
(initial input)

By default it uses breadth-first traversal, collecting child items of
all available sibling items before starting to process those child
items. This means output is ordered in increasing depth.
With the `--depth-first` flag it uses a stack based recursive descend,
which results in output order identical to `jq`'s `recurse`.

It can be used in the following ways:
- `... | recurse`: Recursively traverses the input value, returns each
value it finds as a stream.
- `... | recurse foo.bar`: Only descend through the given cell-path.
- `... | recurse {|parent| ... }`: Produce child values with a closure.

```nushell
{
    "foo": {
        "egg": "X"
        "spam": "Y"
    }
    "bar": {
        "quox": ["A" "B"]
    }
}
| recurse
| update item { to nuon }

# => ╭───┬──────────────┬───────────────────────────────────────────────╮
# => │ # │     path     │                     item                      │
# => ├───┼──────────────┼───────────────────────────────────────────────┤
# => │ 0 │ $.           │ {foo: {egg: X, spam: Y}, bar: {quox: [A, B]}} │
# => │ 1 │ $.foo        │ {egg: X, spam: Y}                             │
# => │ 2 │ $.bar        │ {quox: [A, B]}                                │
# => │ 3 │ $.foo.egg    │ "X"                                           │
# => │ 4 │ $.foo.spam   │ "Y"                                           │
# => │ 5 │ $.bar.quox   │ [A, B]                                        │
# => │ 6 │ $.bar.quox.0 │ "A"                                           │
# => │ 7 │ $.bar.quox.1 │ "B"                                           │
# => ╰───┴──────────────┴───────────────────────────────────────────────╯


{"name": "/", "children": [
    {"name": "/bin", "children": [
        {"name": "/bin/ls", "children": []},
        {"name": "/bin/sh", "children": []}]},
    {"name": "/home", "children": [
        {"name": "/home/stephen", "children": [
            {"name": "/home/stephen/jq", "children": []}]}]}]}
| recurse children
| get item.name

# => ╭───┬──────────────────╮
# => │ 0 │ /                │
# => │ 1 │ /bin             │
# => │ 2 │ /home            │
# => │ 3 │ /bin/ls          │
# => │ 4 │ /bin/sh          │
# => │ 5 │ /home/stephen    │
# => │ 6 │ /home/stephen/jq │
# => ╰───┴──────────────────╯


{"name": "/", "children": [
    {"name": "/bin", "children": [
        {"name": "/bin/ls", "children": []},
        {"name": "/bin/sh", "children": []}]},
    {"name": "/home", "children": [
        {"name": "/home/stephen", "children": [
            {"name": "/home/stephen/jq", "children": []}]}]}]}
| recurse children --depth-first
| get item.name

# => ╭───┬──────────────────╮
# => │ 0 │ /                │
# => │ 1 │ /bin             │
# => │ 2 │ /bin/ls          │
# => │ 3 │ /bin/sh          │
# => │ 4 │ /home            │
# => │ 5 │ /home/stephen    │
# => │ 6 │ /home/stephen/jq │
# => ╰───┴──────────────────╯


2
| recurse { ({path: square item: ($in * $in)}) }
| take while { $in.item < 100 }

# => ╭───┬─────────────────┬──────╮
# => │ # │      path       │ item │
# => ├───┼─────────────────┼──────┤
# => │ 0 │ $.              │    2 │
# => │ 1 │ $.square        │    4 │
# => │ 2 │ $.square.square │   16 │
# => ╰───┴─────────────────┴──────╯
``` 

# User-Facing Changes
No changes other than the new command.

# Tests + Formatting
Added tests for examples. (As we can't run them directly as tests yet.)
- 🟢 `toolkit test stdlib`

# After Submitting
- Update relevant parts of
https://www.nushell.sh/cookbook/jq_v_nushell.html
- `$env.config | recurse | where ($it.item | describe -d).type not-in
[list, record, table]` can partially cover the use case of `config
flatten`, should we do something?

---------

Co-authored-by: Bahex <17417311+Bahex@users.noreply.github.com>
2025-06-03 11:21:12 -04:00
222c307648 overlay new: add --reload(-r) flag (#15849)
# Description
Close: #15747

To support `reload` feature, we just need to save `caller_stack` before
adding overlay, then redirect_env back after the overlay is added.

# User-Facing Changes
NaN

# Tests + Formatting
Added 1 test

# After Submitting
NaN
2025-06-03 10:11:58 +08:00
eb9eb09ac5 Make parse simple patterns ignore fields with placeholder (_) (#15873)
# Description
Simple `parse` patterns let you quickly put together simple parsers, but
sometimes you aren't actually interested in some of the output (such as
variable whitespace). This PR lets you use `{_}` to discard part of the
input.

Example:
```nushell
"hello world" | parse "{foo} {_}"
# => ╭───┬───────╮
# => │ # │  foo  │
# => ├───┼───────┤
# => │ 0 │ hello │
# => ╰───┴───────╯
```

here's a simple parser for the `apropops` using the `_` placeholder to
discard the variable whitespace, without needing to resort to a full
regex pattern:

```nushell
apropos linux | parse "{name} ({section}) {_}- {topic}"
# => ╭───┬───────────────────────────────────────┬─────────┬─────────────────────────────────────────────────────────────────────╮
# => │ # │                 name                  │ section │                                topic                                │
# => ├───┼───────────────────────────────────────┼─────────┼─────────────────────────────────────────────────────────────────────┤
# => │ 0 │ PAM                                   │ 8       │ Pluggable Authentication Modules for Linux                          │
# => │ 1 │ aarch64-linux-gnu-addr2line           │ 1       │ convert addresses or symbol+offset into file names and line numbers │
# => │ 2 │ ...                                   │ ...     │ ...                                                                 │
# => │ 3 │ xcb_selinux_set_window_create_context │ 3       │ (unknown subject)                                                   │
# => │ 4 │ xorriso-dd-target                     │ 1       │ Device evaluator and disk image copier for GNU/Linux                │
# => ╰───┴───────────────────────────────────────┴─────────┴─────────────────────────────────────────────────────────────────────╯
```

# User-Facing Changes
* `parse` simple patterns can now discard input using `{_}`

# Tests + Formatting
N/A

# After Submitting
N/A
2025-06-03 03:11:05 +03:00
6eacbabe17 Add debug env command (#15875)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->

When calling external commands, we convert our `$env` into a map where
each value is a string. If a value cannot be converted, it will be
skipped or when an `ENV_CONVERSION` is defined, will be converted via
that. This makes this conversion not that trivial. To ease debugging
this behavior or allowing to generate `.env` files from the current
environment did I add `debug env`.

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->

New command `debug env`.

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use toolkit.nu; toolkit test stdlib"` to run the
tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

I did not add extra tests, as I just called the function we also call in
`start`, `exec` or `run-external`.

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->

I can use this to make my life easier implementing `colcon-nushell` 😉
2025-06-02 17:29:58 -04:00
33303f083c Disable flaky killing_job_kills_pids test on macOS (#15874)
# Description

This test has failed a number of times specifically on macOS. I'm not
exactly sure what the issue is, it seemed to work fine before. We should
probably actually fix it, but flaky CI is worse than missing this one
test on macOS

cc @cosineblast
2025-06-02 22:34:45 +02:00
483974311d feat(std): further bench improvements (#15856)
# Description

Following #15843, I have tinkered more with it and realized that there
are plenty of features from
[hyperfine](https://github.com/sharkdp/hyperfine) that could be
implemented pretty easily.

- `--warmup` flag to do `n` runs without benchmarking first, useful to
fill disk cache
```nu
@example "use --warmup to fill the disk cache before benchmarking" { bench { fd } { jwalk . -k } -w 1 -n 10 }
```
- `--setup`, `--prepare`, `--cleanup`, `--conclude` flags to run code
before/after benchmarks
```nu
@example "use `--setup` to compile before benchmarking" { bench { ./target/release/foo } --setup { cargo build --release } }
@example "use `--prepare` to benchmark rust compilation speed" { bench { cargo build --release } --prepare { cargo clean } }
```
- `--ignore-errors` to ignore any errors in the benchmarked commands
- benchmarked commands are now `| ignore` so that externals don't fill
the screen
2025-06-02 22:32:44 +02:00
179ea5ae87 fix(which): remove required positional argument to allow spread input (#15870)
## Summary

This PR removes the required positional argument from the `which`
command, allowing it to accept input via the spread (`...`) operator.
This enables expressions like:

```nu
[notepad cmd] | which ...$in
```

Previously, this failed due to a missing required positional argument.
The Nushell runtime already handles empty input gracefully, so the
change aligns with existing behavior.

---

## Motivation

Making `which` compatible with splatted input improves composability and
aligns with user expectations in scriptable environments. It supports
patterns where the input may be constructed dynamically or piped in from
earlier commands.

---

## Changes

* Removed the `required` attribute from the positional argument in the
`which` command signature.
* No additional runtime logic required since empty input is handled
gracefully already.

---

## Examples

### Before

```nu
[notepad cmd] | which ...$in
#  Error: Missing required positional argument
```

### After

```nu
[notepad cmd] | which ...$in
#  Executes correctly
```

---

## Testing

* Ran `cargo test --all` and `cargo test -p nu-command`
* Manually tested using spread input with the `which` command
* Confirmed that empty and non-empty inputs behave correctly

---

## Related Issues

Closes
[[#15801](https://github.com/nushell/nushell/issues/15801)](https://github.com/nushell/nushell/issues/15801)

---------

Co-authored-by: Kumar Ujjawal <kumar.ujjawal@greenpista.com>
2025-06-02 20:18:02 +02:00
bdc7cdbcc4 feat(polars): introducing new polars replace (#15706)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->
This PR seeks to port the polars command `replace`
(https://docs.pola.rs/api/python/stable/reference/expressions/api/polars.Expr.replace.html)
and `replace_strict`
(https://docs.pola.rs/api/python/stable/reference/expressions/api/polars.Expr.replace_strict.html).
See examples below.

Consequently, the current `polars replace` and `polars replace-all` have
been renamed to `polars str-replace` and `polars str-replace-all` to
bring their naming better in-line with `polars str-join` and related str
commands.

```nushell

Usage:
  > polars replace {flags} <old> (new)

Flags:
  -h, --help: Display the help message for this command
  -s, --strict: Require that all values must be replaced or throw an error (ignored if `old` or `new` are expressions).
  -d, --default <any>: Set values that were not replaced to this value. If no default is specified, (default), an error is raised if any values were not replaced. Accepts expression input. Non-expression inputs are parsed as literals.
  -t, --return-dtype <string>: Data type of the resulting expression. If set to `null` (default), the data type is determined automatically based on the other inputs.

Parameters:
  old <one_of(record, list<any>)>: Values to be replaced
  new <list<any>>: Values to replace by (optional)

Input/output types:
  ╭───┬────────────┬────────────╮
  │ # │   input    │   output   │
  ├───┼────────────┼────────────┤
  │ 0 │ expression │ expression │
  ╰───┴────────────┴────────────╯

Examples:
  Replace column with different values of same type
  > [[a]; [1] [1] [2] [2]]
                | polars into-df
                | polars select (polars col a | polars replace [1 2] [10 20])
                | polars collect
  ╭───┬────╮
  │ # │ a  │
  ├───┼────┤
  │ 0 │ 10 │
  │ 1 │ 10 │
  │ 2 │ 20 │
  │ 3 │ 20 │
  ╰───┴────╯

  Replace column with different values of another type
  > [[a]; [1] [1] [2] [2]]
                | polars into-df
                | polars select (polars col a | polars replace [1 2] [a b] --strict)
                | polars collect
  ╭───┬───╮
  │ # │ a │
  ├───┼───┤
  │ 0 │ a │
  │ 1 │ a │
  │ 2 │ b │
  │ 3 │ b │
  ╰───┴───╯

  Replace column with different values based on expressions (cannot be used with strict)
  > [[a]; [1] [1] [2] [2]]
                | polars into-df
                | polars select (polars col a | polars replace [(polars col a | polars max)] [(polars col a | polars max | $in + 5)])
                | polars collect
  ╭───┬───╮
  │ # │ a │
  ├───┼───┤
  │ 0 │ 1 │
  │ 1 │ 1 │
  │ 2 │ 7 │
  │ 3 │ 7 │
  ╰───┴───╯

  Replace column with different values based on expressions with default
  > [[a]; [1] [1] [2] [3]]
                | polars into-df
                | polars select (polars col a | polars replace [1] [10] --default (polars col a | polars max | $in * 100) --strict)
                | polars collect
  ╭───┬─────╮
  │ # │  a  │
  ├───┼─────┤
  │ 0 │  10 │
  │ 1 │  10 │
  │ 2 │ 300 │
  │ 3 │ 300 │
  ╰───┴─────╯

  Replace column with different values based on expressions with default
  > [[a]; [1] [1] [2] [3]]
                | polars into-df
                | polars select (polars col a | polars replace [1] [10] --default (polars col a | polars max | $in * 100) --strict --return-dtype str)
                | polars collect
  ╭───┬─────╮
  │ # │  a  │
  ├───┼─────┤
  │ 0 │ 10  │
  │ 1 │ 10  │
  │ 2 │ 300 │
  │ 3 │ 300 │
  ╰───┴─────╯

  Replace column with different values using a record
  > [[a]; [1] [1] [2] [2]]
                | polars into-df
                | polars select (polars col a | polars replace {1: a, 2: b} --strict --return-dtype str)
                | polars collect
  ╭───┬───╮
  │ # │ a │
  ├───┼───┤
  │ 0 │ a │
  │ 1 │ a │
  │ 2 │ b │
  │ 3 │ b │
  ╰───┴───╯
```

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->
**BREAKING CHANGE**: `polars replace` and `polars replace-all` have been
renamed to `polars str-replace` and `polars str-replace-all`.

The new `polars replace` now replaces elements in a series/column rather
than patterns within strings.

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use toolkit.nu; toolkit test stdlib"` to run the
tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->
Example tests were added.

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
2025-06-01 12:32:56 -07:00
2b524cd861 feat(polars): add maintain-order flag to polars group-by and allow expression inputs in polars filter (#15865)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->
This PR involves two changes: (1) adding `maintain-order` flag to
`polars group-by` for stable sorting when aggregating and (2) allow
expression inputs in `polars filter`. The first change was necessary to
reliably test the second change, and the two commits are therefore
combined in one PR. See example:


```nushell
#  Filter a single column in a group-by context
  > [[a b]; [foo 1] [foo 2] [foo 3] [bar 2] [bar 3] [bar 4]] | polars into-df
                    | polars group-by a --maintain-order
                    | polars agg {
                        lt: (polars col b | polars filter ((polars col b) < 2) | polars sum)
                        gte: (polars col b | polars filter ((polars col b) >= 3) | polars sum)
                    }
                    | polars collect
  ╭───┬─────┬────┬─────╮
  │ # │  a  │ lt │ gte │
  ├───┼─────┼────┼─────┤
  │ 0 │ foo │  1 │   3 │
  │ 1 │ bar │  0 │   7 │
  ╰───┴─────┴────┴─────╯

```

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->
No breaking changes.

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use toolkit.nu; toolkit test stdlib"` to run the
tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->
An example test was added to `polars filter` demonstrating both the
stable group-by feature and the expression filtering feature.

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
2025-06-01 12:32:23 -07:00
ad9f051d61 Update deprecation warnings (#15867)
# Description
- Use #15770 to
  - improve `get --sensitive` deprecation warning
  - add deprecation warning for `filter`
- refactor `filter` to use `where` as its implementation
- replace usages of `filter` with `where` in `std`

# User-Facing Changes
- `get --sensitive` will raise a warning only once, during parsing
whereas before it was raised during runtime for each usage.
- using `filter` will raise a deprecation warning, once

# Tests + Formatting
No existing test broke or required tweaking. Additional tests covering
this case was added.
- 🟢 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-01 19:21:07 +03:00
cfbe835910 Add unified deprecation system and @deprecated attribute (#15770) 2025-06-01 15:55:47 +02:00
8896ba80a4 make sure new nul chars don't print in char --list (#15858)
# Description

This PR fixes and oversight. When we added `nul`, `null_byte`, and
`zero_byte` we forgot to make them non-printable for `char --list`.
That's what this PR fixes.

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use toolkit.nu; toolkit test stdlib"` to run the
tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
2025-05-31 08:04:46 -05:00
803c24f9ce fix(parser): don't parse closure in block position (fixes #15417) (#15680)
Hello!

This is my 1st contribution and an attempt at fixing #15417. 

# Description

When parsing a brace expression, check if the shape is a block or match
block before attempting to parse it as a closure.
Results:
- `if true {|| print hi}` now produces a `nu::parser` error instead of
executing and outputting `hi`. The `nu::parser` error is the same one
produced by running `|| print hi` (`nu::parser::shell_oror`)
- `match true {|| print hi}` now fails with a `nu::parser` error instead
of passing parsing and failing with `nu::compile::invalid_keyword_call`

My understanding reading the code/docs is that the shape is a contextual
constraint that needs to be satisfied for parsing to succeed, in this
case the `if` placing a `Block` shape constraint on next tokens. So it
would need to be checked in priority (if not `Any`) to understand how
the next tokens should be parsed. Is that correct? Or is there a reason
I'm not aware of to ignore the shape and attempt to parse as closure
like it's currently the case when the parser sees `|` or `||` as next
tokens?

# User-Facing Changes

No change in behaviour, but this PR fixes parsing to fail on some
incorrect syntax which could be considered a breaking change.

# Tests + Formatting
- Added corresponding tests
- `toolkit check pr` passed
2025-05-31 14:59:01 +08:00
2f74574e35 Fix for null handling #15788 (#15857)
Fixes #15788 

# Description
Fixes null handling. Thanks to @MMesch for reporting and taking a first
stab at fixing.

Co-authored-by: Jack Wright <jack.wright@nike.com>
2025-05-30 15:38:46 -07:00
8b9f02246f Allow polars first to be used with polars group-by (#15855)
# Description
Provides functionality similar to
https://docs.pola.rs/api/python/stable/reference/dataframe/api/polars.dataframe.group_by.GroupBy.first.html
by allowing polars first to be used with a group by

```
> ❯ : [[a b c d]; [1 0.5 true Apple] [2 0.5 true Orange] [2 4 true Apple] [3 10 false Apple] [4 13 false Banana] [5 14 true Banana]] | polars into-df -s {a: u8, b: f32, c: bool, d: str} | polars group-by d | polars first | polars collect
╭───┬────────┬───┬───────┬───────╮
│ # │   d    │ a │   b   │   c   │
├───┼────────┼───┼───────┼───────┤
│ 0 │ Apple  │ 1 │  0.50 │ true  │
│ 1 │ Banana │ 4 │ 13.00 │ false │
│ 2 │ Orange │ 2 │  0.50 │ true  │
╰───┴────────┴───┴───────┴───────╯
```

Additionally, I am setting the POLARS_ALLOW_EXTENSION to true to avoid
panicking with operations using the dtype object. The conversion will
fallback to object when the type cannot be determining, so this could be
a common case.

# User-Facing Changes
- `polars first` can now be used with `polars group-by`

---------

Co-authored-by: Jack Wright <jack.wright@nike.com>
2025-05-30 10:56:44 -07:00
d9ecb7da93 Polars upgrade (#15852)
# Description
Polars 0.48 upgrade

# User-Facing Changes
- (breaking change) Due to a change in behavior in polars, `polars
is-in` now only works as an expression.

---------

Co-authored-by: Jack Wright <jack.wright@nike.com>
2025-05-30 10:20:57 -07:00
18ce5de500 feat(std): add comparison support to bench command (#15843)
# Description

Like [hyperfine](https://github.com/sharkdp/hyperfine), I have added the
option to the `bench` command to benchmark multiple commands and then
compare the results.

```
→ bench { ls -a | is-empty } { fd | is-empty }
 # |         code         |       mean       |       min       |       max        |     std     | ratio
---+----------------------+------------------+-----------------+------------------+-------------+-------
 0 | { ls -a | is-empty } |  3ms 816µs 562ns | 3ms 670µs 400ns |        4ms 334µs | 146µs 304ns |  1.00
 1 | { fd | is-empty }    | 33ms 325µs 304ns |      31ms 963µs | 36ms 328µs 500ns | 701µs 295ns |  8.73

→ bench -p { ls -a | is-empty } { fd | is-empty }
Benchmark 1: { ls -a | is-empty }
    3ms 757µs 124ns +/- 103µs 165ns
Benchmark 2: { fd | is-empty }
    33ms 403µs 680ns +/- 704µs 904ns

{ ls -a | is-empty } ran
    8.89 times faster than { fd | is-empty }
```

When passing a single closure, it should behave the same except that
now, the `--verbose` flag controls whether the durations of every round
is printed, and the progress indicator is in it's own flag `--progress`.

# User-Facing Changes

There are user-facing changes, but I don't think anyone is using the
output of `bench` programmatically so it hopefully won't break anything.

---------

Co-authored-by: Bahex <Bahex@users.noreply.github.com>
2025-05-29 17:53:10 -05:00
fbde02370a Set content_type for view span output (#15842)
# Description

Adds the content type for `view span` output. Allows the display hook to
add syntax highlighting.

# User-Facing Changes

`view span` output will now have a content type set. 

# Tests + Formatting

All pass, except for those that never pass on my machine.
2025-05-29 05:49:30 +03:00
13452a7aa2 Refactor find to handle regex search and non-regex search the same way (#15839)
# Description

Regex search and search with directly provided search terms used to
follow two different code paths. Now all possible search options get
turned into a regex, with optional additional search options, and
handled using a unified code path which mostly follows the logic of the
current term code path.

# User-Facing Changes

Regex search will now behave in the same way as non-regex search:
- split multiline strings into lists of lines, and filter out the lines
that don't match
- highlight matching string sections (unless --no-highlight flag is
used)
- search through the specified record columns if the --columns flag is
used

The behavior of non-regex search should be unaffected by this commit.
2025-05-28 16:32:36 -05:00
a8c49857d9 feat: Use reedline for input implementation (#15369)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->

This PR replaces the default `input` implementation with `reedline`. It
provides a fully backwards compatible implementation, by leveraging left
prompt provided through `input "my-prompt> "` provided by reedline.

The default indicator is hidden to be fully backwards compatible, the
multiline indicator is kept.

The legacy implementation will be used when the user passes options
truncating input such as `--bytes-until` or `--numchar` or
`--suppress-output` which I didn't find a straightforward implementation
through reedline.

# User-Facing Changes
No breaking change. 

- Adds ability to enter multi-line input with reedline.
- Adds ability to pass a command history through the pipe `["command",
"history"] | input`- Adds ability to pass a history file through the
params `input --history-file path/to/history`


# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use toolkit.nu; toolkit test stdlib"` to run the
tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->

---------

Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com>
2025-05-28 16:31:49 -05:00
90afb65329 feat(polars): expand polars shift to allow expressions inputs (#15834)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->
This PR seeks to expand the `polars shift` command to take expression
inputs. See third example below:

```nushell
Examples:
  Shifts the values by a given period
  > [1 2 2 3 3] | polars into-df | polars shift 2 | polars drop-nulls
  ╭───┬───╮
  │ # │ 0 │
  ├───┼───┤
  │ 0 │ 1 │
  │ 1 │ 2 │
  │ 2 │ 2 │
  ╰───┴───╯

  Shifts the values by a given period, fill absent values with 0
  > [1 2 2 3 3] | polars into-lazy | polars shift 2 --fill 0 | polars collect
  ╭───┬───╮
  │ # │ 0 │
  ├───┼───┤
  │ 0 │ 0 │
  │ 1 │ 0 │
  │ 2 │ 1 │
  │ 3 │ 2 │
  │ 4 │ 2 │
  ╰───┴───╯

  Shift values of a column, fill absent values with 0
  > [[a]; [1] [2] [2] [3] [3]]
                    | polars into-lazy
                    | polars with-column {b: (polars col a | polars shift 2 --fill 0)}
                    | polars collect
  ╭───┬───┬───╮
  │ # │ a │ b │
  ├───┼───┼───┤
  │ 0 │ 1 │ 0 │
  │ 1 │ 2 │ 0 │
  │ 2 │ 2 │ 1 │
  │ 3 │ 3 │ 2 │
  │ 4 │ 3 │ 2 │
  ╰───┴───┴───╯

```

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->
No breaking changes.

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use toolkit.nu; toolkit test stdlib"` to run the
tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->
An example test was added to `polars shift`

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
2025-05-28 08:10:49 -07:00
ff4907ed3b Allow specifying MSI version via env var and workflow input (#15828)
# Description

This PR enhances the MSI release workflow by allowing the MSI package
version to be specified either through an environment variable or a
workflow input. This improvement provides greater flexibility when
building MSI packages for tags that do **not** match the latest package
version in `Cargo.toml`.

Fix possible **403** error while updating `SHA256SUMS` file in the
nushell/nightly repo

# User-Facing Changes
None

# Tests + Formatting
A example running record:
https://github.com/nushell/nightly/actions/runs/15265879087/job/42931344366#step:5:11
2025-05-28 21:03:01 +08:00
cbd7608898 Fix build failure of aarch64 and armv7 musl targets (#15835)
# Description

Fix https://github.com/nushell/nushell/issues/15833 build failure of
aarch64 and armv7 musl targets:
https://github.com/nushell/nushell/actions/runs/15288712454/job/43005766777#step:7:462

The failure was caused by downloading error of related assets

I just downloaded the assets and uploaded to `nushell/integrations`
without any modification

https://github.com/nushell/integrations/releases/tag/build-tools
2025-05-28 21:01:40 +08:00
adc9bbdc18 Handle multiple exact matches (#15772)
# Description

Fixes #15734. With case-insensitive matching, when completing a
file/folder, there can be multiple exact matches. For example, if you
have three folders `aa/`, `AA/`, and `aaa/`, `aa/<TAB>` should match all
of them. But, as reported in #15734, when using prefix matching, only
`AA/` will be shown. This is because when there's an exact match in
prefix match mode, we only show the first exact match.

There are two options for fixing this:
- Show all matched suggestions (`aa/`, `AA/`, and `aaa/`)
  - I chose this option
- Show only the suggestions that matched exactly (`aa/` and `AA/`) but
not others (`aaa/`)
  - This felt unintuitive

# User-Facing Changes

As mentioned above, when:
- you have multiple folders with the same name but in different cases
- and you're using prefix matching
- and you're using case-insensitive matching
- and you type in the name of one of these folders exactly

then you'll be suggested every folder matching the typed text, rather
than just exact matches

# Tests + Formatting

I added a test that doesn't run on Windows or MacOS (to avoid
case-insensitive filesystems). While adding this test, I felt like using
`Playground` rather than adding files to `tests/fixtures`. To make this
easier, I refactored the `new_*_engine()` helpers in
`completion_helpers.rs` a bit. There was quite a bit of code duplication
there.

# After Submitting

N/A
2025-05-28 21:00:55 +08:00
37bc922a67 feat(polars): add polars math expression (#15822)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->
This PR adds a number of math functions under a single `polars math`
command that apply to one or more column expressions.

Note, `polars math` currently resides in the new module
dataframe/command/command/computation/math.rs. I'm open to alternative
organization and naming suggestions.

```nushell
Collection of math functions to be applied on one or more column expressions

This is an incomplete implementation of the available functions listed here: https://docs.pola.rs/api/python/stable/reference/expressions/computation.html.

        The following functions are currently available:
        - abs
        - cos
        - dot <expression>
        - exp
        - log <base; default e>
        - log1p
        - sign
        - sin
        - sqrt


Usage:
  > polars math <type> ...(args)

Flags:
  -h, --help: Display the help message for this command

Parameters:
  type <string>: Function name. See extra description for full list of accepted values
  ...args <any>: Extra arguments required by some functions

Input/output types:
  ╭───┬────────────┬────────────╮
  │ # │   input    │   output   │
  ├───┼────────────┼────────────┤
  │ 0 │ expression │ expression │
  ╰───┴────────────┴────────────╯

Examples:
  Apply function to column expression
  > [[a]; [0] [-1] [2] [-3] [4]]
                    | polars into-df
                    | polars select [
                        (polars col a | polars math abs | polars as a_abs)
                        (polars col a | polars math sign | polars as a_sign)
                        (polars col a | polars math exp | polars as a_exp)]
                    | polars collect
  ╭───┬───────┬────────┬────────╮
  │ # │ a_abs │ a_sign │ a_exp  │
  ├───┼───────┼────────┼────────┤
  │ 0 │     0 │      0 │  1.000 │
  │ 1 │     1 │     -1 │  0.368 │
  │ 2 │     2 │      1 │  7.389 │
  │ 3 │     3 │     -1 │  0.050 │
  │ 4 │     4 │      1 │ 54.598 │
  ╰───┴───────┴────────┴────────╯

  Specify arguments for select functions. See description for more information.
  > [[a]; [0] [1] [2] [4] [8] [16]]
                    | polars into-df
                    | polars select [
                        (polars col a | polars math log 2 | polars as a_base2)]
                    | polars collect
  ╭───┬─────────╮
  │ # │ a_base2 │
  ├───┼─────────┤
  │ 0 │    -inf │
  │ 1 │   0.000 │
  │ 2 │   1.000 │
  │ 3 │   2.000 │
  │ 4 │   3.000 │
  │ 5 │   4.000 │
  ╰───┴─────────╯

  Specify arguments for select functions. See description for more information.
  > [[a b]; [0 0] [1 1] [2 2] [3 3] [4 4] [5 5]]
                    | polars into-df
                    | polars select [
                        (polars col a | polars math dot (polars col b) | polars as ab)]
                    | polars collect
  ╭───┬────────╮
  │ # │   ab   │
  ├───┼────────┤
  │ 0 │ 55.000 │
  ╰───┴────────╯
``` 

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->
No breaking changes.

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use toolkit.nu; toolkit test stdlib"` to run the
tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->
Example tests were added to `polars math`.

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
2025-05-27 16:35:48 -07:00
ae51f6d722 fix(polars): add Value::Record to NuExpression::can_downcast logic (#15826)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->
Merged PR #15553 added the ability to provide expressions in the form of
records. This PR conforms the `NuExpression::can_downcast` logic to
account for the newly allowed records argument type. As such, commands
that rely on `can_downcast` in their implementation (e.g., `polars
with-column`) will no longer err when provided with a record. See
example below:

```nushell
#  Current error
> [[a b]; [1 2] [3 4]]
    | polars into-df <-- only works if cast as lazyframe
    | polars with-column {
        c: ((polars col a) * 2)
        d: ((polars col a) * 3)
      }
Error: nu:🐚:cant_convert

  × Can't convert to NuDataFrame, NuLazyFrame, NuExpression, NuLazyGroupBy, NuWhen,
  │ NuDataType, NuSchema.
   ╭─[entry #24:3:26]
 2 │         | polars into-df
 3 │ ╭─▶     | polars with-column {
 4 │ │           c: ((polars col a) * 2)
 5 │ │           d: ((polars col a) * 3)
 6 │ ├─▶       }
   · ╰──── can't convert record<c: NuExpression, d: NuExpression> to NuDataFrame, NuLazyFrame, NuExpression, NuLazyGroupBy, NuWhen, NuDataType, NuSchema
   ╰────


# Fixed
> [[a b]; [1 2] [3 4]]
    | polars into-df
    | polars with-column {
        c: ((polars col a) * 2)
        d: ((polars col a) * 3)
      } | polars collect
╭───┬───┬───┬───┬───╮
│ # │ a │ b │ c │ d │
├───┼───┼───┼───┼───┤
│ 0 │ 1 │ 2 │ 2 │ 3 │
│ 1 │ 3 │ 4 │ 6 │ 9 │
╰───┴───┴───┴───┴───╯
```

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->
No breaking changes


# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use toolkit.nu; toolkit test stdlib"` to run the
tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->
An example test was added to `polars with-column`.

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
2025-05-27 11:37:07 -07:00
1b2079ffdb [FIX] #15813 passing infinity to random float generate causes error (#15818)
# Description

This pull request addresses an issue#15813 where passing a infinite
value in the random float 1.. command that causes a panic in the shell.
The root cause of this problem lies within the rng library, which is
responsible for generating random numbers.

Before

![image](https://github.com/user-attachments/assets/5416e23d-d5a2-40ed-aa9f-4ff46d0e5583)

# User-Facing Changes
Users where seeing panic error when passed unbounded end into range.

# Tests + Formatting
added `generate_inf`

# After Submitting

![image](https://github.com/user-attachments/assets/8453ffad-ad94-44bf-aec4-8d1090842f32)
No error should be there after 

Edit history
1. Updated `After Submitting` section

---------

Co-authored-by: Ritik Ranjan <e02948@ritik.ranjan@hsc.com>
2025-05-27 19:25:50 +02:00
9a968c4bdd Move job errors into ShellError::Job variant (#15820)
- related #10698

# Description


In my endeavor to make the `ShellError` less crowded I moved the job
related errors into `ShellError::Job` with a `JobError` enum. Mostly I
just moved the codes, errors and labels over to the new enum.
2025-05-26 18:04:43 +02:00
89df01f829 Provide a better error for prefix-only path for PWD (#15817) 2025-05-24 21:11:26 +02:00
dbb30cc9e0 feat: default http protocol when none used in http request (#15804)
https://github.com/nushell/nushell/issues/10957

Hello, this PR proposes a solution for some requested features mentioned
in https://github.com/nushell/nushell/issues/10957. I personally think
these are very simple changes that bring significant quality of life
improvements.
It gives the possibility to do `http get google.com` instead of `http
get http://google.com` and `http get :8080` instead of `http get
http://localhost:8080`.
I did not address the other part of the issue (data management) as those
are more controversial.
2025-05-24 19:53:59 +02:00
02d63705cc Update comments of release-pkg.nu for building of MSI package (#15815)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->

Update comments of release-pkg.nu for building of MSI package
2025-05-24 22:10:18 +08:00
ea97229688 Fix: use ring as a crypto provider instead of aws_lc (#15812) 2025-05-24 15:01:29 +02:00
6bf955a5a5 Fix #15571 panic on write to source parquet file (#15601)
Fixes #15571 

# Description

Writing to a source `.parquet` (`polars open some_file.parquet | polars
save some_file.parquet`) file made the plugin panic, added a guard to
check the data_source path as per [this
comment](https://github.com/nushell/nushell/issues/15571#issuecomment-2812707161)

Example output now:
<img width="850" alt="Screenshot 2025-04-18 at 21 10 30"
src="https://github.com/user-attachments/assets/40a73cc7-6635-43dc-a423-19c7a0c8f59c"
/>

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->

# Tests + Formatting
 - Add 1 test
 - clippy OK
 - cargo fmt OK

# After Submitting
No action required
2025-05-23 19:31:28 -04:00
f90035e084 Improve error handling for unsupported --theme in to html command (#15787) 2025-05-23 23:43:32 +02:00
cc8b623ff8 Add rustls for TLS (#15810)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

closes #14041

# Description

<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->

This PR switches our default TLS backend from `native-tls` to `rustls`.
Cross-compiles, `musl`, and other targets build smoother because we drop
the OpenSSL requirement.

`native-tls` is still available as an opt-in on `nu-command` via the
`native-tls` feature.
WASM + `network` still fails for unrelated crates, but the OpenSSL
roadblock is gone.

# User-Facing Changes

<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->

No changes to the Nushell API.

If you embed Nushell you now need to pick a
[`rustls::crypto::CryptoProvider`](https://docs.rs/rustls/0.23.27/rustls/crypto/struct.CryptoProvider.html)
at startup:

```rust
use nu_command::tls::CRYPTO_PROVIDER;

// common case
CRYPTO_PROVIDER.default();

// or supply your own
CRYPTO_PROVIDER.set(|| Ok(my_provider()));
```

# Tests + Formatting

<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use toolkit.nu; toolkit test stdlib"` to run the
tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

* 🟢 `toolkit fmt`
* 🟢 `toolkit clippy`
* 🟢 `toolkit test`
* 🟢 `toolkit test stdlib`

# After Submitting

<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
2025-05-23 22:45:15 +02:00
60cb13c493 source: make sure the block is compiled when parsing (#15798)
# Description
Fixes: https://github.com/nushell/nushell/issues/15749

When sourcing a file, the ir block might be empty because it has been
used before, this pr is going to make sure that the ir block is
compiled.

# User-Facing Changes
```
touch aaa.nu
use aaa.nu
source aaa.nu
```
Will no longer raise an error.

# Tests + Formatting
Added 1 test

# After Submitting
NaN
2025-05-23 22:30:21 +03:00
c10e483683 Bump dev version to 0.104.2 (#15809)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->
Bump dev version to 0.104.2
2025-05-24 00:54:33 +08:00
2d0c7b2214 Use nushell's fork for winget-pkgs publishing (#15808)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->

Try to use nushell's fork for winget-pkgs publishing
2025-05-23 21:08:07 +08:00
88d421dcb6 std-rfc/kv: optimize kv get by only selecting one row from the stor db (#15792)
Optimize std-rfc/kv, kv get to only read one row from the sqlite db.
2025-05-22 21:14:31 -04:00
7c50f7c714 Clean public API of EngineState and friends (#15636)
# Description
`pub` has been overused in many parts of `nu-protocol`. This exposes
implementation details in ways that things could break should we involve
the internals. Also each public member can slow down the decisions to
improve a certain implementation. Furthermore dead code can't be
detected if things are marked as `pub`. Thus we need to judiciously
remove more accidentally `pub` markings and eliminate the dead code if
we come across it.

This PR tackles `EngineState` and `StateWorkingSet` as important
components of the engine and `nu-protocol`. Prompted by a large number
of confusingly named methods surrounding overlays and scope management.

- **Hide overlay predecl logic**
- **Remove dead overlay code**
- **Remove unused helper**
- **Remove dead overlay code from `EngineState`**
- **Hide update_plugin_file impl detail**
- **Hide another overlay internal detail`**

# API User-Facing Changes
Removal of several formerly public members that potentially give
intrusive access to the engine. We will button up some of our public
API, feel free to explicitly complain so we can figure out what access
should be granted. We want to evolve to stable APIs as much as possible
which means hiding more implementation details and committing to a
select few well defined and documented interfaces
2025-05-23 07:26:34 +08:00
bc043dcaeb Add a lightweight MSI packages release workflow for winget (#15800) 2025-05-23 04:56:49 +08:00
10be753ab7 Fix Windows arm64 release binaries and winget related issues (#15690)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->
Publishing Nushell to winget has always been a challenge for us, and to
this day, many issues remain unresolved—and some seem almost impossible
to fix. The road to solving these problems may be winding and long, but
it's time for us to set out on this journey.

This PR try to fix the Windows arm64 release binaries and some `winget`
related issues:

- [x] Fixes https://github.com/nushell/nushell/issues/14815: build
Windows arm64 binaries by Windows arm64 runner
- [x] Upgrade WiX Toolset to latest 6.0 version: WiX 3 we used currently
doesn't support arm64 arch and [WiX v4 Security Fixes End Date is
2025/02/05](https://docs.firegiant.com/wix/)
- [x] Update the **nightly** workflow to make it work for all future
releases
- [x] Update the **release** workflow to make it work for all future
releases
- [x] Fixes https://github.com/nushell/nushell/issues/15698
- [x] Fixes https://github.com/nushell/nushell/issues/13719 so that
Nushell should be possible to be installed via winget with both user and
machine scope
- [x] Fixes https://github.com/nushell/nushell/issues/5927
- [x] Try to fix https://github.com/nushell/nushell/issues/14786
- [x] Fixes https://github.com/nushell/nushell/issues/9537

## Related but not planed issues:

- Related https://github.com/nushell/nushell/issues/13017
- Related https://github.com/nushell/nushell/issues/8053

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->

- Nushell should be possible to be installed via winget with both user
and machine scope and The default should be user scope
  - User scope install by winget: `winget install Nushell.Nushell`
- User scope install by msiexec: `msiexec /i
nu-0.104.1-x86_64-pc-windows-msvc.msi /quiet /qn`
- Machine scope install by winget: `winget install Nushell.Nushell
--override 'ALLUSERS=1'`
- Machine scope install by msiexec: `msiexec /i
nu-0.104.1-x86_64-pc-windows-msvc.msi ALLUSERS=1`
- Note that `--scope` flag for `winget install` does not work use
`--override` instead
- Default user scope install dir:
`$'($nu.home-path)\AppData\Local\Programs\nu\'`
  - Default machine scope install dir: `C:\Program Files\nu\`
- When a standard user runs the installer and selects "Install for
everyone" (per-machine installation), Windows will automatically trigger
a UAC prompt, the user can enter admin credentials and the installation
will proceed with elevated privileges
- [hustcer/setup-nu](https://github.com/hustcer/setup-nu) should work
for `windows-11-arm` runners


# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use toolkit.nu; toolkit test stdlib"` to run the
tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

The latest MSI builds are available here:
https://github.com/nushell/nightly/releases/tag/v0.104.1
Actually all the nightly releases were built with latest changes
included: https://github.com/nushell/nightly/releases

`winget` and `msiexec` install tests goes here:
https://github.com/nushell/integrations/pull/49

https://github.com/nushell/integrations/actions/runs/14974621061
https://github.com/nushell/integrations/actions/runs/14974621054

### Test winget install locally:
- git clone git@github.com:nushell/integrations.git
- User scope install: `winget install -m
manifests\n\Nushell\Nushell\0.104.1\`
- Run: `use tests\common.nu *; check-user-install`
- Machine scope install: `winget install -m
manifests\n\Nushell\Nushell\0.104.1\ --override 'ALLUSERS=1'`
- Run: `use tests\common.nu *; check-local-machine-install`

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->

@fdncred I suggest releasing a patch version after merging this PR (only
the changes of this PR will be included) to ensure that the winget
release process works properly. This way, we can be more confident when
releasing version 0.105.0.

References:

-
https://learn.microsoft.com/en-us/windows/win32/msi/single-package-authoring
-
https://learn.microsoft.com/en-us/windows/package-manager/winget/source#add
-
https://github.com/microsoft/winget-pkgs/blob/master/doc/tools/SandboxTest.md
- https://docs.firegiant.com/quick-start/
-
https://docs.firegiant.com/wix3/tutorial/getting-started/putting-it-to-use/#_top
-
https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/msiexec#set-public-properties
2025-05-22 19:15:52 +08:00
6906a0ca50 fix: implicitly running .ps1 scripts with spaces in path (#15781)
- this PR should close #15757

# Description

> [!NOTE]
> [`-File <filePath>
<args>`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1#-file----filepath-args)
> - Enter the script filepath and any parameters
> - All values typed after the File parameter are interpreted as the
script filepath and parameters passed to that script.

> [!NOTE]
>
[`-Command`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1#-command)
> - The value of Command can be -, a _script block_, or a _string_.
> - In `cmd.exe` (and other externall callers), there is no such thing
as a _script block_, so the value passed to Command is always a
_**string**_.
> - A string passed to Command is still executed as PowerShell code.

> [!NOTE]
> [Call operator
`&`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operators?view=powershell-5.1#call-operator-)
> - Runs a command, ***script***, or script block.

Basically using `-Command` to run scripts would require _another_ layer
of quoting and escaping. It looks like `-File` is the way to run
powershell scripts as an external caller.

# User-Facing Changes

# Tests + Formatting

# After Submitting

Co-authored-by: Bahex <17417311+Bahex@users.noreply.github.com>
2025-05-21 14:47:26 -05:00
833471241a Refactor: Construct IoError from std::io::Error instead of std::io::ErrorKind (#15777) 2025-05-18 14:52:40 +02:00
c4dcfdb77b feat!: Explicit cell-path case sensitivity syntax (#15692)
Related:
- #15683
- #14551
- #849
- #12701
- #11527

# Description
Currently various commands have differing behavior regarding cell-paths

```nushell
{a: 1, A: 2} | get a A
# => ╭───┬───╮
# => │ 0 │ 2 │
# => │ 1 │ 2 │
# => ╰───┴───╯
{a: 1, A: 2} | select a A
# => ╭───┬───╮
# => │ a │ 1 │
# => │ A │ 2 │
# => ╰───┴───╯
{A: 1} | update a 2
# => Error: nu:🐚:column_not_found
# => 
# =>   × Cannot find column 'a'
# =>    ╭─[entry #62:1:1]
# =>  1 │ {A: 1} | update a 2
# =>    · ───┬──          ┬
# =>    ·    │            ╰── cannot find column 'a'
# =>    ·    ╰── value originates here
# =>    ╰────
```

Proposal: making cell-path access case-sensitive by default and adding
new syntax for case-insensitive parts, similar to optional (?) parts.

```nushell
{FOO: BAR}.foo
# => Error: nu:🐚:name_not_found
# => 
# =>   × Name not found
# =>    ╭─[entry #60:1:21]
# =>  1 │ {FOO: BAR}.foo
# =>    ·            ─┬─
# =>    ·             ╰── did you mean 'FOO'?
# =>    ╰────
{FOO: BAR}.foo!
# => BAR
```

This would solve the problem of case sensitivity for all commands
without causing an explosion of flags _and_ make it more granular

Assigning to a field using a case-insensitive path is case-preserving.
```nushell
mut val = {FOO: "I'm FOO"}; $val
# => ╭─────┬─────────╮
# => │ FOO │ I'm FOO │
# => ╰─────┴─────────╯
$val.foo! = "I'm still FOO"; $val
# => ╭─────┬───────────────╮
# => │ FOO │ I'm still FOO │
# => ╰─────┴───────────────╯
```

For `update`, case-insensitive is case-preserving.
```nushell
{FOO: 1} | update foo! { $in + 1 }
# => ╭─────┬───╮
# => │ FOO │ 2 │
# => ╰─────┴───╯
```

`insert` can insert values into nested values so accessing into existing
columns is case-insensitive, but creating new columns uses the cell-path
as it is.
So `insert foo! ...` and `insert FOO! ...` would work exactly as they do
without `!`
```nushell
{FOO: {quox: 0}}
# => ╭─────┬──────────────╮
# => │     │ ╭──────┬───╮ │
# => │ FOO │ │ quox │ 0 │ │
# => │     │ ╰──────┴───╯ │
# => ╰─────┴──────────────╯
{FOO: {quox: 0}} | insert foo.bar 1
# => ╭─────┬──────────────╮
# => │     │ ╭──────┬───╮ │
# => │ FOO │ │ quox │ 0 │ │
# => │     │ ╰──────┴───╯ │
# => │     │ ╭─────┬───╮  │
# => │ foo │ │ bar │ 1 │  │
# => │     │ ╰─────┴───╯  │
# => ╰─────┴──────────────╯
{FOO: {quox: 0}} | insert foo!.bar 1
# => ╭─────┬──────────────╮
# => │     │ ╭──────┬───╮ │
# => │ FOO │ │ quox │ 0 │ │
# => │     │ │ bar  │ 1 │ │
# => │     │ ╰──────┴───╯ │
# => ╰─────┴──────────────╯
```

`upsert` is tricky, depending on the input, the data might end up with
different column names in rows. We can either forbid case-insensitive
cell-paths for `upsert` or trust the user to keep their data in a
sensible shape.

This would be a breaking change as it would make existing cell-path
accesses case-sensitive, however the case-sensitivity is already
inconsistent and any attempt at making it consistent would be a breaking
change.

> What about `$env`?

1. Initially special case it so it keeps its current behavior.
2. Accessing environment variables with non-matching paths gives a
deprecation warning urging users to either use exact casing or use the
new explicit case-sensitivity syntax
3. Eventuall remove `$env`'s special case, making `$env` accesses
case-sensitive by default as well.

> `$env.ENV_CONVERSIONS`?

In addition to `from_string` and `to_string` add an optional field to
opt into case insensitive/preserving behavior.

# User-Facing Changes

- `get`, `where` and other previously case-insensitive commands are now
case-sensitive by default.
- `get`'s `--sensitive` flag removed, similar to `--ignore-errors` there
is now an `--ignore-case` flag that treats all parts of the cell-path as
case-insensitive.
- Users can explicitly choose the case case-sensitivity of cell-path
accesses or commands.

# Tests + Formatting

Existing tests required minimal modification. ***However, new tests are
not yet added***.

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

# After Submitting

- Update the website to include the new syntax
- Update [tree-sitter-nu](https://github.com/nushell/tree-sitter-nu)

---------

Co-authored-by: Bahex <17417311+Bahex@users.noreply.github.com>
2025-05-18 12:19:09 +03:00
1e8876b076 run-external spreads command if it's a list (#15776) 2025-05-18 10:09:32 +02:00
5483519c7d fix kv set examples (#15769)
As talked in #15588, I have updated the examples of `kv set` so that it
correctly shows how to use the command with closures.
2025-05-17 23:31:46 -04:00
457f162fd9 feat(polars): expand polars unique to allow expressions inputs (#15771)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->
`polars unique` currently only operates on entire dataframes. This PR
seeks to expand this command to handle expressions as well. See
examples:

```nushell
  Returns unique values in a subset of lazyframe columns
  > [[a]; [2] [1] [2]]
    | polars into-lazy
    | polars select (polars col a | polars unique)
    | polars collect
  ╭───┬───╮
  │ # │ a │
  ├───┼───┤
  │ 0 │ 1 │
  │ 1 │ 2 │
  ╰───┴───╯

  Returns unique values in a subset of lazyframe columns
  > [[a]; [2] [1] [2]]
    | polars into-lazy
    | polars select (polars col a | polars unique --maintain-order)
    | polars collect
  ╭───┬───╮
  │ # │ a │
  ├───┼───┤
  │ 0 │ 2 │
  │ 1 │ 1 │
  ╰───┴───╯
```

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->
No breaking changes. Users have the added option to use `polars unique`
in an expressions context.

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use toolkit.nu; toolkit test stdlib"` to run the
tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->
Example tests have been added to `polars unique`

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
2025-05-17 12:26:26 -04:00
58a8f30a25 small refactoring around units and add tests (#15746)
Closes #14469

# Description
- ~~Implement the ``--unit`` conversion in "into int" command~~
- New ``ShellError::InvalidUnit`` unit if users enter wrong units
- Made ``ShellError::CantConvertToDuration`` more generic: became
``CantConvertToUnit``
- Tried to improve the way we parse units and get the supported units.
It's not complete, though, I will continue this refactoring in another
PR. But I already did some small refactorings in the "format duration"
and "format filesize" commands
- Add tests for "format filesize" and "format duration"

# User-Facing Changes

```nu
~> 1MB | format filesize sec
Error: nu:🐚:invalid_unit

  × Invalid unit
   ╭─[entry #7:1:23]
 1 │ 1MB | format filesize sec
   ·                       ─┬─
   ·                        ╰── encountered here
   ╰────
  help: Supported units are: B, kB, MB, GB, TB, PB, EB, KiB, MiB, GiB, TiB, PiB, EiB

```
2025-05-16 17:41:26 -05:00
70ba5d9d68 fix duplicate short_name in ansi command (#15767) 2025-05-16 13:56:15 -05:00
7b88bda9a1 Use Default for making Suggestions in attribute_completions (#15764)
# Description

In preparation for https://github.com/nushell/reedline/pull/798, which
adds a new field to `Suggestion`, this PR makes sure that `Suggestion`s
are created using `..Default::default()` inside
`attribute_completions.rs`.

# User-Facing Changes

None

# Tests + Formatting

None

# After Submitting
2025-05-16 14:21:40 +08:00
bb37306d07 Add lazy closure evaluation to default (#14160) (#15654)
# Description

This PR adds lazy closure evaluation to the `default` command (closes
#14160).

- For non-closure values and without providing a column name, `default`
acts the same as before
- The user can now provide multiple column names to populate if empty
- If the user provides a column name, the input must be a record or
list, otherwise an error is created.
- The user can now provide a closure as a default value
  - This closure is run without any arguments or input
  - The closure is never evaluated if the value isn't needed
- Even when column names are supplied, the closure is only run once (and
cached to prevent re-calling it)

For example:

```nushell
> default { 1 + 2 } # => 3
> null | default 3 a   # => previously `null`, now errors
> 1 | default { sleep 5sec; 3 } # => `1`, without waiting 5 seconds

> let optional_var = null; $optional_var | default { input 'Enter value: ' } # => Returns user input
> 5 | default { input 'Enter value: ' } # => `5`, without prompting user

> ls | default { sleep 5sec; 'N/A' } name # => No-op since `name` column is never empty
> ls | default { sleep 5sec; 'N/A' } foo bar # => creates columns `foo` and `bar`; only takes 5 seconds since closure result is cached

# Old behavior is the same
> [] | default 'foo' # => []
> [] | default --empty 'foo' # => 'foo'
> default 5 # => 5
```

# User-Facing Changes

- Users can add default values to multiple columns now.
- Users can now use closures as the default value passed to `default`.
- To return a closure, the user must wrap the closure they want to
return inside another closure, which will be run (`default { $my_closure
}`).

# Tests + Formatting

All tests pass.

# After Submitting

---------

Co-authored-by: 132ikl <132@ikl.sh>
2025-05-15 10:10:56 -04:00
505cc014ac Correct use-facing to user-facing in CONTRIBUTING.md (#15761)
# Description
Simple missed `r`, but wanted to exercise the PR flow while I'm ramping
up.
2025-05-14 21:56:22 +02:00
ff79959fdf build(deps): bump tempfile from 3.15.0 to 3.20.0 (#15753) 2025-05-14 18:21:34 +00:00
8c2b1a22d4 allow powershell scripts in the path to be executed (#15760)
# Description

This PR fixes a bug where powershell scripts were only allowed to be
executed if they were in the directory that you executed them from. This
fix allows the scripts to be anywhere in the path.

closes #15759

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use toolkit.nu; toolkit test stdlib"` to run the
tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
2025-05-14 13:21:02 -05:00
3d62753e80 fix: empty tables now respect $env.config.use_ansi_coloring (closes #14896) (#15751)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

- fixes #14896
- related to #15163

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->
This PR fixes the presence of ansi color codes in empty tables, when
`$env.config.table.show_empty = true` and `$env.config.use_ansi_coloring
= false`

# User-Facing Changes
Empty tables respect `$env.config.use_ansi_coloring`

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use toolkit.nu; toolkit test stdlib"` to run the
tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->
Added a test for this case.

# After Submitting
2025-05-14 06:40:15 -05:00
36c30ade3a fix parsing of bare word string interpolations that start with a sub expression (#15735)
- fixes #15731

# Description
Existing bare word string interpolation only works if the string doesn't
start with a subxpression.
```nushell
echo fork(2)
# => fork2

echo (2)fork
# => Error: nu::parser::unclosed_delimiter
# => 
# =>   × Unclosed delimiter.
# =>    ╭─[entry #25:1:13]
# =>  1 │ echo (2)fork
# =>    ╰────
```
This PR lifts that restriction.
```nushell
echo fork(2)
# => fork2

echo (2)fork
# => 2fork
```

This was first brought to my attention on discord with the following
command failing to parse.
```nushell
docker run -u (id -u):(id -g)
```
It now works.

# User-Facing Changes

# Tests + Formatting
No existing test broke or required tweaking. Additional tests covering
this case was added.
- 🟢 toolkit fmt
- 🟢 toolkit clippy
- 🟢 toolkit test
- 🟢 toolkit test stdlib

# After Submitting

---------

Co-authored-by: Bahex <17417311+Bahex@users.noreply.github.com>
2025-05-13 22:25:07 +03:00
e0eb29f161 feat(where): Support stored closure (#15697)
# Description

- `where` used to be able to filter using stored closures at some point
using a flag.
  > #5955
- This was later removed and `filter` command added to cover the use
case.
  > #7365

This PR once again allows using `where` with closures stored in
variables.

```nushell
let cond = { $in mod 2 == 0 }
1..10 | where $cond
# => ╭───┬────╮
# => │ 0 │  2 │
# => │ 1 │  4 │
# => │ 2 │  6 │
# => │ 3 │  8 │
# => │ 4 │ 10 │
# => ╰───┴────╯

let nested = {cond: { $in mod 2 == 0 }}
1..10 | where $nested.cond 
# => ╭───┬────╮
# => │ 0 │  2 │
# => │ 1 │  4 │
# => │ 2 │  6 │
# => │ 3 │  8 │
# => │ 4 │ 10 │
# => ╰───┴────╯
``` 

This does not interfere with using `$it` or one of its fields as the
condition.
```nushell
[[name state]; [foo true] [bar false] [baz true] [quox false]]
| where $it.state
# => ╭───┬──────┬───────╮
# => │ # │ name │ state │
# => ├───┼──────┼───────┤
# => │ 0 │ foo  │ true  │
# => │ 1 │ baz  │ true  │
# => ╰───┴──────┴───────╯
``` 

This change obsoletes `filter`, deprecate it in the future?

# User-Facing Changes

# Tests + Formatting

Added examples and tests.

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


# After Submitting

---------

Co-authored-by: Bahex <17417311+Bahex@users.noreply.github.com>
2025-05-13 22:24:45 +03:00
c2ac8f730e Rust 1.85, edition=2024 (#15741) 2025-05-13 16:49:30 +02:00
1a0986903f Minor DataType refactor (#15728)
# Description
This is needed for the enum work. The recent polars changes have broken
my enum work, so I am breaking it into smaller pull requests.
2025-05-12 08:11:17 -07:00
0f25641722 Update lscolors from 0.17 to 0.20 (#15737)
# Description
Update `lscolors` from 0.17.0 to 0.20.0.

- [0.20.0](https://github.com/sharkdp/lscolors/releases/tag/v0.20.0):
Updated `crossterm` dependency
- [0.19.0](https://github.com/sharkdp/lscolors/releases/tag/v0.19.0):
Fast extension matching
- [0.18.0](https://github.com/sharkdp/lscolors/releases/tag/v0.18.0):
Add `owo-colors` as an ansi backend; make `fi=0` disable fallback to no

# User-Facing Changes
N/A

# Tests + Formatting
`cargo test --workspace` and `cargo run -- -c "use toolkit.nu; toolkit
test stdlib"` still pass

# After Submitting
N/A
2025-05-12 16:44:45 +08:00
7d6d48f3f7 Allow path join to read ByteStream input (#15128) (#15736)
# Description
Fixes #15128. Allows `path join` to use ByteStream pipeline data to join
on if it's coercible to string. Binary ByteStream input still results in
an error. Tested with `^$nu.current-exe -c '$nu.config-path' | path join
foo` and `^tar.exe -c assets/nu_logo.ico | path join foo`

# User-Facing Changes
If an external command returns a path, users would previously need to
use `^show-path-cmd | collect | path join 'foo'`, now they can drop the
intermediate `collect`.
2025-05-12 16:44:06 +08:00
6a8c183c1a Add match examples for simple value and alternative values (#15732)
Even with some experience in Nushell I did not find information about
the match syntax for alternative value matches. The `match` command help
does not mention it at all. I suggest we add an example.

Previously, the examples only had "advanced" matching operations. It
seems appropriate to start with the simplest one: Matching by value.

Add both of these examples.

# User-Facing Changes

`help match` and the [command reference
docs](https://www.nushell.sh/commands/docs/match.html) now have examples
for

* simple value matching
* alternative value matching
2025-05-11 05:41:24 -05:00
0beb28e827 build(deps): bump miette from 7.5.0 to 7.6.0 (#15667)
Bumps [miette](https://github.com/zkat/miette) from 7.5.0 to 7.6.0.
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/zkat/miette/blob/main/CHANGELOG.md">miette's
changelog</a>.</em></p>
<blockquote>
<h2>7.6.0 (2025-04-27)</h2>
<h3>Bug Fixes</h3>
<ul>
<li><strong>graphical:</strong> prevent leading newline when no
link/code (<a
href="https://redirect.github.com/zkat/miette/issues/418">#418</a>) (<a
href="1e1938a099">1e1938a0</a>)</li>
<li><strong>clippy:</strong> elide lifetimes (<a
href="https://redirect.github.com/zkat/miette/issues/423">#423</a>) (<a
href="9ba6fad769">9ba6fad7</a>)</li>
<li><strong>highlight:</strong> increase syntax highlighter config
priority (<a
href="https://redirect.github.com/zkat/miette/issues/424">#424</a>) (<a
href="58d9f12411">58d9f124</a>)</li>
<li><strong>deps:</strong> miette can now be used without syn (<a
href="https://redirect.github.com/zkat/miette/issues/436">#436</a>) (<a
href="521ef91f77">521ef91f</a>)</li>
</ul>
<h3>Features</h3>
<ul>
<li><strong>graphical:</strong> support rendering related diagnostics as
nested (<a
href="https://redirect.github.com/zkat/miette/issues/417">#417</a>) (<a
href="771a07519f">771a0751</a>)</li>
<li><strong>labels:</strong> add support for disabling the primary label
line/col information (<a
href="https://redirect.github.com/zkat/miette/issues/419">#419</a>) (<a
href="f2ef693d1c">f2ef693d</a>)</li>
<li><strong>deps:</strong> update <code>thiserror</code> from 1.0.56 to
2.0.11 (<a
href="https://redirect.github.com/zkat/miette/issues/426">#426</a>) (<a
href="59c81617de">59c81617</a>)</li>
</ul>
<p><!-- raw HTML omitted --><!-- raw HTML omitted --></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li>See full diff in <a
href="https://github.com/zkat/miette/commits/miette-derive-v7.6.0">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=miette&package-manager=cargo&previous-version=7.5.0&new-version=7.6.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-05-10 22:33:18 +08:00
8352a09117 fix: inefficient select with large row number (#15730)
Fixes #15716

# Description

Returns None early if the input iterator is depleted.

# User-Facing Changes

Should be none

# Tests + Formatting

+1

# After Submitting
2025-05-10 11:28:18 +03:00
a9252c5075 nu-table: (table --expand) Remove unnessary use of truncate logic (#15727)
A small optimization;

Must be measurable on large tables.
In case of `scope commands` for me seems like a bit faster in debug
(~100ms).
But I've had like a few runs.
If someone is interested to check if it's any faster would be nice to
see it :)

cc: @fdncred
2025-05-09 18:21:33 -05:00
73fbe26ef9 feat: make to nuon raw option remove all white space (#15609)
# Description
Fixes #9942

This adds a new `--minified` flag to `to nuon` which removes all
possible white space. I added an example test to demonstrate the
functionality.

# User-Facing Changes

New flag becomes available to the user.
2025-05-09 09:38:24 +08:00
52fa9a978b Fix #15653 regression with not counting padding properly (#15704)
ref #15653

Thanks for reproducible.

So @Bahex indeed padding was not properly handled.
I am not sure whether there's more issues related to your examples
@fdncred but I seems like don't get them.

Also added a test for future regressions (well to be honest didn't
tested that it's failing on main but at least at may catch something)

PS: Also got some panic related to #15138 (which PR fixed) :(
There's nothing on my end stopping me releasing a WASM issue fix; I just
sort of always worrying with releasing a `patch` (`0.0.x`)......and
there's 1 quite big thing I wanna do before a minor release.......
2025-05-08 17:18:50 -05:00
d4357ad981 Remove legacy code in some core commands (#15560)
# Description

See [this
discussion](https://discord.com/channels/601130461678272522/1353434388938883143/1360664695962341647)
on discord

Goal: as the AST evaluator isn't supported anymore, I removed the body
of the "run" methods of some commands that were actually never run
because the IR is used instead.

Note: the code inside the "run_const" methods seems to be run, so I left
it.

Cc @132ikl 

# User-Facing Changes
None

# Tests + Formatting
I didn't do any manual testing, I just ran the tests

# After Submitting
Nothing required I think
2025-05-08 12:12:36 -04:00
a0d7c1a4fd Add SyntaxShape::OneOf syntax users can use (#15646)
# Description
Built-in commands can have parameter of `SyntaxShape::OneOf`.
This PR changes `OneOf`'s string representation and gives users the
ability to use it in definitions.

> _Syntax updated after discussion on discord._

```nushell
def foo [
    param: oneof<binary, string>
] { .. }
```
```
Usage:
  > foo <param> 

Flags:
  -h, --help: Display the help message for this command

Parameters:
  param <oneof<binary, string>>

Input/output types:
  ╭───┬───────┬────────╮
  │ # │ input │ output │
  ├───┼───────┼────────┤
  │ 0 │ any   │ any    │
  ╰───┴───────┴────────╯
```

<details><summary>Previous iterations</summary>
<p>

> ```nushell
> def foo [
>     param: (binary | string)
> ] { .. }
> ```

> ---
>
> ```nushell
> def foo [
>     param: one_of(binary, string)
> ] { .. }
> ```

</p>
</details> 


# User-Facing Changes

# Tests + Formatting
Added some test cases.

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

# After Submitting
- Update the website to include the new syntax
[here](https://github.com/nushell/nushell.github.io/blob/main/book/custom_commands.md)
- Update [tree-sitter-nu](https://github.com/nushell/tree-sitter-nu)
- Update `std` and `std-rfc` where applicable

---------

Co-authored-by: Bahex <17417311+Bahex@users.noreply.github.com>
2025-05-07 15:43:01 -05:00
a340511e95 build(deps): bump crate-ci/typos from 1.31.2 to 1.32.0 (#15708) 2025-05-07 18:54:34 +08:00
426e64501d build(deps): bump quickcheck_macros from 1.0.0 to 1.1.0 (#15711)
Bumps [quickcheck_macros](https://github.com/BurntSushi/quickcheck) from
1.0.0 to 1.1.0.
<details>
<summary>Commits</summary>
<ul>
<li><a
href="d58e3cffb7"><code>d58e3cf</code></a>
quickcheck_macros-1.1.0</li>
<li><a
href="03ab585865"><code>03ab585</code></a>
Fix README examples</li>
<li><a
href="826f10baa1"><code>826f10b</code></a>
Add shrinking support for arrays (<a
href="https://redirect.github.com/BurntSushi/quickcheck/issues/330">#330</a>)</li>
<li><a
href="87b46b90ec"><code>87b46b9</code></a>
Update some links (<a
href="https://redirect.github.com/BurntSushi/quickcheck/issues/332">#332</a>)</li>
<li><a
href="a0216c932f"><code>a0216c9</code></a>
Revert <code>Gen</code> renaming, rename <code>gen</code> method</li>
<li><a
href="2c2cd21935"><code>2c2cd21</code></a>
Update to rand 0.9</li>
<li><a
href="9ddbbd6b68"><code>9ddbbd6</code></a>
deps: update to syn 2.0 (<a
href="https://redirect.github.com/BurntSushi/quickcheck/issues/317">#317</a>)</li>
<li><a
href="238f340a36"><code>238f340</code></a>
Bump MSRV to 1.71</li>
<li><a
href="32d7bc4edf"><code>32d7bc4</code></a>
Upgrade to 2021 edition</li>
<li><a
href="44b81bebcf"><code>44b81be</code></a>
deps: update to env_logger 0.11 (<a
href="https://redirect.github.com/BurntSushi/quickcheck/issues/327">#327</a>)</li>
<li>Additional commits viewable in <a
href="https://github.com/BurntSushi/quickcheck/compare/quickcheck_macros-1.0.0...quickcheck_macros-1.1.0">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=quickcheck_macros&package-manager=cargo&previous-version=1.0.0&new-version=1.1.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-05-07 17:28:10 +08:00
b0d68c31e8 build(deps): bump tokio from 1.44.2 to 1.45.0 (#15710)
Bumps [tokio](https://github.com/tokio-rs/tokio) from 1.44.2 to 1.45.0.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/tokio-rs/tokio/releases">tokio's
releases</a>.</em></p>
<blockquote>
<h2>Tokio v1.45.0</h2>
<h3>Added</h3>
<ul>
<li>metrics: stabilize <code>worker_total_busy_duration</code>,
<code>worker_park_count</code>, and <code>worker_unpark_count</code> (<a
href="https://redirect.github.com/tokio-rs/tokio/issues/6899">#6899</a>,
<a
href="https://redirect.github.com/tokio-rs/tokio/issues/7276">#7276</a>)</li>
<li>process: add <code>Command::spawn_with</code> (<a
href="https://redirect.github.com/tokio-rs/tokio/issues/7249">#7249</a>)</li>
</ul>
<h3>Changed</h3>
<ul>
<li>io: do not require <code>Unpin</code> for some trait impls (<a
href="https://redirect.github.com/tokio-rs/tokio/issues/7204">#7204</a>)</li>
<li>rt: mark <code>runtime::Handle</code> as unwind safe (<a
href="https://redirect.github.com/tokio-rs/tokio/issues/7230">#7230</a>)</li>
<li>time: revert internal sharding implementation (<a
href="https://redirect.github.com/tokio-rs/tokio/issues/7226">#7226</a>)</li>
</ul>
<h3>Unstable</h3>
<ul>
<li>rt: remove alt multi-threaded runtime (<a
href="https://redirect.github.com/tokio-rs/tokio/issues/7275">#7275</a>)</li>
</ul>
<p><a
href="https://redirect.github.com/tokio-rs/tokio/issues/6899">#6899</a>:
<a
href="https://redirect.github.com/tokio-rs/tokio/pull/6899">tokio-rs/tokio#6899</a>
<a
href="https://redirect.github.com/tokio-rs/tokio/issues/7276">#7276</a>:
<a
href="https://redirect.github.com/tokio-rs/tokio/pull/7276">tokio-rs/tokio#7276</a>
<a
href="https://redirect.github.com/tokio-rs/tokio/issues/7249">#7249</a>:
<a
href="https://redirect.github.com/tokio-rs/tokio/pull/7249">tokio-rs/tokio#7249</a>
<a
href="https://redirect.github.com/tokio-rs/tokio/issues/7204">#7204</a>:
<a
href="https://redirect.github.com/tokio-rs/tokio/pull/7204">tokio-rs/tokio#7204</a>
<a
href="https://redirect.github.com/tokio-rs/tokio/issues/7230">#7230</a>:
<a
href="https://redirect.github.com/tokio-rs/tokio/pull/7230">tokio-rs/tokio#7230</a>
<a
href="https://redirect.github.com/tokio-rs/tokio/issues/7226">#7226</a>:
<a
href="https://redirect.github.com/tokio-rs/tokio/pull/7226">tokio-rs/tokio#7226</a>
<a
href="https://redirect.github.com/tokio-rs/tokio/issues/7275">#7275</a>:
<a
href="https://redirect.github.com/tokio-rs/tokio/pull/7275">tokio-rs/tokio#7275</a></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="00754c8f9c"><code>00754c8</code></a>
chore: prepare Tokio v1.45.0 (<a
href="https://redirect.github.com/tokio-rs/tokio/issues/7308">#7308</a>)</li>
<li><a
href="1ae9434e8e"><code>1ae9434</code></a>
time: revert &quot;use sharding for timer implementation&quot; related
changes (<a
href="https://redirect.github.com/tokio-rs/tokio/issues/7226">#7226</a>)</li>
<li><a
href="8895bba448"><code>8895bba</code></a>
ci: Test AArch64 Windows (<a
href="https://redirect.github.com/tokio-rs/tokio/issues/7288">#7288</a>)</li>
<li><a
href="48ca254d92"><code>48ca254</code></a>
time: update <code>sleep</code> documentation to reflect maximum allowed
duration (<a
href="https://redirect.github.com/tokio-rs/tokio/issues/7302">#7302</a>)</li>
<li><a
href="a0af02a396"><code>a0af02a</code></a>
compat: add more documentation to <code>tokio_util::compat</code> (<a
href="https://redirect.github.com/tokio-rs/tokio/issues/7279">#7279</a>)</li>
<li><a
href="0ce3a1188a"><code>0ce3a11</code></a>
metrics: stabilize <code>worker_park_count</code> and
<code>worker_unpark_count</code> (<a
href="https://redirect.github.com/tokio-rs/tokio/issues/7276">#7276</a>)</li>
<li><a
href="1ea9ce11d4"><code>1ea9ce1</code></a>
ci: fix cfg!(miri) declarations in tests (<a
href="https://redirect.github.com/tokio-rs/tokio/issues/7286">#7286</a>)</li>
<li><a
href="4d4d12613b"><code>4d4d126</code></a>
chore: prepare tokio-util v0.7.15 (<a
href="https://redirect.github.com/tokio-rs/tokio/issues/7283">#7283</a>)</li>
<li><a
href="5490267a79"><code>5490267</code></a>
fs: update the mockall dev dependency to 0.13.0 (<a
href="https://redirect.github.com/tokio-rs/tokio/issues/7234">#7234</a>)</li>
<li><a
href="1434b32b5a"><code>1434b32</code></a>
examples: improve echo example consistency (<a
href="https://redirect.github.com/tokio-rs/tokio/issues/7256">#7256</a>)</li>
<li>Additional commits viewable in <a
href="https://github.com/tokio-rs/tokio/compare/tokio-1.44.2...tokio-1.45.0">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=tokio&package-manager=cargo&previous-version=1.44.2&new-version=1.45.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-05-07 17:28:02 +08:00
583cb96cff fix: clear jobs _after_ traversing jobs for kill_all (#15685)
# Description

Move clear jobs to _after_ traversing them, in order to kill them.

# User-Facing Changes

None

# Tests + Formatting

It looks like it's only used once, in crates/nu-engine/src/exit.rs
2025-05-07 17:25:16 +08:00
ff8831318d Added polars struct-encode-json, providing the ability to encode structs as json (#15678)
# Description
This PR introduces `polars struct-encode-json`. This exposes the ability
to encode struct columns as json strings. This is useful when converting
things to formats like CSV that do not support complex types.

```nushell
> ❯ : [[id person]; [1 {name: "Bob", age: 36}] [2 {name: "Betty", age: 63}]]
                    | polars into-df -s {id: i64, person: {name: str, age: u8}}
                    | polars select id (polars col person | polars struct-json-encode | polars as encoded) 
                    | polars collect
╭───┬────┬───────────────────────────╮
│ # │ id │          encoded          │
├───┼────┼───────────────────────────┤
│ 0 │  1 │ {"age":36,"name":"Bob"}   │
│ 1 │  2 │ {"age":63,"name":"Betty"} │
╰───┴────┴───────────────────────────╯
```

# User-Facing Changes
* Added `polars struct-encode-json`, providing the ability to encode
structs as json
2025-05-06 13:58:51 -07:00
ce308ee461 build(deps): bump crate-ci/typos from 1.31.1 to 1.31.2 (#15665)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-05-06 12:53:44 +02:00
21388175b8 build(deps): bump actions-rust-lang/setup-rust-toolchain from 1.11.0 to 1.12.0 (#15666)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-05-06 12:53:03 +02:00
520f11fb8f docs: Add vfox to list of tools supporting Nushell (#15687)
This change adds [vfox](https://github.com/version-fox/vfox) to the list
of tools that support Nushell in the readme.

This is a tool for managing multiple versions of SDKs (similar to
[asdf](https://asdf-vm.com/), but cross-platform). After some work by me
and another contributor (see
https://github.com/version-fox/vfox/issues/207), vfox now works in
Nushell!
2025-05-04 20:56:10 -05:00
39b95fc59e Environment-aware help for open and save (#15651)
# Description

This extends the documentation on the commands `open` and `save` can run
under the hood, and explicitly lists those, based on the current user
environment.

Also see [this discord
thread](https://discord.com/channels/601130461678272522/988303282931912704/1364930487092777020)

# User-Facing Changes

Users will be able to see the list of commands that `open` and `save`
can run, and the extensions that each command is run for, in `help open`
and `help save` respectively:

## `help open`

![image](https://github.com/user-attachments/assets/b245d12c-c6ef-4c6d-a9f1-6c5111cb0684)

## `help save`

![image](https://github.com/user-attachments/assets/e92ddb6b-6a1e-40cc-9139-78db8a921d4a)


# Tests + Formatting

All pass except for the ones that don't (and never did pass for me
before).

# After Submitting

No updates needed.
2025-05-03 17:07:39 -05:00
63e68934f6 Numbers proceeded with the escape character ignored fix (#15684)
Fixes #15675

I've added relevant test cases to ensure coverage of the identified bug.
The issue originated from my crate and pertains to the bracoxide
dependency—a bug I’ve internally referred to as IgnorantNumbers. I’ve
submitted a fix and updated the bracoxide dependency accordingly.
2025-05-03 08:10:51 -05:00
acc152564c docs: fix available fields in history import command (#15686)
- The ID field cannot be set (see `item_from_record`)
- Fix command line's field name
2025-05-03 08:09:58 -05:00
8f63db4c95 Add 'single' to supported table modes (#15681)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use toolkit.nu; toolkit test stdlib"` to run the
tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
2025-05-02 16:21:11 -05:00
cb133ed387 feat(table): Add new 'single' table mode (#15672)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->
closes #15381

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->
Adds a new table mode called `single`, it looks like the `heavy` mode,
but the key difference is that it uses thinner lines. I decided on the
name `single` because it's one of the border styles Neovim uses, and
they look practically the same.

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->

New config option:

```nushell
$env.config.table.mode = 'single'
```

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use toolkit.nu; toolkit test stdlib"` to run the
tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->
Added new tests in `crates/nu-table/tests/style.rs` to cover the single
table mode.

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
2025-05-01 15:30:57 -05:00
a7547a54bc fix(parser): namespace pollution of constants by use module.nu (#15518)
A bug introduced by #14920 

When `use module.nu` is called, all exported constants defined in it are
added to the scope.

# Description

On the branch of empty arguments, the constant var_id vector should be
empty, only constant_values (for `$module.foo` access) are injected.

# User-Facing Changes

# Tests + Formatting

~todo!~

adjusted

# After Submitting
2025-05-01 09:47:16 -05:00
d1969a3c9a docs: update ubuntu version in PLATFORM_SUPPORT.md (#15662)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->

I was interested in how nu-shell handles glibc, especially older
versions of it. I figured out from the docs that ubuntu 20.04 is
utilized. However, in reality, github has deprecated ubuntu 20.04, and
the code for ci.yaml in github workflow clearly states that it is 22.04.

This is just a minor doc update to clarify forgotten information
2025-05-01 09:44:49 -05:00
ce582cdafb feat(polars): add polars horizontal aggregation command (#15656)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->
This PR seeks to port over the `*_horizontal` commands in polars
rust/python (e.g.,
https://docs.pola.rs/api/python/stable/reference/expressions/api/polars.sum_horizontal.html),
which aggregate across multiple columns (as opposed to rows). See below
for several examples.

```nushell
#  Horizontal sum across two columns (ignore nulls by default)
  > [[a b]; [1 2] [2 3] [3 4] [4 5] [5 null]]
                    | polars into-df
                    | polars select (polars horizontal sum a b)
                    | polars collect
  ╭───┬─────╮
  │ # │ sum │
  ├───┼─────┤
  │ 0 │   3 │
  │ 1 │   5 │
  │ 2 │   7 │
  │ 3 │   9 │
  │ 4 │   5 │
  ╰───┴─────╯

#  Horizontal sum across two columns while accounting for nulls
  > [[a b]; [1 2] [2 3] [3 4] [4 5] [5 null]]
                    | polars into-df
                    | polars select (polars horizontal sum a b --nulls)
                    | polars collect
  ╭───┬─────╮
  │ # │ sum │
  ├───┼─────┤
  │ 0 │   3 │
  │ 1 │   5 │
  │ 2 │   7 │
  │ 3 │   9 │
  │ 4 │     │
  ╰───┴─────╯
```

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->
No breaking changes. Users have access to a new command, `polars
horizontal`.

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use toolkit.nu; toolkit test stdlib"` to run the
tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->
Example tests were added to `polars horizontal`.

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
2025-05-01 09:44:15 -05:00
55de232a1c refactor Value::follow_cell_path to reduce clones and return Cow (#15640)
# Description
While working on something else, I noticed that
`Value::follow_cell_path` receives `self`.

While it would be ideal for the signature to be `(&'a self, cell_path)
-> &'a Value`, that's not possible because:
1. Selecting a row from a list and field from a record can be done with
a reference but selecting a column from a table requires creating a new
list.
2. `Value::Custom` returns new `Value`s when indexed.

So the signature becomes `(&'a self, cell_path) -> Cow<'a, Value>`.

Another complication that arises is, once a new `Value` is created, and
it is further indexed, the `current` variable
1. can't be `&'a Value`, as the lifetime requirement means it can't
refer to local variables
2. _shouldn't_ be `Cow<'a, Value>`, as once it becomes an owned value,
it can't be borrowed ever again, as `current` is derived from its
previous value in further iterations. So once it's owned, it can't be
indexed by reference, leading to more clones

We need `current` to have _two_ possible lifetimes
1. `'out`: references derived from `&self`
2. `'local`: references derived from an owned value stored in a local
variable

```rust
enum MultiLife<'out, 'local, T>
where
    'out: 'local,
    T: ?Sized,
{
    Out(&'out T),
    Local(&'local T),
}
```
With `current: MultiLife<'out, '_, Value>`, we can traverse values with
minimal clones, and we can transform it to `Cow<'out, Value>` easily
(`MultiLife::Out -> Cow::Borrowed, MultiLife::Local -> Cow::Owned`) to
return it

# User-Facing Changes

# Tests + Formatting

# After Submitting

---------

Co-authored-by: Bahex <17417311+Bahex@users.noreply.github.com>
2025-05-01 09:43:57 -05:00
deca337a56 nu-table/ 1 refactoring + a few optimizations + small fix (#15653)
- A few days back I've got this idea regarding recalculus of width.
Now it calculates step by step.
So 1 loop over all data was removed.
All though there's full recalculation in case of `header_on_border`
😞 (can be fixed..... but I decided to be short)

In perfect world it also shall be refactored ......

- Also have done small refactoring to switch build table from
`Vec<Vec<_>>>` to table itself. To hide internals (kind of still there's
things which I don't like).
It touched the `--expand` algorithm lightly you can see the tests
changes.

- And when doing that noticed one more opportunity, to remove HashMap
usage and directly use `tabled::ColoredConfig`. Which reduces copy
operations and allocations.

- And fixed a small issue where trailing column being using deleted
column styles.


![image](https://github.com/user-attachments/assets/19b09dba-c688-4e91-960a-e11ed11fd275)

To conclude optimizations;
I did small testing and it's not slower.
But I didn't get the faster results either.
But I believe it must be faster well in all cases, I think maybe bigger
tables must be tested.
Maybe someone could have a few runs to compare performance.

cc: @fdncred
2025-05-01 09:43:30 -05:00
60e9f469af change http get header example to use a record (#15674)
# Description

When first using `http get`, I was confused that all the examples used a
list for headers, leading me to believe this was the only way, and it
seemed a little weird having records in the language. Then, I found out
that you can indeed use record, so I changed the example to show this
behavior in a way users can find. There still is another examples that
uses a list so there should be no problem there.

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use toolkit.nu; toolkit test stdlib"` to run the
tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
2025-05-01 09:42:53 -05:00
b500ac57c2 Update job_recv.rs (#15673)
remove j

<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use toolkit.nu; toolkit test stdlib"` to run the
tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
2025-05-01 06:19:32 -05:00
923 changed files with 14982 additions and 8656 deletions

View File

@ -37,7 +37,7 @@ jobs:
- uses: actions/checkout@v4.1.7
- name: Setup Rust toolchain and cache
uses: actions-rust-lang/setup-rust-toolchain@v1.11.0
uses: actions-rust-lang/setup-rust-toolchain@v1.12.0
- name: cargo fmt
run: cargo fmt --all -- --check
@ -65,7 +65,7 @@ jobs:
- uses: actions/checkout@v4.1.7
- name: Setup Rust toolchain and cache
uses: actions-rust-lang/setup-rust-toolchain@v1.11.0
uses: actions-rust-lang/setup-rust-toolchain@v1.12.0
- name: Tests
run: cargo test --workspace --profile ci --exclude nu_plugin_*
@ -94,7 +94,7 @@ jobs:
- uses: actions/checkout@v4.1.7
- name: Setup Rust toolchain and cache
uses: actions-rust-lang/setup-rust-toolchain@v1.11.0
uses: actions-rust-lang/setup-rust-toolchain@v1.12.0
- name: Install Nushell
run: cargo install --path . --locked --force
@ -145,7 +145,7 @@ jobs:
- uses: actions/checkout@v4.1.7
- name: Setup Rust toolchain and cache
uses: actions-rust-lang/setup-rust-toolchain@v1.11.0
uses: actions-rust-lang/setup-rust-toolchain@v1.12.0
- name: Clippy
run: cargo clippy --package nu_plugin_* -- $CLIPPY_OPTIONS
@ -186,7 +186,7 @@ jobs:
- uses: actions/checkout@v4.1.7
- name: Setup Rust toolchain and cache
uses: actions-rust-lang/setup-rust-toolchain@v1.11.0
uses: actions-rust-lang/setup-rust-toolchain@v1.12.0
- name: Add wasm32-unknown-unknown target
run: rustup target add wasm32-unknown-unknown

View File

@ -4,17 +4,18 @@
# 2. https://github.com/JasonEtco/create-an-issue
# 3. https://docs.github.com/en/actions/learn-github-actions/variables
# 4. https://github.com/actions/github-script
# 5. https://docs.github.com/en/actions/writing-workflows/workflow-syntax-for-github-actions#jobsjob_idneeds
#
name: Nightly Build
on:
workflow_dispatch:
push:
branches:
- nightly # Just for test purpose only with the nightly repo
# This schedule will run only from the default branch
schedule:
- cron: '15 0 * * *' # run at 00:15 AM UTC
workflow_dispatch:
defaults:
run:
@ -26,6 +27,11 @@ jobs:
runs-on: ubuntu-latest
# This job is required by the release job, so we should make it run both from Nushell repo and nightly repo
# if: github.repository == 'nushell/nightly'
# Map a step output to a job output
outputs:
skip: ${{ steps.vars.outputs.skip }}
build_date: ${{ steps.vars.outputs.build_date }}
nightly_tag: ${{ steps.vars.outputs.nightly_tag }}
steps:
- name: Checkout
uses: actions/checkout@v4
@ -58,16 +64,53 @@ jobs:
# All the changes will be overwritten by the upstream main branch
git reset --hard src/main
git push origin main -f
let sha_short = (git rev-parse --short origin/main | str trim | str substring 0..7)
let tag_name = $'nightly-($sha_short)'
if (git ls-remote --tags origin $tag_name | is-empty) {
git tag -a $tag_name -m $'Nightly build from ($sha_short)'
- name: Create Tag and Output Tag Name
if: github.repository == 'nushell/nightly'
id: vars
shell: nu {0}
run: |
let date = date now | format date %m%d
let version = open Cargo.toml | get package.version
let sha_short = (git rev-parse --short origin/main | str trim | str substring 0..6)
let latest_meta = http get https://api.github.com/repos/nushell/nightly/releases
| sort-by -r created_at
| where tag_name =~ nightly
| get tag_name?.0? | default ''
| parse '{version}-nightly.{build}+{hash}'
if ($latest_meta.0?.hash? | default '') == $sha_short {
print $'(ansi g)Latest nightly build is up-to-date, skip rebuilding.(ansi reset)'
$'skip=true(char nl)' o>> $env.GITHUB_OUTPUT
exit 0
}
let prev_ver = $latest_meta.0?.version? | default '0.0.0'
let build = if ($latest_meta | is-empty) or ($version != $prev_ver) { 1 } else {
($latest_meta | get build?.0? | default 0 | into int) + 1
}
let nightly_tag = $'($version)-nightly.($build)+($sha_short)'
$'build_date=($date)(char nl)' o>> $env.GITHUB_OUTPUT
$'nightly_tag=($nightly_tag)(char nl)' o>> $env.GITHUB_OUTPUT
if (git ls-remote --tags origin $nightly_tag | is-empty) {
ls **/Cargo.toml | each {|file|
open --raw $file.name
| str replace --all $'version = "($version)"' $'version = "($version)-nightly.($build)"'
| save --force $file.name
}
# Disable the following two workflows for the automatic committed changes
rm .github/workflows/ci.yml
rm .github/workflows/audit.yml
git add .
git commit -m $'Update version to ($version)-nightly.($build)'
git tag -a $nightly_tag -m $'Nightly build from ($sha_short)'
git push origin --tags
git push origin main -f
}
standard:
release:
name: Nu
needs: prepare
if: needs.prepare.outputs.skip != 'true'
strategy:
fail-fast: false
matrix:
@ -84,24 +127,15 @@ jobs:
- armv7-unknown-linux-musleabihf
- riscv64gc-unknown-linux-gnu
- loongarch64-unknown-linux-gnu
extra: ['bin']
include:
- target: aarch64-apple-darwin
os: macos-latest
- target: x86_64-apple-darwin
os: macos-latest
- target: x86_64-pc-windows-msvc
extra: 'bin'
os: windows-latest
- target: x86_64-pc-windows-msvc
extra: msi
os: windows-latest
- target: aarch64-pc-windows-msvc
extra: 'bin'
os: windows-latest
- target: aarch64-pc-windows-msvc
extra: msi
os: windows-latest
os: windows-11-arm
- target: x86_64-unknown-linux-gnu
os: ubuntu-22.04
- target: x86_64-unknown-linux-musl
@ -120,40 +154,64 @@ jobs:
os: ubuntu-22.04
runs-on: ${{matrix.os}}
steps:
- uses: actions/checkout@v4
with:
ref: main
fetch-depth: 0
- name: Install Wix Toolset 6 for Windows
shell: pwsh
if: ${{ startsWith(matrix.os, 'windows') }}
run: |
dotnet tool install --global wix --version 6.0.0
dotnet workload install wix
$wixPath = "$env:USERPROFILE\.dotnet\tools"
echo "$wixPath" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
$env:PATH = "$wixPath;$env:PATH"
wix --version
- name: Update Rust Toolchain Target
run: |
echo "targets = ['${{matrix.target}}']" >> rust-toolchain.toml
- name: Setup Rust toolchain and cache
uses: actions-rust-lang/setup-rust-toolchain@v1.11.0
uses: actions-rust-lang/setup-rust-toolchain@v1
# WARN: Keep the rustflags to prevent from the winget submission error: `CAQuietExec: Error 0xc0000135`
with:
rustflags: ''
- name: Setup Nushell
uses: hustcer/setup-nu@v3
if: ${{ matrix.os != 'windows-11-arm' }}
with:
version: 0.103.0
- name: Release Nu Binary
id: nu
if: ${{ matrix.os != 'windows-11-arm' }}
run: nu .github/workflows/release-pkg.nu
env:
OS: ${{ matrix.os }}
REF: ${{ github.ref }}
TARGET: ${{ matrix.target }}
_EXTRA_: ${{ matrix.extra }}
- name: Build Nu for Windows ARM64
id: nu0
shell: pwsh
if: ${{ matrix.os == 'windows-11-arm' }}
run: |
$env:OS = 'windows'
$env:REF = '${{ github.ref }}'
$env:TARGET = '${{ matrix.target }}'
cargo build --release --all --target aarch64-pc-windows-msvc
cp ./target/${{ matrix.target }}/release/nu.exe .
./nu.exe -c 'version'
./nu.exe ${{github.workspace}}/.github/workflows/release-pkg.nu
- name: Create an Issue for Release Failure
if: ${{ failure() }}
uses: JasonEtco/create-an-issue@v2.9.2
uses: JasonEtco/create-an-issue@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
@ -161,13 +219,6 @@ jobs:
search_existing: open
filename: .github/AUTO_ISSUE_TEMPLATE/nightly-build-fail.md
- name: Set Outputs of Short SHA
id: vars
run: |
echo "date=$(date -u +'%Y-%m-%d')" >> $GITHUB_OUTPUT
sha_short=$(git rev-parse --short HEAD)
echo "sha_short=${sha_short:0:7}" >> $GITHUB_OUTPUT
# REF: https://github.com/marketplace/actions/gh-release
# Create a release only in nushell/nightly repo
- name: Publish Archive
@ -175,9 +226,39 @@ jobs:
if: ${{ startsWith(github.repository, 'nushell/nightly') }}
with:
prerelease: true
files: ${{ steps.nu.outputs.archive }}
tag_name: nightly-${{ steps.vars.outputs.sha_short }}
name: Nu-nightly-${{ steps.vars.outputs.date }}-${{ steps.vars.outputs.sha_short }}
files: |
${{ steps.nu.outputs.msi }}
${{ steps.nu0.outputs.msi }}
${{ steps.nu.outputs.archive }}
${{ steps.nu0.outputs.archive }}
tag_name: ${{ needs.prepare.outputs.nightly_tag }}
name: ${{ needs.prepare.outputs.build_date }}-${{ needs.prepare.outputs.nightly_tag }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
sha256sum:
needs: [prepare, release]
name: Create Sha256sum
runs-on: ubuntu-latest
if: github.repository == 'nushell/nightly'
steps:
- name: Download Release Archives
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: >-
gh release download ${{ needs.prepare.outputs.nightly_tag }}
--repo ${{ github.repository }}
--pattern '*'
--dir release
- name: Create Checksums
run: cd release && shasum -a 256 * > ../SHA256SUMS
- name: Publish Checksums
uses: softprops/action-gh-release@v2.0.9
with:
draft: false
prerelease: true
files: SHA256SUMS
tag_name: ${{ needs.prepare.outputs.nightly_tag }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@ -185,12 +266,9 @@ jobs:
name: Cleanup
# Should only run in nushell/nightly repo
if: github.repository == 'nushell/nightly'
needs: [release, sha256sum]
runs-on: ubuntu-latest
steps:
# Sleep for 30 minutes, waiting for the release to be published
- name: Waiting for Release
run: sleep 1800
- uses: actions/checkout@v4
with:
ref: main
@ -205,7 +283,7 @@ jobs:
shell: nu {0}
run: |
let KEEP_COUNT = 10
let deprecated = (http get https://api.github.com/repos/nushell/nightly/releases | sort-by -r created_at | select tag_name id | range $KEEP_COUNT..)
let deprecated = (http get https://api.github.com/repos/nushell/nightly/releases | sort-by -r created_at | select tag_name id | slice $KEEP_COUNT..)
for release in $deprecated {
print $'Deleting tag ($release.tag_name)'
git push origin --delete $release.tag_name

62
.github/workflows/release-msi.nu vendored Executable file
View File

@ -0,0 +1,62 @@
#!/usr/bin/env nu
# Created: 2025/05/21 19:05:20
# Description:
# A script to build Windows MSI packages for NuShell. Need wix 6.0 to be installed.
# The script will download the specified NuShell release, extract it, and create an MSI package.
# Can be run locally or in GitHub Actions.
# To run this script locally:
# load-env { TARGET: 'x86_64-pc-windows-msvc' REF: '0.103.0' GITHUB_REPOSITORY: 'nushell/nushell' }
# nu .github/workflows/release-msi.nu
def build-msi [] {
let target = $env.TARGET
# We should read the version from the environment variable first
# As we may build the MSI package for a specific version not the latest one
let version = $env.MSI_VERSION? | default (open Cargo.toml | get package.version)
let arch = if $nu.os-info.arch =~ 'x86_64' { 'x64' } else { 'arm64' }
print $'Building msi package for (ansi g)($target)(ansi reset) with version (ansi g)($version)(ansi reset) from tag (ansi g)($env.REF)(ansi reset)...'
fetch-nu-pkg
# Create extra Windows msi release package if dotnet and wix are available
let installed = [dotnet wix] | all { (which $in | length) > 0 }
if $installed and (wix --version | split row . | first | into int) >= 6 {
print $'(char nl)Start creating Windows msi package with the following contents...'
cd wix; hr-line
cp nu/README.txt .
ls -f nu/* | print
./nu/nu.exe -c $'NU_RELEASE_VERSION=($version) dotnet build -c Release -p:Platform=($arch)'
glob **/*.msi | print
# Workaround for https://github.com/softprops/action-gh-release/issues/280
let wixRelease = (glob **/*.msi | where $it =~ bin | get 0 | str replace --all '\' '/')
let msi = $'($wixRelease | path dirname)/nu-($version)-($target).msi'
mv $wixRelease $msi
print $'MSI archive: ---> ($msi)';
# Run only in GitHub Actions
if ($env.GITHUB_ACTIONS? | default false | into bool) {
echo $"msi=($msi)(char nl)" o>> $env.GITHUB_OUTPUT
}
}
}
def fetch-nu-pkg [] {
mkdir wix/nu
# See: https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/store-information-in-variables#default-environment-variables
gh release download $env.REF --repo $env.GITHUB_REPOSITORY --pattern $'*-($env.TARGET).zip' --dir wix/nu
cd wix/nu
let pkg = ls *.zip | get name.0
unzip $pkg
rm $pkg
ls | print
}
# Print a horizontal line marker
def 'hr-line' [
--blank-line(-b)
] {
print $'(ansi g)---------------------------------------------------------------------------->(ansi reset)'
if $blank_line { char nl }
}
alias main = build-msi

103
.github/workflows/release-msi.yml vendored Normal file
View File

@ -0,0 +1,103 @@
#
# REF:
# 1. https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstrategymatrixinclude
#
name: Build Windows MSI
on:
workflow_dispatch:
inputs:
tag:
required: true
description: 'Tag to Rebuild MSI'
version:
description: 'Version of Rebuild MSI'
permissions:
contents: write
packages: write
defaults:
run:
shell: bash
jobs:
release:
name: Nu
strategy:
fail-fast: false
matrix:
target:
- x86_64-pc-windows-msvc
- aarch64-pc-windows-msvc
extra: ['bin']
include:
- target: x86_64-pc-windows-msvc
os: windows-latest
- target: aarch64-pc-windows-msvc
os: windows-11-arm
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- name: Install Wix Toolset 6 for Windows
shell: pwsh
if: ${{ startsWith(matrix.os, 'windows') }}
run: |
dotnet tool install --global wix --version 6.0.0
dotnet workload install wix
$wixPath = "$env:USERPROFILE\.dotnet\tools"
echo "$wixPath" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
$env:PATH = "$wixPath;$env:PATH"
wix --version
- name: Setup Nushell
uses: hustcer/setup-nu@v3
with:
version: nightly
- name: Release MSI Packages
id: nu
run: nu .github/workflows/release-msi.nu
env:
OS: ${{ matrix.os }}
REF: ${{ inputs.tag }}
TARGET: ${{ matrix.target }}
MSI_VERSION: ${{ inputs.version }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# REF: https://github.com/marketplace/actions/gh-release
- name: Publish Archive
uses: softprops/action-gh-release@v2.0.5
with:
tag_name: ${{ inputs.tag }}
files: ${{ steps.nu.outputs.msi }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
sha256sum:
needs: release
name: Create Sha256sum
runs-on: ubuntu-latest
steps:
- name: Download Release Archives
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: >-
gh release download ${{ inputs.tag }}
--repo ${{ github.repository }}
--pattern '*'
--dir release
- name: Create Checksums
run: cd release && rm -f SHA256SUMS && shasum -a 256 * > ../SHA256SUMS
- name: Publish Checksums
uses: softprops/action-gh-release@v2.0.5
with:
files: SHA256SUMS
tag_name: ${{ inputs.tag }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@ -8,10 +8,10 @@
# Instructions for manually creating an MSI for Winget Releases when they fail
# Added 2022-11-29 when Windows packaging wouldn't work
# Updated again on 2023-02-23 because msis are still failing validation
# Updated again on 2023-02-23 because MSIs are still failing validation
# To run this manual for windows here are the steps I take
# checkout the release you want to publish
# 1. git checkout 0.86.0
# 1. git checkout 0.103.0
# unset CARGO_TARGET_DIR if set (I have to do this in the parent shell to get it to work)
# 2. $env:CARGO_TARGET_DIR = ""
# 2. hide-env CARGO_TARGET_DIR
@ -23,19 +23,13 @@
# 7. $env.Path = ($env.Path | append 'c:\apps\7-zip')
# make sure aria2c.exe is in your path https://github.com/aria2/aria2
# 8. $env.Path = ($env.Path | append 'c:\path\to\aria2c')
# make sure you have the wixtools installed https://wixtoolset.org/
# 9. $env.Path = ($env.Path | append 'C:\Users\dschroeder\AppData\Local\tauri\WixTools')
# You need to run the release-pkg twice. The first pass, with _EXTRA_ as 'bin', makes the output
# folder and builds everything. The second pass, that generates the msi file, with _EXTRA_ as 'msi'
# 10. $env._EXTRA_ = 'bin'
# 11. source .github\workflows\release-pkg.nu
# 12. cd ..
# 13. $env._EXTRA_ = 'msi'
# 14. source .github\workflows\release-pkg.nu
# make sure you have the wix 6.0 installed: dotnet tool install --global wix --version 6.0.0
# then build nu*.exe and the MSI installer by running:
# 9. source .github\workflows\release-pkg.nu
# After msi is generated, you have to update winget-pkgs repo, you'll need to patch the release
# by deleting the existing msi and uploading this new msi. Then you'll need to update the hash
# on the winget-pkgs PR. To generate the hash, run this command
# 15. open target\wix\nu-0.74.0-x86_64-pc-windows-msvc.msi | hash sha256
# 10. open wix\bin\x64\Release\nu-0.103.0-x86_64-pc-windows-msvc.msi | hash sha256
# Then, just take the output and put it in the winget-pkgs PR for the hash on the msi
@ -85,14 +79,14 @@ if $os in ['macos-latest'] or $USE_UBUNTU {
cargo-build-nu
}
'aarch64-unknown-linux-musl' => {
aria2c https://musl.cc/aarch64-linux-musl-cross.tgz
aria2c https://github.com/nushell/integrations/releases/download/build-tools/aarch64-linux-musl-cross.tgz
tar -xf aarch64-linux-musl-cross.tgz -C $env.HOME
$env.PATH = ($env.PATH | split row (char esep) | prepend $'($env.HOME)/aarch64-linux-musl-cross/bin')
$env.CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER = 'aarch64-linux-musl-gcc'
cargo-build-nu
}
'armv7-unknown-linux-musleabihf' => {
aria2c https://musl.cc/armv7r-linux-musleabihf-cross.tgz
aria2c https://github.com/nushell/integrations/releases/download/build-tools/armv7r-linux-musleabihf-cross.tgz
tar -xf armv7r-linux-musleabihf-cross.tgz -C $env.HOME
$env.PATH = ($env.PATH | split row (char esep) | prepend $'($env.HOME)/armv7r-linux-musleabihf-cross/bin')
$env.CARGO_TARGET_ARMV7_UNKNOWN_LINUX_MUSLEABIHF_LINKER = 'armv7r-linux-musleabihf-gcc'
@ -175,37 +169,13 @@ if $os in ['macos-latest'] or $USE_UBUNTU {
tar -czf $archive $dest
print $'archive: ---> ($archive)'; ls $archive
# REF: https://github.blog/changelog/2022-10-11-github-actions-deprecating-save-state-and-set-output-commands/
echo $"archive=($archive)" | save --append $env.GITHUB_OUTPUT
echo $"archive=($archive)(char nl)" o>> $env.GITHUB_OUTPUT
} else if $os =~ 'windows' {
let releaseStem = $'($bin)-($version)-($target)'
print $'(char nl)Download less related stuffs...'; hr-line
# todo: less-v661 is out but is released as a zip file. maybe we should switch to that and extract it?
aria2c https://github.com/jftuga/less-Windows/releases/download/less-v608/less.exe -o less.exe
# the below was renamed because it was failing to download for darren. it should work but it wasn't
# todo: maybe we should get rid of this aria2c dependency and just use http get?
#aria2c https://raw.githubusercontent.com/jftuga/less-Windows/master/LICENSE -o LICENSE-for-less.txt
aria2c https://github.com/jftuga/less-Windows/blob/master/LICENSE -o LICENSE-for-less.txt
# Create Windows msi release package
if (get-env _EXTRA_) == 'msi' {
let wixRelease = $'($src)/target/wix/($releaseStem).msi'
print $'(char nl)Start creating Windows msi package with the following contents...'
cd $src; hr-line
# Wix need the binaries be stored in target/release/
cp -r ($'($dist)/*' | into glob) target/release/
ls target/release/* | print
cargo install cargo-wix --version 0.3.8
cargo wix --no-build --nocapture --package nu --output $wixRelease
# Workaround for https://github.com/softprops/action-gh-release/issues/280
let archive = ($wixRelease | str replace --all '\' '/')
print $'archive: ---> ($archive)';
echo $"archive=($archive)" | save --append $env.GITHUB_OUTPUT
} else {
let arch = if $nu.os-info.arch =~ 'x86_64' { 'x64' } else { 'arm64' }
fetch-less $arch
print $'(char nl)(ansi g)Archive contents:(ansi reset)'; hr-line; ls | print
let archive = $'($dist)/($releaseStem).zip'
@ -215,9 +185,40 @@ if $os in ['macos-latest'] or $USE_UBUNTU {
# Workaround for https://github.com/softprops/action-gh-release/issues/280
let archive = ($pkg | get 0 | str replace --all '\' '/')
print $'archive: ---> ($archive)'
echo $"archive=($archive)" | save --append $env.GITHUB_OUTPUT
echo $"archive=($archive)(char nl)" o>> $env.GITHUB_OUTPUT
}
# Create extra Windows msi release package if dotnet and wix are available
let installed = [dotnet wix] | all { (which $in | length) > 0 }
if $installed and (wix --version | split row . | first | into int) >= 6 {
print $'(char nl)Start creating Windows msi package with the following contents...'
cd $src; cd wix; hr-line; mkdir nu
# Wix need the binaries be stored in nu folder
cp -r ($'($dist)/*' | into glob) nu/
cp $'($dist)/README.txt' .
ls -f nu/* | print
./nu/nu.exe -c $'NU_RELEASE_VERSION=($version) dotnet build -c Release -p:Platform=($arch)'
glob **/*.msi | print
# Workaround for https://github.com/softprops/action-gh-release/issues/280
let wixRelease = (glob **/*.msi | where $it =~ bin | get 0 | str replace --all '\' '/')
let msi = $'($wixRelease | path dirname)/nu-($version)-($target).msi'
mv $wixRelease $msi
print $'MSI archive: ---> ($msi)';
echo $"msi=($msi)(char nl)" o>> $env.GITHUB_OUTPUT
}
}
def fetch-less [
arch: string = 'x64' # The architecture to fetch
] {
let less_zip = $'less-($arch).zip'
print $'Fetching less archive: (ansi g)($less_zip)(ansi reset)'
let url = $'https://github.com/jftuga/less-Windows/releases/download/less-v668/($less_zip)'
http get https://github.com/jftuga/less-Windows/blob/master/LICENSE | save -rf LICENSE-for-less.txt
http get $url | save -rf $less_zip
unzip $less_zip
rm $less_zip lesskey.exe
}
def 'cargo-build-nu' [] {

View File

@ -35,24 +35,15 @@ jobs:
- armv7-unknown-linux-musleabihf
- riscv64gc-unknown-linux-gnu
- loongarch64-unknown-linux-gnu
extra: ['bin']
include:
- target: aarch64-apple-darwin
os: macos-latest
- target: x86_64-apple-darwin
os: macos-latest
- target: x86_64-pc-windows-msvc
extra: 'bin'
os: windows-latest
- target: x86_64-pc-windows-msvc
extra: msi
os: windows-latest
- target: aarch64-pc-windows-msvc
extra: 'bin'
os: windows-latest
- target: aarch64-pc-windows-msvc
extra: msi
os: windows-latest
os: windows-11-arm
- target: x86_64-unknown-linux-gnu
os: ubuntu-22.04
- target: x86_64-unknown-linux-musl
@ -75,12 +66,23 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: Install Wix Toolset 6 for Windows
shell: pwsh
if: ${{ startsWith(matrix.os, 'windows') }}
run: |
dotnet tool install --global wix --version 6.0.0
dotnet workload install wix
$wixPath = "$env:USERPROFILE\.dotnet\tools"
echo "$wixPath" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
$env:PATH = "$wixPath;$env:PATH"
wix --version
- name: Update Rust Toolchain Target
run: |
echo "targets = ['${{matrix.target}}']" >> rust-toolchain.toml
- name: Setup Rust toolchain
uses: actions-rust-lang/setup-rust-toolchain@v1.11.0
uses: actions-rust-lang/setup-rust-toolchain@v1.12.0
# WARN: Keep the rustflags to prevent from the winget submission error: `CAQuietExec: Error 0xc0000135`
with:
cache: false
@ -88,17 +90,31 @@ jobs:
- name: Setup Nushell
uses: hustcer/setup-nu@v3
if: ${{ matrix.os != 'windows-11-arm' }}
with:
version: 0.103.0
- name: Release Nu Binary
id: nu
if: ${{ matrix.os != 'windows-11-arm' }}
run: nu .github/workflows/release-pkg.nu
env:
OS: ${{ matrix.os }}
REF: ${{ github.ref }}
TARGET: ${{ matrix.target }}
_EXTRA_: ${{ matrix.extra }}
- name: Build Nu for Windows ARM64
id: nu0
shell: pwsh
if: ${{ matrix.os == 'windows-11-arm' }}
run: |
$env:OS = 'windows'
$env:REF = '${{ github.ref }}'
$env:TARGET = '${{ matrix.target }}'
cargo build --release --all --target aarch64-pc-windows-msvc
cp ./target/${{ matrix.target }}/release/nu.exe .
./nu.exe -c 'version'
./nu.exe ${{github.workspace}}/.github/workflows/release-pkg.nu
# WARN: Don't upgrade this action due to the release per asset issue.
# See: https://github.com/softprops/action-gh-release/issues/445
@ -107,7 +123,11 @@ jobs:
if: ${{ startsWith(github.ref, 'refs/tags/') }}
with:
draft: true
files: ${{ steps.nu.outputs.archive }}
files: |
${{ steps.nu.outputs.msi }}
${{ steps.nu0.outputs.msi }}
${{ steps.nu.outputs.archive }}
${{ steps.nu0.outputs.archive }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@ -10,4 +10,4 @@ jobs:
uses: actions/checkout@v4.1.7
- name: Check spelling
uses: crate-ci/typos@v1.31.1
uses: crate-ci/typos@v1.33.1

View File

@ -10,6 +10,11 @@ on:
required: true
type: string
permissions:
contents: write
packages: write
pull-requests: write
jobs:
winget:
@ -26,4 +31,4 @@ jobs:
version: ${{ inputs.tag_name || github.event.release.tag_name }}
release-tag: ${{ inputs.tag_name || github.event.release.tag_name }}
token: ${{ secrets.NUSHELL_PAT }}
fork-user: fdncred
fork-user: nushell

View File

@ -31,7 +31,7 @@ The review process can be summarized as follows:
1. You want to make some change to Nushell that is more involved than simple bug-fixing.
2. Go to [Discord](https://discordapp.com/invite/NtAbbGn) or a [GitHub issue](https://github.com/nushell/nushell/issues/new/choose) and chat with some core team members and/or other contributors about it.
3. After getting a green light from the core team, implement the feature, open a pull request (PR) and write a concise but comprehensive description of the change.
4. If your PR includes any use-facing features (such as adding a flag to a command), clearly list them in the PR description.
4. If your PR includes any user-facing features (such as adding a flag to a command), clearly list them in the PR description.
5. Then, core team members and other regular contributors will review the PR and suggest changes.
6. When we all agree, the PR will be merged.
7. If your PR includes any user-facing features, make sure the changes are also reflected in [the documentation](https://github.com/nushell/nushell.github.io) after the PR is merged.

569
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -4,14 +4,14 @@ build = "scripts/build.rs"
default-run = "nu"
description = "A new type of shell"
documentation = "https://www.nushell.sh/book/"
edition = "2021"
edition = "2024"
exclude = ["images"]
homepage = "https://www.nushell.sh"
license = "MIT"
name = "nu"
repository = "https://github.com/nushell/nushell"
rust-version = "1.84.1"
version = "0.104.1"
rust-version = "1.85.1"
version = "0.105.2"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@ -63,15 +63,15 @@ members = [
[workspace.dependencies]
alphanumeric-sort = "1.5"
ansi-str = "0.8"
ansi-str = "0.9"
anyhow = "1.0.82"
base64 = "0.22.1"
bracoxide = "0.1.5"
bracoxide = "0.1.6"
brotli = "7.0"
byteorder = "1.5"
bytes = "1"
bytesize = "1.3.3"
calamine = "0.27"
calamine = "0.26"
chardetng = "0.1.17"
chrono = { default-features = false, version = "0.4.34" }
chrono-humanize = "0.2.3"
@ -96,18 +96,18 @@ indexmap = "2.9"
indicatif = "0.17"
interprocess = "2.2.0"
is_executable = "1.0"
itertools = "0.13"
itertools = "0.14"
libc = "0.2"
libproc = "0.14"
log = "0.4"
lru = "0.12"
lscolors = { version = "0.17", default-features = false }
lscolors = { version = "0.20", default-features = false }
lsp-server = "0.7.8"
lsp-types = { version = "0.97.0", features = ["proposed"] }
lsp-textdocument = "0.4.2"
mach2 = "0.4"
md5 = { version = "0.10", package = "md-5" }
miette = "7.5"
miette = "7.6"
mime = "0.3.17"
mime_guess = "2.0"
mockito = { version = "1.7", default-features = false }
@ -133,7 +133,7 @@ procfs = "0.17.0"
pwd = "1.3"
quick-xml = "0.37.0"
quickcheck = "1.0"
quickcheck_macros = "1.0"
quickcheck_macros = "1.1"
quote = "1.0"
rand = "0.9"
getrandom = "0.2" # pick same version that rand requires
@ -148,6 +148,8 @@ rstest = { version = "0.23", default-features = false }
rstest_reuse = "0.7"
rusqlite = "0.31"
rust-embed = "8.7.0"
rustls = { version = "0.23", default-features = false, features = ["std", "tls12"] }
rustls-native-certs = "0.8"
scopeguard = { version = "1.2.0" }
serde = { version = "1.0" }
serde_json = "1.0.97"
@ -159,12 +161,12 @@ strum = "0.26"
strum_macros = "0.26"
syn = "2.0"
sysinfo = "0.33"
tabled = { version = "0.17.0", default-features = false }
tempfile = "3.15"
titlecase = "3.5"
tabled = { version = "0.20", default-features = false }
tempfile = "3.20"
titlecase = "3.6"
toml = "0.8"
trash = "5.2"
update-informer = { version = "1.2.0", default-features = false, features = ["github", "native-tls", "ureq"] }
update-informer = { version = "1.2.0", default-features = false, features = ["github", "ureq"] }
umask = "2.1"
unicode-segmentation = "1.12"
unicode-width = "0.2"
@ -182,11 +184,12 @@ uuid = "1.16.0"
v_htmlescape = "0.15.0"
wax = "0.6"
web-time = "1.1.0"
which = "7.0.0"
which = "7.0.3"
windows = "0.56"
windows-sys = "0.48"
winreg = "0.52"
memchr = "2.7.4"
webpki-roots = "1.0"
[workspace.lints.clippy]
# Warning: workspace lints affect library code as well as tests, so don't enable lints that would be too noisy in tests like that.
@ -197,22 +200,22 @@ unchecked_duration_subtraction = "warn"
workspace = true
[dependencies]
nu-cli = { path = "./crates/nu-cli", version = "0.104.1" }
nu-cmd-base = { path = "./crates/nu-cmd-base", version = "0.104.1" }
nu-cmd-lang = { path = "./crates/nu-cmd-lang", version = "0.104.1" }
nu-cmd-plugin = { path = "./crates/nu-cmd-plugin", version = "0.104.1", optional = true }
nu-cmd-extra = { path = "./crates/nu-cmd-extra", version = "0.104.1" }
nu-command = { path = "./crates/nu-command", version = "0.104.1" }
nu-engine = { path = "./crates/nu-engine", version = "0.104.1" }
nu-explore = { path = "./crates/nu-explore", version = "0.104.1" }
nu-lsp = { path = "./crates/nu-lsp/", version = "0.104.1" }
nu-parser = { path = "./crates/nu-parser", version = "0.104.1" }
nu-path = { path = "./crates/nu-path", version = "0.104.1" }
nu-plugin-engine = { path = "./crates/nu-plugin-engine", optional = true, version = "0.104.1" }
nu-protocol = { path = "./crates/nu-protocol", version = "0.104.1" }
nu-std = { path = "./crates/nu-std", version = "0.104.1" }
nu-system = { path = "./crates/nu-system", version = "0.104.1" }
nu-utils = { path = "./crates/nu-utils", version = "0.104.1" }
nu-cli = { path = "./crates/nu-cli", version = "0.105.2" }
nu-cmd-base = { path = "./crates/nu-cmd-base", version = "0.105.2" }
nu-cmd-lang = { path = "./crates/nu-cmd-lang", version = "0.105.2" }
nu-cmd-plugin = { path = "./crates/nu-cmd-plugin", version = "0.105.2", optional = true }
nu-cmd-extra = { path = "./crates/nu-cmd-extra", version = "0.105.2" }
nu-command = { path = "./crates/nu-command", version = "0.105.2", default-features = false, features = ["os"] }
nu-engine = { path = "./crates/nu-engine", version = "0.105.2" }
nu-explore = { path = "./crates/nu-explore", version = "0.105.2" }
nu-lsp = { path = "./crates/nu-lsp/", version = "0.105.2" }
nu-parser = { path = "./crates/nu-parser", version = "0.105.2" }
nu-path = { path = "./crates/nu-path", version = "0.105.2" }
nu-plugin-engine = { path = "./crates/nu-plugin-engine", optional = true, version = "0.105.2" }
nu-protocol = { path = "./crates/nu-protocol", version = "0.105.2" }
nu-std = { path = "./crates/nu-std", version = "0.105.2" }
nu-system = { path = "./crates/nu-system", version = "0.105.2" }
nu-utils = { path = "./crates/nu-utils", version = "0.105.2" }
reedline = { workspace = true, features = ["bashisms", "sqlite"] }
crossterm = { workspace = true }
@ -241,9 +244,9 @@ nix = { workspace = true, default-features = false, features = [
] }
[dev-dependencies]
nu-test-support = { path = "./crates/nu-test-support", version = "0.104.1" }
nu-plugin-protocol = { path = "./crates/nu-plugin-protocol", version = "0.104.1" }
nu-plugin-core = { path = "./crates/nu-plugin-core", version = "0.104.1" }
nu-test-support = { path = "./crates/nu-test-support", version = "0.105.2" }
nu-plugin-protocol = { path = "./crates/nu-plugin-protocol", version = "0.105.2" }
nu-plugin-core = { path = "./crates/nu-plugin-core", version = "0.105.2" }
assert_cmd = "2.0"
dirs = { workspace = true }
tango-bench = "0.6"
@ -269,10 +272,14 @@ plugin = [
"nu-protocol/plugin",
]
native-tls = ["nu-command/native-tls"]
rustls-tls = ["nu-command/rustls-tls"]
default = [
"plugin",
"trash-support",
"sqlite",
"rustls-tls"
]
stable = ["default"]
# NOTE: individual features are also passed to `nu-cmd-lang` that uses them to generate the feature matrix in the `version` command

View File

@ -222,6 +222,7 @@ Please submit an issue or PR to be added to this list.
- [Dorothy](http://github.com/bevry/dorothy)
- [Direnv](https://github.com/direnv/direnv/blob/master/docs/hook.md#nushell)
- [x-cmd](https://x-cmd.com/mod/nu)
- [vfox](https://github.com/version-fox/vfox)
## Contributing

View File

@ -2,8 +2,8 @@ use nu_cli::{eval_source, evaluate_commands};
use nu_plugin_core::{Encoder, EncodingType};
use nu_plugin_protocol::{PluginCallResponse, PluginOutput};
use nu_protocol::{
engine::{EngineState, Stack},
PipelineData, Signals, Span, Spanned, Value,
engine::{EngineState, Stack},
};
use nu_std::load_standard_library;
use nu_utils::{get_default_config, get_default_env};
@ -11,9 +11,9 @@ use std::{
fmt::Write,
hint::black_box,
rc::Rc,
sync::{atomic::AtomicBool, Arc},
sync::{Arc, atomic::AtomicBool},
};
use tango_bench::{benchmark_fn, tango_benchmarks, tango_main, IntoBenchmarks};
use tango_bench::{IntoBenchmarks, benchmark_fn, tango_benchmarks, tango_main};
fn load_bench_commands() -> EngineState {
nu_command::add_shell_command_context(nu_cmd_lang::create_default_context())
@ -68,14 +68,14 @@ fn encoding_test_data(row_cnt: usize, col_cnt: usize) -> Value {
}
fn bench_command(
name: &str,
command: &str,
name: impl Into<String>,
command: impl Into<String> + Clone,
stack: Stack,
engine: EngineState,
) -> impl IntoBenchmarks {
let commands = Spanned {
span: Span::unknown(),
item: command.to_string(),
item: command.into(),
};
[benchmark_fn(name, move |b| {
let commands = commands.clone();
@ -175,8 +175,8 @@ fn create_example_table_nrows(n: usize) -> String {
fn bench_record_create(n: usize) -> impl IntoBenchmarks {
bench_command(
&format!("record_create_{n}"),
&create_flat_record_string(n),
format!("record_create_{n}"),
create_flat_record_string(n),
Stack::new(),
setup_engine(),
)
@ -186,7 +186,7 @@ fn bench_record_flat_access(n: usize) -> impl IntoBenchmarks {
let setup_command = create_flat_record_string(n);
let (stack, engine) = setup_stack_and_engine_from_command(&setup_command);
bench_command(
&format!("record_flat_access_{n}"),
format!("record_flat_access_{n}"),
"$record.col_0 | ignore",
stack,
engine,
@ -198,8 +198,8 @@ fn bench_record_nested_access(n: usize) -> impl IntoBenchmarks {
let (stack, engine) = setup_stack_and_engine_from_command(&setup_command);
let nested_access = ".col".repeat(n);
bench_command(
&format!("record_nested_access_{n}"),
&format!("$record{} | ignore", nested_access),
format!("record_nested_access_{n}"),
format!("$record{} | ignore", nested_access),
stack,
engine,
)
@ -213,13 +213,13 @@ fn bench_record_insert(n: usize, m: usize) -> impl IntoBenchmarks {
write!(insert, " | insert col_{i} {i}").unwrap();
}
insert.push_str(" | ignore");
bench_command(&format!("record_insert_{n}_{m}"), &insert, stack, engine)
bench_command(format!("record_insert_{n}_{m}"), insert, stack, engine)
}
fn bench_table_create(n: usize) -> impl IntoBenchmarks {
bench_command(
&format!("table_create_{n}"),
&create_example_table_nrows(n),
format!("table_create_{n}"),
create_example_table_nrows(n),
Stack::new(),
setup_engine(),
)
@ -229,7 +229,7 @@ fn bench_table_get(n: usize) -> impl IntoBenchmarks {
let setup_command = create_example_table_nrows(n);
let (stack, engine) = setup_stack_and_engine_from_command(&setup_command);
bench_command(
&format!("table_get_{n}"),
format!("table_get_{n}"),
"$table | get bar | math sum | ignore",
stack,
engine,
@ -240,7 +240,7 @@ fn bench_table_select(n: usize) -> impl IntoBenchmarks {
let setup_command = create_example_table_nrows(n);
let (stack, engine) = setup_stack_and_engine_from_command(&setup_command);
bench_command(
&format!("table_select_{n}"),
format!("table_select_{n}"),
"$table | select foo baz | ignore",
stack,
engine,
@ -255,7 +255,7 @@ fn bench_table_insert_row(n: usize, m: usize) -> impl IntoBenchmarks {
write!(insert, " | insert {i} {{ foo: 0, bar: 1, baz: {i} }}").unwrap();
}
insert.push_str(" | ignore");
bench_command(&format!("table_insert_row_{n}_{m}"), &insert, stack, engine)
bench_command(format!("table_insert_row_{n}_{m}"), insert, stack, engine)
}
fn bench_table_insert_col(n: usize, m: usize) -> impl IntoBenchmarks {
@ -266,15 +266,15 @@ fn bench_table_insert_col(n: usize, m: usize) -> impl IntoBenchmarks {
write!(insert, " | insert col_{i} {i}").unwrap();
}
insert.push_str(" | ignore");
bench_command(&format!("table_insert_col_{n}_{m}"), &insert, stack, engine)
bench_command(format!("table_insert_col_{n}_{m}"), insert, stack, engine)
}
fn bench_eval_interleave(n: usize) -> impl IntoBenchmarks {
let engine = setup_engine();
let stack = Stack::new();
bench_command(
&format!("eval_interleave_{n}"),
&format!("seq 1 {n} | wrap a | interleave {{ seq 1 {n} | wrap b }} | ignore"),
format!("eval_interleave_{n}"),
format!("seq 1 {n} | wrap a | interleave {{ seq 1 {n} | wrap b }} | ignore"),
stack,
engine,
)
@ -285,8 +285,8 @@ fn bench_eval_interleave_with_interrupt(n: usize) -> impl IntoBenchmarks {
engine.set_signals(Signals::new(Arc::new(AtomicBool::new(false))));
let stack = Stack::new();
bench_command(
&format!("eval_interleave_with_interrupt_{n}"),
&format!("seq 1 {n} | wrap a | interleave {{ seq 1 {n} | wrap b }} | ignore"),
format!("eval_interleave_with_interrupt_{n}"),
format!("seq 1 {n} | wrap a | interleave {{ seq 1 {n} | wrap b }} | ignore"),
stack,
engine,
)
@ -296,8 +296,8 @@ fn bench_eval_for(n: usize) -> impl IntoBenchmarks {
let engine = setup_engine();
let stack = Stack::new();
bench_command(
&format!("eval_for_{n}"),
&format!("(for $x in (1..{n}) {{ 1 }}) | ignore"),
format!("eval_for_{n}"),
format!("(for $x in (1..{n}) {{ 1 }}) | ignore"),
stack,
engine,
)
@ -307,8 +307,8 @@ fn bench_eval_each(n: usize) -> impl IntoBenchmarks {
let engine = setup_engine();
let stack = Stack::new();
bench_command(
&format!("eval_each_{n}"),
&format!("(1..{n}) | each {{|_| 1 }} | ignore"),
format!("eval_each_{n}"),
format!("(1..{n}) | each {{|_| 1 }} | ignore"),
stack,
engine,
)
@ -318,8 +318,8 @@ fn bench_eval_par_each(n: usize) -> impl IntoBenchmarks {
let engine = setup_engine();
let stack = Stack::new();
bench_command(
&format!("eval_par_each_{n}"),
&format!("(1..{}) | par-each -t 2 {{|_| 1 }} | ignore", n),
format!("eval_par_each_{n}"),
format!("(1..{}) | par-each -t 2 {{|_| 1 }} | ignore", n),
stack,
engine,
)

View File

@ -2,32 +2,32 @@
authors = ["The Nushell Project Developers"]
description = "CLI-related functionality for Nushell"
repository = "https://github.com/nushell/nushell/tree/main/crates/nu-cli"
edition = "2021"
edition = "2024"
license = "MIT"
name = "nu-cli"
version = "0.104.1"
version = "0.105.2"
[lib]
bench = false
[dev-dependencies]
nu-cmd-lang = { path = "../nu-cmd-lang", version = "0.104.1" }
nu-command = { path = "../nu-command", version = "0.104.1" }
nu-std = { path = "../nu-std", version = "0.104.1" }
nu-test-support = { path = "../nu-test-support", version = "0.104.1" }
nu-cmd-lang = { path = "../nu-cmd-lang", version = "0.105.2" }
nu-command = { path = "../nu-command", version = "0.105.2" }
nu-std = { path = "../nu-std", version = "0.105.2" }
nu-test-support = { path = "../nu-test-support", version = "0.105.2" }
rstest = { workspace = true, default-features = false }
tempfile = { workspace = true }
[dependencies]
nu-cmd-base = { path = "../nu-cmd-base", version = "0.104.1" }
nu-engine = { path = "../nu-engine", version = "0.104.1", features = ["os"] }
nu-glob = { path = "../nu-glob", version = "0.104.1" }
nu-path = { path = "../nu-path", version = "0.104.1" }
nu-parser = { path = "../nu-parser", version = "0.104.1" }
nu-plugin-engine = { path = "../nu-plugin-engine", version = "0.104.1", optional = true }
nu-protocol = { path = "../nu-protocol", version = "0.104.1", features = ["os"] }
nu-utils = { path = "../nu-utils", version = "0.104.1" }
nu-color-config = { path = "../nu-color-config", version = "0.104.1" }
nu-cmd-base = { path = "../nu-cmd-base", version = "0.105.2" }
nu-engine = { path = "../nu-engine", version = "0.105.2", features = ["os"] }
nu-glob = { path = "../nu-glob", version = "0.105.2" }
nu-path = { path = "../nu-path", version = "0.105.2" }
nu-parser = { path = "../nu-parser", version = "0.105.2" }
nu-plugin-engine = { path = "../nu-plugin-engine", version = "0.105.2", optional = true }
nu-protocol = { path = "../nu-protocol", version = "0.105.2", features = ["os"] }
nu-utils = { path = "../nu-utils", version = "0.105.2" }
nu-color-config = { path = "../nu-color-config", version = "0.105.2" }
nu-ansi-term = { workspace = true }
reedline = { workspace = true, features = ["bashisms", "sqlite"] }

View File

@ -1,5 +1,8 @@
use nu_engine::command_prelude::*;
use nu_protocol::{shell_error::io::IoError, HistoryFileFormat};
use nu_protocol::{
HistoryFileFormat,
shell_error::{self, io::IoError},
};
use reedline::{
FileBackedHistory, History as ReedlineHistory, HistoryItem, SearchDirection, SearchQuery,
SqliteBackedHistory,
@ -94,7 +97,7 @@ impl Command for History {
})
})
.ok_or(IoError::new(
std::io::ErrorKind::NotFound,
shell_error::io::ErrorKind::FileNotFound,
head,
history_path,
))?
@ -110,7 +113,7 @@ impl Command for History {
})
})
.ok_or(IoError::new(
std::io::ErrorKind::NotFound,
shell_error::io::ErrorKind::FileNotFound,
head,
history_path,
))?

View File

@ -2,8 +2,8 @@ use std::path::{Path, PathBuf};
use nu_engine::command_prelude::*;
use nu_protocol::{
shell_error::{self, io::IoError},
HistoryFileFormat,
shell_error::{self, io::IoError},
};
use reedline::{
@ -26,7 +26,7 @@ impl Command for HistoryImport {
fn extra_description(&self) -> &str {
r#"Can import history from input, either successive command lines or more detailed records. If providing records, available fields are:
command_line, id, start_timestamp, hostname, cwd, duration, exit_status.
command, start_timestamp, hostname, cwd, duration, exit_status.
If no input is provided, will import all history items from existing history in the other format: if current history is stored in sqlite, it will store it in plain text and vice versa.
@ -48,8 +48,7 @@ Note that history item IDs are ignored when importing from file."#
vec![
Example {
example: "history import",
description:
"Append all items from history in the other format to the current history",
description: "Append all items from history in the other format to the current history",
result: None,
},
Example {
@ -198,7 +197,7 @@ fn item_from_record(mut rec: Record, span: Span) -> Result<HistoryItem, ShellErr
return Err(ShellError::TypeMismatch {
err_message: format!("missing column: {}", fields::COMMAND_LINE),
span,
})
});
}
};
@ -283,22 +282,22 @@ fn backup(path: &Path, span: Span) -> Result<Option<PathBuf>, ShellError> {
PathBuf::from(path),
"history path exists but is not a file",
)
.into())
.into());
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => {
return Err(IoError::new_internal(
e.kind(),
e,
"Could not get metadata",
nu_protocol::location!(),
)
.into())
.into());
}
}
let bak_path = find_backup_path(path, span)?;
std::fs::copy(path, &bak_path).map_err(|err| {
IoError::new_internal(
err.kind(),
err.not_found_as(NotFound::File),
"Could not copy backup",
nu_protocol::location!(),
)

View File

@ -1,9 +1,9 @@
use crossterm::{
event::Event, event::KeyCode, event::KeyEvent, execute, terminal, QueueableCommand,
QueueableCommand, event::Event, event::KeyCode, event::KeyEvent, execute, terminal,
};
use nu_engine::command_prelude::*;
use nu_protocol::shell_error::io::IoError;
use std::io::{stdout, Write};
use std::io::{Write, stdout};
#[derive(Clone)]
pub struct KeybindingsListen;
@ -42,7 +42,7 @@ impl Command for KeybindingsListen {
Err(e) => {
terminal::disable_raw_mode().map_err(|err| {
IoError::new_internal(
err.kind(),
err,
"Could not disable raw mode",
nu_protocol::location!(),
)
@ -71,18 +71,10 @@ pub fn print_events(engine_state: &EngineState) -> Result<Value, ShellError> {
let config = engine_state.get_config();
stdout().flush().map_err(|err| {
IoError::new_internal(
err.kind(),
"Could not flush stdout",
nu_protocol::location!(),
)
IoError::new_internal(err, "Could not flush stdout", nu_protocol::location!())
})?;
terminal::enable_raw_mode().map_err(|err| {
IoError::new_internal(
err.kind(),
"Could not enable raw mode",
nu_protocol::location!(),
)
IoError::new_internal(err, "Could not enable raw mode", nu_protocol::location!())
})?;
if config.use_kitty_protocol {
@ -114,7 +106,7 @@ pub fn print_events(engine_state: &EngineState) -> Result<Value, ShellError> {
loop {
let event = crossterm::event::read().map_err(|err| {
IoError::new_internal(err.kind(), "Could not read event", nu_protocol::location!())
IoError::new_internal(err, "Could not read event", nu_protocol::location!())
})?;
if event == Event::Key(KeyCode::Esc.into()) {
break;
@ -136,7 +128,7 @@ pub fn print_events(engine_state: &EngineState) -> Result<Value, ShellError> {
};
stdout.queue(crossterm::style::Print(o)).map_err(|err| {
IoError::new_internal(
err.kind(),
err,
"Could not print output record",
nu_protocol::location!(),
)
@ -144,14 +136,10 @@ pub fn print_events(engine_state: &EngineState) -> Result<Value, ShellError> {
stdout
.queue(crossterm::style::Print("\r\n"))
.map_err(|err| {
IoError::new_internal(
err.kind(),
"Could not print linebreak",
nu_protocol::location!(),
)
IoError::new_internal(err, "Could not print linebreak", nu_protocol::location!())
})?;
stdout.flush().map_err(|err| {
IoError::new_internal(err.kind(), "Could not flush", nu_protocol::location!())
IoError::new_internal(err, "Could not flush", nu_protocol::location!())
})?;
}
@ -163,11 +151,7 @@ pub fn print_events(engine_state: &EngineState) -> Result<Value, ShellError> {
}
terminal::disable_raw_mode().map_err(|err| {
IoError::new_internal(
err.kind(),
"Could not disable raw mode",
nu_protocol::location!(),
)
IoError::new_internal(err, "Could not disable raw mode", nu_protocol::location!())
})?;
Ok(Value::nothing(Span::unknown()))

View File

@ -1,11 +1,11 @@
use super::{completion_options::NuMatcher, SemanticSuggestion};
use super::{SemanticSuggestion, completion_options::NuMatcher};
use crate::{
completions::{Completer, CompletionOptions},
SuggestionKind,
completions::{Completer, CompletionOptions},
};
use nu_protocol::{
engine::{Stack, StateWorkingSet},
Span,
engine::{Stack, StateWorkingSet},
};
use reedline::Suggestion;
@ -33,13 +33,12 @@ impl Completer for AttributeCompletion {
suggestion: Suggestion {
value: String::from_utf8_lossy(name).into_owned(),
description: desc,
style: None,
extra: None,
span: reedline::Span {
start: span.start - offset,
end: span.end - offset,
},
append_whitespace: false,
..Default::default()
},
kind: Some(SuggestionKind::Command(ty, Some(decl_id))),
});
@ -70,13 +69,12 @@ impl Completer for AttributableCompletion {
suggestion: Suggestion {
value: cmd.name().into(),
description: Some(cmd.description().into()),
style: None,
extra: None,
span: reedline::Span {
start: span.start - offset,
end: span.end - offset,
},
append_whitespace: false,
..Default::default()
},
kind: Some(SuggestionKind::Command(cmd.command_type(), None)),
});

View File

@ -1,7 +1,7 @@
use crate::completions::CompletionOptions;
use nu_protocol::{
engine::{Stack, StateWorkingSet},
DeclId, Span,
engine::{Stack, StateWorkingSet},
};
use reedline::Suggestion;

View File

@ -1,10 +1,12 @@
use std::borrow::Cow;
use crate::completions::{Completer, CompletionOptions, SemanticSuggestion, SuggestionKind};
use nu_engine::{column::get_columns, eval_variable};
use nu_protocol::{
ShellError, Span, Value,
ast::{Expr, Expression, FullCellPath, PathMember},
engine::{Stack, StateWorkingSet},
eval_const::eval_constant,
ShellError, Span, Value,
};
use reedline::Suggestion;
@ -101,7 +103,9 @@ pub(crate) fn eval_cell_path(
} else {
eval_constant(working_set, head)
}?;
head_value.follow_cell_path(path_members, false)
head_value
.follow_cell_path(path_members)
.map(Cow::into_owned)
}
fn get_suggestions_by_value(

View File

@ -1,16 +1,16 @@
use std::collections::HashMap;
use crate::{
completions::{Completer, CompletionOptions},
SuggestionKind,
completions::{Completer, CompletionOptions},
};
use nu_protocol::{
engine::{CommandType, Stack, StateWorkingSet},
Span,
engine::{CommandType, Stack, StateWorkingSet},
};
use reedline::Suggestion;
use super::{completion_options::NuMatcher, SemanticSuggestion};
use super::{SemanticSuggestion, completion_options::NuMatcher};
pub struct CommandCompletion {
/// Whether to include internal commands

View File

@ -1,17 +1,17 @@
use crate::completions::{
base::{SemanticSuggestion, SuggestionKind},
AttributableCompletion, AttributeCompletion, CellPathCompletion, CommandCompletion, Completer,
CompletionOptions, CustomCompletion, DirectoryCompletion, DotNuCompletion,
ExportableCompletion, FileCompletion, FlagCompletion, OperatorCompletion, VariableCompletion,
base::{SemanticSuggestion, SuggestionKind},
};
use nu_color_config::{color_record_to_nustyle, lookup_ansi_color_style};
use nu_engine::eval_block;
use nu_parser::{flatten_expression, parse, parse_module_file_or_dir};
use nu_protocol::{
PipelineData, Span, Type, Value,
ast::{Argument, Block, Expr, Expression, FindMapResult, ListItem, Traverse},
debugger::WithoutDebug,
engine::{Closure, EngineState, Stack, StateWorkingSet},
PipelineData, Span, Type, Value,
};
use reedline::{Completer as ReedlineCompleter, Suggestion};
use std::sync::Arc;

View File

@ -1,16 +1,16 @@
use super::{completion_options::NuMatcher, MatchAlgorithm};
use super::{MatchAlgorithm, completion_options::NuMatcher};
use crate::completions::CompletionOptions;
use nu_ansi_term::Style;
use nu_engine::env_to_string;
use nu_path::dots::expand_ndots;
use nu_path::{expand_to_real_path, home_dir};
use nu_protocol::{
engine::{EngineState, Stack, StateWorkingSet},
Span,
engine::{EngineState, Stack, StateWorkingSet},
};
use nu_utils::get_ls_colors;
use nu_utils::IgnoreCaseExt;
use std::path::{is_separator, Component, Path, PathBuf, MAIN_SEPARATOR as SEP};
use nu_utils::get_ls_colors;
use std::path::{Component, MAIN_SEPARATOR as SEP, Path, PathBuf, is_separator};
#[derive(Clone, Default)]
pub struct PathBuiltFromString {
@ -39,8 +39,10 @@ fn complete_rec(
isdir: bool,
enable_exact_match: bool,
) -> Vec<PathBuiltFromString> {
let has_more = !partial.is_empty() && (partial.len() > 1 || isdir);
if let Some((&base, rest)) = partial.split_first() {
if base.chars().all(|c| c == '.') && (isdir || !rest.is_empty()) {
if base.chars().all(|c| c == '.') && has_more {
let built_paths: Vec<_> = built_paths
.iter()
.map(|built| {
@ -64,6 +66,9 @@ fn complete_rec(
let prefix = partial.first().unwrap_or(&"");
let mut matcher = NuMatcher::new(prefix, options);
let mut exact_match = None;
// Only relevant for case insensitive matching
let mut multiple_exact_matches = false;
for built in built_paths {
let mut path = built.cwd.clone();
for part in &built.parts {
@ -83,48 +88,56 @@ fn complete_rec(
built.isdir = entry_isdir && !entry.path().is_symlink();
if !want_directory || entry_isdir {
matcher.add(entry_name.clone(), (entry_name, built));
if enable_exact_match && !multiple_exact_matches && has_more {
let matches = if options.case_sensitive {
entry_name.eq(prefix)
} else {
entry_name.eq_ignore_case(prefix)
};
if matches {
if exact_match.is_none() {
exact_match = Some(built.clone());
} else {
multiple_exact_matches = true;
}
}
}
let mut completions = vec![];
for (entry_name, built) in matcher.results() {
match partial.split_first() {
Some((base, rest)) => {
// We use `isdir` to confirm that the current component has
// at least one next component or a slash.
// Serves as confirmation to ignore longer completions for
// components in between.
if !rest.is_empty() || isdir {
// Don't show longer completions if we have an exact match (#13204, #14794)
let exact_match = enable_exact_match
&& (if options.case_sensitive {
entry_name.eq(base)
} else {
entry_name.eq_ignore_case(base)
});
completions.extend(complete_rec(
rest,
matcher.add(entry_name, built);
}
}
}
// Don't show longer completions if we have a single exact match (#13204, #14794)
if !multiple_exact_matches {
if let Some(built) = exact_match {
return complete_rec(
&partial[1..],
&[built],
options,
want_directory,
isdir,
exact_match,
true,
);
}
}
if has_more {
let mut completions = vec![];
for built in matcher.results() {
completions.extend(complete_rec(
&partial[1..],
&[built],
options,
want_directory,
isdir,
false,
));
if exact_match {
break;
}
} else {
completions.push(built);
}
}
None => {
completions.push(built);
}
}
}
completions
} else {
matcher.results()
}
}
#[derive(Debug)]

View File

@ -2,8 +2,8 @@ use nu_parser::trim_quotes_str;
use nu_protocol::{CompletionAlgorithm, CompletionSort};
use nu_utils::IgnoreCaseExt;
use nucleo_matcher::{
pattern::{Atom, AtomKind, CaseMatching, Normalization},
Config, Matcher, Utf32Str,
pattern::{Atom, AtomKind, CaseMatching, Normalization},
};
use std::{borrow::Cow, fmt::Display};

View File

@ -1,13 +1,13 @@
use crate::completions::{
completer::map_value_completions, Completer, CompletionOptions, MatchAlgorithm,
SemanticSuggestion,
Completer, CompletionOptions, MatchAlgorithm, SemanticSuggestion,
completer::map_value_completions,
};
use nu_engine::eval_call;
use nu_protocol::{
DeclId, PipelineData, Span, Type, Value,
ast::{Argument, Call, Expr, Expression},
debugger::WithoutDebug,
engine::{EngineState, Stack, StateWorkingSet},
DeclId, PipelineData, Span, Type, Value,
};
use std::collections::HashMap;
@ -106,7 +106,9 @@ impl<T: Completer> Completer for CustomCompletion<T> {
let positional =
options.get("positional").and_then(|val| val.as_bool().ok());
if positional.is_some() {
log::warn!("Use of the positional option is deprecated. Use the substring match algorithm instead.");
log::warn!(
"Use of the positional option is deprecated. Use the substring match algorithm instead."
);
}
if let Some(algorithm) = options
.get("completion_algorithm")

View File

@ -1,15 +1,15 @@
use crate::completions::{
completion_common::{adjust_if_intermediate, complete_item, AdjustView},
Completer, CompletionOptions,
completion_common::{AdjustView, adjust_if_intermediate, complete_item},
};
use nu_protocol::{
engine::{EngineState, Stack, StateWorkingSet},
Span,
engine::{EngineState, Stack, StateWorkingSet},
};
use reedline::Suggestion;
use std::path::Path;
use super::{completion_common::FileSuggestion, SemanticSuggestion, SuggestionKind};
use super::{SemanticSuggestion, SuggestionKind, completion_common::FileSuggestion};
pub struct DirectoryCompletion;

View File

@ -1,17 +1,18 @@
use crate::completions::{
completion_common::{surround_remove, FileSuggestion},
Completer, CompletionOptions, SemanticSuggestion, SuggestionKind,
completion_common::{FileSuggestion, surround_remove},
completion_options::NuMatcher,
file_path_completion, Completer, CompletionOptions, SemanticSuggestion, SuggestionKind,
file_path_completion,
};
use nu_path::expand_tilde;
use nu_protocol::{
engine::{Stack, StateWorkingSet, VirtualPath},
Span,
engine::{Stack, StateWorkingSet, VirtualPath},
};
use reedline::Suggestion;
use std::{
collections::HashSet,
path::{is_separator, PathBuf, MAIN_SEPARATOR_STR},
path::{MAIN_SEPARATOR_STR, PathBuf, is_separator},
};
pub struct DotNuCompletion {

View File

@ -1,10 +1,10 @@
use crate::completions::{
completion_common::surround_remove, completion_options::NuMatcher, Completer,
CompletionOptions, SemanticSuggestion, SuggestionKind,
Completer, CompletionOptions, SemanticSuggestion, SuggestionKind,
completion_common::surround_remove, completion_options::NuMatcher,
};
use nu_protocol::{
engine::{Stack, StateWorkingSet},
ModuleId, Span,
engine::{Stack, StateWorkingSet},
};
use reedline::Suggestion;

View File

@ -1,15 +1,15 @@
use crate::completions::{
completion_common::{adjust_if_intermediate, complete_item, AdjustView},
Completer, CompletionOptions,
completion_common::{AdjustView, adjust_if_intermediate, complete_item},
};
use nu_protocol::{
engine::{EngineState, Stack, StateWorkingSet},
Span,
engine::{EngineState, Stack, StateWorkingSet},
};
use reedline::Suggestion;
use std::path::Path;
use super::{completion_common::FileSuggestion, SemanticSuggestion, SuggestionKind};
use super::{SemanticSuggestion, SuggestionKind, completion_common::FileSuggestion};
pub struct FileCompletion;

View File

@ -1,9 +1,9 @@
use crate::completions::{
completion_options::NuMatcher, Completer, CompletionOptions, SemanticSuggestion, SuggestionKind,
Completer, CompletionOptions, SemanticSuggestion, SuggestionKind, completion_options::NuMatcher,
};
use nu_protocol::{
engine::{Stack, StateWorkingSet},
DeclId, Span,
engine::{Stack, StateWorkingSet},
};
use reedline::Suggestion;

View File

@ -24,7 +24,7 @@ pub use custom_completions::CustomCompletion;
pub use directory_completions::DirectoryCompletion;
pub use dotnu_completions::DotNuCompletion;
pub use exportable_completions::ExportableCompletion;
pub use file_completions::{file_path_completion, FileCompletion};
pub use file_completions::{FileCompletion, file_path_completion};
pub use flag_completions::FlagCompletion;
pub use operator_completions::OperatorCompletion;
pub use variable_completions::VariableCompletion;

View File

@ -1,10 +1,10 @@
use crate::completions::{
completion_options::NuMatcher, Completer, CompletionOptions, SemanticSuggestion, SuggestionKind,
Completer, CompletionOptions, SemanticSuggestion, SuggestionKind, completion_options::NuMatcher,
};
use nu_protocol::{
ENV_VARIABLE_ID, Span, Type, Value,
ast::{self, Comparison, Expr, Expression},
engine::{Stack, StateWorkingSet},
Span, Type, Value, ENV_VARIABLE_ID,
};
use reedline::Suggestion;
use strum::{EnumMessage, IntoEnumIterator};

View File

@ -1,7 +1,7 @@
use crate::completions::{Completer, CompletionOptions, SemanticSuggestion, SuggestionKind};
use nu_protocol::{
engine::{Stack, StateWorkingSet},
Span, VarId,
engine::{Stack, StateWorkingSet},
};
use reedline::Suggestion;

View File

@ -2,10 +2,11 @@ use crate::util::eval_source;
#[cfg(feature = "plugin")]
use nu_path::canonicalize_with;
#[cfg(feature = "plugin")]
use nu_protocol::{engine::StateWorkingSet, ParseError, PluginRegistryFile, Spanned};
use nu_protocol::{ParseError, PluginRegistryFile, Spanned, engine::StateWorkingSet};
use nu_protocol::{
PipelineData,
engine::{EngineState, Stack},
report_shell_error, PipelineData,
report_shell_error,
};
#[cfg(feature = "plugin")]
use nu_utils::perf;
@ -18,7 +19,7 @@ const OLD_PLUGIN_FILE: &str = "plugin.nu";
#[cfg(feature = "plugin")]
pub fn read_plugin_file(engine_state: &mut EngineState, plugin_file: Option<Spanned<String>>) {
use nu_protocol::{shell_error::io::IoError, ShellError};
use nu_protocol::{ShellError, shell_error::io::IoError};
use std::path::Path;
let span = plugin_file.as_ref().map(|s| s.span);
@ -79,7 +80,7 @@ pub fn read_plugin_file(engine_state: &mut EngineState, plugin_file: Option<Span
report_shell_error(
engine_state,
&ShellError::Io(IoError::new_internal_with_path(
err.kind(),
err,
"Could not open plugin registry file",
nu_protocol::location!(),
plugin_path,
@ -230,8 +231,8 @@ pub fn eval_config_contents(
#[cfg(feature = "plugin")]
pub fn migrate_old_plugin_file(engine_state: &EngineState) -> bool {
use nu_protocol::{
shell_error::io::IoError, PluginExample, PluginIdentity, PluginRegistryItem,
PluginRegistryItemData, PluginSignature, ShellError,
PluginExample, PluginIdentity, PluginRegistryItem, PluginRegistryItemData, PluginSignature,
ShellError, shell_error::io::IoError,
};
use std::collections::BTreeMap;
@ -322,7 +323,7 @@ pub fn migrate_old_plugin_file(engine_state: &EngineState) -> bool {
if let Err(err) = std::fs::File::create(&new_plugin_file_path)
.map_err(|err| {
IoError::new_internal_with_path(
err.kind(),
err,
"Could not create new plugin file",
nu_protocol::location!(),
new_plugin_file_path.clone(),

View File

@ -2,10 +2,11 @@ use log::info;
use nu_engine::eval_block;
use nu_parser::parse;
use nu_protocol::{
PipelineData, ShellError, Spanned, Value,
cli_error::report_compile_error,
debugger::WithoutDebug,
engine::{EngineState, Stack, StateWorkingSet},
report_parse_error, report_parse_warning, PipelineData, ShellError, Spanned, Value,
report_parse_error, report_parse_warning,
};
use std::sync::Arc;

View File

@ -4,12 +4,12 @@ use nu_engine::eval_block;
use nu_parser::parse;
use nu_path::canonicalize_with;
use nu_protocol::{
PipelineData, ShellError, Span, Value,
cli_error::report_compile_error,
debugger::WithoutDebug,
engine::{EngineState, Stack, StateWorkingSet},
report_parse_error, report_parse_warning,
shell_error::io::*,
PipelineData, ShellError, Span, Value,
};
use std::{path::PathBuf, sync::Arc};
@ -28,7 +28,7 @@ pub fn evaluate_file(
let file_path = canonicalize_with(&path, cwd).map_err(|err| {
IoError::new_internal_with_path(
err.kind().not_found_as(NotFound::File),
err.not_found_as(NotFound::File),
"Could not access file",
nu_protocol::location!(),
PathBuf::from(&path),
@ -47,7 +47,7 @@ pub fn evaluate_file(
let file = std::fs::read(&file_path).map_err(|err| {
IoError::new_internal_with_path(
err.kind().not_found_as(NotFound::File),
err.not_found_as(NotFound::File),
"Could not read file",
nu_protocol::location!(),
file_path.clone(),

View File

@ -18,7 +18,7 @@ mod validation;
pub use commands::add_cli_context;
pub use completions::{FileCompletion, NuCompleter, SemanticSuggestion, SuggestionKind};
pub use config_files::eval_config_contents;
pub use eval_cmds::{evaluate_commands, EvaluateCommandsOpts};
pub use eval_cmds::{EvaluateCommandsOpts, evaluate_commands};
pub use eval_file::evaluate_file;
pub use menus::NuHelpCompleter;
pub use nu_highlight::NuHighlight;

View File

@ -1,5 +1,5 @@
use nu_engine::documentation::{get_flags_section, HelpStyle};
use nu_protocol::{engine::EngineState, levenshtein_distance, Config};
use nu_engine::documentation::{HelpStyle, get_flags_section};
use nu_protocol::{Config, engine::EngineState, levenshtein_distance};
use nu_utils::IgnoreCaseExt;
use reedline::{Completer, Suggestion};
use std::{fmt::Write, sync::Arc};

View File

@ -1,10 +1,10 @@
use nu_engine::eval_block;
use nu_protocol::{
BlockId, IntoPipelineData, Span, Value,
debugger::WithoutDebug,
engine::{EngineState, Stack},
BlockId, IntoPipelineData, Span, Value,
};
use reedline::{menu_functions::parse_selection_char, Completer, Suggestion};
use reedline::{Completer, Suggestion, menu_functions::parse_selection_char};
use std::sync::Arc;
const SELECTION_CHAR: char = '!';

View File

@ -2,8 +2,9 @@ use crate::NushellPrompt;
use log::{trace, warn};
use nu_engine::ClosureEvalOnce;
use nu_protocol::{
Config, PipelineData, Value,
engine::{EngineState, Stack},
report_shell_error, Config, PipelineData, Value,
report_shell_error,
};
use reedline::Prompt;

View File

@ -1,19 +1,20 @@
use crate::{menus::NuMenuCompleter, NuHelpCompleter};
use crate::{NuHelpCompleter, menus::NuMenuCompleter};
use crossterm::event::{KeyCode, KeyModifiers};
use nu_ansi_term::Style;
use nu_color_config::{color_record_to_nustyle, lookup_ansi_color_style};
use nu_engine::eval_block;
use nu_parser::parse;
use nu_protocol::{
Config, EditBindings, FromValue, ParsedKeybinding, ParsedMenu, PipelineData, Record,
ShellError, Span, Type, Value,
debugger::WithoutDebug,
engine::{EngineState, Stack, StateWorkingSet},
extract_value, Config, EditBindings, FromValue, ParsedKeybinding, ParsedMenu, PipelineData,
Record, ShellError, Span, Type, Value,
extract_value,
};
use reedline::{
default_emacs_keybindings, default_vi_insert_keybindings, default_vi_normal_keybindings,
ColumnarMenu, DescriptionMenu, DescriptionMode, EditCommand, IdeMenu, Keybindings, ListMenu,
MenuBuilder, Reedline, ReedlineEvent, ReedlineMenu,
MenuBuilder, Reedline, ReedlineEvent, ReedlineMenu, default_emacs_keybindings,
default_vi_insert_keybindings, default_vi_normal_keybindings,
};
use std::sync::Arc;

View File

@ -6,12 +6,12 @@ use crate::prompt_update::{
VSCODE_PRE_EXECUTION_MARKER,
};
use crate::{
NuHighlighter, NuValidator, NushellPrompt,
completions::NuCompleter,
nu_highlight::NoOpHighlighter,
prompt_update,
reedline_config::{add_menus, create_keybindings, KeybindingsMode},
reedline_config::{KeybindingsMode, add_menus, create_keybindings},
util::eval_source,
NuHighlighter, NuValidator, NushellPrompt,
};
use crossterm::cursor::SetCursorStyle;
use log::{error, trace, warn};
@ -22,15 +22,16 @@ use nu_color_config::StyleComputer;
use nu_engine::env_to_strings;
use nu_engine::exit::cleanup_exit;
use nu_parser::{lex, parse, trim_quotes_str};
use nu_protocol::shell_error;
use nu_protocol::shell_error::io::IoError;
use nu_protocol::{
HistoryConfig, HistoryFileFormat, PipelineData, ShellError, Span, Spanned, Value,
config::NuCursorShape,
engine::{EngineState, Stack, StateWorkingSet},
report_shell_error, HistoryConfig, HistoryFileFormat, PipelineData, ShellError, Span, Spanned,
Value,
report_shell_error,
};
use nu_utils::{
filesystem::{have_permission, PermissionResult},
filesystem::{PermissionResult, have_permission},
perf,
};
use reedline::{
@ -42,7 +43,7 @@ use std::{
collections::HashMap,
env::temp_dir,
io::{self, IsTerminal, Write},
panic::{catch_unwind, AssertUnwindSafe},
panic::{AssertUnwindSafe, catch_unwind},
path::{Path, PathBuf},
sync::Arc,
time::{Duration, Instant},
@ -854,7 +855,7 @@ fn do_auto_cd(
report_shell_error(
engine_state,
&ShellError::Io(IoError::new_with_additional_context(
std::io::ErrorKind::NotFound,
shell_error::io::ErrorKind::DirectoryNotFound,
span,
PathBuf::from(&path),
"Cannot change directory",
@ -868,7 +869,7 @@ fn do_auto_cd(
report_shell_error(
engine_state,
&ShellError::Io(IoError::new_with_additional_context(
std::io::ErrorKind::PermissionDenied,
shell_error::io::ErrorKind::from_std(std::io::ErrorKind::PermissionDenied),
span,
PathBuf::from(path),
"Cannot change directory",
@ -1451,7 +1452,7 @@ fn are_session_ids_in_sync() {
#[cfg(test)]
mod test_auto_cd {
use super::{do_auto_cd, escape_special_vscode_bytes, parse_operation, ReplOperation};
use super::{ReplOperation, do_auto_cd, escape_special_vscode_bytes, parse_operation};
use nu_path::AbsolutePath;
use nu_protocol::engine::{EngineState, Stack};
use tempfile::tempdir;

View File

@ -2,11 +2,11 @@ use log::trace;
use nu_ansi_term::Style;
use nu_color_config::{get_matching_brackets_style, get_shape_color};
use nu_engine::env;
use nu_parser::{flatten_block, parse, FlatShape};
use nu_parser::{FlatShape, flatten_block, parse};
use nu_protocol::{
Span,
ast::{Block, Expr, Expression, PipelineRedirection, RecordItem},
engine::{EngineState, Stack, StateWorkingSet},
Span,
};
use reedline::{Highlighter, StyledText};
use std::sync::Arc;

View File

@ -2,13 +2,13 @@
use nu_cmd_base::hook::eval_hook;
use nu_engine::{eval_block, eval_block_with_early_return};
use nu_parser::{lex, parse, unescape_unquote_string, Token, TokenContents};
use nu_parser::{Token, TokenContents, lex, parse, unescape_unquote_string};
use nu_protocol::{
PipelineData, ShellError, Span, Value,
cli_error::report_compile_error,
debugger::WithoutDebug,
engine::{EngineState, Stack, StateWorkingSet},
report_parse_error, report_parse_warning, report_shell_error, PipelineData, ShellError, Span,
Value,
report_parse_error, report_parse_warning, report_shell_error,
};
#[cfg(windows)]
use nu_utils::enable_vt_processing;

View File

@ -1,7 +1,7 @@
use nu_parser::parse;
use nu_protocol::{
engine::{EngineState, StateWorkingSet},
ParseError,
engine::{EngineState, StateWorkingSet},
};
use reedline::{ValidationResult, Validator};
use std::sync::Arc;

View File

@ -1,5 +1,5 @@
use nu_protocol::HistoryFileFormat;
use nu_test_support::{nu, Outcome};
use nu_test_support::{Outcome, nu};
use reedline::{
FileBackedHistory, History, HistoryItem, HistoryItemId, ReedlineError, SearchQuery,
SqliteBackedHistory,

View File

@ -1,8 +1,8 @@
pub mod support;
use std::{
fs::{read_dir, FileType, ReadDir},
path::{PathBuf, MAIN_SEPARATOR},
fs::{FileType, ReadDir, read_dir},
path::{MAIN_SEPARATOR, PathBuf},
sync::Arc,
};
@ -10,7 +10,7 @@ use nu_cli::NuCompleter;
use nu_engine::eval_block;
use nu_parser::parse;
use nu_path::expand_tilde;
use nu_protocol::{debugger::WithoutDebug, engine::StateWorkingSet, Config, PipelineData};
use nu_protocol::{Config, PipelineData, debugger::WithoutDebug, engine::StateWorkingSet};
use nu_std::load_standard_library;
use reedline::{Completer, Suggestion};
use rstest::{fixture, rstest};
@ -1579,16 +1579,25 @@ fn attribute_completions() {
// Create a new engine
let (_, _, engine, stack) = new_engine();
// Compile a list of built-in attribute names (without the "attr " prefix)
let attribute_names: Vec<String> = engine
.get_signatures_and_declids(false)
.into_iter()
.map(|(sig, _)| sig.name)
.filter(|name| name.starts_with("attr "))
.map(|name| name[5..].to_string())
.collect();
// Make sure we actually found some attributes so the test is valid
assert!(attribute_names.contains(&String::from("example")));
// Instantiate a new completer
let mut completer = NuCompleter::new(Arc::new(engine), Arc::new(stack));
// Test completions for the 'ls' flags
let suggestions = completer.complete("@", 1);
// Only checking for the builtins and not the std attributes
let expected: Vec<_> = vec!["category", "example", "search-terms"];
// Match results
match_suggestions(&expected, &suggestions);
match_suggestions_by_string(&attribute_names, &suggestions);
}
#[test]
@ -2346,6 +2355,32 @@ fn exact_match() {
assert!(suggestions.len() > 1);
}
#[cfg(all(not(windows), not(target_os = "macos")))]
#[test]
fn exact_match_case_insensitive() {
use nu_test_support::playground::Playground;
use support::completions_helpers::new_engine_helper;
Playground::setup("exact_match_case_insensitive", |dirs, playground| {
playground.mkdir("AA/foo");
playground.mkdir("aa/foo");
playground.mkdir("aaa/foo");
let (dir, _, engine, stack) = new_engine_helper(dirs.test().into());
let mut completer = NuCompleter::new(Arc::new(engine), Arc::new(stack));
let target = format!("open {}", folder(dir.join("aa")));
match_suggestions(
&vec![
folder(dir.join("AA").join("foo")).as_str(),
folder(dir.join("aa").join("foo")).as_str(),
folder(dir.join("aaa").join("foo")).as_str(),
],
&completer.complete(&target, target.len()),
);
});
}
#[ignore = "was reverted, still needs fixing"]
#[rstest]
fn alias_offset_bug_7648() {

View File

@ -2,9 +2,9 @@ use nu_engine::eval_block;
use nu_parser::parse;
use nu_path::{AbsolutePathBuf, PathBuf};
use nu_protocol::{
PipelineData, ShellError, Span, Value,
debugger::WithoutDebug,
engine::{EngineState, Stack, StateWorkingSet},
PipelineData, ShellError, Span, Value,
};
use nu_test_support::fs;
use reedline::Suggestion;
@ -14,11 +14,8 @@ fn create_default_context() -> EngineState {
nu_command::add_shell_command_context(nu_cmd_lang::create_default_context())
}
/// creates a new engine with the current path into the completions fixtures folder
pub fn new_engine() -> (AbsolutePathBuf, String, EngineState, Stack) {
// Target folder inside assets
let dir = fs::fixtures().join("completions");
let dir_str = dir
pub fn new_engine_helper(pwd: AbsolutePathBuf) -> (AbsolutePathBuf, String, EngineState, Stack) {
let pwd_str = pwd
.clone()
.into_os_string()
.into_string()
@ -36,13 +33,13 @@ pub fn new_engine() -> (AbsolutePathBuf, String, EngineState, Stack) {
// Add pwd as env var
stack.add_env_var(
"PWD".to_string(),
Value::string(dir_str.clone(), nu_protocol::Span::new(0, dir_str.len())),
Value::string(pwd_str.clone(), nu_protocol::Span::new(0, pwd_str.len())),
);
stack.add_env_var(
"TEST".to_string(),
Value::string(
"NUSHELL".to_string(),
nu_protocol::Span::new(0, dir_str.len()),
nu_protocol::Span::new(0, pwd_str.len()),
),
);
#[cfg(windows)]
@ -50,7 +47,7 @@ pub fn new_engine() -> (AbsolutePathBuf, String, EngineState, Stack) {
"Path".to_string(),
Value::string(
"c:\\some\\path;c:\\some\\other\\path".to_string(),
nu_protocol::Span::new(0, dir_str.len()),
nu_protocol::Span::new(0, pwd_str.len()),
),
);
#[cfg(not(windows))]
@ -58,7 +55,7 @@ pub fn new_engine() -> (AbsolutePathBuf, String, EngineState, Stack) {
"PATH".to_string(),
Value::string(
"/some/path:/some/other/path".to_string(),
nu_protocol::Span::new(0, dir_str.len()),
nu_protocol::Span::new(0, pwd_str.len()),
),
);
@ -66,7 +63,12 @@ pub fn new_engine() -> (AbsolutePathBuf, String, EngineState, Stack) {
let merge_result = engine_state.merge_env(&mut stack);
assert!(merge_result.is_ok());
(dir, dir_str, engine_state, stack)
(pwd, pwd_str, engine_state, stack)
}
/// creates a new engine with the current path in the completions fixtures folder
pub fn new_engine() -> (AbsolutePathBuf, String, EngineState, Stack) {
new_engine_helper(fs::fixtures().join("completions"))
}
/// Adds pseudo PATH env for external completion tests
@ -88,23 +90,13 @@ pub fn new_external_engine() -> EngineState {
engine
}
/// creates a new engine with the current path into the completions fixtures folder
/// creates a new engine with the current path in the dotnu_completions fixtures folder
pub fn new_dotnu_engine() -> (AbsolutePathBuf, String, EngineState, Stack) {
// Target folder inside assets
let dir = fs::fixtures().join("dotnu_completions");
let dir_str = dir
.clone()
.into_os_string()
.into_string()
.unwrap_or_default();
let (dir, dir_str, mut engine_state, mut stack) = new_engine_helper(dir);
let dir_span = nu_protocol::Span::new(0, dir_str.len());
// Create a new engine with default context
let mut engine_state = create_default_context();
// Add $nu
engine_state.generate_nu_constant();
// const $NU_LIB_DIRS
let mut working_set = StateWorkingSet::new(&engine_state);
let var_id = working_set.add_variable(
@ -122,15 +114,6 @@ pub fn new_dotnu_engine() -> (AbsolutePathBuf, String, EngineState, Stack) {
);
let _ = engine_state.merge_delta(working_set.render());
// New stack
let mut stack = Stack::new();
// Add pwd as env var
stack.add_env_var("PWD".to_string(), Value::string(dir_str.clone(), dir_span));
stack.add_env_var(
"TEST".to_string(),
Value::string("NUSHELL".to_string(), dir_span),
);
stack.add_env_var(
"NU_LIB_DIRS".into(),
Value::test_list(vec![
@ -147,73 +130,11 @@ pub fn new_dotnu_engine() -> (AbsolutePathBuf, String, EngineState, Stack) {
}
pub fn new_quote_engine() -> (AbsolutePathBuf, String, EngineState, Stack) {
// Target folder inside assets
let dir = fs::fixtures().join("quoted_completions");
let dir_str = dir
.clone()
.into_os_string()
.into_string()
.unwrap_or_default();
// Create a new engine with default context
let mut engine_state = create_default_context();
// New stack
let mut stack = Stack::new();
// Add pwd as env var
stack.add_env_var(
"PWD".to_string(),
Value::string(dir_str.clone(), nu_protocol::Span::new(0, dir_str.len())),
);
stack.add_env_var(
"TEST".to_string(),
Value::string(
"NUSHELL".to_string(),
nu_protocol::Span::new(0, dir_str.len()),
),
);
// Merge environment into the permanent state
let merge_result = engine_state.merge_env(&mut stack);
assert!(merge_result.is_ok());
(dir, dir_str, engine_state, stack)
new_engine_helper(fs::fixtures().join("quoted_completions"))
}
pub fn new_partial_engine() -> (AbsolutePathBuf, String, EngineState, Stack) {
// Target folder inside assets
let dir = fs::fixtures().join("partial_completions");
let dir_str = dir
.clone()
.into_os_string()
.into_string()
.unwrap_or_default();
// Create a new engine with default context
let mut engine_state = create_default_context();
// New stack
let mut stack = Stack::new();
// Add pwd as env var
stack.add_env_var(
"PWD".to_string(),
Value::string(dir_str.clone(), nu_protocol::Span::new(0, dir_str.len())),
);
stack.add_env_var(
"TEST".to_string(),
Value::string(
"NUSHELL".to_string(),
nu_protocol::Span::new(0, dir_str.len()),
),
);
// Merge environment into the permanent state
let merge_result = engine_state.merge_env(&mut stack);
assert!(merge_result.is_ok());
(dir, dir_str, engine_state, stack)
new_engine_helper(fs::fixtures().join("partial_completions"))
}
/// match a list of suggestions with the expected values
@ -273,13 +194,15 @@ pub fn merge_input(
engine_state.merge_delta(delta)?;
assert!(eval_block::<WithoutDebug>(
assert!(
eval_block::<WithoutDebug>(
engine_state,
stack,
&block,
PipelineData::Value(Value::nothing(Span::unknown()), None),
)
.is_ok());
.is_ok()
);
// Merge environment into the permanent state
engine_state.merge_env(stack)

View File

@ -1,11 +1,11 @@
[package]
authors = ["The Nushell Project Developers"]
description = "The foundation tools to build Nushell commands."
edition = "2021"
edition = "2024"
license = "MIT"
name = "nu-cmd-base"
repository = "https://github.com/nushell/nushell/tree/main/crates/nu-cmd-base"
version = "0.104.1"
version = "0.105.2"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@ -13,10 +13,10 @@ version = "0.104.1"
workspace = true
[dependencies]
nu-engine = { path = "../nu-engine", version = "0.104.1", default-features = false }
nu-parser = { path = "../nu-parser", version = "0.104.1" }
nu-path = { path = "../nu-path", version = "0.104.1" }
nu-protocol = { path = "../nu-protocol", version = "0.104.1", default-features = false }
nu-engine = { path = "../nu-engine", version = "0.105.2", default-features = false }
nu-parser = { path = "../nu-parser", version = "0.105.2" }
nu-path = { path = "../nu-path", version = "0.105.2" }
nu-protocol = { path = "../nu-protocol", version = "0.105.2", default-features = false }
indexmap = { workspace = true }
miette = { workspace = true }

View File

@ -1,4 +1,4 @@
use indexmap::{indexset, IndexSet};
use indexmap::{IndexSet, indexset};
use nu_protocol::Value;
pub fn merge_descriptors(values: &[Value]) -> Vec<String> {

View File

@ -2,10 +2,10 @@ use miette::Result;
use nu_engine::{eval_block, eval_block_with_early_return};
use nu_parser::parse;
use nu_protocol::{
PipelineData, PositionalArg, ShellError, Span, Type, Value, VarId,
cli_error::{report_parse_error, report_shell_error},
debugger::WithoutDebug,
engine::{Closure, EngineState, Stack, StateWorkingSet},
PipelineData, PositionalArg, ShellError, Span, Type, Value, VarId,
};
use std::{collections::HashMap, sync::Arc};

View File

@ -1,4 +1,4 @@
use nu_protocol::{ast::CellPath, PipelineData, ShellError, Signals, Span, Value};
use nu_protocol::{PipelineData, ShellError, Signals, Span, Value, ast::CellPath};
use std::sync::Arc;
pub trait CmdArgument {

View File

@ -3,3 +3,6 @@ pub mod formats;
pub mod hook;
pub mod input_handler;
pub mod util;
mod wrap_call;
pub use wrap_call::*;

View File

@ -1,6 +1,6 @@
use nu_protocol::{
engine::{EngineState, Stack},
Range, ShellError, Span, Value,
engine::{EngineState, Stack},
};
use std::ops::Bound;

View File

@ -0,0 +1,101 @@
use nu_engine::CallExt;
use nu_protocol::{
DeclId, FromValue, ShellError, Span,
engine::{Call, EngineState, Stack, StateWorkingSet},
};
/// A helper utility to aid in implementing commands which have the same behavior for `run` and `run_const`.
///
/// Only supports functions in [`Call`] and [`CallExt`] which have a `const` suffix.
///
/// To use, the actual command logic should be moved to a function. Then, `eval` and `eval_const` can be implemented like this:
/// ```rust
/// # use nu_engine::command_prelude::*;
/// # use nu_cmd_base::WrapCall;
/// # fn do_command_logic(call: WrapCall) -> Result<PipelineData, ShellError> { Ok(PipelineData::Empty) }
///
/// # struct Command {}
/// # impl Command {
/// fn run(&self, engine_state: &EngineState, stack: &mut Stack, call: &Call) -> Result<PipelineData, ShellError> {
/// let call = WrapCall::Eval(engine_state, stack, call);
/// do_command_logic(call)
/// }
///
/// fn run_const(&self, working_set: &StateWorkingSet, call: &Call) -> Result<PipelineData, ShellError> {
/// let call = WrapCall::ConstEval(working_set, call);
/// do_command_logic(call)
/// }
/// # }
/// ```
///
/// Then, the typical [`Call`] and [`CallExt`] operations can be called using destructuring:
///
/// ```rust
/// # use nu_engine::command_prelude::*;
/// # use nu_cmd_base::WrapCall;
/// # let call = WrapCall::Eval(&EngineState::new(), &mut Stack::new(), &Call::new(Span::unknown()));
/// # fn do_command_logic(call: WrapCall) -> Result<(), ShellError> {
/// let (call, required): (_, String) = call.req(0)?;
/// let (call, flag): (_, Option<i64>) = call.get_flag("number")?;
/// # Ok(())
/// # }
/// ```
///
/// A new `WrapCall` instance has to be returned after each function to ensure
/// that there is only ever one copy of mutable [`Stack`] reference.
pub enum WrapCall<'a> {
Eval(&'a EngineState, &'a mut Stack, &'a Call<'a>),
ConstEval(&'a StateWorkingSet<'a>, &'a Call<'a>),
}
/// Macro to choose between the non-const and const versions of each [`Call`]/[`CallExt`] function
macro_rules! proxy {
($self:ident , $eval:ident , $const:ident , $( $args:expr ),*) => {
match $self {
WrapCall::Eval(engine_state, stack, call) => {
Call::$eval(call, engine_state, stack, $( $args ),*)
.map(|val| (WrapCall::Eval(engine_state, stack, call), val))
},
WrapCall::ConstEval(working_set, call) => {
Call::$const(call, working_set, $( $args ),*)
.map(|val| (WrapCall::ConstEval(working_set, call), val))
},
}
};
}
impl WrapCall<'_> {
pub fn head(&self) -> Span {
match self {
WrapCall::Eval(_, _, call) => call.head,
WrapCall::ConstEval(_, call) => call.head,
}
}
pub fn decl_id(&self) -> DeclId {
match self {
WrapCall::Eval(_, _, call) => call.decl_id,
WrapCall::ConstEval(_, call) => call.decl_id,
}
}
pub fn has_flag<T: FromValue>(self, flag_name: &str) -> Result<(Self, bool), ShellError> {
proxy!(self, has_flag, has_flag_const, flag_name)
}
pub fn get_flag<T: FromValue>(self, name: &str) -> Result<(Self, Option<T>), ShellError> {
proxy!(self, get_flag, get_flag_const, name)
}
pub fn req<T: FromValue>(self, pos: usize) -> Result<(Self, T), ShellError> {
proxy!(self, req, req_const, pos)
}
pub fn rest<T: FromValue>(self, pos: usize) -> Result<(Self, Vec<T>), ShellError> {
proxy!(self, rest, rest_const, pos)
}
pub fn opt<T: FromValue>(self, pos: usize) -> Result<(Self, Option<T>), ShellError> {
proxy!(self, opt, opt_const, pos)
}
}

View File

@ -1,11 +1,11 @@
[package]
authors = ["The Nushell Project Developers"]
description = "Nushell's extra commands that are not part of the 1.0 api standard."
edition = "2021"
edition = "2024"
license = "MIT"
name = "nu-cmd-extra"
repository = "https://github.com/nushell/nushell/tree/main/crates/nu-cmd-extra"
version = "0.104.1"
version = "0.105.2"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@ -16,13 +16,13 @@ bench = false
workspace = true
[dependencies]
nu-cmd-base = { path = "../nu-cmd-base", version = "0.104.1" }
nu-engine = { path = "../nu-engine", version = "0.104.1", default-features = false }
nu-json = { version = "0.104.1", path = "../nu-json" }
nu-parser = { path = "../nu-parser", version = "0.104.1" }
nu-pretty-hex = { version = "0.104.1", path = "../nu-pretty-hex" }
nu-protocol = { path = "../nu-protocol", version = "0.104.1", default-features = false }
nu-utils = { path = "../nu-utils", version = "0.104.1", default-features = false }
nu-cmd-base = { path = "../nu-cmd-base", version = "0.105.2" }
nu-engine = { path = "../nu-engine", version = "0.105.2", default-features = false }
nu-json = { version = "0.105.2", path = "../nu-json" }
nu-parser = { path = "../nu-parser", version = "0.105.2" }
nu-pretty-hex = { version = "0.105.2", path = "../nu-pretty-hex" }
nu-protocol = { path = "../nu-protocol", version = "0.105.2", default-features = false }
nu-utils = { path = "../nu-utils", version = "0.105.2", default-features = false }
# Potential dependencies for extras
heck = { workspace = true }
@ -37,6 +37,6 @@ itertools = { workspace = true }
mime = { workspace = true }
[dev-dependencies]
nu-cmd-lang = { path = "../nu-cmd-lang", version = "0.104.1" }
nu-command = { path = "../nu-command", version = "0.104.1" }
nu-test-support = { path = "../nu-test-support", version = "0.104.1" }
nu-cmd-lang = { path = "../nu-cmd-lang", version = "0.105.2" }
nu-command = { path = "../nu-command", version = "0.105.2" }
nu-test-support = { path = "../nu-test-support", version = "0.105.2" }

View File

@ -16,8 +16,8 @@ mod test_examples {
};
use nu_protocol::{
engine::{Command, EngineState, StateWorkingSet},
Type,
engine::{Command, EngineState, StateWorkingSet},
};
use std::collections::HashSet;

View File

@ -65,7 +65,7 @@ impl Command for BitsAnd {
return Err(ShellError::TypeMismatch {
err_message: "Endian must be one of native, little, big".to_string(),
span: endian.span,
})
});
}
}
} else {
@ -113,8 +113,7 @@ impl Command for BitsAnd {
])),
},
Example {
description:
"Apply bitwise and to binary data of varying lengths with specified endianness",
description: "Apply bitwise and to binary data of varying lengths with specified endianness",
example: "0x[c0 ff ee] | bits and 0x[ff] --endian big",
result: Some(Value::test_binary(vec![0x00, 0x00, 0xee])),
},

View File

@ -1,5 +1,5 @@
use super::{get_number_bytes, NumberBytes};
use nu_cmd_base::input_handler::{operate, CmdArgument};
use super::{NumberBytes, get_number_bytes};
use nu_cmd_base::input_handler::{CmdArgument, operate};
use nu_engine::command_prelude::*;
#[derive(Clone)]
@ -100,8 +100,7 @@ impl Command for BitsNot {
)),
},
Example {
description:
"Apply logical negation to a list of numbers, treat input as 2 bytes number",
description: "Apply logical negation to a list of numbers, treat input as 2 bytes number",
example: "[4 3 2] | bits not --number-bytes 2",
result: Some(Value::list(
vec![
@ -113,8 +112,7 @@ impl Command for BitsNot {
)),
},
Example {
description:
"Apply logical negation to a list of numbers, treat input as signed number",
description: "Apply logical negation to a list of numbers, treat input as signed number",
example: "[4 3 2] | bits not --signed",
result: Some(Value::list(
vec![

View File

@ -66,7 +66,7 @@ impl Command for BitsOr {
return Err(ShellError::TypeMismatch {
err_message: "Endian must be one of native, little, big".to_string(),
span: endian.span,
})
});
}
}
} else {
@ -106,8 +106,7 @@ impl Command for BitsOr {
result: Some(Value::test_binary(vec![0xca, 0xfe])),
},
Example {
description:
"Apply bitwise or to binary data of varying lengths with specified endianness",
description: "Apply bitwise or to binary data of varying lengths with specified endianness",
example: "0x[c0 ff ee] | bits or 0x[ff] --endian big",
result: Some(Value::test_binary(vec![0xc0, 0xff, 0xff])),
},

View File

@ -1,5 +1,5 @@
use super::{get_input_num_type, get_number_bytes, InputNumType, NumberBytes};
use nu_cmd_base::input_handler::{operate, CmdArgument};
use super::{InputNumType, NumberBytes, get_input_num_type, get_number_bytes};
use nu_cmd_base::input_handler::{CmdArgument, operate};
use nu_engine::command_prelude::*;
struct Arguments {
@ -222,7 +222,8 @@ fn rotate_bytes_and_bits_left(data: &[u8], byte_shift: usize, bit_shift: usize)
debug_assert!(byte_shift < data.len());
debug_assert!(
(1..8).contains(&bit_shift),
"Bit shifts of 0 can't be handled by this impl and everything else should be part of the byteshift");
"Bit shifts of 0 can't be handled by this impl and everything else should be part of the byteshift"
);
let mut bytes = Vec::with_capacity(data.len());
let mut next_index = byte_shift;
for _ in 0..data.len() {

View File

@ -1,5 +1,5 @@
use super::{get_input_num_type, get_number_bytes, InputNumType, NumberBytes};
use nu_cmd_base::input_handler::{operate, CmdArgument};
use super::{InputNumType, NumberBytes, get_input_num_type, get_number_bytes};
use nu_cmd_base::input_handler::{CmdArgument, operate};
use nu_engine::command_prelude::*;
struct Arguments {

View File

@ -1,6 +1,6 @@
use super::{get_input_num_type, get_number_bytes, InputNumType, NumberBytes};
use super::{InputNumType, NumberBytes, get_input_num_type, get_number_bytes};
use itertools::Itertools;
use nu_cmd_base::input_handler::{operate, CmdArgument};
use nu_cmd_base::input_handler::{CmdArgument, operate};
use nu_engine::command_prelude::*;
use std::iter;
@ -237,7 +237,8 @@ fn shift_bytes_left(data: &[u8], byte_shift: usize) -> Vec<u8> {
fn shift_bytes_and_bits_left(data: &[u8], byte_shift: usize, bit_shift: usize) -> Vec<u8> {
use itertools::Position::*;
debug_assert!((1..8).contains(&bit_shift),
debug_assert!(
(1..8).contains(&bit_shift),
"Bit shifts of 0 can't be handled by this impl and everything else should be part of the byteshift"
);
data.iter()

View File

@ -1,5 +1,5 @@
use super::{get_input_num_type, get_number_bytes, InputNumType, NumberBytes};
use nu_cmd_base::input_handler::{operate, CmdArgument};
use super::{InputNumType, NumberBytes, get_input_num_type, get_number_bytes};
use nu_cmd_base::input_handler::{CmdArgument, operate};
use nu_engine::command_prelude::*;
struct Arguments {

View File

@ -66,7 +66,7 @@ impl Command for BitsXor {
return Err(ShellError::TypeMismatch {
err_message: "Endian must be one of native, little, big".to_string(),
span: endian.span,
})
});
}
}
} else {
@ -106,8 +106,7 @@ impl Command for BitsXor {
result: Some(Value::test_binary(vec![0x70, 0x40])),
},
Example {
description:
"Apply bitwise xor to binary data of varying lengths with specified endianness",
description: "Apply bitwise xor to binary data of varying lengths with specified endianness",
example: "0x[ca fe] | bits xor 0x[aa] --endian big",
result: Some(Value::test_binary(vec![0xca, 0x54])),
},

View File

@ -1,4 +1,4 @@
use nu_engine::{command_prelude::*, ClosureEval, ClosureEvalOnce};
use nu_engine::{ClosureEval, ClosureEvalOnce, command_prelude::*};
use nu_protocol::engine::Closure;
#[derive(Clone)]

View File

@ -1,4 +1,4 @@
use super::{vertical_rotate_value, VerticalDirection};
use super::{VerticalDirection, vertical_rotate_value};
use nu_engine::command_prelude::*;
#[derive(Clone)]

View File

@ -1,4 +1,4 @@
use super::{horizontal_rotate_value, HorizontalDirection};
use super::{HorizontalDirection, horizontal_rotate_value};
use nu_engine::command_prelude::*;
#[derive(Clone)]

View File

@ -1,4 +1,4 @@
use super::{horizontal_rotate_value, HorizontalDirection};
use super::{HorizontalDirection, horizontal_rotate_value};
use nu_engine::command_prelude::*;
#[derive(Clone)]

View File

@ -1,4 +1,4 @@
use super::{vertical_rotate_value, VerticalDirection};
use super::{VerticalDirection, vertical_rotate_value};
use nu_engine::command_prelude::*;
#[derive(Clone)]

View File

@ -44,14 +44,12 @@ impl Command for Rotate {
"column0" => Value::test_int(2),
"column1" => Value::test_string("b"),
}),
],
)),
])),
},
Example {
description: "Rotate 2x3 table clockwise",
example: "[[a b]; [1 2] [3 4] [5 6]] | rotate",
result: Some(Value::test_list(
vec![
result: Some(Value::test_list(vec![
Value::test_record(record! {
"column0" => Value::test_int(5),
"column1" => Value::test_int(3),
@ -64,14 +62,12 @@ impl Command for Rotate {
"column2" => Value::test_int(2),
"column3" => Value::test_string("b"),
}),
],
)),
])),
},
Example {
description: "Rotate table clockwise and change columns names",
example: "[[a b]; [1 2]] | rotate col_a col_b",
result: Some(Value::test_list(
vec![
result: Some(Value::test_list(vec![
Value::test_record(record! {
"col_a" => Value::test_int(1),
"col_b" => Value::test_string("a"),
@ -80,14 +76,12 @@ impl Command for Rotate {
"col_a" => Value::test_int(2),
"col_b" => Value::test_string("b"),
}),
],
)),
])),
},
Example {
description: "Rotate table counter clockwise",
example: "[[a b]; [1 2]] | rotate --ccw",
result: Some(Value::test_list(
vec![
result: Some(Value::test_list(vec![
Value::test_record(record! {
"column0" => Value::test_string("b"),
"column1" => Value::test_int(2),
@ -96,14 +90,12 @@ impl Command for Rotate {
"column0" => Value::test_string("a"),
"column1" => Value::test_int(1),
}),
],
)),
])),
},
Example {
description: "Rotate table counter-clockwise",
example: "[[a b]; [1 2] [3 4] [5 6]] | rotate --ccw",
result: Some(Value::test_list(
vec![
result: Some(Value::test_list(vec![
Value::test_record(record! {
"column0" => Value::test_string("b"),
"column1" => Value::test_int(2),
@ -116,14 +108,12 @@ impl Command for Rotate {
"column2" => Value::test_int(3),
"column3" => Value::test_int(5),
}),
],
)),
])),
},
Example {
description: "Rotate table counter-clockwise and change columns names",
example: "[[a b]; [1 2]] | rotate --ccw col_a col_b",
result: Some(Value::test_list(
vec![
result: Some(Value::test_list(vec![
Value::test_record(record! {
"col_a" => Value::test_string("b"),
"col_b" => Value::test_int(2),
@ -132,8 +122,7 @@ impl Command for Rotate {
"col_a" => Value::test_string("a"),
"col_b" => Value::test_int(1),
}),
],
)),
])),
},
]
}

View File

@ -1,5 +1,5 @@
use nu_engine::{command_prelude::*, ClosureEval};
use nu_protocol::{engine::Closure, PipelineIterator};
use nu_engine::{ClosureEval, command_prelude::*};
use nu_protocol::{PipelineIterator, engine::Closure};
use std::collections::HashSet;
#[derive(Clone)]

View File

@ -101,7 +101,7 @@ impl Command for ToHtml {
.named(
"theme",
SyntaxShape::String,
"the name of the theme to use (github, blulocolight, ...)",
"the name of the theme to use (github, blulocolight, ...); case-insensitive",
Some('t'),
)
.switch(
@ -163,9 +163,16 @@ fn get_theme_from_asset_file(
) -> Result<HashMap<&'static str, String>, ShellError> {
let theme_name = match theme {
Some(s) => &s.item,
None => "default", // There is no theme named "default" so this will be HtmlTheme::default(), which is "nu_default".
None => {
return Ok(convert_html_theme_to_hash_map(
is_dark,
&HtmlTheme::default(),
));
}
};
let theme_span = theme.map(|s| s.span).unwrap_or(Span::unknown());
// 228 themes come from
// https://github.com/mbadolato/iTerm2-Color-Schemes/tree/master/windowsterminal
// we should find a hit on any name in there
@ -175,8 +182,17 @@ fn get_theme_from_asset_file(
let th = asset
.themes
.into_iter()
.find(|n| n.name.eq_ignore_case(theme_name)) // case insensitive search
.unwrap_or_default();
.find(|n| n.name.eq_ignore_case(theme_name)); // case insensitive search
let th = match th {
Some(t) => t,
None => {
return Err(ShellError::TypeMismatch {
err_message: format!("Unknown HTML theme '{}'", theme_name),
span: theme_span,
});
}
};
Ok(convert_html_theme_to_hash_map(is_dark, &th))
}
@ -257,18 +273,20 @@ fn to_html(
None => head,
};
let color_hm = get_theme_from_asset_file(dark, theme.as_ref());
let color_hm = match color_hm {
let color_hm = match get_theme_from_asset_file(dark, theme.as_ref()) {
Ok(c) => c,
_ => {
return Err(ShellError::GenericError {
error: "Error finding theme name".into(),
msg: "Error finding theme name".into(),
span: Some(theme_span),
help: None,
inner: vec![],
})
Err(e) => match e {
ShellError::TypeMismatch {
err_message,
span: _,
} => {
return Err(ShellError::TypeMismatch {
err_message,
span: theme_span,
});
}
_ => return Err(e),
},
};
// change the color of the page
@ -703,4 +721,90 @@ mod tests {
test_examples(ToHtml {})
}
#[test]
fn get_theme_from_asset_file_returns_default() {
let result = super::get_theme_from_asset_file(false, None);
assert!(result.is_ok(), "Expected Ok result for None theme");
let theme_map = result.unwrap();
assert_eq!(
theme_map.get("background").map(String::as_str),
Some("white"),
"Expected default background color to be white"
);
assert_eq!(
theme_map.get("foreground").map(String::as_str),
Some("black"),
"Expected default foreground color to be black"
);
assert!(
theme_map.contains_key("red"),
"Expected default theme to have a 'red' color"
);
assert!(
theme_map.contains_key("bold_green"),
"Expected default theme to have a 'bold_green' color"
);
}
#[test]
fn returns_a_valid_theme() {
let theme_name = "Dracula".to_string().into_spanned(Span::new(0, 7));
let result = super::get_theme_from_asset_file(false, Some(&theme_name));
assert!(result.is_ok(), "Expected Ok result for valid theme");
let theme_map = result.unwrap();
let required_keys = [
"background",
"foreground",
"red",
"green",
"blue",
"bold_red",
"bold_green",
"bold_blue",
];
for key in required_keys {
assert!(
theme_map.contains_key(key),
"Expected theme to contain key '{}'",
key
);
}
}
#[test]
fn fails_with_unknown_theme_name() {
let result = super::get_theme_from_asset_file(
false,
Some(&"doesnt-exist".to_string().into_spanned(Span::new(0, 13))),
);
assert!(result.is_err(), "Expected error for invalid theme name");
if let Err(err) = result {
assert!(
matches!(err, ShellError::TypeMismatch { .. }),
"Expected TypeMismatch error, got: {:?}",
err
);
if let ShellError::TypeMismatch { err_message, span } = err {
assert!(
err_message.contains("doesnt-exist"),
"Error message should mention theme name, got: {}",
err_message
);
assert_eq!(span.start, 0);
assert_eq!(span.end, 13);
}
}
}
}

View File

@ -1,4 +1,4 @@
use nu_ansi_term::{build_all_gradient_text, gradient::TargetGround, Gradient, Rgb};
use nu_ansi_term::{Gradient, Rgb, build_all_gradient_text, gradient::TargetGround};
use nu_engine::command_prelude::*;
#[derive(Clone)]
@ -71,26 +71,22 @@ impl Command for SubCommand {
vec![
Example {
description: "draw text in a gradient with foreground start and end colors",
example:
"'Hello, Nushell! This is a gradient.' | ansi gradient --fgstart '0x40c9ff' --fgend '0xe81cff'",
example: "'Hello, Nushell! This is a gradient.' | ansi gradient --fgstart '0x40c9ff' --fgend '0xe81cff'",
result: None,
},
Example {
description: "draw text in a gradient with foreground start and end colors and background start and end colors",
example:
"'Hello, Nushell! This is a gradient.' | ansi gradient --fgstart '0x40c9ff' --fgend '0xe81cff' --bgstart '0xe81cff' --bgend '0x40c9ff'",
example: "'Hello, Nushell! This is a gradient.' | ansi gradient --fgstart '0x40c9ff' --fgend '0xe81cff' --bgstart '0xe81cff' --bgend '0x40c9ff'",
result: None,
},
Example {
description: "draw text in a gradient by specifying foreground start color - end color is assumed to be black",
example:
"'Hello, Nushell! This is a gradient.' | ansi gradient --fgstart '0x40c9ff'",
example: "'Hello, Nushell! This is a gradient.' | ansi gradient --fgstart '0x40c9ff'",
result: None,
},
Example {
description: "draw text in a gradient by specifying foreground end color - start color is assumed to be black",
example:
"'Hello, Nushell! This is a gradient.' | ansi gradient --fgend '0xe81cff'",
example: "'Hello, Nushell! This is a gradient.' | ansi gradient --fgend '0xe81cff'",
result: None,
},
]
@ -300,7 +296,7 @@ fn action(
#[cfg(test)]
mod tests {
use super::{action, SubCommand};
use super::{SubCommand, action};
use nu_ansi_term::Rgb;
use nu_protocol::{Span, Value};
@ -314,7 +310,9 @@ mod tests {
#[test]
fn test_fg_gradient() {
let input_string = Value::test_string("Hello, World!");
let expected = Value::test_string("\u{1b}[38;2;64;201;255mH\u{1b}[38;2;76;187;254me\u{1b}[38;2;89;174;254ml\u{1b}[38;2;102;160;254ml\u{1b}[38;2;115;147;254mo\u{1b}[38;2;128;133;254m,\u{1b}[38;2;141;120;254m \u{1b}[38;2;153;107;254mW\u{1b}[38;2;166;94;254mo\u{1b}[38;2;179;80;254mr\u{1b}[38;2;192;67;254ml\u{1b}[38;2;205;53;254md\u{1b}[38;2;218;40;254m!\u{1b}[0m");
let expected = Value::test_string(
"\u{1b}[38;2;64;201;255mH\u{1b}[38;2;76;187;254me\u{1b}[38;2;89;174;254ml\u{1b}[38;2;102;160;254ml\u{1b}[38;2;115;147;254mo\u{1b}[38;2;128;133;254m,\u{1b}[38;2;141;120;254m \u{1b}[38;2;153;107;254mW\u{1b}[38;2;166;94;254mo\u{1b}[38;2;179;80;254mr\u{1b}[38;2;192;67;254ml\u{1b}[38;2;205;53;254md\u{1b}[38;2;218;40;254m!\u{1b}[0m",
);
let fg_start = Rgb::from_hex_string("0x40c9ff".to_string());
let fg_end = Rgb::from_hex_string("0xe81cff".to_string());
let actual = action(

View File

@ -1,9 +1,9 @@
use std::io::{self, Read, Write};
use nu_cmd_base::input_handler::{operate, CmdArgument};
use nu_cmd_base::input_handler::{CmdArgument, operate};
use nu_engine::command_prelude::*;
use nu_protocol::{shell_error::io::IoError, Signals};
use nu_protocol::{Signals, shell_error::io::IoError};
use num_traits::ToPrimitive;
struct Arguments {
@ -68,42 +68,33 @@ impl Command for FormatBits {
Example {
description: "convert a binary value into a string, padded to 8 places with 0s",
example: "0x[1] | format bits",
result: Some(Value::string("00000001",
Span::test_data(),
)),
result: Some(Value::string("00000001", Span::test_data())),
},
Example {
description: "convert an int into a string, padded to 8 places with 0s",
example: "1 | format bits",
result: Some(Value::string("00000001",
Span::test_data(),
)),
result: Some(Value::string("00000001", Span::test_data())),
},
Example {
description: "convert a filesize value into a string, padded to 8 places with 0s",
example: "1b | format bits",
result: Some(Value::string("00000001",
Span::test_data(),
)),
result: Some(Value::string("00000001", Span::test_data())),
},
Example {
description: "convert a duration value into a string, padded to 8 places with 0s",
example: "1ns | format bits",
result: Some(Value::string("00000001",
Span::test_data(),
)),
result: Some(Value::string("00000001", Span::test_data())),
},
Example {
description: "convert a boolean value into a string, padded to 8 places with 0s",
example: "true | format bits",
result: Some(Value::string("00000001",
Span::test_data(),
)),
result: Some(Value::string("00000001", Span::test_data())),
},
Example {
description: "convert a string into a raw binary string, padded with 0s to 8 places",
example: "'nushell.sh' | format bits",
result: Some(Value::string("01101110 01110101 01110011 01101000 01100101 01101100 01101100 00101110 01110011 01101000",
result: Some(Value::string(
"01101110 01110101 01110011 01101000 01100101 01101100 01101100 00101110 01110011 01101000",
Span::test_data(),
)),
},
@ -143,7 +134,7 @@ fn byte_stream_to_bits(stream: ByteStream, head: Span) -> ByteStream {
let mut byte = [0];
if reader
.read(&mut byte[..])
.map_err(|err| IoError::new(err.kind(), head, None))?
.map_err(|err| IoError::new(err, head, None))?
> 0
{
// Format the byte as bits

View File

@ -1,5 +1,5 @@
use nu_engine::command_prelude::*;
use nu_protocol::{ast::PathMember, engine::StateWorkingSet, Config, ListStream};
use nu_protocol::{Config, ListStream, ast::PathMember, casing::Casing, engine::StateWorkingSet};
#[derive(Clone)]
pub struct FormatPattern;
@ -214,7 +214,7 @@ fn format(
wrong_type: val.get_type().to_string(),
dst_span: head_span,
src_span: val.span(),
})
});
}
}
}
@ -251,14 +251,14 @@ fn format_record(
val: path.to_string(),
span: *span,
optional: false,
casing: Casing::Sensitive,
})
.collect();
match data_as_value.clone().follow_cell_path(&path_members, false) {
Ok(value_at_column) => {
output.push_str(value_at_column.to_expanded_string(", ", config).as_str())
}
Err(se) => return Err(se),
}
let expanded_string = data_as_value
.follow_cell_path(&path_members)?
.to_expanded_string(", ", config);
output.push_str(expanded_string.as_str())
}
}
}

View File

@ -1,4 +1,4 @@
use nu_cmd_base::input_handler::{operate, CellPathOnlyArgs};
use nu_cmd_base::input_handler::{CellPathOnlyArgs, operate};
use nu_engine::command_prelude::*;
#[derive(Clone)]

View File

@ -14,7 +14,7 @@ pub use snake_case::StrSnakeCase;
pub use str_::Str;
pub use title_case::StrTitleCase;
use nu_cmd_base::input_handler::{operate as general_operate, CmdArgument};
use nu_cmd_base::input_handler::{CmdArgument, operate as general_operate};
use nu_engine::command_prelude::*;
struct Arguments<F: Fn(&str) -> String + Send + Sync + 'static> {

View File

@ -3,10 +3,10 @@ authors = ["The Nushell Project Developers"]
build = "build.rs"
description = "Nushell's core language commands"
repository = "https://github.com/nushell/nushell/tree/main/crates/nu-cmd-lang"
edition = "2021"
edition = "2024"
license = "MIT"
name = "nu-cmd-lang"
version = "0.104.1"
version = "0.105.2"
[lib]
bench = false
@ -15,10 +15,11 @@ bench = false
workspace = true
[dependencies]
nu-engine = { path = "../nu-engine", version = "0.104.1", default-features = false }
nu-parser = { path = "../nu-parser", version = "0.104.1" }
nu-protocol = { path = "../nu-protocol", version = "0.104.1", default-features = false }
nu-utils = { path = "../nu-utils", version = "0.104.1", default-features = false }
nu-engine = { path = "../nu-engine", version = "0.105.2", default-features = false }
nu-parser = { path = "../nu-parser", version = "0.105.2" }
nu-protocol = { path = "../nu-protocol", version = "0.105.2", default-features = false }
nu-utils = { path = "../nu-utils", version = "0.105.2", default-features = false }
nu-cmd-base = { path = "../nu-cmd-base", version = "0.105.2" }
itertools = { workspace = true }
shadow-rs = { version = "1.1", default-features = false }
@ -29,6 +30,7 @@ shadow-rs = { version = "1.1", default-features = false, features = ["build"] }
[dev-dependencies]
quickcheck = { workspace = true }
quickcheck_macros = { workspace = true }
miette = { workspace = true }
[features]
default = ["os"]

View File

@ -0,0 +1,148 @@
use nu_cmd_base::WrapCall;
use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct AttrDeprecated;
impl Command for AttrDeprecated {
fn name(&self) -> &str {
"attr deprecated"
}
fn signature(&self) -> Signature {
Signature::build("attr deprecated")
.input_output_types(vec![
(Type::Nothing, Type::Nothing),
(Type::Nothing, Type::String),
])
.optional(
"message",
SyntaxShape::String,
"Help message to include with deprecation warning.",
)
.named(
"flag",
SyntaxShape::String,
"Mark a flag as deprecated rather than the command",
None,
)
.named(
"since",
SyntaxShape::String,
"Denote a version when this item was deprecated",
Some('s'),
)
.named(
"remove",
SyntaxShape::String,
"Denote a version when this item will be removed",
Some('r'),
)
.named(
"report",
SyntaxShape::String,
"How to warn about this item. One of: first (default), every",
None,
)
.category(Category::Core)
}
fn description(&self) -> &str {
"Attribute for marking a command or flag as deprecated."
}
fn extra_description(&self) -> &str {
"Mark a command (default) or flag/switch (--flag) as deprecated. By default, only the first usage will trigger a deprecation warning.
A help message can be included to provide more context for the deprecation, such as what to use as a replacement.
Also consider setting the category to deprecated with @category deprecated"
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let call = WrapCall::Eval(engine_state, stack, call);
Ok(deprecated_record(call)?.into_pipeline_data())
}
fn run_const(
&self,
working_set: &StateWorkingSet,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let call = WrapCall::ConstEval(working_set, call);
Ok(deprecated_record(call)?.into_pipeline_data())
}
fn is_const(&self) -> bool {
true
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Add a deprecation warning to a custom command",
example: r###"@deprecated
def outdated [] {}"###,
result: Some(Value::nothing(Span::test_data())),
},
Example {
description: "Add a deprecation warning with a custom message",
example: r###"@deprecated "Use my-new-command instead."
@category deprecated
def my-old-command [] {}"###,
result: Some(Value::string(
"Use my-new-command instead.",
Span::test_data(),
)),
},
]
}
}
fn deprecated_record(call: WrapCall) -> Result<Value, ShellError> {
let (call, message): (_, Option<Spanned<String>>) = call.opt(0)?;
let (call, flag): (_, Option<Spanned<String>>) = call.get_flag("flag")?;
let (call, since): (_, Option<Spanned<String>>) = call.get_flag("since")?;
let (call, remove): (_, Option<Spanned<String>>) = call.get_flag("remove")?;
let (call, report): (_, Option<Spanned<String>>) = call.get_flag("report")?;
let mut record = Record::new();
if let Some(message) = message {
record.push("help", Value::string(message.item, message.span))
}
if let Some(flag) = flag {
record.push("flag", Value::string(flag.item, flag.span))
}
if let Some(since) = since {
record.push("since", Value::string(since.item, since.span))
}
if let Some(remove) = remove {
record.push("expected_removal", Value::string(remove.item, remove.span))
}
let report = if let Some(Spanned { item, span }) = report {
match item.as_str() {
"every" => Value::string(item, span),
"first" => Value::string(item, span),
_ => {
return Err(ShellError::IncorrectValue {
msg: "The report mode must be one of: every, first".into(),
val_span: span,
call_span: call.head(),
});
}
}
} else {
Value::string("first", call.head())
};
record.push("report", report);
Ok(Value::record(record, call.head()))
}

View File

@ -1,7 +1,9 @@
mod category;
mod deprecated;
mod example;
mod search_terms;
pub use category::AttrCategory;
pub use deprecated::AttrDeprecated;
pub use example::AttrExample;
pub use search_terms::AttrSearchTerms;

View File

@ -34,10 +34,15 @@ impl Command for Break {
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
_call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
Err(ShellError::Break { span: call.head })
// This is compiled specially by the IR compiler. The code here is never used when
// running in IR mode.
eprintln!(
"Tried to execute 'run' for the 'break' command: this code path should never be reached in IR mode"
);
unreachable!()
}
fn examples(&self) -> Vec<Example> {

View File

@ -1,5 +1,5 @@
use nu_engine::{command_prelude::*, get_eval_block, redirect_env};
use nu_protocol::{engine::Closure, DataSource, PipelineMetadata};
use nu_protocol::{DataSource, PipelineMetadata, engine::Closure};
#[derive(Clone)]
pub struct Collect;

View File

@ -41,35 +41,17 @@ impl Command for Const {
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_engine_state: &EngineState,
_stack: &mut Stack,
_call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
// This is compiled specially by the IR compiler. The code here is never used when
// running in IR mode.
let call = call.assert_ast_call()?;
let var_id = if let Some(id) = call.positional_nth(0).and_then(|pos| pos.as_var()) {
id
} else {
return Err(ShellError::NushellFailedSpanned {
msg: "Could not get variable".to_string(),
label: "variable not added by the parser".to_string(),
span: call.head,
});
};
if let Some(constval) = &engine_state.get_var(var_id).const_val {
stack.add_var(var_id, constval.clone());
Ok(PipelineData::empty())
} else {
Err(ShellError::NushellFailedSpanned {
msg: "Missing Constant".to_string(),
label: "constant not added by the parser".to_string(),
span: call.head,
})
}
eprintln!(
"Tried to execute 'run' for the 'const' command: this code path should never be reached in IR mode"
);
unreachable!()
}
fn run_const(

View File

@ -33,10 +33,15 @@ impl Command for Continue {
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
_call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
Err(ShellError::Continue { span: call.head })
// This is compiled specially by the IR compiler. The code here is never used when
// running in IR mode.
eprintln!(
"Tried to execute 'run' for the 'continue' command: this code path should never be reached in IR mode"
);
unreachable!()
}
fn examples(&self) -> Vec<Example> {

View File

@ -1,7 +1,7 @@
use nu_engine::command_prelude::*;
use nu_protocol::{
engine::{Closure, StateWorkingSet},
BlockId, ByteStreamSource, Category, PipelineMetadata, Signature,
engine::{Closure, StateWorkingSet},
};
use std::any::type_name;
#[derive(Clone)]
@ -72,8 +72,7 @@ impl Command for Describe {
},
Example {
description: "Describe the type of a record in a detailed way",
example:
"{shell:'true', uwu:true, features: {bugs:false, multiplatform:true, speed: 10}, fib: [1 1 2 3 5 8], on_save: {|x| $'Saving ($x)'}, first_commit: 2019-05-10, my_duration: (4min + 20sec)} | describe -d",
example: "{shell:'true', uwu:true, features: {bugs:false, multiplatform:true, speed: 10}, fib: [1 1 2 3 5 8], on_save: {|x| $'Saving ($x)'}, first_commit: 2019-05-10, my_duration: (4min + 20sec)} | describe -d",
result: Some(Value::test_record(record!(
"type" => Value::test_string("record"),
"detailed_type" => Value::test_string("record<shell: string, uwu: bool, features: record<bugs: bool, multiplatform: bool, speed: int>, fib: list<int>, on_save: closure, first_commit: datetime, my_duration: duration>"),
@ -191,7 +190,7 @@ impl Command for Describe {
Example {
description: "Describe the type of a stream with detailed information",
example: "[1 2 3] | each {|i| echo $i} | describe -d",
result: None // Give "Running external commands not supported" error
result: None, // Give "Running external commands not supported" error
// result: Some(Value::test_record(record!(
// "type" => Value::test_string("stream"),
// "origin" => Value::test_string("nushell"),
@ -209,13 +208,13 @@ impl Command for Describe {
Example {
description: "Describe a stream of data, collecting it first",
example: "[1 2 3] | each {|i| echo $i} | describe",
result: None // Give "Running external commands not supported" error
result: None, // Give "Running external commands not supported" error
// result: Some(Value::test_string("list<int> (stream)")),
},
Example {
description: "Describe the input but do not collect streams",
example: "[1 2 3] | each {|i| echo $i} | describe --no-collect",
result: None // Give "Running external commands not supported" error
result: None, // Give "Running external commands not supported" error
// result: Some(Value::test_string("stream")),
},
]

View File

@ -2,7 +2,7 @@ use nu_engine::{command_prelude::*, get_eval_block_with_early_return, redirect_e
#[cfg(feature = "os")]
use nu_protocol::process::{ChildPipe, ChildProcess};
use nu_protocol::{
engine::Closure, shell_error::io::IoError, ByteStream, ByteStreamSource, OutDest,
ByteStream, ByteStreamSource, OutDest, engine::Closure, shell_error::io::IoError,
};
use std::{
@ -107,14 +107,14 @@ impl Command for Do {
let mut buf = Vec::new();
stdout.read_to_end(&mut buf).map_err(|err| {
IoError::new_internal(
err.kind(),
err,
"Could not read stdout to end",
nu_protocol::location!(),
)
})?;
Ok::<_, ShellError>(buf)
})
.map_err(|err| IoError::new(err.kind(), head, None))
.map_err(|err| IoError::new(err, head, None))
})
.transpose()?;
@ -126,7 +126,7 @@ impl Command for Do {
let mut buf = String::new();
stderr
.read_to_string(&mut buf)
.map_err(|err| IoError::new(err.kind(), span, None))?;
.map_err(|err| IoError::new(err, span, None))?;
buf
}
};

View File

@ -63,8 +63,7 @@ little reason to use this over just writing the values as-is."#
)),
},
Example {
description:
"Returns the piped-in value, by using the special $in variable to obtain it.",
description: "Returns the piped-in value, by using the special $in variable to obtain it.",
example: "echo $in",
result: None,
},

View File

@ -76,8 +76,7 @@ impl Command for ErrorMake {
result: None,
},
Example {
description:
"Create a custom error for a custom command that shows the span of the argument",
description: "Create a custom error for a custom command that shows the span of the argument",
example: r#"def foo [x] {
error make {
msg: "this is fishy"
@ -106,7 +105,7 @@ fn make_other_error(value: &Value, throw_span: Option<Span>) -> ShellError {
span: throw_span,
help: None,
inner: vec![],
}
};
}
};
@ -119,7 +118,7 @@ fn make_other_error(value: &Value, throw_span: Option<Span>) -> ShellError {
span: Some(span),
help: None,
inner: vec![],
}
};
}
None => {
return ShellError::GenericError {
@ -128,7 +127,7 @@ fn make_other_error(value: &Value, throw_span: Option<Span>) -> ShellError {
span: Some(span),
help: None,
inner: vec![],
}
};
}
};
@ -146,7 +145,7 @@ fn make_other_error(value: &Value, throw_span: Option<Span>) -> ShellError {
span: Some(span),
help: None,
inner: vec![],
}
};
}
// correct return: no label
None => {
@ -156,7 +155,7 @@ fn make_other_error(value: &Value, throw_span: Option<Span>) -> ShellError {
span: throw_span,
help,
inner: vec![],
}
};
}
};
@ -180,7 +179,7 @@ fn make_other_error(value: &Value, throw_span: Option<Span>) -> ShellError {
span: Some(label_span),
help: None,
inner: vec![],
}
};
}
None => {
return ShellError::GenericError {
@ -189,7 +188,7 @@ fn make_other_error(value: &Value, throw_span: Option<Span>) -> ShellError {
span: Some(label_span),
help: None,
inner: vec![],
}
};
}
};
@ -202,7 +201,7 @@ fn make_other_error(value: &Value, throw_span: Option<Span>) -> ShellError {
span: Some(value.span()),
help: None,
inner: vec![],
}
};
}
// correct return: label, no span
None => {
@ -212,7 +211,7 @@ fn make_other_error(value: &Value, throw_span: Option<Span>) -> ShellError {
span: throw_span,
help,
inner: vec![],
}
};
}
};

View File

@ -1,5 +1,5 @@
use nu_engine::{command_prelude::*, get_eval_block, get_eval_expression};
use nu_protocol::{engine::CommandType, Signals};
use nu_engine::command_prelude::*;
use nu_protocol::engine::CommandType;
#[derive(Clone)]
pub struct For;
@ -43,83 +43,17 @@ impl Command for For {
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_engine_state: &EngineState,
_stack: &mut Stack,
_call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
// This is compiled specially by the IR compiler. The code here is never used when
// running in IR mode.
let call = call.assert_ast_call()?;
let head = call.head;
let var_id = call
.positional_nth(0)
.expect("checked through parser")
.as_var()
.expect("internal error: missing variable");
let keyword_expr = call
.positional_nth(1)
.expect("checked through parser")
.as_keyword()
.expect("internal error: missing keyword");
let block_id = call
.positional_nth(2)
.expect("checked through parser")
.as_block()
.expect("internal error: missing block");
let eval_expression = get_eval_expression(engine_state);
let eval_block = get_eval_block(engine_state);
let value = eval_expression(engine_state, stack, keyword_expr)?;
let engine_state = engine_state.clone();
let block = engine_state.get_block(block_id);
let stack = &mut stack.push_redirection(None, None);
let span = value.span();
match value {
Value::List { vals, .. } => {
for x in vals.into_iter() {
engine_state.signals().check(head)?;
// with_env() is used here to ensure that each iteration uses
// a different set of environment variables.
// Hence, a 'cd' in the first loop won't affect the next loop.
stack.add_var(var_id, x);
match eval_block(&engine_state, stack, block, PipelineData::empty()) {
Err(ShellError::Break { .. }) => break,
Err(ShellError::Continue { .. }) => continue,
Err(err) => return Err(err),
Ok(data) => data.drain()?,
}
}
}
Value::Range { val, .. } => {
for x in val.into_range_iter(span, Signals::empty()) {
engine_state.signals().check(head)?;
stack.add_var(var_id, x);
match eval_block(&engine_state, stack, block, PipelineData::empty()) {
Err(ShellError::Break { .. }) => break,
Err(ShellError::Continue { .. }) => continue,
Err(err) => return Err(err),
Ok(data) => data.drain()?,
}
}
}
x => {
stack.add_var(var_id, x);
eval_block(&engine_state, stack, block, PipelineData::empty())?.into_value(head)?;
}
}
Ok(PipelineData::empty())
eprintln!(
"Tried to execute 'run' for the 'for' command: this code path should never be reached in IR mode"
);
unreachable!()
}
fn examples(&self) -> Vec<Example> {

View File

@ -1,6 +1,4 @@
use nu_engine::{
command_prelude::*, get_eval_block, get_eval_expression, get_eval_expression_with_input,
};
use nu_engine::command_prelude::*;
use nu_protocol::{
engine::{CommandType, StateWorkingSet},
eval_const::{eval_const_subexpression, eval_constant, eval_constant_with_input},
@ -60,8 +58,6 @@ impl Command for If {
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
// This is compiled specially by the IR compiler. The code here is never used when
// running in IR mode.
let call = call.assert_ast_call()?;
let cond = call.positional_nth(0).expect("checked through parser");
let then_block = call
@ -97,43 +93,17 @@ impl Command for If {
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
_engine_state: &EngineState,
_stack: &mut Stack,
_call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
// This is compiled specially by the IR compiler. The code here is never used when
// running in IR mode.
let call = call.assert_ast_call()?;
let cond = call.positional_nth(0).expect("checked through parser");
let then_block = call
.positional_nth(1)
.expect("checked through parser")
.as_block()
.expect("internal error: missing block");
let else_case = call.positional_nth(2);
let eval_expression = get_eval_expression(engine_state);
let eval_expression_with_input = get_eval_expression_with_input(engine_state);
let eval_block = get_eval_block(engine_state);
if eval_expression(engine_state, stack, cond)?.as_bool()? {
let block = engine_state.get_block(then_block);
eval_block(engine_state, stack, block, input)
} else if let Some(else_case) = else_case {
if let Some(else_expr) = else_case.as_keyword() {
if let Some(block_id) = else_expr.as_block() {
let block = engine_state.get_block(block_id);
eval_block(engine_state, stack, block, input)
} else {
eval_expression_with_input(engine_state, stack, else_expr, input)
}
} else {
eval_expression_with_input(engine_state, stack, else_case, input)
}
} else {
Ok(PipelineData::empty())
}
eprintln!(
"Tried to execute 'run' for the 'if' command: this code path should never be reached in IR mode"
);
unreachable!()
}
fn search_terms(&self) -> Vec<&str> {

View File

@ -1,5 +1,5 @@
use nu_engine::command_prelude::*;
use nu_protocol::{engine::StateWorkingSet, ByteStreamSource, OutDest};
use nu_protocol::{ByteStreamSource, OutDest, engine::StateWorkingSet};
#[derive(Clone)]
pub struct Ignore;

View File

@ -1,4 +1,4 @@
use nu_engine::{command_prelude::*, get_eval_block};
use nu_engine::command_prelude::*;
use nu_protocol::engine::CommandType;
#[derive(Clone)]
@ -41,47 +41,17 @@ impl Command for Let {
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
_engine_state: &EngineState,
_stack: &mut Stack,
_call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
// This is compiled specially by the IR compiler. The code here is never used when
// running in IR mode.
let call = call.assert_ast_call()?;
let var_id = call
.positional_nth(0)
.expect("checked through parser")
.as_var()
.expect("internal error: missing variable");
let block_id = call
.positional_nth(1)
.expect("checked through parser")
.as_block()
.expect("internal error: missing right hand side");
let block = engine_state.get_block(block_id);
let eval_block = get_eval_block(engine_state);
let stack = &mut stack.start_collect_value();
let pipeline_data = eval_block(engine_state, stack, block, input)?;
let value = pipeline_data.into_value(call.head)?;
// if given variable type is Glob, and our result is string
// then nushell need to convert from Value::String to Value::Glob
// it's assigned by demand, then it's not quoted, and it's required to expand
// if we pass it to other commands.
let var_type = &engine_state.get_var(var_id).ty;
let val_span = value.span();
let value = match value {
Value::String { val, .. } if var_type == &Type::Glob => {
Value::glob(val, false, val_span)
}
value => value,
};
stack.add_var(var_id, value);
Ok(PipelineData::empty())
eprintln!(
"Tried to execute 'run' for the 'let' command: this code path should never be reached in IR mode"
);
unreachable!()
}
fn examples(&self) -> Vec<Example> {

View File

@ -1,4 +1,4 @@
use nu_engine::{command_prelude::*, get_eval_block};
use nu_engine::command_prelude::*;
use nu_protocol::engine::CommandType;
#[derive(Clone)]
@ -32,37 +32,17 @@ impl Command for Loop {
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_engine_state: &EngineState,
_stack: &mut Stack,
_call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
// This is compiled specially by the IR compiler. The code here is never used when
// running in IR mode.
let call = call.assert_ast_call()?;
let head = call.head;
let block_id = call
.positional_nth(0)
.expect("checked through parser")
.as_block()
.expect("internal error: missing block");
let block = engine_state.get_block(block_id);
let eval_block = get_eval_block(engine_state);
let stack = &mut stack.push_redirection(None, None);
loop {
engine_state.signals().check(head)?;
match eval_block(engine_state, stack, block, PipelineData::empty()) {
Err(ShellError::Break { .. }) => break,
Err(ShellError::Continue { .. }) => continue,
Err(err) => return Err(err),
Ok(data) => data.drain()?,
}
}
Ok(PipelineData::empty())
eprintln!(
"Tried to execute 'run' for the 'loop' command: this code path should never be reached in IR mode"
);
unreachable!()
}
fn examples(&self) -> Vec<Example> {

View File

@ -1,7 +1,5 @@
use nu_engine::{
command_prelude::*, get_eval_block, get_eval_expression, get_eval_expression_with_input,
};
use nu_protocol::engine::{CommandType, Matcher};
use nu_engine::command_prelude::*;
use nu_protocol::engine::CommandType;
#[derive(Clone)]
pub struct Match;
@ -38,62 +36,31 @@ impl Command for Match {
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
_engine_state: &EngineState,
_stack: &mut Stack,
_call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
// This is compiled specially by the IR compiler. The code here is never used when
// running in IR mode.
let call = call.assert_ast_call()?;
let value: Value = call.req(engine_state, stack, 0)?;
let matches = call
.positional_nth(1)
.expect("checked through parser")
.as_match_block()
.expect("missing match block");
let eval_expression = get_eval_expression(engine_state);
let eval_expression_with_input = get_eval_expression_with_input(engine_state);
let eval_block = get_eval_block(engine_state);
let mut match_variables = vec![];
for (pattern, expr) in matches {
if pattern.match_value(&value, &mut match_variables) {
// This case does match, go ahead and return the evaluated expression
for (id, value) in match_variables.drain(..) {
stack.add_var(id, value);
}
let guard_matches = if let Some(guard) = &pattern.guard {
let Value::Bool { val, .. } = eval_expression(engine_state, stack, guard)?
else {
return Err(ShellError::MatchGuardNotBool { span: guard.span });
};
val
} else {
true
};
if guard_matches {
return if let Some(block_id) = expr.as_block() {
let block = engine_state.get_block(block_id);
eval_block(engine_state, stack, block, input)
} else {
eval_expression_with_input(engine_state, stack, expr, input)
};
}
} else {
match_variables.clear();
}
}
Ok(PipelineData::Empty)
eprintln!(
"Tried to execute 'run' for the 'match' command: this code path should never be reached in IR mode"
);
unreachable!()
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Match on a value",
example: "match 3 { 1 => 'one', 2 => 'two', 3 => 'three' }",
result: Some(Value::test_string("three")),
},
Example {
description: "Match against alternative values",
example: "match 'three' { 1 | 'one' => '-', 2 | 'two' => '--', 3 | 'three' => '---' }",
result: Some(Value::test_string("---")),
},
Example {
description: "Match on a value in range",
example: "match 3 { 1..10 => 'yes!' }",

View File

@ -1,4 +1,4 @@
use nu_engine::{command_prelude::*, get_eval_block};
use nu_engine::command_prelude::*;
use nu_protocol::engine::CommandType;
#[derive(Clone)]
@ -41,47 +41,17 @@ impl Command for Mut {
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
_engine_state: &EngineState,
_stack: &mut Stack,
_call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
// This is compiled specially by the IR compiler. The code here is never used when
// running in IR mode.
let call = call.assert_ast_call()?;
let var_id = call
.positional_nth(0)
.expect("checked through parser")
.as_var()
.expect("internal error: missing variable");
let block_id = call
.positional_nth(1)
.expect("checked through parser")
.as_block()
.expect("internal error: missing right hand side");
let block = engine_state.get_block(block_id);
let eval_block = get_eval_block(engine_state);
let stack = &mut stack.start_collect_value();
let pipeline_data = eval_block(engine_state, stack, block, input)?;
let value = pipeline_data.into_value(call.head)?;
// if given variable type is Glob, and our result is string
// then nushell need to convert from Value::String to Value::Glob
// it's assigned by demand, then it's not quoted, and it's required to expand
// if we pass it to other commands.
let var_type = &engine_state.get_var(var_id).ty;
let val_span = value.span();
let value = match value {
Value::String { val, .. } if var_type == &Type::Glob => {
Value::glob(val, false, val_span)
}
value => value,
};
stack.add_var(var_id, value);
Ok(PipelineData::empty())
eprintln!(
"Tried to execute 'run' for the 'mut' command: this code path should never be reached in IR mode"
);
unreachable!()
}
fn examples(&self) -> Vec<Example> {

View File

@ -76,7 +76,7 @@ impl Command for OverlayHide {
return Err(ShellError::EnvVarNotFoundAtRuntime {
envvar_name: name.item,
span: name.span,
})
});
}
}
}
@ -86,12 +86,16 @@ impl Command for OverlayHide {
vec![]
};
// also restore env vars which has been hidden
let env_vars_to_restore = stack.get_hidden_env_vars(&overlay_name.item, engine_state);
stack.remove_overlay(&overlay_name.item);
for (name, val) in env_vars_to_restore {
stack.add_env_var(name, val);
}
for (name, val) in env_vars_to_keep {
stack.add_env_var(name, val);
}
Ok(PipelineData::empty())
}

View File

@ -1,4 +1,4 @@
use nu_engine::command_prelude::*;
use nu_engine::{command_prelude::*, redirect_env};
use nu_protocol::engine::CommandType;
#[derive(Clone)]
@ -18,6 +18,11 @@ impl Command for OverlayNew {
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
.allow_variants_without_examples(true)
.required("name", SyntaxShape::String, "Name of the overlay.")
.switch(
"reload",
"If the overlay already exists, reload its environment.",
Some('r'),
)
// TODO:
// .switch(
// "prefix",
@ -41,13 +46,20 @@ This command is a parser keyword. For details, check:
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
caller_stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let name_arg: Spanned<String> = call.req(engine_state, stack, 0)?;
let name_arg: Spanned<String> = call.req(engine_state, caller_stack, 0)?;
let reload = call.has_flag(engine_state, caller_stack, "reload")?;
stack.add_overlay(name_arg.item);
if reload {
let callee_stack = caller_stack.clone();
caller_stack.add_overlay(name_arg.item);
redirect_env(engine_state, caller_stack, &callee_stack);
} else {
caller_stack.add_overlay(name_arg.item);
}
Ok(PipelineData::empty())
}

View File

@ -2,7 +2,7 @@ use nu_engine::{
command_prelude::*, find_in_dirs_env, get_dirs_var_from_call, get_eval_block, redirect_env,
};
use nu_parser::trim_quotes_str;
use nu_protocol::{ast::Expr, engine::CommandType, ModuleId};
use nu_protocol::{ModuleId, ast::Expr, engine::CommandType};
use std::path::Path;

View File

@ -35,17 +35,17 @@ impl Command for Return {
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_engine_state: &EngineState,
_stack: &mut Stack,
_call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let return_value: Option<Value> = call.opt(engine_state, stack, 0)?;
let value = return_value.unwrap_or(Value::nothing(call.head));
Err(ShellError::Return {
span: call.head,
value: Box::new(value),
})
// This is compiled specially by the IR compiler. The code here is never used when
// running in IR mode.
eprintln!(
"Tried to execute 'run' for the 'return' command: this code path should never be reached in IR mode"
);
unreachable!()
}
fn examples(&self) -> Vec<Example> {

Some files were not shown because too many files have changed in this diff Show More