Compare commits

...

90 Commits

Author SHA1 Message Date
6e1e824473 Bump version to 0.98.0 (#13865) 2024-09-18 00:48:46 -07:00
af77bc60e2 Improved null handling when converting from nu -> dataframe. (#13855)
# Description
Fixes: #12726 and #13185

Previously converting columns that contained null caused polars to force
a dtype of object even when using a schema.

Now:
1. When using a schema, the type the schema defines for the column will
always be used.
2. When a schema is not used, the previous type is used when a value is
null.

# User-Facing Changes
- The type defined by the schema we be respected when passing in a null
value `[a]; [null] | polars into-df -s {a: str}` will create a df with
an str dtype column with one null value versus a column of type object.
- *BREAKING CHANGE* If you define a schema, all columns must be in the
schema.
2024-09-16 18:07:13 -05:00
9ca0fb772d Make IR the default evaluator (#13718)
# Description

Makes IR the default evaluator, in preparation to remove the non-IR
evaluator in a future release.

# User-Facing Changes

* Remove `NU_USE_IR` option
* Add `NU_DISABLE_IR` option
* IR is enabled unless `NU_DISABLE_IR` is set

# After Submitting
- [ ] release notes
2024-09-15 14:54:38 -07:00
c535c24d03 catch unwrap on panics with polars collect (#13850)
# Description
This resurrects the work from #12866 and fixes #12732. 

Polars panics for a plethora or reasons. While handling panics is
generally frowned upon, in cases like with `polars collect` a panic
cause a lot of work to be lost. Often you might have multiple dataframes
in memory and you are trying one operation and lose all state.

While it possible the panic can leave things a strange state, it is
pretty unlikely as part of a polars pipeline. Most of the time polars
objects are not manipulating dataframes in memory mutability, but rather
creating a new dataframe the operations being applied. This is always
the case with a lazy pipeline. After the collect call, the original
dataframes are intact still and I haven't observed any side effects.
2024-09-15 07:21:02 -05:00
c9cb62067c Fix dockerfile and reset Nu config to default (#13851)
<!--
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

Fix dockerfile and reset Nu config to default, fetching config file from
the remote may cause compatible issues
2024-09-15 20:03:22 +08:00
ebc7b80c23 allow tab to be retained with find (#13848)
# Description

This PR allows the tab character to be retained when using `find`.

### Before

![image](https://github.com/user-attachments/assets/92d78f55-58fb-42f4-be8f-82992292c900)

### After

![image](https://github.com/user-attachments/assets/fbd8e47f-9806-4e30-89a1-6c88b12a612c)


closes #13846

# 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.
-->
2024-09-14 08:51:00 -05:00
aaaab8e070 Update Nu for release workflow and fix build warning of musl targets (#13840)
<!--
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

1. Update Nushell to v0.97.1 for release workflow
2. Fix musl targets cross compiling warning like: `warning: File system
loop found:
/home/runner/work/nightly/nightly/aarch64-linux-musl-cross/usr points to
an ancestor /home/runner/work/nightly/nightly/aarch64-linux-musl-cross/`

Tested in
https://github.com/nushell/nightly/actions/runs/10849647834/job/30109290106
2024-09-13 22:03:31 +08:00
a59477205d Fix try: Add set_last_error() to prepare_error_handler() for IR eval (#13838)
# Description

Fixes a bug with `set_last_error()` introduced by @IanManske not being
called during the jump to an error handler in IR eval. Without this,
`$env.LAST_EXIT_CODE` wasn't getting set in the `catch` block for an
external.

# Tests + Formatting

Added a `tests/eval` test to cover this in both IR and non-IR eval
2024-09-13 00:07:22 -07:00
5101b5e306 Add --number flag to split column (#13831)
This allows parsing of data (e.g. key-value pairs) where the last column
may contain the delimiter.

- this PR should close #13742

# Description

Adds a `--number (-n)` flag to `split column`, analogous to `split row
--number`.

```
~> ['author: Salina Yoon' r#'title: Where's Ellie?: A Hide-and-Seek Book'#] | split column --number 2 ': ' key value
╭───┬────────┬──────────────────────────────────────╮
│ # │  key   │                value                 │
├───┼────────┼──────────────────────────────────────┤
│ 0 │ author │ Salina Yoon                          │
│ 1 │ title  │ Where's Ellie?: A Hide-and-Seek Book │
╰───┴────────┴──────────────────────────────────────╯
```

# User-Facing Changes
* `split column` gains a `--number` option

# Tests + Formatting
Tests included in strings::split::column::test::test_examples and
commands::split_column::to_column.

# After Submitting
Reference documentation is auto-generated from code. No other
documentation updates necessary.
2024-09-12 07:16:33 -05:00
fb34a4fc6c Make polars save return an empty pipeline (#13833)
# Description
In order to be more consistent with it's nu counterpart, `polars save`
now returns an empty pipeline instead of a message of the saved file.

# User-Facing Changes
- `polars save` no longer displays a save message, making it consistent
with `save` behavior.
2024-09-12 06:23:40 -05:00
1bcceafd93 Improve #12008 UX, clear scrollback by default on clear (#13821)
<!--
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.
-->

Related to #11693. It looks like there is no reason for Nu shell's
`clear` to behave differently than other shells' `clear`. To improve the
UX and fulfill the user expectations, the default has been adjusted to
work the same as in other shells by clearing the scrollback buffer. For
edge cases where someone depends on the current behavior of keeping the
scrollback, a `-k` option has been added.

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

- Improve the UX of `clear` by changing the default behavior to the same
as other popular shells, i.e clear scrollback by default.
- Remove `-a --all` flag, make it the default behavior to clear the
scrollback
- Add `-k --keep-scrollback` flag for backward compat to keep the
scrollback buffer

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

This is a simple change flipping the flag and default behavior, no tests
should be needed.

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

- [ ] update the `clear` command docs

---------

Co-authored-by: Douglas <32344964+NotTheDr01ds@users.noreply.github.com>
Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com>
2024-09-11 15:33:20 -05:00
217eb4ed70 fix path exists on a non-directory file (#13763)
# Description
Fixes:  #13460

The issue is caused by `try_exists` method on path, it will return
`Err(NotADirectory)` if user tried to check for a path under a regular
file.
To fix it, I think it's ok to use `exists` rather than `try_exists`,
although
[Path::exists()](https://doc.rust-lang.org/std/path/struct.Path.html#method.exists)
only checks whether or not a path was both found and readable. I think
it's ok, and we can add this information under `extra_description`.

# User-Facing Changes
The following code will no longer raise error:
```
touch a; 'a/b' | path exists
```

# Tests + Formatting
Added 1 test.
2024-09-11 12:45:39 -05:00
78af66f2ce Config: change ctrl-k to cuttolineend event (#13801)
# Description
According to emacs doc, I think `ctrl-k` should map to `cuttolineend`.

# User-Facing Changes
`ctrl-k` will no longer cut to the end of buffer
2024-09-11 12:45:12 -05:00
f63cecc316 add metadata access command (#13785)
# Description
Add `metadata access`, which allows accessing/inspecting the metadata of
a stream in a closure.
```nu
ls | metadata access {|meta|
    ...
}
```

- The metadata is provided as an argument to the closure, identical to
the record obtained with `metadata` command.

- `metadata access` passes its input stream into the closure as it is.

- Within the closure, both the metadata and the stream are available.
The closure may modify, collect or pass the stream as it is.

# Motivation
- Without this command, nu code can't act on metadata without losing the
stream, use cases requiring both the stream and metadata must be
implemented either as a built-in or a plugin.

- This command allows users to enhance presentation of data, similar to
`table` coloring the output of `ls`.
2024-09-11 12:44:06 -05:00
8d60c0d35d Migrating polars commands away from macros, removed custom DataFrame comparison. (#13829)
# Description
This PR:
- Removes the lazy_command, expr_command macros and migrates the
commands that were utilizing them.
- Removes the custom logic in DataFrameValues::is_equals to use the
polars DataFrame version of PartialEq
- Adds examples to commands that previously did not have examples or had
inadequate ones.

NOTE: A lot of examples now have a `polars sort` at the end. This is
needed due to the comparison in the result. The new polars version of
equals cares about the ordering. I removed the custom equals logic as it
causes comparisons to lock up when comparing dataframes that contain a
row that contains a list. I discovered this issue when adding examples
to `polars implode`
2024-09-11 10:33:05 -07:00
0c139c7411 Fix padding issue with header_on_border (#13808)
close #13803 

For your @amtoine  example we get

```
#┬c-a┬c-b┬c-c┬c-d─┬─c-e─
0│  1│ 12│123│1234│12345
─┴───┴───┴───┴────┴─────
```
2024-09-11 06:12:53 -05:00
c4bac90b35 Bump crate-ci/typos from 1.24.4 to 1.24.5 (#13826)
Bumps [crate-ci/typos](https://github.com/crate-ci/typos) from 1.24.4 to
1.24.5.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/crate-ci/typos/releases">crate-ci/typos's
releases</a>.</em></p>
<blockquote>
<h2>v1.24.5</h2>
<h2>[1.24.5] - 2024-09-04</h2>
<h3>Features</h3>
<ul>
<li><em>(action)</em> Support windows</li>
</ul>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/crate-ci/typos/blob/master/CHANGELOG.md">crate-ci/typos's
changelog</a>.</em></p>
<blockquote>
<h2>[1.24.5] - 2024-09-04</h2>
<h3>Features</h3>
<ul>
<li><em>(action)</em> Support windows</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="945d407a5f"><code>945d407</code></a>
chore: Release</li>
<li><a
href="e972e95d22"><code>e972e95</code></a>
docs: Update changelog</li>
<li><a
href="fcfade456a"><code>fcfade4</code></a>
Merge pull request <a
href="https://redirect.github.com/crate-ci/typos/issues/1095">#1095</a>
from zyf722/actions-windows</li>
<li><a
href="264f549c13"><code>264f549</code></a>
feat(action): Add Windows support to actions</li>
<li>See full diff in <a
href="https://github.com/crate-ci/typos/compare/v1.24.4...v1.24.5">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=crate-ci/typos&package-manager=github_actions&previous-version=1.24.4&new-version=1.24.5)](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>
2024-09-11 14:35:46 +08:00
2ab8751ff9 Bump hustcer/setup-nu from 3.12 to 3.13 (#13827)
Bumps [hustcer/setup-nu](https://github.com/hustcer/setup-nu) from 3.12
to 3.13.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/hustcer/setup-nu/releases">hustcer/setup-nu's
releases</a>.</em></p>
<blockquote>
<h2>v3.13</h2>
<h2>[3.13] - 2024-09-07</h2>
<h3>Features</h3>
<ul>
<li>Add <code>aarch64_linux</code> and <code>aarch64_windows</code>
runners support</li>
</ul>
<h3>Deps</h3>
<ul>
<li>Upgrade
<code>@​octokit/rest</code>,globby,<code>@​biomejs/biome</code>,lefthook,
etc.</li>
<li>Upgrade semver,lefthook,<code>@​octokit/rest</code> and
@typescript-eslint/*</li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/hustcer/setup-nu/compare/v3.12...v3.13">https://github.com/hustcer/setup-nu/compare/v3.12...v3.13</a></p>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/hustcer/setup-nu/blob/main/CHANGELOG.md">hustcer/setup-nu's
changelog</a>.</em></p>
<blockquote>
<h2>[3.13] - 2024-09-07</h2>
<h3>Features</h3>
<ul>
<li>Add <code>aarch64_linux</code> and <code>aarch64_windows</code>
runners support</li>
</ul>
<h3>Deps</h3>
<ul>
<li>Upgrade
<code>@​octokit/rest</code>,globby,<code>@​biomejs/biome</code>,lefthook,
etc.</li>
<li>Upgrade semver,lefthook,<code>@​octokit/rest</code> and
@typescript-eslint/*</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="5dfe3b1a9e"><code>5dfe3b1</code></a>
Bump to v3.13</li>
<li><a
href="7f30320d51"><code>7f30320</code></a>
deps: Upgrade <code>@​octokit/rest</code>, lefthook and
@typescript-eslint/*</li>
<li><a
href="aed3675fdb"><code>aed3675</code></a>
deps: Upgrade semver,lefthook,<code>@​octokit/rest</code> and
@typescript-eslint/*</li>
<li><a
href="cb4476b15e"><code>cb4476b</code></a>
deps: Upgrade
<code>@​octokit/rest</code>,globby,<code>@​biomejs/biome</code>,lefthook
and <a
href="https://github.com/typescript-es"><code>@​typescript-es</code></a>...</li>
<li><a
href="25c9361cd1"><code>25c9361</code></a>
feat: Add aarch64_linux and aarch64_windows runners support</li>
<li>See full diff in <a
href="https://github.com/hustcer/setup-nu/compare/v3.12...v3.13">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=hustcer/setup-nu&package-manager=github_actions&previous-version=3.12&new-version=3.13)](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>
2024-09-11 14:35:38 +08:00
d192d854d6 Bump shadow-rs from 0.33.0 to 0.34.0 (#13825)
Bumps [shadow-rs](https://github.com/baoyachi/shadow-rs) from 0.33.0 to
0.34.0.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/baoyachi/shadow-rs/releases">shadow-rs's
releases</a>.</em></p>
<blockquote>
<h2>v0.34.0</h2>
<h2>What's Changed</h2>
<ul>
<li>Make using the CARGO_METADATA object simpler by <a
href="https://github.com/baoyachi"><code>@​baoyachi</code></a> in <a
href="https://redirect.github.com/baoyachi/shadow-rs/pull/181">baoyachi/shadow-rs#181</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/baoyachi/shadow-rs/compare/v0.33.0...v0.34.0">https://github.com/baoyachi/shadow-rs/compare/v0.33.0...v0.34.0</a></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="ccb09f154b"><code>ccb09f1</code></a>
Merge pull request <a
href="https://redirect.github.com/baoyachi/shadow-rs/issues/181">#181</a>
from baoyachi/issue/179</li>
<li><a
href="65c56630da"><code>65c5663</code></a>
fix cargo clippy check</li>
<li><a
href="998d000023"><code>998d000</code></a>
Make using the CARGO_METADATA object simpler</li>
<li>See full diff in <a
href="https://github.com/baoyachi/shadow-rs/compare/v0.33.0...v0.34.0">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=shadow-rs&package-manager=cargo&previous-version=0.33.0&new-version=0.34.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>
2024-09-11 14:35:27 +08:00
6b5906613c Fix remaining mismatch for env handling in IR (#13796)
# Description

This fixes a couple of remaining differences between the IR evaluator's
handling of env vars and the AST evaluator's handling of env vars.

Blocker for #13718 (this is why those tests failed)

# User-Facing Changes

1. Handles checking overlays for hidden env vars properly, when getting
an env var from IR instruction
2. Updates config properly when doing `redirect_env()` (these probably
shouldn't be separate functions anyway, though, they're basically the
same. I did this because I intended to remove one, but now it's just
like that)

# Tests + Formatting

The `nu_repl` testbin now handles `NU_USE_IR` properly, so these tests
now work as expected.

# After Submitting

- [ ] check in on #13718 again
2024-09-10 11:03:06 +08:00
493850b1bf Fix IR for try (#13811)
# Description
Fixes a bug in the IR for `try` to match that of the regular evaluator
(continuing from #13515):
```nushell
# without IR:
try { ^false } catch { 'caught' } # == 'caught'

# with IR:
try { ^false } catch { 'caught' } # error, non-zero exit code
```

In this PR, both now evaluate to `caught`. For the implementation, I had
to add another instruction, and feel free to suggest better
alternatives. In the future, it might be possible to get rid of this
extra instruction.

# User-Facing Changes
Bug fix, `try { ^false } catch { 'caught' }` now works in IR.
2024-09-09 19:44:04 -07:00
6600b3edfb Expand multiple dots in path in completions (#13725)
# Description
This is my first PR, and I'm looking for feedback to help me improve! 

This PR fixes #13380 by expanding the path prior to parsing it.
Also I've removed some unused code in
[completion_common.rs](84e92bb02c/crates/nu-cli/src/completions/completion_common.rs
)
# User-Facing Changes

Auto-completion for "cd .../" now works by expanding to "cd ../../". 

# Tests + Formatting

Formatted and added 2 tests for triple dots in the middle of a path and
at the end.
Also added a test for the expand_ndots() function.
2024-09-09 14:39:18 -04:00
aff974552a Add aarch64-unknown-linux-musl and armv7-unknown-linux-musleabihf targets to release workflow (#13800)
# Description

Add aarch64-unknown-linux-musl and armv7-unknown-linux-musleabihf
targets to release workflow. This PR and
https://github.com/nushell/nushell/pull/13775 will close:
https://github.com/nushell/nushell/issues/10444

It works well here:
https://github.com/nushell/nightly/releases/tag/nightly-2d360fd
2024-09-09 09:47:59 +08:00
2afc6a974e bump rust version to 1.79.0 (#13809)
# Description

This PR bumps our rust version from 1.78 to 1.79.0 due to the 1.81.0
release.

# 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.
-->
2024-09-08 16:15:54 -05:00
1e64f59220 Added documentation explanation explaining how to select all columns with polars col (#13806)
# Description
Previously there were no examples or explanations that you can use '*'
to select all columns. Updated description and added a new example.
2024-09-08 17:12:03 +00:00
3e074bc447 Refining error handling in http post (#13805)
Related to #13701

# Description
Refining some of the error handling related to http post command
2024-09-07 23:57:34 +02:00
3d008e2c4e Error on non-zero exit statuses (#13515)
# Description
This PR makes it so that non-zero exit codes and termination by signal
are treated as a normal `ShellError`. Currently, these are silent
errors. That is, if an external command fails, then it's code block is
aborted, but the parent block can sometimes continue execution. E.g.,
see #8569 and this example:
```nushell
[1 2] | each { ^false }
```

Before this would give:
```
╭───┬──╮
│ 0 │  │
│ 1 │  │
╰───┴──╯
```

Now, this shows an error:
```
Error: nu:🐚:eval_block_with_input

  × Eval block failed with pipeline input
   ╭─[entry #1:1:2]
 1 │ [1 2] | each { ^false }
   ·  ┬
   ·  ╰── source value
   ╰────

Error: nu:🐚:non_zero_exit_code

  × External command had a non-zero exit code
   ╭─[entry #1:1:17]
 1 │ [1 2] | each { ^false }
   ·                 ──┬──
   ·                   ╰── exited with code 1
   ╰────
```

This PR fixes #12874, fixes #5960, fixes #10856, and fixes #5347. This
PR also partially addresses #10633 and #10624 (only the last command of
a pipeline is currently checked). It looks like #8569 is already fixed,
but this PR will make sure it is definitely fixed (fixes #8569).

# User-Facing Changes
- Non-zero exit codes and termination by signal now cause an error to be
thrown.
- The error record value passed to a `catch` block may now have an
`exit_code` column containing the integer exit code if the error was due
to an external command.
- Adds new config values, `display_errors.exit_code` and
`display_errors.termination_signal`, which determine whether an error
message should be printed in the respective error cases. For
non-interactive sessions, these are set to `true`, and for interactive
sessions `display_errors.exit_code` is false (via the default config).

# Tests
Added a few tests.

# After Submitting
- Update docs and book.
- Future work:
- Error if other external commands besides the last in a pipeline exit
with a non-zero exit code. Then, deprecate `do -c` since this will be
the default behavior everywhere.
- Add a better mechanism for exit codes and deprecate
`$env.LAST_EXIT_CODE` (it's buggy).
2024-09-07 06:44:26 +00:00
6c1c7f9509 Added expression support for polars cumulative (#13799)
# Description
Provides the ability to use `polars cumulative` as an expression:

<img width="1266" alt="Screenshot 2024-09-06 at 17 47 15"
src="https://github.com/user-attachments/assets/73c11f79-598c-4efa-bfcd-755e536ead66">

# User-Facing Changes
- `polars cumulative` can now be used as an expression.
2024-09-06 22:03:51 -05:00
f531cc2058 Polars command reorg (#13798)
# Description
House keeping. Restructures polars modules as discussed in:
https://docs.google.com/spreadsheets/d/1gyA58i_yTXKCJ5DbO_RxBNAlK6S7C1M22ppKwVLZltc/edit?usp=sharing
2024-09-06 13:46:37 -07:00
edd69aa283 update the latest reedline (#13797)
# Description

I swear, I only did `cargo update -p reedline`. However, I feel down the
dependency rabbit hole. We need to get nushell on crossterm 28.1 and
ratatui on 28.1 but we can't because tabled uses papergrid which uses an
older version of unicode-width that can't be upgraded apparently. Ugh.
I've opened an issue at the tabled repo about this.

# 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.
-->
2024-09-06 09:57:45 -05:00
3d20c53904 make a user friendly message when use_grid_icons is used in config (#13795)
# Description
After merging #13788, I get an error message which says that
`use_grid_icons` is invalid.

I think it's good to report the specific error, and guide user to delete
it.
2024-09-06 06:39:52 -05:00
2d360fda7f String values should pass their content-type correctly on http requests with a body (e.g. http post) (#13731)
# Description
The content-type was not being handled appropriately when sending
requests with a string value.

# User-Facing Changes
- Passing a string value through a pipeline with a content-type set as
metadata is handled correctly
- Passing a string value as a parameter with a content-type set as a
flag is handled correctly.
2024-09-05 16:29:50 -07:00
d0c2adabf7 remove config use_grid_icons, move to parameter of grid command (#13788)
# Description

After looking at #13751 I noticed that the config setting
`use_grid_icons` seems out of place. So, I removed it from the config
and made it a parameter to the `grid` command.
2024-09-06 07:25:43 +08:00
870eb2530c fixed issue with find not working with symbols that should be escaped (#13792)
# Description

Thanks to @weirdan's suggestion, this now works.

![image](https://github.com/user-attachments/assets/34522c7b-b012-4f73-883d-9913142e85b9)

Closes #13789
2024-09-06 07:22:03 +08:00
b2cab3274b fix --ide-ast when there are errors (#13737)
# Description

This PR fixes #13732. However, I don't think it's a proper fix.
1. It doesn't really show what the problem is.
2. It kind of side-steps the error entirely.

I do think the change in span.rs may be valid because I don't think
span.end should ever be 0. In the example in 13732 the span end was
always 0 and so that made contains_span() return true, which seems like
a false positive.

The `checked_sub()` in ide.rs kind of just stops it from failing
outloud.

I'll leave it to smarter folks than me to land this if they think it's
worthy.
2024-09-06 07:17:40 +08:00
92091599ff Fixup serde feature selection in nu-protocol (#13793)
Discovered by @cptpiepmatz that #13749 broke the standalone check for
`nu-protocol`

Explicit use of the feature as workspace root also disables all features
for `serde`. Alternatively we could reconsider this there.
2024-09-06 00:57:36 +02:00
4d2d553cca Use String::contains instead of exact match when matching content types for http requests. (#13791)
# Description
The existing code uses exact matches on content type. This can caused
things like "application/json; charset=utf-8" that contain a charset not
using send_json method.

NOTE: The charset portion in the above example would still be ignored as
we rely on serde and the client library to control the encoding, it is
still better to catch the json case.

---------

Co-authored-by: Ian Manske <ian.manske@pm.me>
2024-09-05 13:08:19 -05:00
dc53c20628 Renamed polars concatenate and added expression support. (#13781)
# Description
In order to be more consistent with the nushell terminology and with
polars expression terminology `polars concatenate` is now `polars
str-join`. `polars str-join` can also be used as expression.

<img width="857" alt="Screenshot 2024-09-04 at 12 41 25"
src="https://github.com/user-attachments/assets/8cc5a0c2-194c-49ec-9fe1-65ec4825414d">


# User-Facing Changes
- `polars concatenate` is now `polars str-join`
- `polars str-join` can be used as an expression
2024-09-05 09:28:34 -07:00
e7c5f83460 Added expression support for polars str-lengths (#13782)
# Description
Allows `polars str-lengths` to be used as an expression:

<img width="826" alt="Screenshot 2024-09-04 at 13 57 45"
src="https://github.com/user-attachments/assets/b74139e0-e8ba-4910-84c2-cf4be4a084b6">

# User-Facing Changes
- `polars str-lengths` can be used as an expression.
- char length is now the default. Use the --bytes flag to get bytes
length.
2024-09-05 09:26:09 -07:00
f611196373 Expression support for polars str-slice (#13783)
# Description
Provides expression support for `polars str-slice`:
<img width="893" alt="Screenshot 2024-09-04 at 18 03 05"
src="https://github.com/user-attachments/assets/d8a8a2a7-53cf-4c3a-ae7a-dfdaf48a05ee">

# User-Facing Changes
- `polars str-slice` can now be used as an expression
2024-09-05 09:06:37 -07:00
abd230e12e Use IntoValue in config code (#13751)
# Description

Cleans up and refactors the config code using the `IntoValue` macro.
Shoutout to @cptpiepmatz for making the macro!

# User-Facing Changes

Should be none.

# After Submitting

Somehow refactor the reverse transformation.
2024-09-05 09:44:23 +02:00
4792328d0e Refactor send_request in client.rs (#13701)
Closes #13687
Closes #13686

# Description
Light refactoring of `send_request `in `client.rs`. In the end there are
more lines but now the logic is more concise and facilitates adding new
conditions in the future. Unit tests ran fine and I tested a few cases
manually.
Cool project btw, I'll be using nushell from now on.
2024-09-04 23:05:39 +02:00
63b94dbd28 Added expression support for polars contains (#13769)
# Description
Adds the ability to use `polars contains` as an expression:
<img width="785" alt="Screenshot 2024-09-03 at 14 39 03"
src="https://github.com/user-attachments/assets/35c0d4e5-6bef-4974-a31f-463c7203bd03">


# User-Facing Changes
- `polars contains` can now be used with expressions
2024-09-04 12:19:45 +02:00
eb0de25d19 Expression support for polars strftime (#13767)
# Description
Allows `polars strftime` to be used as an expression:
<img width="849" alt="Screenshot 2024-09-03 at 13 14 11"
src="https://github.com/user-attachments/assets/2a987fdf-cf00-4c57-b6e1-0b706c594c20">

# User-Facing Changes
- `polars strftime` can now be used as an expression.
2024-09-04 12:19:29 +02:00
ebe42241fe Add #[nu_value(rename = "...")] as helper attribute on members for derive macros (#13761)
# Description

This PR allows the helper attribute `nu_value(rename = "...")` to be
used on struct fields and enum variants. This allows renaming keys and
variants just like [`#[serde(rename =
"name")]`](https://serde.rs/field-attrs.html#rename). This has no
singular variants for `IntoValue` or `FromValue`, both need to use the
same (but I think this shouldn't be an issue for now).

# User-Facing Changes

Users of the derive macros `IntoValue` and `FromValue` may now use
`#[nu_value(rename = "...")]` to rename single fields, but no already
existing code will break.
2024-09-04 11:27:21 +02:00
fa4f9b083e Bump crate-ci/typos from 1.24.1 to 1.24.4 (#13770)
Bumps [crate-ci/typos](https://github.com/crate-ci/typos) from 1.24.1 to
1.24.4.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/crate-ci/typos/releases">crate-ci/typos's
releases</a>.</em></p>
<blockquote>
<h2>v1.24.4</h2>
<h2>[1.24.4] - 2024-09-03</h2>
<h3>Fixes</h3>
<ul>
<li>Offer a correction for <code>grather</code></li>
</ul>
<h2>v1.24.3</h2>
<h2>[1.24.3] - 2024-08-30</h2>
<h3>Fixes</h3>
<ul>
<li>Updated the dictionary with the <a
href="https://redirect.github.com/crate-ci/typos/issues/1069">August
2024</a> changes</li>
</ul>
<h2>v1.24.2</h2>
<h2>[1.24.2] - 2024-08-30</h2>
<h3>Performance</h3>
<ul>
<li>Cap unbounded parsing to avoid worst case performance (hit with test
data)</li>
</ul>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/crate-ci/typos/blob/master/CHANGELOG.md">crate-ci/typos's
changelog</a>.</em></p>
<blockquote>
<h2>[1.24.4] - 2024-09-03</h2>
<h3>Fixes</h3>
<ul>
<li>Offer a correction for <code>grather</code></li>
</ul>
<h2>[1.24.3] - 2024-08-30</h2>
<h3>Fixes</h3>
<ul>
<li>Updated the dictionary with the <a
href="https://redirect.github.com/crate-ci/typos/issues/1069">August
2024</a> changes</li>
</ul>
<h2>[1.24.2] - 2024-08-30</h2>
<h3>Performance</h3>
<ul>
<li>Cap unbounded parsing to avoid worst case performance (hit with test
data)</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="853bbe8898"><code>853bbe8</code></a>
chore: Release</li>
<li><a
href="b5f56600b2"><code>b5f5660</code></a>
docs: Update changelog</li>
<li><a
href="39f678e520"><code>39f678e</code></a>
Merge pull request <a
href="https://redirect.github.com/crate-ci/typos/issues/1093">#1093</a>
from kachick/grather-suggest-candidates</li>
<li><a
href="bb6905fdc9"><code>bb6905f</code></a>
Merge pull request <a
href="https://redirect.github.com/crate-ci/typos/issues/1092">#1092</a>
from crate-ci/renovate/embarkstudios-cargo-deny-acti...</li>
<li><a
href="786c825f17"><code>786c825</code></a>
fix(dict): Add suggestions for the typo &quot;grather&quot;</li>
<li><a
href="340058181b"><code>3400581</code></a>
chore(deps): Update EmbarkStudios/cargo-deny-action action to v2</li>
<li><a
href="9ad6f5c054"><code>9ad6f5c</code></a>
chore: Release</li>
<li><a
href="12e101ec51"><code>12e101e</code></a>
docs: Update changelog</li>
<li><a
href="8c58591ec4"><code>8c58591</code></a>
Merge pull request <a
href="https://redirect.github.com/crate-ci/typos/issues/1091">#1091</a>
from epage/august</li>
<li><a
href="250dcc73e6"><code>250dcc7</code></a>
fix(dict): Aug updates</li>
<li>Additional commits viewable in <a
href="https://github.com/crate-ci/typos/compare/v1.24.1...v1.24.4">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=crate-ci/typos&package-manager=github_actions&previous-version=1.24.1&new-version=1.24.4)](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>
2024-09-04 10:03:07 +08:00
e7b7c7f39a Bump nix from 0.28.0 to 0.29.0 (#13773)
Bumps [nix](https://github.com/nix-rust/nix) from 0.28.0 to 0.29.0.
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/nix-rust/nix/blob/master/CHANGELOG.md">nix's
changelog</a>.</em></p>
<blockquote>
<h2>[0.29.0] - 2024-05-24</h2>
<h3>Added</h3>
<ul>
<li>Add <code>getregset()/setregset()</code> for
Linux/glibc/x86/x86_64/aarch64/riscv64 and
<code>getregs()/setregs()</code> for Linux/glibc/aarch64/riscv64
(<a
href="https://redirect.github.com/nix-rust/nix/pull/2044">#2044</a>)</li>
<li>Add socket option Ipv6Ttl for apple targets.
(<a
href="https://redirect.github.com/nix-rust/nix/pull/2287">#2287</a>)</li>
<li>Add socket option UtunIfname.
(<a
href="https://redirect.github.com/nix-rust/nix/pull/2325">#2325</a>)</li>
<li>make SigAction repr(transparent) &amp; can be converted to the libc
raw type
(<a
href="https://redirect.github.com/nix-rust/nix/pull/2326">#2326</a>)</li>
<li>Add <code>From</code> trait implementation for conversions between
<code>sockaddr_in</code> and
<code>SockaddrIn</code>, <code>sockaddr_in6</code> and
<code>SockaddrIn6</code>
(<a
href="https://redirect.github.com/nix-rust/nix/pull/2328">#2328</a>)</li>
<li>Add socket option ReusePortLb for FreeBSD.
(<a
href="https://redirect.github.com/nix-rust/nix/pull/2332">#2332</a>)</li>
<li>Added support for openat2 on linux.
(<a
href="https://redirect.github.com/nix-rust/nix/pull/2339">#2339</a>)</li>
<li>Add if_indextoname function.
(<a
href="https://redirect.github.com/nix-rust/nix/pull/2340">#2340</a>)</li>
<li>Add <code>mount</code> and <code>unmount</code> API for apple
targets.
(<a
href="https://redirect.github.com/nix-rust/nix/pull/2347">#2347</a>)</li>
<li>Added <code>_PC_MIN_HOLE_SIZE</code> for <code>pathconf</code> and
<code>fpathconf</code>.
(<a
href="https://redirect.github.com/nix-rust/nix/pull/2349">#2349</a>)</li>
<li>Added <code>impl AsFd for pty::PtyMaster</code>
(<a
href="https://redirect.github.com/nix-rust/nix/pull/2355">#2355</a>)</li>
<li>Add <code>open</code> flag <code>O_SEARCH</code> to AIX,
Empscripten, FreeBSD, Fuchsia, solarish,
WASI (<a
href="https://redirect.github.com/nix-rust/nix/pull/2374">#2374</a>)</li>
<li>Add prctl function <code>prctl_set_vma_anon_name</code> for
Linux/Android.
(<a
href="https://redirect.github.com/nix-rust/nix/pull/2378">#2378</a>)</li>
<li>Add <code>sync(2)</code> for
<code>apple_targets/solarish/haiku/aix/hurd</code>,
<code>syncfs(2)</code> for
<code>hurd</code> and <code>fdatasync(2)</code> for
<code>aix/hurd</code>
(<a
href="https://redirect.github.com/nix-rust/nix/pull/2379">#2379</a>)</li>
<li>Add fdatasync support for Apple targets.
(<a
href="https://redirect.github.com/nix-rust/nix/pull/2380">#2380</a>)</li>
<li>Add <code>fcntl::OFlag::O_PATH</code> for FreeBSD and Fuchsia
(<a
href="https://redirect.github.com/nix-rust/nix/pull/2382">#2382</a>)</li>
<li>Added <code>PathconfVar::MIN_HOLE_SIZE</code> for apple_targets.
(<a
href="https://redirect.github.com/nix-rust/nix/pull/2388">#2388</a>)</li>
<li>Add <code>open</code> flag <code>O_SEARCH</code> to apple_targets
(<a
href="https://redirect.github.com/nix-rust/nix/pull/2391">#2391</a>)</li>
<li><code>O_DSYNC</code> may now be used with <code>aio_fsync</code> and
<code>fcntl</code> on FreeBSD.
(<a
href="https://redirect.github.com/nix-rust/nix/pull/2404">#2404</a>)</li>
<li>Added <code>Flock::relock</code> for upgrading and downgrading
locks.
(<a
href="https://redirect.github.com/nix-rust/nix/pull/2407">#2407</a>)</li>
</ul>
<h3>Changed</h3>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="1dad4d8d04"><code>1dad4d8</code></a>
chore: prepare for 0.29.0</li>
<li><a
href="f7431971b4"><code>f743197</code></a>
fix ControlMessageOwned::UdpGroSegments UDP packets processing type. (<a
href="https://redirect.github.com/nix-rust/nix/issues/2406">#2406</a>)</li>
<li><a
href="208b80b65d"><code>208b80b</code></a>
recvmsg: Check if CMSG buffer was too small and return an error (<a
href="https://redirect.github.com/nix-rust/nix/issues/2413">#2413</a>)</li>
<li><a
href="ecd12a9990"><code>ecd12a9</code></a>
test: remove test of inode count in test_statfs.rs (<a
href="https://redirect.github.com/nix-rust/nix/issues/2414">#2414</a>)</li>
<li><a
href="663506a602"><code>663506a</code></a>
fix: only close <code>fanotify</code> events with a valid fd (<a
href="https://redirect.github.com/nix-rust/nix/issues/2399">#2399</a>)</li>
<li><a
href="1604723757"><code>1604723</code></a>
revert: impl From&lt;sigaction&gt; for SigAction (<a
href="https://redirect.github.com/nix-rust/nix/issues/2410">#2410</a>)</li>
<li><a
href="ec4beb5a22"><code>ec4beb5</code></a>
docs: correct limit value of FAN_UNLIMITED_QUEUE and
FAN_UNLIMITED_MARKS[skip...</li>
<li><a
href="84c0444c3a"><code>84c0444</code></a>
chore: bump libc to 0.2.155 (<a
href="https://redirect.github.com/nix-rust/nix/issues/2409">#2409</a>)</li>
<li><a
href="c5af4adffd"><code>c5af4ad</code></a>
Add Flock::relock (<a
href="https://redirect.github.com/nix-rust/nix/issues/2407">#2407</a>)</li>
<li><a
href="e7acaff07f"><code>e7acaff</code></a>
Enable O_DSYNC on FreeBSD with fcntl and aio_fsync (<a
href="https://redirect.github.com/nix-rust/nix/issues/2404">#2404</a>)</li>
<li>Additional commits viewable in <a
href="https://github.com/nix-rust/nix/compare/v0.28.0...v0.29.0">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=nix&package-manager=cargo&previous-version=0.28.0&new-version=0.29.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>
2024-09-04 10:03:02 +08:00
6be458c686 Bump itertools from 0.12.1 to 0.13.0 (#13774)
Bumps [itertools](https://github.com/rust-itertools/itertools) from
0.12.1 to 0.13.0.
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/rust-itertools/itertools/blob/master/CHANGELOG.md">itertools's
changelog</a>.</em></p>
<blockquote>
<h2>0.13.0</h2>
<h3>Breaking</h3>
<ul>
<li>Removed implementation of <code>DoubleEndedIterator</code> for
<code>ConsTuples</code> (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/853">#853</a>)</li>
<li>Made <code>MultiProduct</code> fused and fixed on an empty iterator
(<a
href="https://redirect.github.com/rust-itertools/itertools/issues/835">#835</a>,
<a
href="https://redirect.github.com/rust-itertools/itertools/issues/834">#834</a>)</li>
<li>Changed <code>iproduct!</code> to return tuples for maxi one
iterator too (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/870">#870</a>)</li>
<li>Changed <code>PutBack::put_back</code> to return the old value (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/880">#880</a>)</li>
<li>Removed deprecated <code>repeat_call, Itertools::{foreach, step,
map_results, fold_results}</code> (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/878">#878</a>)</li>
<li>Removed <code>TakeWhileInclusive::new</code> (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/912">#912</a>)</li>
</ul>
<h3>Added</h3>
<ul>
<li>Added <code>Itertools::{smallest_by, smallest_by_key, largest,
largest_by, largest_by_key}</code> (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/654">#654</a>,
<a
href="https://redirect.github.com/rust-itertools/itertools/issues/885">#885</a>)</li>
<li>Added <code>Itertools::tail</code> (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/899">#899</a>)</li>
<li>Implemented <code>DoubleEndedIterator</code> for
<code>ProcessResults</code> (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/910">#910</a>)</li>
<li>Implemented <code>Debug</code> for <code>FormatWith</code> (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/931">#931</a>)</li>
<li>Added <code>Itertools::get</code> (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/891">#891</a>)</li>
</ul>
<h3>Changed</h3>
<ul>
<li>Deprecated <code>Itertools::group_by</code> (renamed
<code>chunk_by</code>) (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/866">#866</a>,
<a
href="https://redirect.github.com/rust-itertools/itertools/issues/879">#879</a>)</li>
<li>Deprecated <code>unfold</code> (use <code>std::iter::from_fn</code>
instead) (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/871">#871</a>)</li>
<li>Optimized <code>GroupingMapBy</code> (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/873">#873</a>,
<a
href="https://redirect.github.com/rust-itertools/itertools/issues/876">#876</a>)</li>
<li>Relaxed <code>Fn</code> bounds to <code>FnMut</code> in
<code>diff_with, Itertools::into_group_map_by</code> (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/886">#886</a>)</li>
<li>Relaxed <code>Debug/Clone</code> bounds for <code>MapInto</code> (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/889">#889</a>)</li>
<li>Documented the <code>use_alloc</code> feature (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/887">#887</a>)</li>
<li>Optimized <code>Itertools::set_from</code> (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/888">#888</a>)</li>
<li>Removed badges in <code>README.md</code> (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/890">#890</a>)</li>
<li>Added &quot;no-std&quot; categories in <code>Cargo.toml</code> (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/894">#894</a>)</li>
<li>Fixed <code>Itertools::k_smallest</code> on short unfused iterators
(<a
href="https://redirect.github.com/rust-itertools/itertools/issues/900">#900</a>)</li>
<li>Deprecated <code>Itertools::tree_fold1</code> (renamed
<code>tree_reduce</code>) (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/895">#895</a>)</li>
<li>Deprecated <code>GroupingMap::fold_first</code> (renamed
<code>reduce</code>) (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/902">#902</a>)</li>
<li>Fixed <code>Itertools::k_smallest(0)</code> to consume the iterator,
optimized <code>Itertools::k_smallest(1)</code> (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/909">#909</a>)</li>
<li>Specialized <code>Combinations::nth</code> (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/914">#914</a>)</li>
<li>Specialized <code>MergeBy::fold</code> (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/920">#920</a>)</li>
<li>Specialized <code>CombinationsWithReplacement::nth</code> (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/923">#923</a>)</li>
<li>Specialized <code>FlattenOk::{fold, rfold}</code> (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/927">#927</a>)</li>
<li>Specialized <code>Powerset::nth</code> (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/924">#924</a>)</li>
<li>Documentation fixes (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/882">#882</a>,
<a
href="https://redirect.github.com/rust-itertools/itertools/issues/936">#936</a>)</li>
<li>Fixed <code>assert_equal</code> for iterators longer than
<code>i32::MAX</code> (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/932">#932</a>)</li>
<li>Updated the <code>must_use</code> message of non-lazy
<code>KMergeBy</code> and <code>TupleCombinations</code> (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/939">#939</a>)</li>
</ul>
<h3>Notable Internal Changes</h3>
<ul>
<li>Tested iterator laziness (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/792">#792</a>)</li>
<li>Created <code>CONTRIBUTING.md</code> (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/767">#767</a>)</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="d5084d15e9"><code>d5084d1</code></a>
Prepare v0.13.0 release (<a
href="https://redirect.github.com/rust-itertools/itertools/issues/937">#937</a>)</li>
<li><a
href="d7c99d55da"><code>d7c99d5</code></a>
<code>TupleCombinations</code> is not lazy but must be used
nonetheless</li>
<li><a
href="074c7fcc07"><code>074c7fc</code></a>
<code>KMergeBy</code> is not lazy but must be used nonetheless</li>
<li><a
href="2ad9e07ae8"><code>2ad9e07</code></a>
<code>assert_equal</code>: fix
<code>clippy::default_numeric_fallback</code></li>
<li><a
href="0d4efc8432"><code>0d4efc8</code></a>
Remove free function <code>get</code></li>
<li><a
href="05cc0ee256"><code>05cc0ee</code></a>
<code>get(s..=usize::MAX)</code> should be fine when <code>s !=
0</code></li>
<li><a
href="3c16f14baa"><code>3c16f14</code></a>
<code>get</code>: when is it ESI and/or DEI</li>
<li><a
href="4dd6ba0e7c"><code>4dd6ba0</code></a>
<code>get</code>: panics if the range includes
<code>usize::MAX</code></li>
<li><a
href="7a9ce56fc5"><code>7a9ce56</code></a>
<code>get(r: Range)</code> as <code>Skip\&lt;Take&gt;</code></li>
<li><a
href="f676f2f964"><code>f676f2f</code></a>
Remove the unspecified check about
<code>.get(exhausted_range_inclusive)</code></li>
<li>Additional commits viewable in <a
href="https://github.com/rust-itertools/itertools/compare/v0.12.1...v0.13.0">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=itertools&package-manager=cargo&previous-version=0.12.1&new-version=0.13.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>
2024-09-04 10:02:48 +08:00
348c59b740 Bump indexmap from 2.4.0 to 2.5.0 (#13772)
Bumps [indexmap](https://github.com/indexmap-rs/indexmap) from 2.4.0 to
2.5.0.
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/indexmap-rs/indexmap/blob/master/RELEASES.md">indexmap's
changelog</a>.</em></p>
<blockquote>
<h2>2.5.0</h2>
<ul>
<li>Added an <code>insert_before</code> method to <code>IndexMap</code>
and <code>IndexSet</code>, as an
alternative to <code>shift_insert</code> with different behavior on
existing entries.</li>
<li>Added <code>first_entry</code> and <code>last_entry</code> methods
to <code>IndexMap</code>.</li>
<li>Added <code>From</code> implementations between
<code>IndexedEntry</code> and <code>OccupiedEntry</code>.</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="48ed49017c"><code>48ed490</code></a>
Release 2.5.0</li>
<li><a
href="139d7addfb"><code>139d7ad</code></a>
Merge pull request <a
href="https://redirect.github.com/indexmap-rs/indexmap/issues/340">#340</a>
from cuviper/insert-bounds</li>
<li><a
href="1d9b5e3d03"><code>1d9b5e3</code></a>
Add doc examples for <code>insert_before</code> and
<code>shift_insert</code></li>
<li><a
href="8ca01b0df7"><code>8ca01b0</code></a>
Use <code>insert_before</code> for &quot;new&quot; entries in
<code>insert_sorted</code></li>
<li><a
href="7224def010"><code>7224def</code></a>
Add <code>insert_before</code> as an alternate to
<code>shift_insert</code></li>
<li><a
href="0247a1555d"><code>0247a15</code></a>
Document and assert index bounds in <code>shift_insert</code></li>
<li><a
href="922c6ad1af"><code>922c6ad</code></a>
Update the CI badge</li>
<li><a
href="e482e1768a"><code>e482e17</code></a>
Merge pull request <a
href="https://redirect.github.com/indexmap-rs/indexmap/issues/342">#342</a>
from cuviper/btree-like</li>
<li><a
href="b63e4a1556"><code>b63e4a1</code></a>
Merge pull request <a
href="https://redirect.github.com/indexmap-rs/indexmap/issues/341">#341</a>
from cuviper/from-entry</li>
<li><a
href="264e5b7304"><code>264e5b7</code></a>
Add doc aliases like <code>BTreeMap</code>/<code>BTreeSet</code></li>
<li>Additional commits viewable in <a
href="https://github.com/indexmap-rs/indexmap/compare/2.4.0...2.5.0">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=indexmap&package-manager=cargo&previous-version=2.4.0&new-version=2.5.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>
2024-09-04 10:02:01 +08:00
2c827d2bf4 Try to add aarch64-unknown-linux-musl and armv7-unknown-linux-musleabihf release target (#13775)
Related: https://github.com/nushell/nushell/issues/10444

<!--
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
Try to add `aarch64-unknown-linux-musl` and
`armv7-unknown-linux-musleabihf` release target
I will test these two new targets in the nightly workflow, It should
work:
https://github.com/nushell/nightly/actions/runs/10692449465/job/29640875827,
and check the release binaries. If everything goes well we can add the
`musl` targets in the next release
2024-09-04 09:28:00 +08:00
61544eecd6 add version and path to plugin executable help (#13764)
# Description

This change allows one to see the version of their plugin file without
trying to register it.


![image](https://github.com/user-attachments/assets/9f1ddbd7-f63f-47f7-87c8-0d839f5e4b1f)


# 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.
-->
2024-09-03 12:46:36 -05:00
c150af4279 Don't panic on detect columns with --guess flag (#13752)
# Description
This pr addresses the comment:
https://github.com/nushell/nushell/issues/11791#issuecomment-2308384155

It's caused by if the last row have a very different format to the first
row, the value of `end_char` will exceed the `line_char_boundaries`.
Adding a guard for it should avoid such panic.

# User-Facing Changes
The following code should no longer panic:
```shell
"nu_plugin_highlight = '1.2.2+0.97.1'    # A nushell plugin for syntax highlighting
trace_nu_plugin = '0.3.1'               # A wrapper to trace Nu plugins
nu_plugin_bash_env = '0.13.0'           # Nu plugin bash-env
nu_plugin_from_sse = '0.4.0'            # Nushell plugin to convert a HTTP server sent event stream to structured data
... and 90 crates more (use --limit N to see more)" | detect columns -n --guess
```

# Tests + Formatting
Added 1 test.
2024-09-02 16:29:53 +02:00
39bda8986e Make tee work more nicely with non-collections (#13652)
# Description

This changes the behavior of `tee` to be more transparent when given a
value that isn't a list or range. Previously, anything that wasn't a
byte stream would converted to a list stream using the iterator
implementation, which led to some surprising results. Instead, now, if
the value is a string or binary, it will be treated the same way a byte
stream is, and the output of `tee` is a byte stream instead of the
original value. This is done so that we can synchronize with the other
thread on collect, and potentially capture any error produced by the
closure.

For values that can't be converted to streams, the closure is just run
with a clone of the value instead on another thread. Because we can't
wait for the other thread, there is no way to send an error back to the
original thread, so instead it's just written to stderr using
`report_error_new()`.

There are a couple of follow up edge cases I see where byte streams
aren't necessarily treated exactly the same way strings are, but this
should mostly be a good experience.

Fixes #13489.

# User-Facing Changes

Breaking change.

- `tee` now outputs and sends string/binary stream for string/binary
input.
- `tee` now outputs and sends the original value for any other input
other than lists/ranges.

# Tests + Formatting

Added for new behavior.

# After Submitting

- [ ] release notes: breaking change, command change
2024-09-01 19:03:46 +02:00
ee997ef3dd Remove unneeded serde feature on byte-unit dep (#13749)
removing the `std` feature as well would drop some dependencies tied to
`rust_decimal` from the `Cargo.lock` but unclear to me what the actual
impact on compile times is.

We may want to consider dropping the `byte-unit` dependency altogether
as we have a significant fraction of our own logic to support the byte
units with 1024 and 1000 prefixes. Not sure which fraction is covered by
us or the dependency.
2024-09-01 19:02:28 +02:00
e3f59910b8 Implement IntoValue for more types (#13744)
# Description

Implements `IntoValue` for `&str` and `DateTime` as well as other
nushell types like `Record` and `Closure`. Also allows `HashMap`s with
keys besides `String` to implement `IntoValue`.
2024-09-01 19:02:12 +02:00
f4940e115f Remove bincode and use MessagePack instead for plugin custom values (#13745)
# Description

This changes the serialization of custom values within the plugin
protocol to use MessagePack instead of bincode, removing the dependency
on bincode entirely.

Bincode does not seem to be very maintained anymore, and the externally
tagged enum representation doesn't seem to always work now even though
it should. Since we use MessagePack already anyway for the plugin
protocol, this seems like an obvious choice. This uses the unnamed
variant of the serialization rather than the named variant, which is
what the plugin protocol in general uses. The unnamed variant does not
include field names, which aren't really required here, so this should
give us something that's more or less as efficient as bincode is.

Should fix #13743.

# User-Facing Changes

- Will need to recompile plugins (but always do anyway)
- Doesn't technically break the plugin protocol (custom value data is a
black box / plugin implementation specific), but breaks compatibility
between `nu-plugin-engine` and `nu-plugin` so they do need to both be
updated to match.

# Tests + Formatting

All tests pass.

# After Submitting

- [ ] release notes
2024-09-01 17:33:10 +02:00
3f31ca7b8e remove cfg_atter tarpaulin (#13739)
# Description

Remove the `#[cfg_attr(tarpaulin, ignore)]` code coverage attributes to
get rid warnings when compiling plugins with a more recent rust version
than nushell.
2024-08-31 16:45:15 +02:00
0119534f61 Expression support polars replace and polars replace-all (#13726)
# Description
Adds the ability for `polars replace` and `polars replace-all` to work
as expressions.

# User-Facing Changes
- `polars replace` can be used with polars expressions
- `polars replace-all` can be used with polars expressions
2024-08-29 13:59:44 -07:00
84e1ac27e5 Setup global cargo lint configuration (#13691)
# Description
`cargo` somewhat recently gained the capability to store `lints`
settings for the crate and workspace, that can override the defaults
from `rustc` and `clippy` lints. This means we can enforce some lints
without having to actively pass them to clippy via `cargo clippy -- -W
...`. So users just forking the repo have an easier time to follow
similar requirements like our CI.

## Limitation

An exception that remains is that those lints apply to both the primary
code base and the tests. Thus we can't include e.g. `unwrap_used`
without generating noise in the tests. Here the setup in the CI remains
the most helpful.

## Included lints

- Add `clippy::unchecked_duration_subtraction` (added by #12549)
# User-Facing Changes
Running `cargo clippy --workspace` should be closer to the CI. This has
benefits for editor configured runs of clippy and saves you from having
to use `toolkit` to be close to CI in more cases.
2024-08-28 23:37:17 +02:00
644bebf4c6 Expression support for polars uppercase and polars lowercase (#13724) 2024-08-28 14:08:16 -07:00
f58a4b5017 Add split cell-path (#13705)
this PR should close #12168

# Description
Add `split cell-path`, inverse of `into cell-path`.

# User-Facing Changes
Currently there is no way to make use of cell-path values as a user,
other than passing them to builtin commands. This PR makes more use
cases possible.
2024-08-28 23:01:26 +02:00
ae0e13733d Fix parsing record values containing colons (#13413)
This PR is an attempt to fix #8257 and fix #10985 (which is
duplicate-ish)

# Description
The parser currently doesn't know how to deal with colons appearing
while lexing whitespace-terminated tokens specifying a record value.
Most notably, this means you can't use datetime literals in record value
position (and as a consequence, `| to nuon | from nuon` roundtrips can
fail), but it also means that bare words containing colons cause a
non-useful error message.

![image](https://github.com/user-attachments/assets/f04a8417-ee18-44e7-90eb-a0ecef943a0f)

`parser::parse_record` calls `lex::lex` with the `:` colon character in
the `special_tokens` argument. This allows colons to terminate record
keys, but as a side effect, it also causes colons to terminate record
*values*. I added a new function `lex::lex_n_tokens`, which allows the
caller to drive the lexing process more explicitly, and used it in
`parser::parse_record` to let colons terminate record keys while not
giving them special treatment when appearing in record values.

This PR description previously said: *Another approach suggested in one
of the issues was to support an additional datetime literal format that
doesn't require colons. I like that that wouldn't require new
`lex::lex_internal` behaviour, but an advantage of my approach is that
it also newly allows for string record values given as bare words
containing colons. I think this eliminates another possible source of
confusion.* It was determined that this is undesirable, and in the
current state of this PR, bare word record values with colons are
rejected explicitly. The better error message is still a win.

# User-Facing Changes
In addition to the above, this PR also disables the use of "special"
(non-item) tokens in record key and value position, and the use of a
single bare `:` as a record key.

Examples of behaviour *before* this PR:
```nu
{ a: b } # Valid, same as { 'a': 'b' }
{ a: b:c } # Error: expected ':'
{ a: 2024-08-13T22:11:09 } # Error: expected ':'
{ :: 1 } # Valid, same as { ':': 1 }
{ ;: 1 } # Valid, same as { ';': 1 }
{ a: || } # Valid, same as { 'a': '||' }
```

Examples of behaviour *after* this PR:
```nu
{ a: b } # (Unchanged) Valid, same as { 'a': 'b' }
{ a: b:c } # Error: colon in bare word specifying record value
{ a: 2024-08-13T22:11:09 } # Valid, same as { a: (2024-08-13T22:11:09) }
{ :: 1 } # Error: colon in bare word specifying record key
{ ;: 1 } # Error: expected item in record key position
{ a: || } # Error: expected item in record value position
```

# Tests + Formatting
I added tests, but I'm not sure if they're sufficient and in the right
place.

# After Submitting
I don't think documentation changes are needed for this, but please let
me know if you disagree.
2024-08-28 22:53:56 +02:00
2c379cba71 Remove system-clipboard from the default build (#13694)
# Description
This feature tried to connect reedline with the system clipboard for
three special bindings.
To do so it uses the `arboard` crate with heavy dependencies for the
system X or Wayland server or the Windows APIs. We had issues in the
headless CI with it and builds with musl seem to stall.

Removing it from the default build should negatively impact only a small
subset of users aware of the extra bindings. You can still use the
internal clipboard for binding based selection and the terminals extra
bindings to copy arbitrary content into the system clipboard.

For all other users it removes potential sources of failure and a whole
1 MB of release mode binary size (> 2% reduction). Furthermore a
potentially substantial attack surface for Nushell is gone for default
builds.

- Should resolve #13019
- Work in the spirit of #13603


# User-Facing Changes

The `edit` entries
`copyselectionsystem`/`copyselectionsystem`/`pastesystem` for
keybindings are gone in the default build

If you strictly depend on this behavior, you can still build with the
addition of `--features system-clipboard`
2024-08-28 22:19:13 +02:00
7171c9b84a Bump shadow-rs from 0.31.1 to 0.33.0 (#13713) 2024-08-28 13:05:11 +00:00
055d7e27e9 Use heck instead of convert_case for nu-derive-value (#13708)
<!--
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.
-->
@sholderbach mentioned that I introduced `convert_case` as a dependency
while we already had `heck` for case conversion. So in this PR replaced
the use `convert_case` with `heck`. Mostly I rebuilt the `convert_case`
API with `heck` to work with it as I like the API of `convert_case` more
than `heck`.

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->
Nothing changed, the use of `convert_case` wasn't exposed anywhere and
all case conversions are still available.

# 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
> ```
-->
No new tests required but my tests in `test_derive` captured some errors
I made while developing this change, (hurray, tests work 🎉)
- 🟢 `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.
-->
2024-08-28 08:02:25 -05:00
af76e11dd6 Remove str deunicode (#13693)
# Description
Closes #13677

Remove the command `str deunicode`, as it has a narrow application, is
loosely defined by the data provided by the `deunicode` crate and thus a
stabilization liability post-1.0.

Furthermore the data to perform the look-up is quite substantial.

Removing the command and the `deunicode` dependency saves 0.9 MB of
binary data in release mode (~ 2% of total)

(checked via `cargo bloat --release` for a linux x86 build)


# User-Facing Changes
The `str deunicode` command recently added in #13270 is gone
2024-08-28 07:58:38 -05:00
7dda39a89e Simplify our bug reporting form (#13695)
The two additional boxes for "additional context" and screenshots may be
somewhat redundant to the primary `Steps to reproduce`. Sadly folks are
already a bit lazy with the core task of providing a succinct
reproducing example. Having additional fields may not actually improve
the quality and lead to waffling or if left empty some deadspace to
scroll past.
2024-08-28 07:58:10 -05:00
4f822e263f Respect user-defined $env.NU_LOG_FORMAT and $env.NU_LOG_DATE_FORMAT (#13692)
Fixes nushell/nushell#13689

# Description

Respect user-defined `$env.NU_LOG_FORMAT` and `$env.NU_LOG_DATE_FORMAT`

Additionally I fixed `nu_with_std!()` macro (it was not working
correctly)

# User-Facing Changes

Users now may set `$env.NU_LOG_FORMAT` and `$env.NU_LOG_DATE_FORMAT` in
`env.nu` and it will work even if `use std` is used after that.

# Tests + Formatting

Added a couple of tests for the new functionality.

# After Submitting
2024-08-28 07:57:43 -05:00
a39e94de8a Added polars commands for converting string columns to integer and decimal columns (#13711)
# Description
Introduces two new polars commands for converting string columns to
decimal and integer columns:

<img width="740" alt="Screenshot 2024-08-27 at 15 32 28"
src="https://github.com/user-attachments/assets/f9573b6e-48f6-4bbf-8782-39ffb95eb934">

<img width="720" alt="Screenshot 2024-08-27 at 15 33 46"
src="https://github.com/user-attachments/assets/90a66bb5-fa78-4ed3-8b2b-ae05cddd2f3a">

# User-Facing Changes
- Addition of the `polars integer` command
- Addition of the `polars decimal` command
2024-08-28 07:54:31 -05:00
a88f46c6c9 update virtual terminal processing (#13710)
# Description

With Windows Terminal Canary 1.23.240826001-llm, this enables nushell to
query the terminal and receive a response.


![image](https://github.com/user-attachments/assets/c4c43328-c431-47e4-b377-8b3a2bc12b74)

The red component here is
```nushell
❯ ("0c0c" | into int -r 16) / 256 | math round | fmt | get lowerhex
0xc
```

This example queries the background and the response is a r/g/b color.
The response really should be
```
␛]11;1;rgb:0c0c/0c0c/0c0c
```
I'm not sure why nushell's input is eating the first part.

# 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.
-->
2024-08-28 07:54:01 -05:00
4ca1f95b6c Bump crate-ci/typos from 1.23.6 to 1.24.1 (#13716) 2024-08-28 12:36:03 +00:00
71ced35987 Changed category for panic and added search terms and examples (#13707)
# Description
Cosmetic changes around `panic` command. Changed category, added search
terms, and examples.

# User-Facing Changes
See above
2024-08-27 16:58:05 -07:00
1128df2d29 Added record key renaming for derive macros IntoValue and FromValue (#13699)
# Description

Using derived `IntoValue` and `FromValue` implementations on structs
with named fields currently produce `Value::Record`s where each key is
the key of the Rust struct. For records like the `$nu` constant, that
won't work as this record uses `kebab-case` for it's keys. To accomodate
this, I upgraded the `#[nu_value(rename_all = "...")]` helper attribute
to also work on structs with named fields which will rename the keys via
the same case conversion as the enums already have.

# User-Facing Changes
Users of these macros may choose different key styles for their in
`Value` representation.

# Tests + Formatting
I added the same test suite as enums already have and updated the traits
documentation with more examples that also pass the doc test.

# After Submitting
I played around with the `$nu` constant but got stuck at the point that
these keys are kebab-cased, with this, I can play around more with it.
2024-08-27 20:00:44 +02:00
da98c23ab3 Use right options in custom completions (#13698)
<!--
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 issue was reported by kira in
[Discord](https://discord.com/channels/601130461678272522/1276981416307069019).
In https://github.com/nushell/nushell/pull/13311, I accidentally made it
so that custom completions are filtered according to the user's
configured completion options (`$env.config.completions`) rather than
the completion options provided as part of the custom completions. This
PR is a quick fix for that.

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

It should once again be possible to override match algorithm, case
sensitivity, and substring matching (`positional`) in custom
completions.

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

# 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 and I discussed this in Discord a bit and we thought it might be
better to not allow custom completions to override the user's config.
However, `positional` can't currently be set inside one's config, so you
can only do strict prefix matching, no substring matching. Another PR
could do one of the following:
- Document the fact that you can provide completion options inside
custom completions
- Remove the ability to provide completion options with custom
completions and add a `$env.config.completions.positional: true` option
- Remove the ability to provide completion options with custom
completions and add a new match algorithm `substring` (this is the one I
like most, since `positional` only applies to prefix matching anyway)

Separately from these options, we could also allow completers to specify
that they don't Nushell to do any filtering and sorting on the provided
custom completions.
2024-08-26 12:14:57 -05:00
e3efc8da9f Remove unnecessary sort in explore search fn (#13690)
Noticed when playing with the `stable_sort_primitive` lint that the
elements from `enumerate` are already sorted.
2024-08-25 20:13:05 +02:00
3f332bef35 Fix encode/decode todo's (#13683)
Mistakes have been made. I forgot about a bunch of `todo`s in the helper
functions. So, this PR replaces them with proper errors. It also adds
tests for parse-time evaluation, because one `todo` I missed was in a
`run_const` function.
2024-08-24 09:02:02 -05:00
525eac1afd [DRAFT] Check fix for emojie, wrap issues (#13430)
Hi there

Here I am using latest tabled.

My tests shows it does fixes panics, but I am wanna be sure.

@fdncred could you verify that it does fixes those panics/errors?

Closes #13405 
Closes #12786
2024-08-23 17:35:42 -05:00
7003b007d5 doc: fix broken doc links (#13644)
Some broken doc links I saw when compiling with `cargo +stable doc
--no-deps --document-private-items --workspace --open`
2024-08-23 21:17:44 +02:00
dfdb2b5d31 Improve help output for scripts (#13445)
# 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.
-->
Currently the parser and the documentation generation use the signature
of the command, which means that it doesn't pick up on the changed name
of the `main` block, and therefore shows the name of the command as
"main" and doesn't find the subcommands. This PR changes the
aforementioned places to use the block signature to fix these issues.
This closes #13397. Incidentally it also causes input/output types to be
shown in the help, which is kinda pointless for scripts since they don't
operate on structured data but maybe not worth the effort to remove.

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->
```
# example.nu
export def main [] { help main }
export def 'main sub' [] { print 'sub' }
```
Before:

![image](https://github.com/user-attachments/assets/49fdcf8d-e56a-4c27-b7c8-7d2902c2a807)

![image](https://github.com/user-attachments/assets/4d1f4faa-5928-4269-b0b5-fd654563bb8b)


After:

![image](https://github.com/user-attachments/assets/a7232a1f-f997-4988-808c-8fa957e39bae)

![image](https://github.com/user-attachments/assets/c5628dc6-69b5-443a-b103-9e5faa9bb4ba)

# Tests
<!--
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
> ```
-->

Tests are still missing for the subcommands and the input/output types

---------

Co-authored-by: Stefan Holderbach <sholderbach@users.noreply.github.com>
2024-08-23 21:08:27 +02:00
822007dbbb Remove unused same-file workspace dependency (#13678)
A small no-op change. It was used in a two years old `mv` fix
(848550771a, pre `uu_mv`). But now it's redundant.
2024-08-23 20:51:34 +02:00
0560826414 encode/decode for multiple alphabets (#13428)
Based on the discussion in #13419.


## Description

Reworks the `decode`/`encode` commands by adding/changing the following
bases:

- `base32`
- `base32hex`
- `hex`
- `new-base64`

The `hex` base is compatible with the previous version of `hex` out of
the box (it only adds more flags). `base64` isn't, so the PR adds a new
version and deprecates the old one.

All commands have `string -> binary` signature for decoding and `string
| binary -> string` signature for encoding. A few `base64` encodings,
which are not a part of the
[RFC4648](https://datatracker.ietf.org/doc/html/rfc4648#section-6), have
been dropped.


## Example usage

```Nushell
~/fork/nushell> "string" | encode base32 | decode base32 | decode
string
```

```Nushell
~/fork/nushell> "ORSXG5A=" | decode base32
# `decode` always returns a binary value
Length: 4 (0x4) bytes | printable whitespace ascii_other non_ascii
00000000:   74 65 73 74                                          test
```


## User-Facing Changes

- New commands: `encode/decode base32/base32hex`.
- `encode hex` gets a `--lower` flag.
- `encode/decode base64` deprecated in favor of `encode/decode
new-base64`.
2024-08-23 11:18:51 -05:00
39b0f3bdda Change expected type for derived FromValue implementations via attribute (#13647)
<!--
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.
-->
In this PR I expanded the helper attribute `#[nu_value]` on
`#[derive(FromValue)]`. It now allows the usage of `#[nu_value(type_name
= "...")]` to set a type name for the `FromValue::expected_type`
implementation. Currently it only uses the default implementation but
I'd like to change that without having to manually implement the entire
trait on my own.

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->
Users that derive `FromValue` may now change the name of the expected
type.

# 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 added some tests that check if this feature work and updated the
documentation about the derive macro.

- 🟢 `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.
-->
2024-08-23 06:47:15 -05:00
712fec166d Improve working with IntoValue and FromValue for byte collections (#13641)
<!--
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 working with byte collections like `Vec<u8>` and
[`bytes::Bytes`](https://docs.rs/bytes/1.7.1/bytes/struct.Bytes.html),
both are currently not possible to be used directly in a struct that
derives `IntoValue` and `FromValue` at the same time. The `Vec<u8>` will
convert itself into a `Value::List` but expects a `Value::String` or
`Value::Binary` to load from. I now also implemented that it can load
from `Value::List` just like the other `Vec<uX>` versions. For further
working with byte collections the type `bytes::Bytes` is wildly used,
therefore I added a implementation for it. `bytes` is already part of
the dependency graph as many crates (more than 5000 to crates.io) use
it.

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->
User of `nu-protocol` as library, e.g. plugin developers, can now use
byte collections more easily in their data structures and derive
`IntoValue` and `FromValue` for it.

# 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 added a few tests that check that these byte collections are correctly
translated in and from `Value`. They live in `test_derive.rs` as part of
the `ByteContainer` and I also explicitely tested that `FromValue` for
`Vec<u8>` works as expected.

- 🟢 `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.
-->
Maybe it should be explored if `Value::Binary` should use `bytes::Bytes`
instead of `Vec<u8>`.
2024-08-22 17:59:00 -05:00
43dcf19ac3 Fix bits ror/bits rol implementation (#13673)
# Description
`bits rol` and `bits ror` were both undefined for the full byte rotates
and panicked when exceeding the byte rotation range.
`bits ror` further more produced nonsensical results by pulling bits
from the following byte instead of the preceding byte.

Those bugs are now fixed

# User-Facing Changes
Sound Nushell `IncorrectValue` error when exceeding the available bits

# Tests + Formatting
Added the necessary tests
2024-08-22 21:22:10 +02:00
ffddee5678 add more granularity for into record with dates (#13650)
# Description

This PR adds a little more granularity when using `into record` with
dates.

### Before
```nushell
❯ date now | into record
╭──────────┬────────╮
│ year     │ 2024   │
│ month    │ 8      │
│ day      │ 19     │
│ hour     │ 18     │
│ minute   │ 31     │
│ second   │ 27     │
│ timezone │ -05:00 │
╰──────────┴────────╯
```

### After
```nushell
❯ date now | into record
╭─────────────┬────────╮
│ year        │ 2024   │
│ month       │ 8      │
│ day         │ 19     │
│ hour        │ 18     │
│ minute      │ 30     │
│ second      │ 51     │
│ millisecond │ 928    │
│ microsecond │ 980    │
│ nanosecond  │ 0      │
│ timezone    │ -05:00 │
╰─────────────┴────────╯
```
2024-08-22 12:09:27 +02:00
95b78eee25 Change the usage misnomer to "description" (#13598)
# Description
    
The meaning of the word usage is specific to describing how a command
function is *used* and not a synonym for general description. Usage can
be used to describe the SYNOPSIS or EXAMPLES sections of a man page
where the permitted argument combinations are shown or example *uses*
are given.
Let's not confuse people and call it what it is a description.

Our `help` command already creates its own *Usage* section based on the
available arguments and doesn't refer to the description with usage.

# User-Facing Changes

`help commands` and `scope commands` will now use `description` or
`extra_description`
`usage`-> `description`
`extra_usage` -> `extra_description`

Breaking change in the plugin protocol:

In the signature record communicated with the engine.
`usage`-> `description`
`extra_usage` -> `extra_description`

The same rename also takes place for the methods on
`SimplePluginCommand` and `PluginCommand`

# Tests + Formatting
- Updated plugin protocol specific changes
# After Submitting
- [ ] update plugin protocol doc
2024-08-22 12:02:08 +02:00
3ab9f0b90a Fix bugs and UB in bit shifting ops (#13663)
# Description
Fixes #11267

Shifting by a `shift >= num_bits` is undefined in the underlying
operation. Previously we also had an overflow on negative shifts for the
operators `bit-shl` and `bit-shr`
Furthermore I found a severe bug in the implementation of shifting of
`binary` data with the commands `bits shl` and `bits shr`, this
categorically produced incorrect results with shifts that were not
`shift % 4 == 0`. `bits shr` also was able to produce outputs with
different size to the input if the shift was exceeding the length of the
input data by more than a byte.

# User-Facing Changes
It is now an error trying to shift by more than the available bits with:
- `bit-shl` operator
- `bit-shr` operator
- command `bits shl`
- command `bits shr`

# Tests + Formatting
Added testing for all relevant cases
2024-08-22 11:54:27 +02:00
9261c0c55a Be explicit about reduce args and input (#13646)
# Description

`run_with_value` is meant for running simple closures with one arg.
Using `run_with_value` after `add_arg` is slightly confusing.
2024-08-22 11:39:21 +02:00
7a888c9e9b Change behavior of into record on lists to be more useful (#13637)
# Description

The previous behaviour of `into record` on lists was to create a new
record with each list index as the key. This was not very useful for
creating meaningful records, though, and most people would end up using
commands like `headers` or `transpose` to turn a list of keys and values
into a record.

This PR changes that instead to do what I think the most ergonomic thing
is, and instead:

- A list of records is merged into one record.
- A list of pairs (two element lists) is folded into a record with the
first element of each pair being the key, and the second being the
value.

The former is just generally more useful than having to use `reduce`
with `merge` for such a common operation, and the latter is useful
because it means that `$a | zip $b | into record` *just works* in the
way that seems most obvious.

Example:

```nushell
[[foo bar] [baz quux]] | into record # => {foo: bar, baz: quux}
[{foo: bar} {baz: quux}] | into record # => {foo: bar, baz: quux}
[foo baz] | zip [bar quux] | into record # => {foo: bar, baz: quux}
```

The support for range input has been removed, as it would no longer
reflect the treatment of an equivalent list.

The following is equivalent to the old behavior, in case that's desired:

```
0.. | zip [a b c] | into record # => {0: a, 1: b, 2: c}
```

# User-Facing Changes
- `into record` changed as described above (breaking)
- `into record` no longer supports range input (breaking)

# Tests + Formatting
Examples changed to match, everything works. Some usage in stdlib and
`nu_plugin_nu_example` had to be changed.

# After Submitting
- [ ] release notes (commands, breaking change)
2024-08-22 11:38:43 +02:00
e211b7ba53 Bump version to 0.97.2 (#13666) 2024-08-22 11:36:32 +02:00
847 changed files with 12977 additions and 7859 deletions

View File

@ -13,7 +13,7 @@ body:
id: repro id: repro
attributes: attributes:
label: How to reproduce label: How to reproduce
description: Steps to reproduce the behavior description: Steps to reproduce the behavior (including succinct code examples or screenshots of the observed behavior)
placeholder: | placeholder: |
1. 1.
2. 2.
@ -28,13 +28,6 @@ body:
placeholder: I expected nu to... placeholder: I expected nu to...
validations: validations:
required: true required: true
- type: textarea
id: screenshots
attributes:
label: Screenshots
description: Please add any relevant screenshots here, if any
validations:
required: false
- type: textarea - type: textarea
id: config id: config
attributes: attributes:
@ -55,10 +48,3 @@ body:
| installed_plugins | binaryview, chart bar, chart line, fetch, from bson, from sqlite, inc, match, post, ps, query json, s3, selector, start, sys, textview, to bson, to sqlite, tree, xpath | | installed_plugins | binaryview, chart bar, chart line, fetch, from bson, from sqlite, inc, match, post, ps, query json, s3, selector, start, sys, textview, to bson, to sqlite, tree, xpath |
validations: validations:
required: true required: true
- type: textarea
id: context
attributes:
label: Additional context
description: Add any other context about the problem here.
validations:
required: false

View File

@ -57,11 +57,6 @@ jobs:
fail-fast: true fail-fast: true
matrix: matrix:
platform: [windows-latest, macos-latest, ubuntu-20.04] platform: [windows-latest, macos-latest, ubuntu-20.04]
include:
- default-flags: ""
# linux CI cannot handle clipboard feature
- platform: ubuntu-20.04
default-flags: "--no-default-features --features=default-no-clipboard"
runs-on: ${{ matrix.platform }} runs-on: ${{ matrix.platform }}
@ -72,7 +67,7 @@ jobs:
uses: actions-rust-lang/setup-rust-toolchain@v1.9.0 uses: actions-rust-lang/setup-rust-toolchain@v1.9.0
- name: Tests - name: Tests
run: cargo test --workspace --profile ci --exclude nu_plugin_* ${{ matrix.default-flags }} run: cargo test --workspace --profile ci --exclude nu_plugin_*
- name: Check for clean repo - name: Check for clean repo
shell: bash shell: bash
run: | run: |

View File

@ -36,10 +36,10 @@ jobs:
token: ${{ secrets.WORKFLOW_TOKEN }} token: ${{ secrets.WORKFLOW_TOKEN }}
- name: Setup Nushell - name: Setup Nushell
uses: hustcer/setup-nu@v3.12 uses: hustcer/setup-nu@v3.13
if: github.repository == 'nushell/nightly' if: github.repository == 'nushell/nightly'
with: with:
version: 0.95.0 version: 0.97.1
# Synchronize the main branch of nightly repo with the main branch of Nushell official repo # Synchronize the main branch of nightly repo with the main branch of Nushell official repo
- name: Prepare for Nightly Release - name: Prepare for Nightly Release
@ -78,7 +78,9 @@ jobs:
- x86_64-unknown-linux-gnu - x86_64-unknown-linux-gnu
- x86_64-unknown-linux-musl - x86_64-unknown-linux-musl
- aarch64-unknown-linux-gnu - aarch64-unknown-linux-gnu
- aarch64-unknown-linux-musl
- armv7-unknown-linux-gnueabihf - armv7-unknown-linux-gnueabihf
- armv7-unknown-linux-musleabihf
- riscv64gc-unknown-linux-gnu - riscv64gc-unknown-linux-gnu
extra: ['bin'] extra: ['bin']
include: include:
@ -104,8 +106,12 @@ jobs:
os: ubuntu-22.04 os: ubuntu-22.04
- target: aarch64-unknown-linux-gnu - target: aarch64-unknown-linux-gnu
os: ubuntu-22.04 os: ubuntu-22.04
- target: aarch64-unknown-linux-musl
os: ubuntu-22.04
- target: armv7-unknown-linux-gnueabihf - target: armv7-unknown-linux-gnueabihf
os: ubuntu-22.04 os: ubuntu-22.04
- target: armv7-unknown-linux-musleabihf
os: ubuntu-22.04
- target: riscv64gc-unknown-linux-gnu - target: riscv64gc-unknown-linux-gnu
os: ubuntu-latest os: ubuntu-latest
@ -128,9 +134,9 @@ jobs:
rustflags: '' rustflags: ''
- name: Setup Nushell - name: Setup Nushell
uses: hustcer/setup-nu@v3.12 uses: hustcer/setup-nu@v3.13
with: with:
version: 0.95.0 version: 0.97.1
- name: Release Nu Binary - name: Release Nu Binary
id: nu id: nu
@ -186,9 +192,9 @@ jobs:
ref: main ref: main
- name: Setup Nushell - name: Setup Nushell
uses: hustcer/setup-nu@v3.12 uses: hustcer/setup-nu@v3.13
with: with:
version: 0.95.0 version: 0.97.1
# Keep the last a few releases # Keep the last a few releases
- name: Delete Older Releases - name: Delete Older Releases

View File

@ -84,6 +84,20 @@ if $os in ['macos-latest'] or $USE_UBUNTU {
$env.CARGO_TARGET_ARMV7_UNKNOWN_LINUX_GNUEABIHF_LINKER = 'arm-linux-gnueabihf-gcc' $env.CARGO_TARGET_ARMV7_UNKNOWN_LINUX_GNUEABIHF_LINKER = 'arm-linux-gnueabihf-gcc'
cargo-build-nu cargo-build-nu
} }
'aarch64-unknown-linux-musl' => {
aria2c https://musl.cc/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
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'
cargo-build-nu
}
_ => { _ => {
# musl-tools to fix 'Failed to find tool. Is `musl-gcc` installed?' # musl-tools to fix 'Failed to find tool. Is `musl-gcc` installed?'
# Actually just for x86_64-unknown-linux-musl target # Actually just for x86_64-unknown-linux-musl target

View File

@ -28,7 +28,9 @@ jobs:
- x86_64-unknown-linux-gnu - x86_64-unknown-linux-gnu
- x86_64-unknown-linux-musl - x86_64-unknown-linux-musl
- aarch64-unknown-linux-gnu - aarch64-unknown-linux-gnu
- aarch64-unknown-linux-musl
- armv7-unknown-linux-gnueabihf - armv7-unknown-linux-gnueabihf
- armv7-unknown-linux-musleabihf
- riscv64gc-unknown-linux-gnu - riscv64gc-unknown-linux-gnu
extra: ['bin'] extra: ['bin']
include: include:
@ -54,8 +56,12 @@ jobs:
os: ubuntu-22.04 os: ubuntu-22.04
- target: aarch64-unknown-linux-gnu - target: aarch64-unknown-linux-gnu
os: ubuntu-22.04 os: ubuntu-22.04
- target: aarch64-unknown-linux-musl
os: ubuntu-22.04
- target: armv7-unknown-linux-gnueabihf - target: armv7-unknown-linux-gnueabihf
os: ubuntu-22.04 os: ubuntu-22.04
- target: armv7-unknown-linux-musleabihf
os: ubuntu-22.04
- target: riscv64gc-unknown-linux-gnu - target: riscv64gc-unknown-linux-gnu
os: ubuntu-latest os: ubuntu-latest
@ -76,9 +82,9 @@ jobs:
rustflags: '' rustflags: ''
- name: Setup Nushell - name: Setup Nushell
uses: hustcer/setup-nu@v3.12 uses: hustcer/setup-nu@v3.13
with: with:
version: 0.95.0 version: 0.97.1
- name: Release Nu Binary - name: Release Nu Binary
id: nu id: nu

View File

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

1463
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -10,8 +10,8 @@ homepage = "https://www.nushell.sh"
license = "MIT" license = "MIT"
name = "nu" name = "nu"
repository = "https://github.com/nushell/nushell" repository = "https://github.com/nushell/nushell"
rust-version = "1.78.0" rust-version = "1.79.0"
version = "0.97.1" version = "0.98.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@ -69,18 +69,17 @@ base64 = "0.22.1"
bracoxide = "0.1.2" bracoxide = "0.1.2"
brotli = "5.0" brotli = "5.0"
byteorder = "1.5" byteorder = "1.5"
bytes = "1"
bytesize = "1.3" bytesize = "1.3"
calamine = "0.24.0" calamine = "0.24.0"
chardetng = "0.1.17" chardetng = "0.1.17"
chrono = { default-features = false, version = "0.4.34" } chrono = { default-features = false, version = "0.4.34" }
chrono-humanize = "0.2.3" chrono-humanize = "0.2.3"
chrono-tz = "0.8" chrono-tz = "0.8"
convert_case = "0.6"
crossbeam-channel = "0.5.8" crossbeam-channel = "0.5.8"
crossterm = "0.27" crossterm = "0.28.1"
csv = "1.3" csv = "1.3"
ctrlc = "3.4" ctrlc = "3.4"
deunicode = "1.6.0"
dialoguer = { default-features = false, version = "0.11" } dialoguer = { default-features = false, version = "0.11" }
digest = { default-features = false, version = "0.10" } digest = { default-features = false, version = "0.10" }
dirs = "5.0" dirs = "5.0"
@ -93,11 +92,11 @@ filetime = "0.2"
fuzzy-matcher = "0.3" fuzzy-matcher = "0.3"
heck = "0.5.0" heck = "0.5.0"
human-date-parser = "0.1.1" human-date-parser = "0.1.1"
indexmap = "2.4" indexmap = "2.5"
indicatif = "0.17" indicatif = "0.17"
interprocess = "2.2.0" interprocess = "2.2.0"
is_executable = "1.0" is_executable = "1.0"
itertools = "0.12" itertools = "0.13"
libc = "0.2" libc = "0.2"
libproc = "0.14" libproc = "0.14"
log = "0.4" log = "0.4"
@ -113,7 +112,7 @@ mime_guess = "2.0"
mockito = { version = "1.5", default-features = false } mockito = { version = "1.5", default-features = false }
multipart-rs = "0.1.11" multipart-rs = "0.1.11"
native-tls = "0.2" native-tls = "0.2"
nix = { version = "0.28", default-features = false } nix = { version = "0.29", default-features = false }
notify-debouncer-full = { version = "0.3", default-features = false } notify-debouncer-full = { version = "0.3", default-features = false }
nu-ansi-term = "0.50.1" nu-ansi-term = "0.50.1"
num-format = "0.4" num-format = "0.4"
@ -135,9 +134,10 @@ quickcheck = "1.0"
quickcheck_macros = "1.0" quickcheck_macros = "1.0"
quote = "1.0" quote = "1.0"
rand = "0.8" rand = "0.8"
rand_chacha = "0.3.1"
ratatui = "0.26" ratatui = "0.26"
rayon = "1.10" rayon = "1.10"
reedline = "0.34.0" reedline = "0.35.0"
regex = "1.9.5" regex = "1.9.5"
rmp = "0.8" rmp = "0.8"
rmp-serde = "1.3" rmp-serde = "1.3"
@ -146,8 +146,7 @@ roxmltree = "0.19"
rstest = { version = "0.18", default-features = false } rstest = { version = "0.18", default-features = false }
rusqlite = "0.31" rusqlite = "0.31"
rust-embed = "8.5.0" rust-embed = "8.5.0"
same-file = "1.0" serde = { version = "1.0" }
serde = { version = "1.0", default-features = false }
serde_json = "1.0" serde_json = "1.0"
serde_urlencoded = "0.7.1" serde_urlencoded = "0.7.1"
serde_yaml = "0.9" serde_yaml = "0.9"
@ -155,7 +154,7 @@ sha2 = "0.10"
strip-ansi-escapes = "0.2.0" strip-ansi-escapes = "0.2.0"
syn = "2.0" syn = "2.0"
sysinfo = "0.30" sysinfo = "0.30"
tabled = { version = "0.14.0", default-features = false } tabled = { version = "0.16.0", default-features = false }
tempfile = "3.10" tempfile = "3.10"
terminal_size = "0.3" terminal_size = "0.3"
titlecase = "2.0" titlecase = "2.0"
@ -181,23 +180,31 @@ windows = "0.54"
windows-sys = "0.48" windows-sys = "0.48"
winreg = "0.52" winreg = "0.52"
[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.
# todo = "warn"
unchecked_duration_subtraction = "warn"
[lints]
workspace = true
[dependencies] [dependencies]
nu-cli = { path = "./crates/nu-cli", version = "0.97.1" } nu-cli = { path = "./crates/nu-cli", version = "0.98.0" }
nu-cmd-base = { path = "./crates/nu-cmd-base", version = "0.97.1" } nu-cmd-base = { path = "./crates/nu-cmd-base", version = "0.98.0" }
nu-cmd-lang = { path = "./crates/nu-cmd-lang", version = "0.97.1" } nu-cmd-lang = { path = "./crates/nu-cmd-lang", version = "0.98.0" }
nu-cmd-plugin = { path = "./crates/nu-cmd-plugin", version = "0.97.1", optional = true } nu-cmd-plugin = { path = "./crates/nu-cmd-plugin", version = "0.98.0", optional = true }
nu-cmd-extra = { path = "./crates/nu-cmd-extra", version = "0.97.1" } nu-cmd-extra = { path = "./crates/nu-cmd-extra", version = "0.98.0" }
nu-command = { path = "./crates/nu-command", version = "0.97.1" } nu-command = { path = "./crates/nu-command", version = "0.98.0" }
nu-engine = { path = "./crates/nu-engine", version = "0.97.1" } nu-engine = { path = "./crates/nu-engine", version = "0.98.0" }
nu-explore = { path = "./crates/nu-explore", version = "0.97.1" } nu-explore = { path = "./crates/nu-explore", version = "0.98.0" }
nu-lsp = { path = "./crates/nu-lsp/", version = "0.97.1" } nu-lsp = { path = "./crates/nu-lsp/", version = "0.98.0" }
nu-parser = { path = "./crates/nu-parser", version = "0.97.1" } nu-parser = { path = "./crates/nu-parser", version = "0.98.0" }
nu-path = { path = "./crates/nu-path", version = "0.97.1" } nu-path = { path = "./crates/nu-path", version = "0.98.0" }
nu-plugin-engine = { path = "./crates/nu-plugin-engine", optional = true, version = "0.97.1" } nu-plugin-engine = { path = "./crates/nu-plugin-engine", optional = true, version = "0.98.0" }
nu-protocol = { path = "./crates/nu-protocol", version = "0.97.1" } nu-protocol = { path = "./crates/nu-protocol", version = "0.98.0" }
nu-std = { path = "./crates/nu-std", version = "0.97.1" } nu-std = { path = "./crates/nu-std", version = "0.98.0" }
nu-system = { path = "./crates/nu-system", version = "0.97.1" } nu-system = { path = "./crates/nu-system", version = "0.98.0" }
nu-utils = { path = "./crates/nu-utils", version = "0.97.1" } nu-utils = { path = "./crates/nu-utils", version = "0.98.0" }
reedline = { workspace = true, features = ["bashisms", "sqlite"] } reedline = { workspace = true, features = ["bashisms", "sqlite"] }
crossterm = { workspace = true } crossterm = { workspace = true }
@ -227,9 +234,9 @@ nix = { workspace = true, default-features = false, features = [
] } ] }
[dev-dependencies] [dev-dependencies]
nu-test-support = { path = "./crates/nu-test-support", version = "0.97.1" } nu-test-support = { path = "./crates/nu-test-support", version = "0.98.0" }
nu-plugin-protocol = { path = "./crates/nu-plugin-protocol", version = "0.97.1" } nu-plugin-protocol = { path = "./crates/nu-plugin-protocol", version = "0.98.0" }
nu-plugin-core = { path = "./crates/nu-plugin-core", version = "0.97.1" } nu-plugin-core = { path = "./crates/nu-plugin-core", version = "0.98.0" }
assert_cmd = "2.0" assert_cmd = "2.0"
dirs = { workspace = true } dirs = { workspace = true }
tango-bench = "0.5" tango-bench = "0.5"
@ -249,10 +256,8 @@ plugin = [
"nu-protocol/plugin", "nu-protocol/plugin",
"nu-engine/plugin", "nu-engine/plugin",
] ]
default = ["default-no-clipboard", "system-clipboard"]
# Enables convenient omitting of the system-clipboard feature, as it leads to problems in ci on linux default = [
# See https://github.com/nushell/nushell/pull/11535
default-no-clipboard = [
"plugin", "plugin",
"trash-support", "trash-support",
"sqlite", "sqlite",
@ -266,6 +271,8 @@ stable = ["default"]
static-link-openssl = ["dep:openssl", "nu-cmd-lang/static-link-openssl"] static-link-openssl = ["dep:openssl", "nu-cmd-lang/static-link-openssl"]
mimalloc = ["nu-cmd-lang/mimalloc", "dep:mimalloc"] mimalloc = ["nu-cmd-lang/mimalloc", "dep:mimalloc"]
# Optional system clipboard support in `reedline`, this behavior has problematic compatibility with some systems.
# Missing X server/ Wayland can cause issues
system-clipboard = [ system-clipboard = [
"reedline/system_clipboard", "reedline/system_clipboard",
"nu-cli/system-clipboard", "nu-cli/system-clipboard",

View File

@ -46,8 +46,8 @@ fn setup_stack_and_engine_from_command(command: &str) -> (Stack, EngineState) {
let mut stack = Stack::new(); let mut stack = Stack::new();
// Support running benchmarks with IR mode // Support running benchmarks without IR mode
stack.use_ir = std::env::var_os("NU_USE_IR").is_some(); stack.use_ir = std::env::var_os("NU_DISABLE_IR").is_none();
evaluate_commands( evaluate_commands(
&commands, &commands,

View File

@ -5,27 +5,27 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu-cli"
edition = "2021" edition = "2021"
license = "MIT" license = "MIT"
name = "nu-cli" name = "nu-cli"
version = "0.97.1" version = "0.98.0"
[lib] [lib]
bench = false bench = false
[dev-dependencies] [dev-dependencies]
nu-cmd-lang = { path = "../nu-cmd-lang", version = "0.97.1" } nu-cmd-lang = { path = "../nu-cmd-lang", version = "0.98.0" }
nu-command = { path = "../nu-command", version = "0.97.1" } nu-command = { path = "../nu-command", version = "0.98.0" }
nu-test-support = { path = "../nu-test-support", version = "0.97.1" } nu-test-support = { path = "../nu-test-support", version = "0.98.0" }
rstest = { workspace = true, default-features = false } rstest = { workspace = true, default-features = false }
tempfile = { workspace = true } tempfile = { workspace = true }
[dependencies] [dependencies]
nu-cmd-base = { path = "../nu-cmd-base", version = "0.97.1" } nu-cmd-base = { path = "../nu-cmd-base", version = "0.98.0" }
nu-engine = { path = "../nu-engine", version = "0.97.1" } nu-engine = { path = "../nu-engine", version = "0.98.0" }
nu-path = { path = "../nu-path", version = "0.97.1" } nu-path = { path = "../nu-path", version = "0.98.0" }
nu-parser = { path = "../nu-parser", version = "0.97.1" } nu-parser = { path = "../nu-parser", version = "0.98.0" }
nu-plugin-engine = { path = "../nu-plugin-engine", version = "0.97.1", optional = true } nu-plugin-engine = { path = "../nu-plugin-engine", version = "0.98.0", optional = true }
nu-protocol = { path = "../nu-protocol", version = "0.97.1" } nu-protocol = { path = "../nu-protocol", version = "0.98.0" }
nu-utils = { path = "../nu-utils", version = "0.97.1" } nu-utils = { path = "../nu-utils", version = "0.98.0" }
nu-color-config = { path = "../nu-color-config", version = "0.97.1" } nu-color-config = { path = "../nu-color-config", version = "0.98.0" }
nu-ansi-term = { workspace = true } nu-ansi-term = { workspace = true }
reedline = { workspace = true, features = ["bashisms", "sqlite"] } reedline = { workspace = true, features = ["bashisms", "sqlite"] }
@ -46,4 +46,7 @@ which = { workspace = true }
[features] [features]
plugin = ["nu-plugin-engine"] plugin = ["nu-plugin-engine"]
system-clipboard = ["reedline/system_clipboard"] system-clipboard = ["reedline/system_clipboard"]
[lints]
workspace = true

View File

@ -14,7 +14,7 @@ impl Command for Commandline {
.category(Category::Core) .category(Category::Core)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"View the current command line input buffer." "View the current command line input buffer."
} }

View File

@ -34,7 +34,7 @@ impl Command for SubCommand {
.category(Category::Core) .category(Category::Core)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Modify the current command line input buffer." "Modify the current command line input buffer."
} }

View File

@ -16,7 +16,7 @@ impl Command for SubCommand {
.category(Category::Core) .category(Category::Core)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Get the current cursor position." "Get the current cursor position."
} }

View File

@ -22,7 +22,7 @@ impl Command for SubCommand {
.category(Category::Core) .category(Category::Core)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Set the current cursor position." "Set the current cursor position."
} }

View File

@ -13,7 +13,7 @@ impl Command for History {
"history" "history"
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Get the command history." "Get the command history."
} }
@ -55,7 +55,7 @@ impl Command for History {
HistoryFileFormat::Sqlite => { HistoryFileFormat::Sqlite => {
history_path.push("history.sqlite3"); history_path.push("history.sqlite3");
} }
HistoryFileFormat::PlainText => { HistoryFileFormat::Plaintext => {
history_path.push("history.txt"); history_path.push("history.txt");
} }
} }
@ -75,7 +75,7 @@ impl Command for History {
.ok() .ok()
} }
HistoryFileFormat::PlainText => FileBackedHistory::with_file( HistoryFileFormat::Plaintext => FileBackedHistory::with_file(
history.max_size as usize, history.max_size as usize,
history_path.clone().into(), history_path.clone().into(),
) )
@ -87,7 +87,7 @@ impl Command for History {
}; };
match history.file_format { match history.file_format {
HistoryFileFormat::PlainText => Ok(history_reader HistoryFileFormat::Plaintext => Ok(history_reader
.and_then(|h| { .and_then(|h| {
h.search(SearchQuery::everything(SearchDirection::Forward, None)) h.search(SearchQuery::everything(SearchDirection::Forward, None))
.ok() .ok()

View File

@ -8,7 +8,7 @@ impl Command for HistorySession {
"history session" "history session"
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Get the command history session." "Get the command history session."
} }

View File

@ -14,11 +14,11 @@ impl Command for Keybindings {
.input_output_types(vec![(Type::Nothing, Type::String)]) .input_output_types(vec![(Type::Nothing, Type::String)])
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Keybindings related commands." "Keybindings related commands."
} }
fn extra_usage(&self) -> &str { fn extra_description(&self) -> &str {
r#"You must use one of the following subcommands. Using this command as-is will only produce this help message. r#"You must use one of the following subcommands. Using this command as-is will only produce this help message.
For more information on input and keybindings, check: For more information on input and keybindings, check:

View File

@ -15,7 +15,7 @@ impl Command for KeybindingsDefault {
.input_output_types(vec![(Type::Nothing, Type::table())]) .input_output_types(vec![(Type::Nothing, Type::table())])
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"List default keybindings." "List default keybindings."
} }

View File

@ -23,7 +23,7 @@ impl Command for KeybindingsList {
.category(Category::Platform) .category(Category::Platform)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"List available options that can be used to create keybindings." "List available options that can be used to create keybindings."
} }

View File

@ -12,11 +12,11 @@ impl Command for KeybindingsListen {
"keybindings listen" "keybindings listen"
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Get input from the user." "Get input from the user."
} }
fn extra_usage(&self) -> &str { fn extra_description(&self) -> &str {
"This is an internal debugging tool. For better output, try `input listen --types [key]`" "This is an internal debugging tool. For better output, try `input listen --types [key]`"
} }

View File

@ -51,7 +51,9 @@ impl CommandCompletion {
if working_set if working_set
.permanent_state .permanent_state
.config .config
.max_external_completion_results .completions
.external
.max_results
> executables.len() as i64 > executables.len() as i64
&& !executables.contains( && !executables.contains(
&item &item
@ -211,7 +213,7 @@ impl Completer for CommandCompletion {
working_set, working_set,
span, span,
offset, offset,
config.enable_external_completion, config.completions.external.enable,
options.match_algorithm, options.match_algorithm,
) )
} else { } else {

View File

@ -46,9 +46,9 @@ impl NuCompleter {
let config = self.engine_state.get_config(); let config = self.engine_state.get_config();
let options = CompletionOptions { let options = CompletionOptions {
case_sensitive: config.case_sensitive_completions, case_sensitive: config.completions.case_sensitive,
match_algorithm: config.completion_algorithm.into(), match_algorithm: config.completions.algorithm.into(),
sort: config.completion_sort, sort: config.completions.sort,
..Default::default() ..Default::default()
}; };
@ -208,7 +208,7 @@ impl NuCompleter {
// We got no results for internal completion // We got no results for internal completion
// now we can check if external completer is set and use it // now we can check if external completer is set and use it
if let Some(closure) = config.external_completer.as_ref() { if let Some(closure) = config.completions.external.completer.as_ref() {
if let Some(external_result) = if let Some(external_result) =
self.external_completion(closure, &spans, fake_offset, new_span) self.external_completion(closure, &spans, fake_offset, new_span)
{ {
@ -338,7 +338,9 @@ impl NuCompleter {
} }
// Try to complete using an external completer (if set) // Try to complete using an external completer (if set)
if let Some(closure) = config.external_completer.as_ref() { if let Some(closure) =
config.completions.external.completer.as_ref()
{
if let Some(external_result) = self.external_completion( if let Some(external_result) = self.external_completion(
closure, closure,
&spans, &spans,

View File

@ -1,3 +1,4 @@
use super::MatchAlgorithm;
use crate::{ use crate::{
completions::{matches, CompletionOptions}, completions::{matches, CompletionOptions},
SemanticSuggestion, SemanticSuggestion,
@ -5,6 +6,7 @@ use crate::{
use fuzzy_matcher::{skim::SkimMatcherV2, FuzzyMatcher}; use fuzzy_matcher::{skim::SkimMatcherV2, FuzzyMatcher};
use nu_ansi_term::Style; use nu_ansi_term::Style;
use nu_engine::env_to_string; use nu_engine::env_to_string;
use nu_path::dots::expand_ndots;
use nu_path::{expand_to_real_path, home_dir}; use nu_path::{expand_to_real_path, home_dir};
use nu_protocol::{ use nu_protocol::{
engine::{EngineState, Stack, StateWorkingSet}, engine::{EngineState, Stack, StateWorkingSet},
@ -13,8 +15,6 @@ use nu_protocol::{
use nu_utils::get_ls_colors; use nu_utils::get_ls_colors;
use std::path::{is_separator, Component, Path, PathBuf, MAIN_SEPARATOR as SEP}; use std::path::{is_separator, Component, Path, PathBuf, MAIN_SEPARATOR as SEP};
use super::MatchAlgorithm;
#[derive(Clone, Default)] #[derive(Clone, Default)]
pub struct PathBuiltFromString { pub struct PathBuiltFromString {
parts: Vec<String>, parts: Vec<String>,
@ -41,7 +41,7 @@ pub fn complete_rec(
let mut completions = vec![]; let mut completions = vec![];
if let Some((&base, rest)) = partial.split_first() { if let Some((&base, rest)) = partial.split_first() {
if (base == "." || base == "..") && (isdir || !rest.is_empty()) { if base.chars().all(|c| c == '.') && (isdir || !rest.is_empty()) {
let mut built = built.clone(); let mut built = built.clone();
built.parts.push(base.to_string()); built.parts.push(base.to_string());
built.isdir = true; built.isdir = true;
@ -156,18 +156,27 @@ pub fn complete_item(
engine_state: &EngineState, engine_state: &EngineState,
stack: &Stack, stack: &Stack,
) -> Vec<(nu_protocol::Span, String, Option<Style>)> { ) -> Vec<(nu_protocol::Span, String, Option<Style>)> {
let partial = surround_remove(partial); let cleaned_partial = surround_remove(partial);
let isdir = partial.ends_with(is_separator); let isdir = cleaned_partial.ends_with(is_separator);
let expanded_partial = expand_ndots(Path::new(&cleaned_partial));
let should_collapse_dots = expanded_partial != Path::new(&cleaned_partial);
let mut partial = expanded_partial.to_string_lossy().to_string();
#[cfg(unix)] #[cfg(unix)]
let path_separator = SEP; let path_separator = SEP;
#[cfg(windows)] #[cfg(windows)]
let path_separator = partial let path_separator = cleaned_partial
.chars() .chars()
.rfind(|c: &char| is_separator(*c)) .rfind(|c: &char| is_separator(*c))
.unwrap_or(SEP); .unwrap_or(SEP);
// Handle the trailing dot case
if cleaned_partial.ends_with(&format!("{path_separator}.")) {
partial.push_str(&format!("{path_separator}."));
}
let cwd_pathbuf = Path::new(cwd).to_path_buf(); let cwd_pathbuf = Path::new(cwd).to_path_buf();
let ls_colors = (engine_state.config.use_ls_colors_completions let ls_colors = (engine_state.config.completions.use_ls_colors
&& engine_state.config.use_ansi_coloring) && engine_state.config.use_ansi_coloring)
.then(|| { .then(|| {
let ls_colors_env_str = match stack.get_env_var(engine_state, "LS_COLORS") { let ls_colors_env_str = match stack.get_env_var(engine_state, "LS_COLORS") {
@ -185,16 +194,11 @@ pub fn complete_item(
match components.peek().cloned() { match components.peek().cloned() {
Some(c @ Component::Prefix(..)) => { Some(c @ Component::Prefix(..)) => {
// windows only by definition // windows only by definition
components.next();
if let Some(Component::RootDir) = components.peek().cloned() {
components.next();
};
cwd = [c, Component::RootDir].iter().collect(); cwd = [c, Component::RootDir].iter().collect();
prefix_len = c.as_os_str().len(); prefix_len = c.as_os_str().len();
original_cwd = OriginalCwd::Prefix(c.as_os_str().to_string_lossy().into_owned()); original_cwd = OriginalCwd::Prefix(c.as_os_str().to_string_lossy().into_owned());
} }
Some(c @ Component::RootDir) => { Some(c @ Component::RootDir) => {
components.next();
// This is kind of a hack. When joining an empty string with the rest, // This is kind of a hack. When joining an empty string with the rest,
// we add the slash automagically // we add the slash automagically
cwd = PathBuf::from(c.as_os_str()); cwd = PathBuf::from(c.as_os_str());
@ -202,7 +206,6 @@ pub fn complete_item(
original_cwd = OriginalCwd::Prefix(String::new()); original_cwd = OriginalCwd::Prefix(String::new());
} }
Some(Component::Normal(home)) if home.to_string_lossy() == "~" => { Some(Component::Normal(home)) if home.to_string_lossy() == "~" => {
components.next();
cwd = home_dir().map(Into::into).unwrap_or(cwd_pathbuf); cwd = home_dir().map(Into::into).unwrap_or(cwd_pathbuf);
prefix_len = 1; prefix_len = 1;
original_cwd = OriginalCwd::Home; original_cwd = OriginalCwd::Home;
@ -227,7 +230,10 @@ pub fn complete_item(
isdir, isdir,
) )
.into_iter() .into_iter()
.map(|p| { .map(|mut p| {
if should_collapse_dots {
p = collapse_ndots(p);
}
let path = original_cwd.apply(p, path_separator); let path = original_cwd.apply(p, path_separator);
let style = ls_colors.as_ref().map(|lsc| { let style = ls_colors.as_ref().map(|lsc| {
lsc.style_for_path_with_metadata( lsc.style_for_path_with_metadata(
@ -340,3 +346,37 @@ pub fn sort_completions<T>(
items items
} }
/// Collapse multiple ".." components into n-dots.
///
/// It performs the reverse operation of `expand_ndots`, collapsing sequences of ".." into n-dots,
/// such as "..." and "....".
///
/// The resulting path will use platform-specific path separators, regardless of what path separators were used in the input.
fn collapse_ndots(path: PathBuiltFromString) -> PathBuiltFromString {
let mut result = PathBuiltFromString {
parts: Vec::with_capacity(path.parts.len()),
isdir: path.isdir,
};
let mut dot_count = 0;
for part in path.parts {
if part == ".." {
dot_count += 1;
} else {
if dot_count > 0 {
result.parts.push(".".repeat(dot_count + 1));
dot_count = 0;
}
result.parts.push(part);
}
}
// Add any remaining dots
if dot_count > 0 {
result.parts.push(".".repeat(dot_count + 1));
}
result
}

View File

@ -126,7 +126,7 @@ impl Completer for CustomCompletion {
let options = custom_completion_options let options = custom_completion_options
.as_ref() .as_ref()
.unwrap_or(completion_options); .unwrap_or(completion_options);
let suggestions = filter(&prefix, suggestions, completion_options); let suggestions = filter(&prefix, suggestions, options);
sort_suggestions(&String::from_utf8_lossy(&prefix), suggestions, options) sort_suggestions(&String::from_utf8_lossy(&prefix), suggestions, options)
} }
} }

View File

@ -2,10 +2,10 @@ use crate::util::eval_source;
#[cfg(feature = "plugin")] #[cfg(feature = "plugin")]
use nu_path::canonicalize_with; use nu_path::canonicalize_with;
#[cfg(feature = "plugin")] #[cfg(feature = "plugin")]
use nu_protocol::{engine::StateWorkingSet, report_error, ParseError, PluginRegistryFile, Spanned}; use nu_protocol::{engine::StateWorkingSet, ParseError, PluginRegistryFile, Spanned};
use nu_protocol::{ use nu_protocol::{
engine::{EngineState, Stack}, engine::{EngineState, Stack},
report_error_new, HistoryFileFormat, PipelineData, report_shell_error, HistoryFileFormat, PipelineData,
}; };
#[cfg(feature = "plugin")] #[cfg(feature = "plugin")]
use nu_utils::perf; use nu_utils::perf;
@ -36,7 +36,7 @@ pub fn read_plugin_file(
.and_then(|p| Path::new(&p.item).extension()) .and_then(|p| Path::new(&p.item).extension())
.is_some_and(|ext| ext == "nu") .is_some_and(|ext| ext == "nu")
{ {
report_error_new( report_shell_error(
engine_state, engine_state,
&ShellError::GenericError { &ShellError::GenericError {
error: "Wrong plugin file format".into(), error: "Wrong plugin file format".into(),
@ -81,7 +81,7 @@ pub fn read_plugin_file(
return; return;
} }
} else { } else {
report_error_new( report_shell_error(
engine_state, engine_state,
&ShellError::GenericError { &ShellError::GenericError {
error: format!( error: format!(
@ -113,7 +113,7 @@ pub fn read_plugin_file(
Ok(contents) => contents, Ok(contents) => contents,
Err(err) => { Err(err) => {
log::warn!("Failed to read plugin registry file: {err:?}"); log::warn!("Failed to read plugin registry file: {err:?}");
report_error_new( report_shell_error(
engine_state, engine_state,
&ShellError::GenericError { &ShellError::GenericError {
error: format!( error: format!(
@ -146,7 +146,7 @@ pub fn read_plugin_file(
nu_plugin_engine::load_plugin_file(&mut working_set, &contents, span); nu_plugin_engine::load_plugin_file(&mut working_set, &contents, span);
if let Err(err) = engine_state.merge_delta(working_set.render()) { if let Err(err) = engine_state.merge_delta(working_set.render()) {
report_error_new(engine_state, &err); report_shell_error(engine_state, &err);
return; return;
} }
@ -166,7 +166,7 @@ pub fn add_plugin_file(
) { ) {
use std::path::Path; use std::path::Path;
let working_set = StateWorkingSet::new(engine_state); use nu_protocol::report_parse_error;
if let Ok(cwd) = engine_state.cwd_as_string(None) { if let Ok(cwd) = engine_state.cwd_as_string(None) {
if let Some(plugin_file) = plugin_file { if let Some(plugin_file) = plugin_file {
@ -181,8 +181,8 @@ pub fn add_plugin_file(
engine_state.plugin_path = Some(path) engine_state.plugin_path = Some(path)
} else { } else {
// It's an error if the directory for the plugin file doesn't exist. // It's an error if the directory for the plugin file doesn't exist.
report_error( report_parse_error(
&working_set, &StateWorkingSet::new(engine_state),
&ParseError::FileNotFound( &ParseError::FileNotFound(
path_dir.to_string_lossy().into_owned(), path_dir.to_string_lossy().into_owned(),
plugin_file.span, plugin_file.span,
@ -214,7 +214,8 @@ pub fn eval_config_contents(
let prev_file = engine_state.file.take(); let prev_file = engine_state.file.take();
engine_state.file = Some(config_path.clone()); engine_state.file = Some(config_path.clone());
eval_source( // TODO: ignore this error?
let _ = eval_source(
engine_state, engine_state,
stack, stack,
&contents, &contents,
@ -230,11 +231,11 @@ pub fn eval_config_contents(
match engine_state.cwd(Some(stack)) { match engine_state.cwd(Some(stack)) {
Ok(cwd) => { Ok(cwd) => {
if let Err(e) = engine_state.merge_env(stack, cwd) { if let Err(e) = engine_state.merge_env(stack, cwd) {
report_error_new(engine_state, &e); report_shell_error(engine_state, &e);
} }
} }
Err(e) => { Err(e) => {
report_error_new(engine_state, &e); report_shell_error(engine_state, &e);
} }
} }
} }
@ -245,7 +246,7 @@ pub(crate) fn get_history_path(storage_path: &str, mode: HistoryFileFormat) -> O
nu_path::config_dir().map(|mut history_path| { nu_path::config_dir().map(|mut history_path| {
history_path.push(storage_path); history_path.push(storage_path);
history_path.push(match mode { history_path.push(match mode {
HistoryFileFormat::PlainText => HISTORY_FILE_TXT, HistoryFileFormat::Plaintext => HISTORY_FILE_TXT,
HistoryFileFormat::Sqlite => HISTORY_FILE_SQLITE, HistoryFileFormat::Sqlite => HISTORY_FILE_SQLITE,
}); });
history_path.into() history_path.into()
@ -280,7 +281,7 @@ pub fn migrate_old_plugin_file(engine_state: &EngineState, storage_path: &str) -
let old_contents = match std::fs::read(&old_plugin_file_path) { let old_contents = match std::fs::read(&old_plugin_file_path) {
Ok(old_contents) => old_contents, Ok(old_contents) => old_contents,
Err(err) => { Err(err) => {
report_error_new( report_shell_error(
engine_state, engine_state,
&ShellError::GenericError { &ShellError::GenericError {
error: "Can't read old plugin file to migrate".into(), error: "Can't read old plugin file to migrate".into(),
@ -349,7 +350,7 @@ pub fn migrate_old_plugin_file(engine_state: &EngineState, storage_path: &str) -
.map_err(|e| e.into()) .map_err(|e| e.into())
.and_then(|file| contents.write_to(file, None)) .and_then(|file| contents.write_to(file, None))
{ {
report_error_new( report_shell_error(
&engine_state, &engine_state,
&ShellError::GenericError { &ShellError::GenericError {
error: "Failed to save migrated plugin file".into(), error: "Failed to save migrated plugin file".into(),

View File

@ -2,9 +2,10 @@ use log::info;
use nu_engine::{convert_env_values, eval_block}; use nu_engine::{convert_env_values, eval_block};
use nu_parser::parse; use nu_parser::parse;
use nu_protocol::{ use nu_protocol::{
cli_error::report_compile_error,
debugger::WithoutDebug, debugger::WithoutDebug,
engine::{EngineState, Stack, StateWorkingSet}, engine::{EngineState, Stack, StateWorkingSet},
report_error, PipelineData, ShellError, Spanned, Value, report_parse_error, report_parse_warning, PipelineData, ShellError, Spanned, Value,
}; };
use std::sync::Arc; use std::sync::Arc;
@ -53,7 +54,7 @@ pub fn evaluate_commands(
// Parse the source code // Parse the source code
let (block, delta) = { let (block, delta) = {
if let Some(ref t_mode) = table_mode { if let Some(ref t_mode) = table_mode {
Arc::make_mut(&mut engine_state.config).table_mode = Arc::make_mut(&mut engine_state.config).table.mode =
t_mode.coerce_str()?.parse().unwrap_or_default(); t_mode.coerce_str()?.parse().unwrap_or_default();
} }
@ -61,16 +62,16 @@ pub fn evaluate_commands(
let output = parse(&mut working_set, None, commands.item.as_bytes(), false); let output = parse(&mut working_set, None, commands.item.as_bytes(), false);
if let Some(warning) = working_set.parse_warnings.first() { if let Some(warning) = working_set.parse_warnings.first() {
report_error(&working_set, warning); report_parse_warning(&working_set, warning);
} }
if let Some(err) = working_set.parse_errors.first() { if let Some(err) = working_set.parse_errors.first() {
report_error(&working_set, err); report_parse_error(&working_set, err);
std::process::exit(1); std::process::exit(1);
} }
if let Some(err) = working_set.compile_errors.first() { if let Some(err) = working_set.compile_errors.first() {
report_error(&working_set, err); report_compile_error(&working_set, err);
// Not a fatal error, for now // Not a fatal error, for now
} }
@ -88,15 +89,11 @@ pub fn evaluate_commands(
} }
if let Some(t_mode) = table_mode { if let Some(t_mode) = table_mode {
Arc::make_mut(&mut engine_state.config).table_mode = Arc::make_mut(&mut engine_state.config).table.mode =
t_mode.coerce_str()?.parse().unwrap_or_default(); t_mode.coerce_str()?.parse().unwrap_or_default();
} }
if let Some(status) = pipeline.print(engine_state, stack, no_newline, false)? { pipeline.print(engine_state, stack, no_newline, false)?;
if status.code() != 0 {
std::process::exit(status.code())
}
}
info!("evaluate {}:{}:{}", file!(), line!(), column!()); info!("evaluate {}:{}:{}", file!(), line!(), column!());

View File

@ -4,9 +4,10 @@ use nu_engine::{convert_env_values, eval_block};
use nu_parser::parse; use nu_parser::parse;
use nu_path::canonicalize_with; use nu_path::canonicalize_with;
use nu_protocol::{ use nu_protocol::{
cli_error::report_compile_error,
debugger::WithoutDebug, debugger::WithoutDebug,
engine::{EngineState, Stack, StateWorkingSet}, engine::{EngineState, Stack, StateWorkingSet},
report_error, PipelineData, ShellError, Span, Value, report_parse_error, report_parse_warning, PipelineData, ShellError, Span, Value,
}; };
use std::sync::Arc; use std::sync::Arc;
@ -77,17 +78,17 @@ pub fn evaluate_file(
let block = parse(&mut working_set, Some(file_path_str), &file, false); let block = parse(&mut working_set, Some(file_path_str), &file, false);
if let Some(warning) = working_set.parse_warnings.first() { if let Some(warning) = working_set.parse_warnings.first() {
report_error(&working_set, warning); report_parse_warning(&working_set, warning);
} }
// If any parse errors were found, report the first error and exit. // If any parse errors were found, report the first error and exit.
if let Some(err) = working_set.parse_errors.first() { if let Some(err) = working_set.parse_errors.first() {
report_error(&working_set, err); report_parse_error(&working_set, err);
std::process::exit(1); std::process::exit(1);
} }
if let Some(err) = working_set.compile_errors.first() { if let Some(err) = working_set.compile_errors.first() {
report_error(&working_set, err); report_compile_error(&working_set, err);
// Not a fatal error, for now // Not a fatal error, for now
} }
@ -118,11 +119,7 @@ pub fn evaluate_file(
}; };
// Print the pipeline output of the last command of the file. // Print the pipeline output of the last command of the file.
if let Some(status) = pipeline.print(engine_state, stack, true, false)? { pipeline.print(engine_state, stack, true, false)?;
if status.code() != 0 {
std::process::exit(status.code())
}
}
// Invoke the main command with arguments. // Invoke the main command with arguments.
// Arguments with whitespaces are quoted, thus can be safely concatenated by whitespace. // Arguments with whitespaces are quoted, thus can be safely concatenated by whitespace.
@ -140,7 +137,7 @@ pub fn evaluate_file(
}; };
if exit_code != 0 { if exit_code != 0 {
std::process::exit(exit_code) std::process::exit(exit_code);
} }
info!("evaluate {}:{}:{}", file!(), line!(), column!()); info!("evaluate {}:{}:{}", file!(), line!(), column!());

View File

@ -30,12 +30,15 @@ impl NuHelpCompleter {
.filter_map(|(_, decl_id)| { .filter_map(|(_, decl_id)| {
let decl = self.engine_state.get_decl(decl_id); let decl = self.engine_state.get_decl(decl_id);
(decl.name().to_folded_case().contains(&folded_line) (decl.name().to_folded_case().contains(&folded_line)
|| decl.usage().to_folded_case().contains(&folded_line) || decl.description().to_folded_case().contains(&folded_line)
|| decl || decl
.search_terms() .search_terms()
.into_iter() .into_iter()
.any(|term| term.to_folded_case().contains(&folded_line)) .any(|term| term.to_folded_case().contains(&folded_line))
|| decl.extra_usage().to_folded_case().contains(&folded_line)) || decl
.extra_description()
.to_folded_case()
.contains(&folded_line))
.then_some(decl) .then_some(decl)
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
@ -47,15 +50,15 @@ impl NuHelpCompleter {
.map(|decl| { .map(|decl| {
let mut long_desc = String::new(); let mut long_desc = String::new();
let usage = decl.usage(); let description = decl.description();
if !usage.is_empty() { if !description.is_empty() {
long_desc.push_str(usage); long_desc.push_str(description);
long_desc.push_str("\r\n\r\n"); long_desc.push_str("\r\n\r\n");
} }
let extra_usage = decl.extra_usage(); let extra_desc = decl.extra_description();
if !extra_usage.is_empty() { if !extra_desc.is_empty() {
long_desc.push_str(extra_usage); long_desc.push_str(extra_desc);
long_desc.push_str("\r\n\r\n"); long_desc.push_str("\r\n\r\n");
} }

View File

@ -17,7 +17,7 @@ impl Command for NuHighlight {
.input_output_types(vec![(Type::String, Type::String)]) .input_output_types(vec![(Type::String, Type::String)])
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Syntax highlight the input string." "Syntax highlight the input string."
} }

View File

@ -30,11 +30,11 @@ impl Command for Print {
.category(Category::Strings) .category(Category::Strings)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Print the given values to stdout." "Print the given values to stdout."
} }
fn extra_usage(&self) -> &str { fn extra_description(&self) -> &str {
r#"Unlike `echo`, this command does not return any value (`print | describe` will return "nothing"). r#"Unlike `echo`, this command does not return any value (`print | describe` will return "nothing").
Since this command has no output, there is no point in piping it with other commands. Since this command has no output, there is no point in piping it with other commands.

View File

@ -3,7 +3,7 @@ use log::trace;
use nu_engine::ClosureEvalOnce; use nu_engine::ClosureEvalOnce;
use nu_protocol::{ use nu_protocol::{
engine::{EngineState, Stack}, engine::{EngineState, Stack},
report_error_new, Config, PipelineData, Value, report_shell_error, Config, PipelineData, Value,
}; };
use reedline::Prompt; use reedline::Prompt;
@ -80,7 +80,7 @@ fn get_prompt_string(
result result
.map_err(|err| { .map_err(|err| {
report_error_new(engine_state, &err); report_shell_error(engine_state, &err);
}) })
.ok() .ok()
} }
@ -118,13 +118,13 @@ pub(crate) fn update_prompt(
// Now that we have the prompt string lets ansify it. // Now that we have the prompt string lets ansify it.
// <133 A><prompt><133 B><command><133 C><command output> // <133 A><prompt><133 B><command><133 C><command output>
let left_prompt_string = if config.shell_integration_osc633 { let left_prompt_string = if config.shell_integration.osc633 {
if stack.get_env_var(engine_state, "TERM_PROGRAM") == Some(Value::test_string("vscode")) { if stack.get_env_var(engine_state, "TERM_PROGRAM") == Some(Value::test_string("vscode")) {
// We're in vscode and we have osc633 enabled // We're in vscode and we have osc633 enabled
Some(format!( Some(format!(
"{VSCODE_PRE_PROMPT_MARKER}{configured_left_prompt_string}{VSCODE_POST_PROMPT_MARKER}" "{VSCODE_PRE_PROMPT_MARKER}{configured_left_prompt_string}{VSCODE_POST_PROMPT_MARKER}"
)) ))
} else if config.shell_integration_osc133 { } else if config.shell_integration.osc133 {
// If we're in VSCode but we don't find the env var, but we have osc133 set, then use it // If we're in VSCode but we don't find the env var, but we have osc133 set, then use it
Some(format!( Some(format!(
"{PRE_PROMPT_MARKER}{configured_left_prompt_string}{POST_PROMPT_MARKER}" "{PRE_PROMPT_MARKER}{configured_left_prompt_string}{POST_PROMPT_MARKER}"
@ -132,7 +132,7 @@ pub(crate) fn update_prompt(
} else { } else {
configured_left_prompt_string.into() configured_left_prompt_string.into()
} }
} else if config.shell_integration_osc133 { } else if config.shell_integration.osc133 {
Some(format!( Some(format!(
"{PRE_PROMPT_MARKER}{configured_left_prompt_string}{POST_PROMPT_MARKER}" "{PRE_PROMPT_MARKER}{configured_left_prompt_string}{POST_PROMPT_MARKER}"
)) ))

View File

@ -159,8 +159,8 @@ fn add_menu(
stack: &Stack, stack: &Stack,
config: Arc<Config>, config: Arc<Config>,
) -> Result<Reedline, ShellError> { ) -> Result<Reedline, ShellError> {
let span = menu.menu_type.span(); let span = menu.r#type.span();
if let Value::Record { val, .. } = &menu.menu_type { if let Value::Record { val, .. } = &menu.r#type {
let layout = extract_value("layout", val, span)?.to_expanded_string("", &config); let layout = extract_value("layout", val, span)?.to_expanded_string("", &config);
match layout.as_str() { match layout.as_str() {
@ -170,15 +170,15 @@ fn add_menu(
"description" => add_description_menu(line_editor, menu, engine_state, stack, config), "description" => add_description_menu(line_editor, menu, engine_state, stack, config),
_ => Err(ShellError::UnsupportedConfigValue { _ => Err(ShellError::UnsupportedConfigValue {
expected: "columnar, list, ide or description".to_string(), expected: "columnar, list, ide or description".to_string(),
value: menu.menu_type.to_abbreviated_string(&config), value: menu.r#type.to_abbreviated_string(&config),
span: menu.menu_type.span(), span: menu.r#type.span(),
}), }),
} }
} else { } else {
Err(ShellError::UnsupportedConfigValue { Err(ShellError::UnsupportedConfigValue {
expected: "only record type".to_string(), expected: "only record type".to_string(),
value: menu.menu_type.to_abbreviated_string(&config), value: menu.r#type.to_abbreviated_string(&config),
span: menu.menu_type.span(), span: menu.r#type.span(),
}) })
} }
} }
@ -224,11 +224,11 @@ pub(crate) fn add_columnar_menu(
stack: &Stack, stack: &Stack,
config: &Config, config: &Config,
) -> Result<Reedline, ShellError> { ) -> Result<Reedline, ShellError> {
let span = menu.menu_type.span(); let span = menu.r#type.span();
let name = menu.name.to_expanded_string("", config); let name = menu.name.to_expanded_string("", config);
let mut columnar_menu = ColumnarMenu::default().with_name(&name); let mut columnar_menu = ColumnarMenu::default().with_name(&name);
if let Value::Record { val, .. } = &menu.menu_type { if let Value::Record { val, .. } = &menu.r#type {
columnar_menu = match extract_value("columns", val, span) { columnar_menu = match extract_value("columns", val, span) {
Ok(columns) => { Ok(columns) => {
let columns = columns.as_int()?; let columns = columns.as_int()?;
@ -299,8 +299,8 @@ pub(crate) fn add_list_menu(
let name = menu.name.to_expanded_string("", &config); let name = menu.name.to_expanded_string("", &config);
let mut list_menu = ListMenu::default().with_name(&name); let mut list_menu = ListMenu::default().with_name(&name);
let span = menu.menu_type.span(); let span = menu.r#type.span();
if let Value::Record { val, .. } = &menu.menu_type { if let Value::Record { val, .. } = &menu.r#type {
list_menu = match extract_value("page_size", val, span) { list_menu = match extract_value("page_size", val, span) {
Ok(page_size) => { Ok(page_size) => {
let page_size = page_size.as_int()?; let page_size = page_size.as_int()?;
@ -352,11 +352,11 @@ pub(crate) fn add_ide_menu(
stack: &Stack, stack: &Stack,
config: Arc<Config>, config: Arc<Config>,
) -> Result<Reedline, ShellError> { ) -> Result<Reedline, ShellError> {
let span = menu.menu_type.span(); let span = menu.r#type.span();
let name = menu.name.to_expanded_string("", &config); let name = menu.name.to_expanded_string("", &config);
let mut ide_menu = IdeMenu::default().with_name(&name); let mut ide_menu = IdeMenu::default().with_name(&name);
if let Value::Record { val, .. } = &menu.menu_type { if let Value::Record { val, .. } = &menu.r#type {
ide_menu = match extract_value("min_completion_width", val, span) { ide_menu = match extract_value("min_completion_width", val, span) {
Ok(min_completion_width) => { Ok(min_completion_width) => {
let min_completion_width = min_completion_width.as_int()?; let min_completion_width = min_completion_width.as_int()?;
@ -536,8 +536,8 @@ pub(crate) fn add_description_menu(
let name = menu.name.to_expanded_string("", &config); let name = menu.name.to_expanded_string("", &config);
let mut description_menu = DescriptionMenu::default().with_name(&name); let mut description_menu = DescriptionMenu::default().with_name(&name);
let span = menu.menu_type.span(); let span = menu.r#type.span();
if let Value::Record { val, .. } = &menu.menu_type { if let Value::Record { val, .. } = &menu.r#type {
description_menu = match extract_value("columns", val, span) { description_menu = match extract_value("columns", val, span) {
Ok(columns) => { Ok(columns) => {
let columns = columns.as_int()?; let columns = columns.as_int()?;

View File

@ -27,7 +27,7 @@ use nu_parser::{lex, parse, trim_quotes_str};
use nu_protocol::{ use nu_protocol::{
config::NuCursorShape, config::NuCursorShape,
engine::{EngineState, Stack, StateWorkingSet}, engine::{EngineState, Stack, StateWorkingSet},
report_error_new, HistoryConfig, HistoryFileFormat, PipelineData, ShellError, Span, Spanned, report_shell_error, HistoryConfig, HistoryFileFormat, PipelineData, ShellError, Span, Spanned,
Value, Value,
}; };
use nu_utils::{ use nu_utils::{
@ -72,11 +72,11 @@ pub fn evaluate_repl(
let mut entry_num = 0; let mut entry_num = 0;
// Let's grab the shell_integration configs // Let's grab the shell_integration configs
let shell_integration_osc2 = config.shell_integration_osc2; let shell_integration_osc2 = config.shell_integration.osc2;
let shell_integration_osc7 = config.shell_integration_osc7; let shell_integration_osc7 = config.shell_integration.osc7;
let shell_integration_osc9_9 = config.shell_integration_osc9_9; let shell_integration_osc9_9 = config.shell_integration.osc9_9;
let shell_integration_osc133 = config.shell_integration_osc133; let shell_integration_osc133 = config.shell_integration.osc133;
let shell_integration_osc633 = config.shell_integration_osc633; let shell_integration_osc633 = config.shell_integration.osc633;
let nu_prompt = NushellPrompt::new( let nu_prompt = NushellPrompt::new(
shell_integration_osc133, shell_integration_osc133,
@ -88,7 +88,7 @@ pub fn evaluate_repl(
let start_time = std::time::Instant::now(); let start_time = std::time::Instant::now();
// Translate environment variables from Strings to Values // Translate environment variables from Strings to Values
if let Err(e) = convert_env_values(engine_state, &unique_stack) { if let Err(e) = convert_env_values(engine_state, &unique_stack) {
report_error_new(engine_state, &e); report_shell_error(engine_state, &e);
} }
perf!("translate env vars", start_time, use_color); perf!("translate env vars", start_time, use_color);
@ -98,7 +98,7 @@ pub fn evaluate_repl(
Value::string("0823", Span::unknown()), Value::string("0823", Span::unknown()),
); );
unique_stack.add_env_var("LAST_EXIT_CODE".into(), Value::int(0, Span::unknown())); unique_stack.set_last_exit_code(0, Span::unknown());
let mut line_editor = get_line_editor(engine_state, nushell_path, use_color)?; let mut line_editor = get_line_editor(engine_state, nushell_path, use_color)?;
let temp_file = temp_dir().join(format!("{}.nu", uuid::Uuid::new_v4())); let temp_file = temp_dir().join(format!("{}.nu", uuid::Uuid::new_v4()));
@ -286,11 +286,11 @@ fn loop_iteration(ctx: LoopContext) -> (bool, Stack, Reedline) {
// Before doing anything, merge the environment from the previous REPL iteration into the // Before doing anything, merge the environment from the previous REPL iteration into the
// permanent state. // permanent state.
if let Err(err) = engine_state.merge_env(&mut stack, cwd) { if let Err(err) = engine_state.merge_env(&mut stack, cwd) {
report_error_new(engine_state, &err); report_shell_error(engine_state, &err);
} }
// Check whether $env.NU_USE_IR is set, so that the user can change it in the REPL // Check whether $env.NU_DISABLE_IR is set, so that the user can change it in the REPL
// Temporary while IR eval is optional // Temporary while IR eval is optional
stack.use_ir = stack.has_env_var(engine_state, "NU_USE_IR"); stack.use_ir = !stack.has_env_var(engine_state, "NU_DISABLE_IR");
perf!("merge env", start_time, use_color); perf!("merge env", start_time, use_color);
start_time = std::time::Instant::now(); start_time = std::time::Instant::now();
@ -302,7 +302,7 @@ fn loop_iteration(ctx: LoopContext) -> (bool, Stack, Reedline) {
// fire the "pre_prompt" hook // fire the "pre_prompt" hook
if let Some(hook) = engine_state.get_config().hooks.pre_prompt.clone() { if let Some(hook) = engine_state.get_config().hooks.pre_prompt.clone() {
if let Err(err) = eval_hook(engine_state, &mut stack, None, vec![], &hook, "pre_prompt") { if let Err(err) = eval_hook(engine_state, &mut stack, None, vec![], &hook, "pre_prompt") {
report_error_new(engine_state, &err); report_shell_error(engine_state, &err);
} }
} }
perf!("pre-prompt hook", start_time, use_color); perf!("pre-prompt hook", start_time, use_color);
@ -312,7 +312,7 @@ fn loop_iteration(ctx: LoopContext) -> (bool, Stack, Reedline) {
// fire the "env_change" hook // fire the "env_change" hook
let env_change = engine_state.get_config().hooks.env_change.clone(); let env_change = engine_state.get_config().hooks.env_change.clone();
if let Err(error) = hook::eval_env_change_hook(env_change, engine_state, &mut stack) { if let Err(error) = hook::eval_env_change_hook(env_change, engine_state, &mut stack) {
report_error_new(engine_state, &error) report_shell_error(engine_state, &error)
} }
perf!("env-change hook", start_time, use_color); perf!("env-change hook", start_time, use_color);
@ -322,9 +322,9 @@ fn loop_iteration(ctx: LoopContext) -> (bool, Stack, Reedline) {
start_time = std::time::Instant::now(); start_time = std::time::Instant::now();
// Find the configured cursor shapes for each mode // Find the configured cursor shapes for each mode
let cursor_config = CursorConfig { let cursor_config = CursorConfig {
vi_insert: map_nucursorshape_to_cursorshape(config.cursor_shape_vi_insert), vi_insert: map_nucursorshape_to_cursorshape(config.cursor_shape.vi_insert),
vi_normal: map_nucursorshape_to_cursorshape(config.cursor_shape_vi_normal), vi_normal: map_nucursorshape_to_cursorshape(config.cursor_shape.vi_normal),
emacs: map_nucursorshape_to_cursorshape(config.cursor_shape_emacs), emacs: map_nucursorshape_to_cursorshape(config.cursor_shape.emacs),
}; };
perf!("get config/cursor config", start_time, use_color); perf!("get config/cursor config", start_time, use_color);
@ -352,8 +352,8 @@ fn loop_iteration(ctx: LoopContext) -> (bool, Stack, Reedline) {
// STACK-REFERENCE 2 // STACK-REFERENCE 2
stack_arc.clone(), stack_arc.clone(),
))) )))
.with_quick_completions(config.quick_completions) .with_quick_completions(config.completions.quick)
.with_partial_completions(config.partial_completions) .with_partial_completions(config.completions.partial)
.with_ansi_colors(config.use_ansi_coloring) .with_ansi_colors(config.use_ansi_coloring)
.with_cwd(Some( .with_cwd(Some(
engine_state engine_state
@ -386,7 +386,7 @@ fn loop_iteration(ctx: LoopContext) -> (bool, Stack, Reedline) {
trace!("adding menus"); trace!("adding menus");
line_editor = line_editor =
add_menus(line_editor, engine_reference, &stack_arc, config).unwrap_or_else(|e| { add_menus(line_editor, engine_reference, &stack_arc, config).unwrap_or_else(|e| {
report_error_new(engine_state, &e); report_shell_error(engine_state, &e);
Reedline::create() Reedline::create()
}); });
@ -457,12 +457,12 @@ fn loop_iteration(ctx: LoopContext) -> (bool, Stack, Reedline) {
.with_completer(Box::<DefaultCompleter>::default()); .with_completer(Box::<DefaultCompleter>::default());
// Let's grab the shell_integration configs // Let's grab the shell_integration configs
let shell_integration_osc2 = config.shell_integration_osc2; let shell_integration_osc2 = config.shell_integration.osc2;
let shell_integration_osc7 = config.shell_integration_osc7; let shell_integration_osc7 = config.shell_integration.osc7;
let shell_integration_osc9_9 = config.shell_integration_osc9_9; let shell_integration_osc9_9 = config.shell_integration.osc9_9;
let shell_integration_osc133 = config.shell_integration_osc133; let shell_integration_osc133 = config.shell_integration.osc133;
let shell_integration_osc633 = config.shell_integration_osc633; let shell_integration_osc633 = config.shell_integration.osc633;
let shell_integration_reset_application_mode = config.shell_integration_reset_application_mode; let shell_integration_reset_application_mode = config.shell_integration.reset_application_mode;
// TODO: we may clone the stack, this can lead to major performance issues // TODO: we may clone the stack, this can lead to major performance issues
// so we should avoid it or making stack cheaper to clone. // so we should avoid it or making stack cheaper to clone.
@ -506,7 +506,7 @@ fn loop_iteration(ctx: LoopContext) -> (bool, Stack, Reedline) {
&hook, &hook,
"pre_execution", "pre_execution",
) { ) {
report_error_new(engine_state, &err); report_shell_error(engine_state, &err);
} }
} }
@ -808,7 +808,7 @@ fn do_auto_cd(
) { ) {
let path = { let path = {
if !path.exists() { if !path.exists() {
report_error_new( report_shell_error(
engine_state, engine_state,
&ShellError::DirectoryNotFound { &ShellError::DirectoryNotFound {
dir: path.to_string_lossy().to_string(), dir: path.to_string_lossy().to_string(),
@ -820,7 +820,7 @@ fn do_auto_cd(
}; };
if let PermissionResult::PermissionDenied(reason) = have_permission(path.clone()) { if let PermissionResult::PermissionDenied(reason) = have_permission(path.clone()) {
report_error_new( report_shell_error(
engine_state, engine_state,
&ShellError::IOError { &ShellError::IOError {
msg: format!("Cannot change directory to {path}: {reason}"), msg: format!("Cannot change directory to {path}: {reason}"),
@ -834,7 +834,7 @@ fn do_auto_cd(
//FIXME: this only changes the current scope, but instead this environment variable //FIXME: this only changes the current scope, but instead this environment variable
//should probably be a block that loads the information from the state in the overlay //should probably be a block that loads the information from the state in the overlay
if let Err(err) = stack.set_cwd(&path) { if let Err(err) = stack.set_cwd(&path) {
report_error_new(engine_state, &err); report_shell_error(engine_state, &err);
return; return;
}; };
let cwd = Value::string(cwd, span); let cwd = Value::string(cwd, span);
@ -867,7 +867,7 @@ fn do_auto_cd(
"NUSHELL_LAST_SHELL".into(), "NUSHELL_LAST_SHELL".into(),
Value::int(last_shell as i64, span), Value::int(last_shell as i64, span),
); );
stack.add_env_var("LAST_EXIT_CODE".into(), Value::int(0, Span::unknown())); stack.set_last_exit_code(0, Span::unknown());
} }
/// ///
@ -1141,7 +1141,7 @@ fn setup_keybindings(engine_state: &EngineState, line_editor: Reedline) -> Reedl
} }
}, },
Err(e) => { Err(e) => {
report_error_new(engine_state, &e); report_shell_error(engine_state, &e);
line_editor line_editor
} }
}; };
@ -1173,7 +1173,7 @@ fn update_line_editor_history(
history_session_id: Option<HistorySessionId>, history_session_id: Option<HistorySessionId>,
) -> Result<Reedline, ErrReport> { ) -> Result<Reedline, ErrReport> {
let history: Box<dyn reedline::History> = match history.file_format { let history: Box<dyn reedline::History> = match history.file_format {
HistoryFileFormat::PlainText => Box::new( HistoryFileFormat::Plaintext => Box::new(
FileBackedHistory::with_file(history.max_size as usize, history_path) FileBackedHistory::with_file(history.max_size as usize, history_path)
.into_diagnostic()?, .into_diagnostic()?,
), ),
@ -1211,10 +1211,10 @@ fn confirm_stdin_is_terminal() -> Result<()> {
fn map_nucursorshape_to_cursorshape(shape: NuCursorShape) -> Option<SetCursorStyle> { fn map_nucursorshape_to_cursorshape(shape: NuCursorShape) -> Option<SetCursorStyle> {
match shape { match shape {
NuCursorShape::Block => Some(SetCursorStyle::SteadyBlock), NuCursorShape::Block => Some(SetCursorStyle::SteadyBlock),
NuCursorShape::UnderScore => Some(SetCursorStyle::SteadyUnderScore), NuCursorShape::Underscore => Some(SetCursorStyle::SteadyUnderScore),
NuCursorShape::Line => Some(SetCursorStyle::SteadyBar), NuCursorShape::Line => Some(SetCursorStyle::SteadyBar),
NuCursorShape::BlinkBlock => Some(SetCursorStyle::BlinkingBlock), NuCursorShape::BlinkBlock => Some(SetCursorStyle::BlinkingBlock),
NuCursorShape::BlinkUnderScore => Some(SetCursorStyle::BlinkingUnderScore), NuCursorShape::BlinkUnderscore => Some(SetCursorStyle::BlinkingUnderScore),
NuCursorShape::BlinkLine => Some(SetCursorStyle::BlinkingBar), NuCursorShape::BlinkLine => Some(SetCursorStyle::BlinkingBar),
NuCursorShape::Inherit => None, NuCursorShape::Inherit => None,
} }

View File

@ -2,9 +2,11 @@ use nu_cmd_base::hook::eval_hook;
use nu_engine::{eval_block, eval_block_with_early_return}; use nu_engine::{eval_block, eval_block_with_early_return};
use nu_parser::{escape_quote_string, lex, parse, unescape_unquote_string, Token, TokenContents}; use nu_parser::{escape_quote_string, lex, parse, unescape_unquote_string, Token, TokenContents};
use nu_protocol::{ use nu_protocol::{
cli_error::report_compile_error,
debugger::WithoutDebug, debugger::WithoutDebug,
engine::{EngineState, Stack, StateWorkingSet}, engine::{EngineState, Stack, StateWorkingSet},
report_error, report_error_new, PipelineData, ShellError, Span, Value, report_parse_error, report_parse_warning, report_shell_error, PipelineData, ShellError, Span,
Value,
}; };
#[cfg(windows)] #[cfg(windows)]
use nu_utils::enable_vt_processing; use nu_utils::enable_vt_processing;
@ -39,7 +41,7 @@ fn gather_env_vars(
init_cwd: &Path, init_cwd: &Path,
) { ) {
fn report_capture_error(engine_state: &EngineState, env_str: &str, msg: &str) { fn report_capture_error(engine_state: &EngineState, env_str: &str, msg: &str) {
report_error_new( report_shell_error(
engine_state, engine_state,
&ShellError::GenericError { &ShellError::GenericError {
error: format!("Environment variable was not captured: {env_str}"), error: format!("Environment variable was not captured: {env_str}"),
@ -70,7 +72,7 @@ fn gather_env_vars(
} }
None => { None => {
// Could not capture current working directory // Could not capture current working directory
report_error_new( report_shell_error(
engine_state, engine_state,
&ShellError::GenericError { &ShellError::GenericError {
error: "Current directory is not a valid utf-8 path".into(), error: "Current directory is not a valid utf-8 path".into(),
@ -210,18 +212,19 @@ pub fn eval_source(
let start_time = std::time::Instant::now(); let start_time = std::time::Instant::now();
let exit_code = match evaluate_source(engine_state, stack, source, fname, input, allow_return) { let exit_code = match evaluate_source(engine_state, stack, source, fname, input, allow_return) {
Ok(code) => code.unwrap_or(0), Ok(failed) => {
let code = failed.into();
stack.set_last_exit_code(code, Span::unknown());
code
}
Err(err) => { Err(err) => {
report_error_new(engine_state, &err); report_shell_error(engine_state, &err);
1 let code = err.exit_code();
stack.set_last_error(&err);
code
} }
}; };
stack.add_env_var(
"LAST_EXIT_CODE".to_string(),
Value::int(exit_code.into(), Span::unknown()),
);
// reset vt processing, aka ansi because illbehaved externals can break it // reset vt processing, aka ansi because illbehaved externals can break it
#[cfg(windows)] #[cfg(windows)]
{ {
@ -244,7 +247,7 @@ fn evaluate_source(
fname: &str, fname: &str,
input: PipelineData, input: PipelineData,
allow_return: bool, allow_return: bool,
) -> Result<Option<i32>, ShellError> { ) -> Result<bool, ShellError> {
let (block, delta) = { let (block, delta) = {
let mut working_set = StateWorkingSet::new(engine_state); let mut working_set = StateWorkingSet::new(engine_state);
let output = parse( let output = parse(
@ -254,16 +257,16 @@ fn evaluate_source(
false, false,
); );
if let Some(warning) = working_set.parse_warnings.first() { if let Some(warning) = working_set.parse_warnings.first() {
report_error(&working_set, warning); report_parse_warning(&working_set, warning);
} }
if let Some(err) = working_set.parse_errors.first() { if let Some(err) = working_set.parse_errors.first() {
report_error(&working_set, err); report_parse_error(&working_set, err);
return Ok(Some(1)); return Ok(true);
} }
if let Some(err) = working_set.compile_errors.first() { if let Some(err) = working_set.compile_errors.first() {
report_error(&working_set, err); report_compile_error(&working_set, err);
// Not a fatal error, for now // Not a fatal error, for now
} }
@ -278,25 +281,23 @@ fn evaluate_source(
eval_block::<WithoutDebug>(engine_state, stack, &block, input) eval_block::<WithoutDebug>(engine_state, stack, &block, input)
}?; }?;
let status = if let PipelineData::ByteStream(..) = pipeline { if let PipelineData::ByteStream(..) = pipeline {
pipeline.print(engine_state, stack, false, false)? pipeline.print(engine_state, stack, false, false)
} else if let Some(hook) = engine_state.get_config().hooks.display_output.clone() {
let pipeline = eval_hook(
engine_state,
stack,
Some(pipeline),
vec![],
&hook,
"display_output",
)?;
pipeline.print(engine_state, stack, false, false)
} else { } else {
if let Some(hook) = engine_state.get_config().hooks.display_output.clone() { pipeline.print(engine_state, stack, true, false)
let pipeline = eval_hook( }?;
engine_state,
stack,
Some(pipeline),
vec![],
&hook,
"display_output",
)?;
pipeline.print(engine_state, stack, false, false)
} else {
pipeline.print(engine_state, stack, true, false)
}?
};
Ok(status.map(|status| status.code())) Ok(false)
} }
#[cfg(test)] #[cfg(test)]

View File

@ -61,6 +61,32 @@ fn extern_completer() -> NuCompleter {
NuCompleter::new(Arc::new(engine), Arc::new(stack)) NuCompleter::new(Arc::new(engine), Arc::new(stack))
} }
#[fixture]
fn completer_strings_with_options() -> NuCompleter {
// Create a new engine
let (dir, _, mut engine, mut stack) = new_engine();
// Add record value as example
let record = r#"
# To test that the config setting has no effect on the custom completions
$env.config.completions.algorithm = "fuzzy"
def animals [] {
{
# Very rare and totally real animals
completions: ["Abcdef", "Foo Abcdef", "Acd Bar" ],
options: {
completion_algorithm: "prefix",
positional: false,
case_sensitive: false,
}
}
}
def my-command [animal: string@animals] { print $animal }"#;
assert!(support::merge_input(record.as_bytes(), &mut engine, &mut stack, dir).is_ok());
// Instantiate a new completer
NuCompleter::new(Arc::new(engine), Arc::new(stack))
}
#[fixture] #[fixture]
fn custom_completer() -> NuCompleter { fn custom_completer() -> NuCompleter {
// Create a new engine // Create a new engine
@ -169,6 +195,20 @@ fn variables_customcompletion_subcommands_with_customcompletion_2(
match_suggestions(&expected, &suggestions); match_suggestions(&expected, &suggestions);
} }
#[rstest]
fn customcompletions_substring_matching(mut completer_strings_with_options: NuCompleter) {
let suggestions = completer_strings_with_options.complete("my-command Abcd", 15);
let expected: Vec<String> = vec!["Abcdef".into(), "Foo Abcdef".into()];
match_suggestions(&expected, &suggestions);
}
#[rstest]
fn customcompletions_case_insensitive(mut completer_strings_with_options: NuCompleter) {
let suggestions = completer_strings_with_options.complete("my-command foo", 14);
let expected: Vec<String> = vec!["Foo Abcdef".into()];
match_suggestions(&expected, &suggestions);
}
#[test] #[test]
fn dotnu_completions() { fn dotnu_completions() {
// Create a new engine // Create a new engine
@ -299,7 +339,7 @@ fn file_completions() {
match_suggestions(&expected_paths, &suggestions); match_suggestions(&expected_paths, &suggestions);
// Test completions for hidden files // Test completions for hidden files
let target_dir = format!("ls {}{MAIN_SEPARATOR}.", folder(dir.join(".hidden_folder"))); let target_dir = format!("ls {}", file(dir.join(".hidden_folder").join(".")));
let suggestions = completer.complete(&target_dir, target_dir.len()); let suggestions = completer.complete(&target_dir, target_dir.len());
let expected_paths: Vec<String> = let expected_paths: Vec<String> =
@ -337,7 +377,7 @@ fn file_completions_with_mixed_separators() {
file(dir.join("lib-dir1").join("baz.nu")), file(dir.join("lib-dir1").join("baz.nu")),
file(dir.join("lib-dir1").join("xyzzy.nu")), file(dir.join("lib-dir1").join("xyzzy.nu")),
]; ];
let expecetd_slash_paths: Vec<String> = expected_paths let expected_slash_paths: Vec<String> = expected_paths
.iter() .iter()
.map(|s| s.replace(MAIN_SEPARATOR, "/")) .map(|s| s.replace(MAIN_SEPARATOR, "/"))
.collect(); .collect();
@ -345,22 +385,22 @@ fn file_completions_with_mixed_separators() {
let target_dir = format!("ls {dir_str}/lib-dir1/"); let target_dir = format!("ls {dir_str}/lib-dir1/");
let suggestions = completer.complete(&target_dir, target_dir.len()); let suggestions = completer.complete(&target_dir, target_dir.len());
match_suggestions(&expecetd_slash_paths, &suggestions); match_suggestions(&expected_slash_paths, &suggestions);
let target_dir = format!("cp {dir_str}\\lib-dir1/"); let target_dir = format!("cp {dir_str}\\lib-dir1/");
let suggestions = completer.complete(&target_dir, target_dir.len()); let suggestions = completer.complete(&target_dir, target_dir.len());
match_suggestions(&expecetd_slash_paths, &suggestions); match_suggestions(&expected_slash_paths, &suggestions);
let target_dir = format!("ls {dir_str}/lib-dir1\\/"); let target_dir = format!("ls {dir_str}/lib-dir1\\/");
let suggestions = completer.complete(&target_dir, target_dir.len()); let suggestions = completer.complete(&target_dir, target_dir.len());
match_suggestions(&expecetd_slash_paths, &suggestions); match_suggestions(&expected_slash_paths, &suggestions);
let target_dir = format!("ls {dir_str}\\lib-dir1\\/"); let target_dir = format!("ls {dir_str}\\lib-dir1\\/");
let suggestions = completer.complete(&target_dir, target_dir.len()); let suggestions = completer.complete(&target_dir, target_dir.len());
match_suggestions(&expecetd_slash_paths, &suggestions); match_suggestions(&expected_slash_paths, &suggestions);
let target_dir = format!("ls {dir_str}\\lib-dir1\\"); let target_dir = format!("ls {dir_str}\\lib-dir1\\");
let suggestions = completer.complete(&target_dir, target_dir.len()); let suggestions = completer.complete(&target_dir, target_dir.len());
@ -524,6 +564,58 @@ fn partial_completions() {
match_suggestions(&expected_paths, &suggestions); match_suggestions(&expected_paths, &suggestions);
} }
#[test]
fn partial_completion_with_dot_expansions() {
let (dir, _, engine, stack) = new_partial_engine();
let mut completer = NuCompleter::new(Arc::new(engine), Arc::new(stack));
let dir_str = file(
dir.join("par")
.join("...")
.join("par")
.join("fi")
.join("so"),
);
let target_dir = format!("rm {dir_str}");
let suggestions = completer.complete(&target_dir, target_dir.len());
// Create the expected values
let expected_paths: Vec<String> = vec![
file(
dir.join("partial")
.join("...")
.join("partial_completions")
.join("final_partial")
.join("somefile"),
),
file(
dir.join("partial-a")
.join("...")
.join("partial_completions")
.join("final_partial")
.join("somefile"),
),
file(
dir.join("partial-b")
.join("...")
.join("partial_completions")
.join("final_partial")
.join("somefile"),
),
file(
dir.join("partial-c")
.join("...")
.join("partial_completions")
.join("final_partial")
.join("somefile"),
),
];
// Match the results
match_suggestions(&expected_paths, &suggestions);
}
#[test] #[test]
fn command_ls_with_filecompletion() { fn command_ls_with_filecompletion() {
let (_, _, engine, stack) = new_engine(); let (_, _, engine, stack) = new_engine();
@ -913,6 +1005,192 @@ fn folder_with_directorycompletions() {
match_suggestions(&expected_paths, &suggestions); match_suggestions(&expected_paths, &suggestions);
} }
#[test]
fn folder_with_directorycompletions_with_dots() {
// Create a new engine
let (dir, _, engine, stack) = new_engine();
let dir_str = dir
.join("directory_completion")
.join("folder_inside_folder")
.into_os_string()
.into_string()
.unwrap();
// Instantiate a new completer
let mut completer = NuCompleter::new(Arc::new(engine), Arc::new(stack));
// Test completions for the current folder
let target_dir = format!("cd {dir_str}{MAIN_SEPARATOR}..{MAIN_SEPARATOR}");
let suggestions = completer.complete(&target_dir, target_dir.len());
// Create the expected values
let expected_paths: Vec<String> = vec![folder(
dir.join("directory_completion")
.join("folder_inside_folder")
.join("..")
.join("folder_inside_folder"),
)];
#[cfg(windows)]
{
let target_dir = format!("cd {dir_str}/../");
let slash_suggestions = completer.complete(&target_dir, target_dir.len());
let expected_slash_paths: Vec<String> = expected_paths
.iter()
.map(|s| s.replace('\\', "/"))
.collect();
match_suggestions(&expected_slash_paths, &slash_suggestions);
}
// Match the results
match_suggestions(&expected_paths, &suggestions);
}
#[test]
fn folder_with_directorycompletions_with_three_trailing_dots() {
// Create a new engine
let (dir, _, engine, stack) = new_engine();
let dir_str = dir
.join("directory_completion")
.join("folder_inside_folder")
.into_os_string()
.into_string()
.unwrap();
// Instantiate a new completer
let mut completer = NuCompleter::new(Arc::new(engine), Arc::new(stack));
// Test completions for the current folder
let target_dir = format!("cd {dir_str}{MAIN_SEPARATOR}...{MAIN_SEPARATOR}");
let suggestions = completer.complete(&target_dir, target_dir.len());
// Create the expected values
let expected_paths: Vec<String> = vec![
folder(
dir.join("directory_completion")
.join("folder_inside_folder")
.join("...")
.join("another"),
),
folder(
dir.join("directory_completion")
.join("folder_inside_folder")
.join("...")
.join("directory_completion"),
),
folder(
dir.join("directory_completion")
.join("folder_inside_folder")
.join("...")
.join("test_a"),
),
folder(
dir.join("directory_completion")
.join("folder_inside_folder")
.join("...")
.join("test_b"),
),
folder(
dir.join("directory_completion")
.join("folder_inside_folder")
.join("...")
.join(".hidden_folder"),
),
];
#[cfg(windows)]
{
let target_dir = format!("cd {dir_str}/.../");
let slash_suggestions = completer.complete(&target_dir, target_dir.len());
let expected_slash_paths: Vec<String> = expected_paths
.iter()
.map(|s| s.replace('\\', "/"))
.collect();
match_suggestions(&expected_slash_paths, &slash_suggestions);
}
// Match the results
match_suggestions(&expected_paths, &suggestions);
}
#[test]
fn folder_with_directorycompletions_do_not_collapse_dots() {
// Create a new engine
let (dir, _, engine, stack) = new_engine();
let dir_str = dir
.join("directory_completion")
.join("folder_inside_folder")
.into_os_string()
.into_string()
.unwrap();
// Instantiate a new completer
let mut completer = NuCompleter::new(Arc::new(engine), Arc::new(stack));
// Test completions for the current folder
let target_dir = format!("cd {dir_str}{MAIN_SEPARATOR}..{MAIN_SEPARATOR}..{MAIN_SEPARATOR}");
let suggestions = completer.complete(&target_dir, target_dir.len());
// Create the expected values
let expected_paths: Vec<String> = vec![
folder(
dir.join("directory_completion")
.join("folder_inside_folder")
.join("..")
.join("..")
.join("another"),
),
folder(
dir.join("directory_completion")
.join("folder_inside_folder")
.join("..")
.join("..")
.join("directory_completion"),
),
folder(
dir.join("directory_completion")
.join("folder_inside_folder")
.join("..")
.join("..")
.join("test_a"),
),
folder(
dir.join("directory_completion")
.join("folder_inside_folder")
.join("..")
.join("..")
.join("test_b"),
),
folder(
dir.join("directory_completion")
.join("folder_inside_folder")
.join("..")
.join("..")
.join(".hidden_folder"),
),
];
#[cfg(windows)]
{
let target_dir = format!("cd {dir_str}/../../");
let slash_suggestions = completer.complete(&target_dir, target_dir.len());
let expected_slash_paths: Vec<String> = expected_paths
.iter()
.map(|s| s.replace('\\', "/"))
.collect();
match_suggestions(&expected_slash_paths, &slash_suggestions);
}
// Match the results
match_suggestions(&expected_paths, &suggestions);
}
#[test] #[test]
fn variables_completions() { fn variables_completions() {
// Create a new engine // Create a new engine

View File

@ -5,15 +5,18 @@ edition = "2021"
license = "MIT" license = "MIT"
name = "nu-cmd-base" name = "nu-cmd-base"
repository = "https://github.com/nushell/nushell/tree/main/crates/nu-cmd-base" repository = "https://github.com/nushell/nushell/tree/main/crates/nu-cmd-base"
version = "0.97.1" version = "0.98.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lints]
workspace = true
[dependencies] [dependencies]
nu-engine = { path = "../nu-engine", version = "0.97.1" } nu-engine = { path = "../nu-engine", version = "0.98.0" }
nu-parser = { path = "../nu-parser", version = "0.97.1" } nu-parser = { path = "../nu-parser", version = "0.98.0" }
nu-path = { path = "../nu-path", version = "0.97.1" } nu-path = { path = "../nu-path", version = "0.98.0" }
nu-protocol = { path = "../nu-protocol", version = "0.97.1" } nu-protocol = { path = "../nu-protocol", version = "0.98.0" }
indexmap = { workspace = true } indexmap = { workspace = true }
miette = { workspace = true } miette = { workspace = true }

View File

@ -3,7 +3,7 @@ use miette::Result;
use nu_engine::{eval_block, eval_block_with_early_return}; use nu_engine::{eval_block, eval_block_with_early_return};
use nu_parser::parse; use nu_parser::parse;
use nu_protocol::{ use nu_protocol::{
cli_error::{report_error, report_error_new}, cli_error::{report_parse_error, report_shell_error},
debugger::WithoutDebug, debugger::WithoutDebug,
engine::{Closure, EngineState, Stack, StateWorkingSet}, engine::{Closure, EngineState, Stack, StateWorkingSet},
PipelineData, PositionalArg, ShellError, Span, Type, Value, VarId, PipelineData, PositionalArg, ShellError, Span, Type, Value, VarId,
@ -91,7 +91,7 @@ pub fn eval_hook(
false, false,
); );
if let Some(err) = working_set.parse_errors.first() { if let Some(err) = working_set.parse_errors.first() {
report_error(&working_set, err); report_parse_error(&working_set, err);
return Err(ShellError::UnsupportedConfigValue { return Err(ShellError::UnsupportedConfigValue {
expected: "valid source code".into(), expected: "valid source code".into(),
@ -123,7 +123,7 @@ pub fn eval_hook(
output = pipeline_data; output = pipeline_data;
} }
Err(err) => { Err(err) => {
report_error_new(engine_state, &err); report_shell_error(engine_state, &err);
} }
} }
@ -223,7 +223,7 @@ pub fn eval_hook(
false, false,
); );
if let Some(err) = working_set.parse_errors.first() { if let Some(err) = working_set.parse_errors.first() {
report_error(&working_set, err); report_parse_error(&working_set, err);
return Err(ShellError::UnsupportedConfigValue { return Err(ShellError::UnsupportedConfigValue {
expected: "valid source code".into(), expected: "valid source code".into(),
@ -251,7 +251,7 @@ pub fn eval_hook(
output = pipeline_data; output = pipeline_data;
} }
Err(err) => { Err(err) => {
report_error_new(engine_state, &err); report_shell_error(engine_state, &err);
} }
} }

View File

@ -5,21 +5,24 @@ edition = "2021"
license = "MIT" license = "MIT"
name = "nu-cmd-extra" name = "nu-cmd-extra"
repository = "https://github.com/nushell/nushell/tree/main/crates/nu-cmd-extra" repository = "https://github.com/nushell/nushell/tree/main/crates/nu-cmd-extra"
version = "0.97.1" version = "0.98.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib] [lib]
bench = false bench = false
[lints]
workspace = true
[dependencies] [dependencies]
nu-cmd-base = { path = "../nu-cmd-base", version = "0.97.1" } nu-cmd-base = { path = "../nu-cmd-base", version = "0.98.0" }
nu-engine = { path = "../nu-engine", version = "0.97.1" } nu-engine = { path = "../nu-engine", version = "0.98.0" }
nu-json = { version = "0.97.1", path = "../nu-json" } nu-json = { version = "0.98.0", path = "../nu-json" }
nu-parser = { path = "../nu-parser", version = "0.97.1" } nu-parser = { path = "../nu-parser", version = "0.98.0" }
nu-pretty-hex = { version = "0.97.1", path = "../nu-pretty-hex" } nu-pretty-hex = { version = "0.98.0", path = "../nu-pretty-hex" }
nu-protocol = { path = "../nu-protocol", version = "0.97.1" } nu-protocol = { path = "../nu-protocol", version = "0.98.0" }
nu-utils = { path = "../nu-utils", version = "0.97.1" } nu-utils = { path = "../nu-utils", version = "0.98.0" }
# Potential dependencies for extras # Potential dependencies for extras
heck = { workspace = true } heck = { workspace = true }
@ -33,6 +36,6 @@ v_htmlescape = { workspace = true }
itertools = { workspace = true } itertools = { workspace = true }
[dev-dependencies] [dev-dependencies]
nu-cmd-lang = { path = "../nu-cmd-lang", version = "0.97.1" } nu-cmd-lang = { path = "../nu-cmd-lang", version = "0.98.0" }
nu-command = { path = "../nu-command", version = "0.97.1" } nu-command = { path = "../nu-command", version = "0.98.0" }
nu-test-support = { path = "../nu-test-support", version = "0.97.1" } nu-test-support = { path = "../nu-test-support", version = "0.98.0" }

View File

@ -37,7 +37,7 @@ impl Command for BitsAnd {
.category(Category::Bits) .category(Category::Bits)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Performs bitwise and for ints or binary values." "Performs bitwise and for ints or binary values."
} }

View File

@ -14,11 +14,11 @@ impl Command for Bits {
.input_output_types(vec![(Type::Nothing, Type::String)]) .input_output_types(vec![(Type::Nothing, Type::String)])
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Various commands for working with bits." "Various commands for working with bits."
} }
fn extra_usage(&self) -> &str { fn extra_description(&self) -> &str {
"You must use one of the following subcommands. Using this command as-is will only produce this help message." "You must use one of the following subcommands. Using this command as-is will only produce this help message."
} }

View File

@ -45,7 +45,7 @@ impl Command for BitsInto {
.category(Category::Conversions) .category(Category::Conversions)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Convert value to a binary primitive." "Convert value to a binary primitive."
} }

View File

@ -44,6 +44,25 @@ enum InputNumType {
SignedEight, SignedEight,
} }
impl InputNumType {
fn num_bits(self) -> u32 {
match self {
InputNumType::One => 8,
InputNumType::Two => 16,
InputNumType::Four => 32,
InputNumType::Eight => 64,
InputNumType::SignedOne => 8,
InputNumType::SignedTwo => 16,
InputNumType::SignedFour => 32,
InputNumType::SignedEight => 64,
}
}
fn is_permitted_bit_shift(self, bits: u32) -> bool {
bits < self.num_bits()
}
}
fn get_number_bytes( fn get_number_bytes(
number_bytes: Option<Spanned<usize>>, number_bytes: Option<Spanned<usize>>,
head: Span, head: Span,

View File

@ -51,7 +51,7 @@ impl Command for BitsNot {
.category(Category::Bits) .category(Category::Bits)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Performs logical negation on each bit." "Performs logical negation on each bit."
} }

View File

@ -38,7 +38,7 @@ impl Command for BitsOr {
.category(Category::Bits) .category(Category::Bits)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Performs bitwise or for ints or binary values." "Performs bitwise or for ints or binary values."
} }

View File

@ -1,11 +1,10 @@
use super::{get_input_num_type, get_number_bytes, InputNumType, NumberBytes}; use super::{get_input_num_type, get_number_bytes, InputNumType, NumberBytes};
use itertools::Itertools;
use nu_cmd_base::input_handler::{operate, CmdArgument}; use nu_cmd_base::input_handler::{operate, CmdArgument};
use nu_engine::command_prelude::*; use nu_engine::command_prelude::*;
struct Arguments { struct Arguments {
signed: bool, signed: bool,
bits: usize, bits: Spanned<usize>,
number_size: NumberBytes, number_size: NumberBytes,
} }
@ -53,7 +52,7 @@ impl Command for BitsRol {
.category(Category::Bits) .category(Category::Bits)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Bitwise rotate left for ints or binary values." "Bitwise rotate left for ints or binary values."
} }
@ -69,7 +68,7 @@ impl Command for BitsRol {
input: PipelineData, input: PipelineData,
) -> Result<PipelineData, ShellError> { ) -> Result<PipelineData, ShellError> {
let head = call.head; let head = call.head;
let bits: usize = call.req(engine_state, stack, 0)?; let bits = call.req(engine_state, stack, 0)?;
let signed = call.has_flag(engine_state, stack, "signed")?; let signed = call.has_flag(engine_state, stack, "signed")?;
let number_bytes: Option<Spanned<usize>> = let number_bytes: Option<Spanned<usize>> =
call.get_flag(engine_state, stack, "number-bytes")?; call.get_flag(engine_state, stack, "number-bytes")?;
@ -119,6 +118,8 @@ fn action(input: &Value, args: &Arguments, span: Span) -> Value {
number_size, number_size,
bits, bits,
} = *args; } = *args;
let bits_span = bits.span;
let bits = bits.item;
match input { match input {
Value::Int { val, .. } => { Value::Int { val, .. } => {
@ -127,6 +128,19 @@ fn action(input: &Value, args: &Arguments, span: Span) -> Value {
let bits = bits as u32; let bits = bits as u32;
let input_num_type = get_input_num_type(val, signed, number_size); let input_num_type = get_input_num_type(val, signed, number_size);
if bits > input_num_type.num_bits() {
return Value::error(
ShellError::IncorrectValue {
msg: format!(
"Trying to rotate by more than the available bits ({})",
input_num_type.num_bits()
),
val_span: bits_span,
call_span: span,
},
span,
);
}
let int = match input_num_type { let int = match input_num_type {
One => (val as u8).rotate_left(bits) as i64, One => (val as u8).rotate_left(bits) as i64,
Two => (val as u16).rotate_left(bits) as i64, Two => (val as u16).rotate_left(bits) as i64,
@ -157,16 +171,28 @@ fn action(input: &Value, args: &Arguments, span: Span) -> Value {
Value::int(int, span) Value::int(int, span)
} }
Value::Binary { val, .. } => { Value::Binary { val, .. } => {
let len = val.len();
if bits > len * 8 {
return Value::error(
ShellError::IncorrectValue {
msg: format!(
"Trying to rotate by more than the available bits ({})",
len * 8
),
val_span: bits_span,
call_span: span,
},
span,
);
}
let byte_shift = bits / 8; let byte_shift = bits / 8;
let bit_rotate = bits % 8; let bit_rotate = bits % 8;
let mut bytes = val let bytes = if bit_rotate == 0 {
.iter() rotate_bytes_left(val, byte_shift)
.copied() } else {
.circular_tuple_windows::<(u8, u8)>() rotate_bytes_and_bits_left(val, byte_shift, bit_rotate)
.map(|(lhs, rhs)| (lhs << bit_rotate) | (rhs >> (8 - bit_rotate))) };
.collect::<Vec<u8>>();
bytes.rotate_left(byte_shift);
Value::binary(bytes, span) Value::binary(bytes, span)
} }
@ -184,6 +210,34 @@ fn action(input: &Value, args: &Arguments, span: Span) -> Value {
} }
} }
fn rotate_bytes_left(data: &[u8], byte_shift: usize) -> Vec<u8> {
let len = data.len();
let mut output = vec![0; len];
output[..len - byte_shift].copy_from_slice(&data[byte_shift..]);
output[len - byte_shift..].copy_from_slice(&data[..byte_shift]);
output
}
fn rotate_bytes_and_bits_left(data: &[u8], byte_shift: usize, bit_shift: usize) -> Vec<u8> {
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");
let mut bytes = Vec::with_capacity(data.len());
let mut next_index = byte_shift;
for _ in 0..data.len() {
let curr_byte = data[next_index];
next_index += 1;
if next_index == data.len() {
next_index = 0;
}
let next_byte = data[next_index];
let new_byte = (curr_byte << bit_shift) | (next_byte >> (8 - bit_shift));
bytes.push(new_byte);
}
bytes
}
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use super::*; use super::*;

View File

@ -1,11 +1,10 @@
use super::{get_input_num_type, get_number_bytes, InputNumType, NumberBytes}; use super::{get_input_num_type, get_number_bytes, InputNumType, NumberBytes};
use itertools::Itertools;
use nu_cmd_base::input_handler::{operate, CmdArgument}; use nu_cmd_base::input_handler::{operate, CmdArgument};
use nu_engine::command_prelude::*; use nu_engine::command_prelude::*;
struct Arguments { struct Arguments {
signed: bool, signed: bool,
bits: usize, bits: Spanned<usize>,
number_size: NumberBytes, number_size: NumberBytes,
} }
@ -53,7 +52,7 @@ impl Command for BitsRor {
.category(Category::Bits) .category(Category::Bits)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Bitwise rotate right for ints or binary values." "Bitwise rotate right for ints or binary values."
} }
@ -69,7 +68,7 @@ impl Command for BitsRor {
input: PipelineData, input: PipelineData,
) -> Result<PipelineData, ShellError> { ) -> Result<PipelineData, ShellError> {
let head = call.head; let head = call.head;
let bits: usize = call.req(engine_state, stack, 0)?; let bits = call.req(engine_state, stack, 0)?;
let signed = call.has_flag(engine_state, stack, "signed")?; let signed = call.has_flag(engine_state, stack, "signed")?;
let number_bytes: Option<Spanned<usize>> = let number_bytes: Option<Spanned<usize>> =
call.get_flag(engine_state, stack, "number-bytes")?; call.get_flag(engine_state, stack, "number-bytes")?;
@ -123,6 +122,8 @@ fn action(input: &Value, args: &Arguments, span: Span) -> Value {
number_size, number_size,
bits, bits,
} = *args; } = *args;
let bits_span = bits.span;
let bits = bits.item;
match input { match input {
Value::Int { val, .. } => { Value::Int { val, .. } => {
@ -131,6 +132,19 @@ fn action(input: &Value, args: &Arguments, span: Span) -> Value {
let bits = bits as u32; let bits = bits as u32;
let input_num_type = get_input_num_type(val, signed, number_size); let input_num_type = get_input_num_type(val, signed, number_size);
if bits > input_num_type.num_bits() {
return Value::error(
ShellError::IncorrectValue {
msg: format!(
"Trying to rotate by more than the available bits ({})",
input_num_type.num_bits()
),
val_span: bits_span,
call_span: span,
},
span,
);
}
let int = match input_num_type { let int = match input_num_type {
One => (val as u8).rotate_right(bits) as i64, One => (val as u8).rotate_right(bits) as i64,
Two => (val as u16).rotate_right(bits) as i64, Two => (val as u16).rotate_right(bits) as i64,
@ -161,16 +175,28 @@ fn action(input: &Value, args: &Arguments, span: Span) -> Value {
Value::int(int, span) Value::int(int, span)
} }
Value::Binary { val, .. } => { Value::Binary { val, .. } => {
let len = val.len();
if bits > len * 8 {
return Value::error(
ShellError::IncorrectValue {
msg: format!(
"Trying to rotate by more than the available bits ({})",
len * 8
),
val_span: bits_span,
call_span: span,
},
span,
);
}
let byte_shift = bits / 8; let byte_shift = bits / 8;
let bit_rotate = bits % 8; let bit_rotate = bits % 8;
let mut bytes = val let bytes = if bit_rotate == 0 {
.iter() rotate_bytes_right(val, byte_shift)
.copied() } else {
.circular_tuple_windows::<(u8, u8)>() rotate_bytes_and_bits_right(val, byte_shift, bit_rotate)
.map(|(lhs, rhs)| (lhs >> bit_rotate) | (rhs << (8 - bit_rotate))) };
.collect::<Vec<u8>>();
bytes.rotate_right(byte_shift);
Value::binary(bytes, span) Value::binary(bytes, span)
} }
@ -188,6 +214,35 @@ fn action(input: &Value, args: &Arguments, span: Span) -> Value {
} }
} }
fn rotate_bytes_right(data: &[u8], byte_shift: usize) -> Vec<u8> {
let len = data.len();
let mut output = vec![0; len];
output[byte_shift..].copy_from_slice(&data[..len - byte_shift]);
output[..byte_shift].copy_from_slice(&data[len - byte_shift..]);
output
}
fn rotate_bytes_and_bits_right(data: &[u8], byte_shift: usize, bit_shift: usize) -> Vec<u8> {
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"
);
let mut bytes = Vec::with_capacity(data.len());
let mut previous_index = data.len() - byte_shift - 1;
for _ in 0..data.len() {
let previous_byte = data[previous_index];
previous_index += 1;
if previous_index == data.len() {
previous_index = 0;
}
let curr_byte = data[previous_index];
let rotated_byte = (curr_byte >> bit_shift) | (previous_byte << (8 - bit_shift));
bytes.push(rotated_byte);
}
bytes
}
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use super::*; use super::*;

View File

@ -7,7 +7,7 @@ use std::iter;
struct Arguments { struct Arguments {
signed: bool, signed: bool,
bits: usize, bits: Spanned<usize>,
number_size: NumberBytes, number_size: NumberBytes,
} }
@ -55,7 +55,7 @@ impl Command for BitsShl {
.category(Category::Bits) .category(Category::Bits)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Bitwise shift left for ints or binary values." "Bitwise shift left for ints or binary values."
} }
@ -71,7 +71,9 @@ impl Command for BitsShl {
input: PipelineData, input: PipelineData,
) -> Result<PipelineData, ShellError> { ) -> Result<PipelineData, ShellError> {
let head = call.head; let head = call.head;
let bits: usize = call.req(engine_state, stack, 0)?; // This restricts to a positive shift value (our underlying operations do not
// permit them)
let bits: Spanned<usize> = call.req(engine_state, stack, 0)?;
let signed = call.has_flag(engine_state, stack, "signed")?; let signed = call.has_flag(engine_state, stack, "signed")?;
let number_bytes: Option<Spanned<usize>> = let number_bytes: Option<Spanned<usize>> =
call.get_flag(engine_state, stack, "number-bytes")?; call.get_flag(engine_state, stack, "number-bytes")?;
@ -131,14 +133,29 @@ fn action(input: &Value, args: &Arguments, span: Span) -> Value {
number_size, number_size,
bits, bits,
} = *args; } = *args;
let bits_span = bits.span;
let bits = bits.item;
match input { match input {
Value::Int { val, .. } => { Value::Int { val, .. } => {
use InputNumType::*; use InputNumType::*;
let val = *val; let val = *val;
let bits = bits as u64; let bits = bits as u32;
let input_num_type = get_input_num_type(val, signed, number_size); let input_num_type = get_input_num_type(val, signed, number_size);
if !input_num_type.is_permitted_bit_shift(bits) {
return Value::error(
ShellError::IncorrectValue {
msg: format!(
"Trying to shift by more than the available bits (permitted < {})",
input_num_type.num_bits()
),
val_span: bits_span,
call_span: span,
},
span,
);
}
let int = match input_num_type { let int = match input_num_type {
One => ((val as u8) << bits) as i64, One => ((val as u8) << bits) as i64,
Two => ((val as u16) << bits) as i64, Two => ((val as u16) << bits) as i64,
@ -147,12 +164,14 @@ fn action(input: &Value, args: &Arguments, span: Span) -> Value {
let Ok(i) = i64::try_from((val as u64) << bits) else { let Ok(i) = i64::try_from((val as u64) << bits) else {
return Value::error( return Value::error(
ShellError::GenericError { ShellError::GenericError {
error: "result out of range for specified number".into(), error: "result out of range for int".into(),
msg: format!( msg: format!(
"shifting left by {bits} is out of range for the value {val}" "shifting left by {bits} is out of range for the value {val}"
), ),
span: Some(span), span: Some(span),
help: None, help: Some(
"Ensure the result fits in a 64-bit signed integer.".into(),
),
inner: vec![], inner: vec![],
}, },
span, span,
@ -172,19 +191,26 @@ fn action(input: &Value, args: &Arguments, span: Span) -> Value {
let byte_shift = bits / 8; let byte_shift = bits / 8;
let bit_shift = bits % 8; let bit_shift = bits % 8;
use itertools::Position::*; // This is purely for symmetry with the int case and the fact that the
let bytes = val // shift right implementation in its current form panicked with an overflow
.iter() if bits > val.len() * 8 {
.copied() return Value::error(
.skip(byte_shift) ShellError::IncorrectValue {
.circular_tuple_windows::<(u8, u8)>() msg: format!(
.with_position() "Trying to shift by more than the available bits ({})",
.map(|(pos, (lhs, rhs))| match pos { val.len() * 8
Last | Only => lhs << bit_shift, ),
_ => (lhs << bit_shift) | (rhs >> bit_shift), val_span: bits_span,
}) call_span: span,
.chain(iter::repeat(0).take(byte_shift)) },
.collect::<Vec<u8>>(); span,
);
}
let bytes = if bit_shift == 0 {
shift_bytes_left(val, byte_shift)
} else {
shift_bytes_and_bits_left(val, byte_shift, bit_shift)
};
Value::binary(bytes, span) Value::binary(bytes, span)
} }
@ -202,6 +228,31 @@ fn action(input: &Value, args: &Arguments, span: Span) -> Value {
} }
} }
fn shift_bytes_left(data: &[u8], byte_shift: usize) -> Vec<u8> {
let len = data.len();
let mut output = vec![0; len];
output[..len - byte_shift].copy_from_slice(&data[byte_shift..]);
output
}
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),
"Bit shifts of 0 can't be handled by this impl and everything else should be part of the byteshift"
);
data.iter()
.copied()
.skip(byte_shift)
.circular_tuple_windows::<(u8, u8)>()
.with_position()
.map(|(pos, (lhs, rhs))| match pos {
Last | Only => lhs << bit_shift,
_ => (lhs << bit_shift) | (rhs >> (8 - bit_shift)),
})
.chain(iter::repeat(0).take(byte_shift))
.collect::<Vec<u8>>()
}
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use super::*; use super::*;

View File

@ -1,13 +1,10 @@
use super::{get_input_num_type, get_number_bytes, InputNumType, NumberBytes}; use super::{get_input_num_type, get_number_bytes, InputNumType, NumberBytes};
use itertools::Itertools;
use nu_cmd_base::input_handler::{operate, CmdArgument}; use nu_cmd_base::input_handler::{operate, CmdArgument};
use nu_engine::command_prelude::*; use nu_engine::command_prelude::*;
use std::iter;
struct Arguments { struct Arguments {
signed: bool, signed: bool,
bits: usize, bits: Spanned<usize>,
number_size: NumberBytes, number_size: NumberBytes,
} }
@ -55,7 +52,7 @@ impl Command for BitsShr {
.category(Category::Bits) .category(Category::Bits)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Bitwise shift right for ints or binary values." "Bitwise shift right for ints or binary values."
} }
@ -71,7 +68,9 @@ impl Command for BitsShr {
input: PipelineData, input: PipelineData,
) -> Result<PipelineData, ShellError> { ) -> Result<PipelineData, ShellError> {
let head = call.head; let head = call.head;
let bits: usize = call.req(engine_state, stack, 0)?; // This restricts to a positive shift value (our underlying operations do not
// permit them)
let bits: Spanned<usize> = call.req(engine_state, stack, 0)?;
let signed = call.has_flag(engine_state, stack, "signed")?; let signed = call.has_flag(engine_state, stack, "signed")?;
let number_bytes: Option<Spanned<usize>> = let number_bytes: Option<Spanned<usize>> =
call.get_flag(engine_state, stack, "number-bytes")?; call.get_flag(engine_state, stack, "number-bytes")?;
@ -121,6 +120,8 @@ fn action(input: &Value, args: &Arguments, span: Span) -> Value {
number_size, number_size,
bits, bits,
} = *args; } = *args;
let bits_span = bits.span;
let bits = bits.item;
match input { match input {
Value::Int { val, .. } => { Value::Int { val, .. } => {
@ -129,6 +130,19 @@ fn action(input: &Value, args: &Arguments, span: Span) -> Value {
let bits = bits as u32; let bits = bits as u32;
let input_num_type = get_input_num_type(val, signed, number_size); let input_num_type = get_input_num_type(val, signed, number_size);
if !input_num_type.is_permitted_bit_shift(bits) {
return Value::error(
ShellError::IncorrectValue {
msg: format!(
"Trying to shift by more than the available bits (permitted < {})",
input_num_type.num_bits()
),
val_span: bits_span,
call_span: span,
},
span,
);
}
let int = match input_num_type { let int = match input_num_type {
One => ((val as u8) >> bits) as i64, One => ((val as u8) >> bits) as i64,
Two => ((val as u16) >> bits) as i64, Two => ((val as u16) >> bits) as i64,
@ -147,21 +161,27 @@ fn action(input: &Value, args: &Arguments, span: Span) -> Value {
let bit_shift = bits % 8; let bit_shift = bits % 8;
let len = val.len(); let len = val.len();
use itertools::Position::*; // This check is done for symmetry with the int case and the previous
let bytes = iter::repeat(0) // implementation would overflow byte indices leading to unexpected output
.take(byte_shift) // lengths
.chain( if bits > len * 8 {
val.iter() return Value::error(
.copied() ShellError::IncorrectValue {
.circular_tuple_windows::<(u8, u8)>() msg: format!(
.with_position() "Trying to shift by more than the available bits ({})",
.map(|(pos, (lhs, rhs))| match pos { len * 8
First | Only => lhs >> bit_shift, ),
_ => (lhs >> bit_shift) | (rhs << bit_shift), val_span: bits_span,
}) call_span: span,
.take(len - byte_shift), },
) span,
.collect::<Vec<u8>>(); );
}
let bytes = if bit_shift == 0 {
shift_bytes_right(val, byte_shift)
} else {
shift_bytes_and_bits_right(val, byte_shift, bit_shift)
};
Value::binary(bytes, span) Value::binary(bytes, span)
} }
@ -178,6 +198,35 @@ fn action(input: &Value, args: &Arguments, span: Span) -> Value {
), ),
} }
} }
fn shift_bytes_right(data: &[u8], byte_shift: usize) -> Vec<u8> {
let len = data.len();
let mut output = vec![0; len];
output[byte_shift..].copy_from_slice(&data[..len - byte_shift]);
output
}
fn shift_bytes_and_bits_right(data: &[u8], byte_shift: usize, bit_shift: usize) -> Vec<u8> {
debug_assert!(
bit_shift > 0 && bit_shift < 8,
"bit_shift should be in the range (0, 8)"
);
let len = data.len();
let mut output = vec![0; len];
for i in byte_shift..len {
let shifted_bits = data[i - byte_shift] >> bit_shift;
let carried_bits = if i > byte_shift {
data[i - byte_shift - 1] << (8 - bit_shift)
} else {
0
};
let shifted_byte = shifted_bits | carried_bits;
output[i] = shifted_byte;
}
output
}
#[cfg(test)] #[cfg(test)]
mod test { mod test {

View File

@ -38,7 +38,7 @@ impl Command for BitsXor {
.category(Category::Bits) .category(Category::Bits)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Performs bitwise xor for ints or binary values." "Performs bitwise xor for ints or binary values."
} }

View File

@ -9,7 +9,7 @@ impl Command for Fmt {
"fmt" "fmt"
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Format a number." "Format a number."
} }

View File

@ -9,7 +9,7 @@ impl Command for EachWhile {
"each while" "each while"
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Run a closure on each row of the input list until a null is found, then create a new list with the results." "Run a closure on each row of the input list until a null is found, then create a new list with the results."
} }

View File

@ -18,11 +18,11 @@ impl Command for Roll {
.input_output_types(vec![(Type::Nothing, Type::String)]) .input_output_types(vec![(Type::Nothing, Type::String)])
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Rolling commands for tables." "Rolling commands for tables."
} }
fn extra_usage(&self) -> &str { fn extra_description(&self) -> &str {
"You must use one of the following subcommands. Using this command as-is will only produce this help message." "You must use one of the following subcommands. Using this command as-is will only produce this help message."
} }

View File

@ -21,7 +21,7 @@ impl Command for RollDown {
.category(Category::Filters) .category(Category::Filters)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Roll table rows down." "Roll table rows down."
} }

View File

@ -33,7 +33,7 @@ impl Command for RollLeft {
.category(Category::Filters) .category(Category::Filters)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Roll record or table columns left." "Roll record or table columns left."
} }

View File

@ -33,7 +33,7 @@ impl Command for RollRight {
.category(Category::Filters) .category(Category::Filters)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Roll table columns right." "Roll table columns right."
} }

View File

@ -21,7 +21,7 @@ impl Command for RollUp {
.category(Category::Filters) .category(Category::Filters)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Roll table rows up." "Roll table rows up."
} }

View File

@ -23,7 +23,7 @@ impl Command for Rotate {
.category(Category::Filters) .category(Category::Filters)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Rotates a table or record clockwise (default) or counter-clockwise (use --ccw flag)." "Rotates a table or record clockwise (default) or counter-clockwise (use --ccw flag)."
} }

View File

@ -27,7 +27,7 @@ impl Command for UpdateCells {
.category(Category::Filters) .category(Category::Filters)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Update the table cells." "Update the table cells."
} }

View File

@ -14,7 +14,7 @@ impl Command for FromUrl {
.category(Category::Formats) .category(Category::Formats)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Parse url-encoded string as a record." "Parse url-encoded string as a record."
} }

View File

@ -138,11 +138,11 @@ impl Command for ToHtml {
] ]
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Convert table into simple HTML." "Convert table into simple HTML."
} }
fn extra_usage(&self) -> &str { fn extra_description(&self) -> &str {
"Screenshots of the themes can be browsed here: https://github.com/mbadolato/iTerm2-Color-Schemes." "Screenshots of the themes can be browsed here: https://github.com/mbadolato/iTerm2-Color-Schemes."
} }

View File

@ -22,7 +22,7 @@ impl Command for SubCommand {
.category(Category::Math) .category(Category::Math)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Returns the arccosine of the number." "Returns the arccosine of the number."
} }

View File

@ -21,7 +21,7 @@ impl Command for SubCommand {
.category(Category::Math) .category(Category::Math)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Returns the inverse of the hyperbolic cosine function." "Returns the inverse of the hyperbolic cosine function."
} }

View File

@ -22,7 +22,7 @@ impl Command for SubCommand {
.category(Category::Math) .category(Category::Math)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Returns the arcsine of the number." "Returns the arcsine of the number."
} }

View File

@ -21,7 +21,7 @@ impl Command for SubCommand {
.category(Category::Math) .category(Category::Math)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Returns the inverse of the hyperbolic sine function." "Returns the inverse of the hyperbolic sine function."
} }

View File

@ -22,7 +22,7 @@ impl Command for SubCommand {
.category(Category::Math) .category(Category::Math)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Returns the arctangent of the number." "Returns the arctangent of the number."
} }

View File

@ -21,7 +21,7 @@ impl Command for SubCommand {
.category(Category::Math) .category(Category::Math)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Returns the inverse of the hyperbolic tangent function." "Returns the inverse of the hyperbolic tangent function."
} }

View File

@ -21,7 +21,7 @@ impl Command for SubCommand {
.category(Category::Math) .category(Category::Math)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Returns the cosine of the number." "Returns the cosine of the number."
} }

View File

@ -21,7 +21,7 @@ impl Command for SubCommand {
.category(Category::Math) .category(Category::Math)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Returns the hyperbolic cosine of the number." "Returns the hyperbolic cosine of the number."
} }

View File

@ -21,7 +21,7 @@ impl Command for SubCommand {
.category(Category::Math) .category(Category::Math)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Returns e raised to the power of x." "Returns e raised to the power of x."
} }

View File

@ -21,7 +21,7 @@ impl Command for SubCommand {
.category(Category::Math) .category(Category::Math)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Returns the natural logarithm. Base: (math e)." "Returns the natural logarithm. Base: (math e)."
} }

View File

@ -21,7 +21,7 @@ impl Command for SubCommand {
.category(Category::Math) .category(Category::Math)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Returns the sine of the number." "Returns the sine of the number."
} }

View File

@ -21,7 +21,7 @@ impl Command for SubCommand {
.category(Category::Math) .category(Category::Math)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Returns the hyperbolic sine of the number." "Returns the hyperbolic sine of the number."
} }

View File

@ -21,7 +21,7 @@ impl Command for SubCommand {
.category(Category::Math) .category(Category::Math)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Returns the tangent of the number." "Returns the tangent of the number."
} }

View File

@ -21,7 +21,7 @@ impl Command for SubCommand {
.category(Category::Math) .category(Category::Math)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Returns the hyperbolic tangent of the number." "Returns the hyperbolic tangent of the number."
} }

View File

@ -45,8 +45,6 @@ pub fn add_extra_command_context(mut engine_state: EngineState) -> EngineState {
bind_command!( bind_command!(
strings::format::FormatPattern, strings::format::FormatPattern,
strings::encode_decode::EncodeHex,
strings::encode_decode::DecodeHex,
strings::str_::case::Str, strings::str_::case::Str,
strings::str_::case::StrCamelCase, strings::str_::case::StrCamelCase,
strings::str_::case::StrKebabCase, strings::str_::case::StrKebabCase,

View File

@ -53,7 +53,7 @@ impl Command for SubCommand {
.category(Category::Platform) .category(Category::Platform)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Add a color gradient (using ANSI color codes) to the given string." "Add a color gradient (using ANSI color codes) to the given string."
} }

View File

@ -29,7 +29,7 @@ impl Command for DecodeHex {
.category(Category::Formats) .category(Category::Formats)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Hex decode a value." "Hex decode a value."
} }

View File

@ -29,7 +29,7 @@ impl Command for EncodeHex {
.category(Category::Formats) .category(Category::Formats)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Encode a binary value using hex." "Encode a binary value using hex."
} }

View File

@ -1,192 +0,0 @@
use nu_cmd_base::input_handler::{operate as general_operate, CmdArgument};
use nu_engine::command_prelude::*;
enum HexDecodingError {
InvalidLength(usize),
InvalidDigit(usize, char),
}
fn hex_decode(value: &str) -> Result<Vec<u8>, HexDecodingError> {
let mut digits = value
.chars()
.enumerate()
.filter(|(_, c)| !c.is_whitespace());
let mut res = Vec::with_capacity(value.len() / 2);
loop {
let c1 = match digits.next() {
Some((ind, c)) => match c.to_digit(16) {
Some(d) => d,
None => return Err(HexDecodingError::InvalidDigit(ind, c)),
},
None => return Ok(res),
};
let c2 = match digits.next() {
Some((ind, c)) => match c.to_digit(16) {
Some(d) => d,
None => return Err(HexDecodingError::InvalidDigit(ind, c)),
},
None => {
return Err(HexDecodingError::InvalidLength(value.len()));
}
};
res.push((c1 << 4 | c2) as u8);
}
}
fn hex_digit(num: u8) -> char {
match num {
0..=9 => (num + b'0') as char,
10..=15 => (num - 10 + b'A') as char,
_ => unreachable!(),
}
}
fn hex_encode(bytes: &[u8]) -> String {
let mut res = String::with_capacity(bytes.len() * 2);
for byte in bytes {
res.push(hex_digit(byte >> 4));
res.push(hex_digit(byte & 0b1111));
}
res
}
#[derive(Clone)]
pub struct HexConfig {
pub action_type: ActionType,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum ActionType {
Encode,
Decode,
}
struct Arguments {
cell_paths: Option<Vec<CellPath>>,
encoding_config: HexConfig,
}
impl CmdArgument for Arguments {
fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> {
self.cell_paths.take()
}
}
pub fn operate(
action_type: ActionType,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let cell_paths: Vec<CellPath> = call.rest(engine_state, stack, 0)?;
let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths);
let args = Arguments {
encoding_config: HexConfig { action_type },
cell_paths,
};
general_operate(action, args, input, call.head, engine_state.signals())
}
fn action(
input: &Value,
// only used for `decode` action
args: &Arguments,
command_span: Span,
) -> Value {
let hex_config = &args.encoding_config;
match input {
// Propagate existing errors.
Value::Error { .. } => input.clone(),
Value::Binary { val, .. } => match hex_config.action_type {
ActionType::Encode => Value::string(hex_encode(val.as_ref()), command_span),
ActionType::Decode => Value::error(
ShellError::UnsupportedInput { msg: "Binary data can only be encoded".to_string(), input: "value originates from here".into(), msg_span: command_span, input_span: input.span() },
command_span,
),
},
Value::String { val, .. } => {
match hex_config.action_type {
ActionType::Encode => Value::error(
ShellError::UnsupportedInput { msg: "String value can only be decoded".to_string(), input: "value originates from here".into(), msg_span: command_span, input_span: input.span() },
command_span,
),
ActionType::Decode => match hex_decode(val.as_ref()) {
Ok(decoded_value) => Value::binary(decoded_value, command_span),
Err(HexDecodingError::InvalidLength(len)) => Value::error(ShellError::GenericError {
error: "value could not be hex decoded".into(),
msg: format!("invalid hex input length: {len}. The length should be even"),
span: Some(command_span),
help: None,
inner: vec![],
},
command_span,
),
Err(HexDecodingError::InvalidDigit(index, digit)) => Value::error(ShellError::GenericError {
error: "value could not be hex decoded".into(),
msg: format!("invalid hex digit: '{digit}' at index {index}. Only 0-9, A-F, a-f are allowed in hex encoding"),
span: Some(command_span),
help: None,
inner: vec![],
},
command_span,
),
},
}
}
other => Value::error(
ShellError::TypeMismatch {
err_message: format!("string or binary, not {}", other.get_type()),
span: other.span(),
},
other.span(),
),
}
}
#[cfg(test)]
mod tests {
use super::{action, ActionType, Arguments, HexConfig};
use nu_protocol::{Span, Value};
#[test]
fn hex_encode() {
let word = Value::binary([77, 97, 110], Span::test_data());
let expected = Value::test_string("4D616E");
let actual = action(
&word,
&Arguments {
encoding_config: HexConfig {
action_type: ActionType::Encode,
},
cell_paths: None,
},
Span::test_data(),
);
assert_eq!(actual, expected);
}
#[test]
fn hex_decode() {
let word = Value::test_string("4D 61\r\n\n6E");
let expected = Value::binary([77, 97, 110], Span::test_data());
let actual = action(
&word,
&Arguments {
encoding_config: HexConfig {
action_type: ActionType::Decode,
},
cell_paths: None,
},
Span::test_data(),
);
assert_eq!(actual, expected);
}
}

View File

@ -1,6 +0,0 @@
mod decode_hex;
mod encode_hex;
mod hex;
pub(crate) use decode_hex::DecodeHex;
pub(crate) use encode_hex::EncodeHex;

View File

@ -24,7 +24,7 @@ impl Command for FormatPattern {
.category(Category::Strings) .category(Category::Strings)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Format columns into a string using a simple pattern." "Format columns into a string using a simple pattern."
} }

View File

@ -1,3 +1,2 @@
pub(crate) mod encode_decode;
pub(crate) mod format; pub(crate) mod format;
pub(crate) mod str_; pub(crate) mod str_;

View File

@ -30,7 +30,7 @@ impl Command for SubCommand {
.category(Category::Strings) .category(Category::Strings)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Convert a string to camelCase." "Convert a string to camelCase."
} }

View File

@ -30,7 +30,7 @@ impl Command for SubCommand {
.category(Category::Strings) .category(Category::Strings)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Convert a string to kebab-case." "Convert a string to kebab-case."
} }

View File

@ -30,7 +30,7 @@ impl Command for SubCommand {
.category(Category::Strings) .category(Category::Strings)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Convert a string to PascalCase." "Convert a string to PascalCase."
} }

View File

@ -30,7 +30,7 @@ impl Command for SubCommand {
.category(Category::Strings) .category(Category::Strings)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Convert a string to SCREAMING_SNAKE_CASE." "Convert a string to SCREAMING_SNAKE_CASE."
} }

View File

@ -30,7 +30,7 @@ impl Command for SubCommand {
.category(Category::Strings) .category(Category::Strings)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Convert a string to snake_case." "Convert a string to snake_case."
} }

View File

@ -14,11 +14,11 @@ impl Command for Str {
.input_output_types(vec![(Type::Nothing, Type::String)]) .input_output_types(vec![(Type::Nothing, Type::String)])
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Various commands for working with string data." "Various commands for working with string data."
} }
fn extra_usage(&self) -> &str { fn extra_description(&self) -> &str {
"You must use one of the following subcommands. Using this command as-is will only produce this help message." "You must use one of the following subcommands. Using this command as-is will only produce this help message."
} }

View File

@ -30,7 +30,7 @@ impl Command for SubCommand {
.category(Category::Strings) .category(Category::Strings)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Convert a string to Title Case." "Convert a string to Title Case."
} }

View File

@ -6,22 +6,25 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu-cmd-lang"
edition = "2021" edition = "2021"
license = "MIT" license = "MIT"
name = "nu-cmd-lang" name = "nu-cmd-lang"
version = "0.97.1" version = "0.98.0"
[lib] [lib]
bench = false bench = false
[lints]
workspace = true
[dependencies] [dependencies]
nu-engine = { path = "../nu-engine", version = "0.97.1" } nu-engine = { path = "../nu-engine", version = "0.98.0" }
nu-parser = { path = "../nu-parser", version = "0.97.1" } nu-parser = { path = "../nu-parser", version = "0.98.0" }
nu-protocol = { path = "../nu-protocol", version = "0.97.1" } nu-protocol = { path = "../nu-protocol", version = "0.98.0" }
nu-utils = { path = "../nu-utils", version = "0.97.1" } nu-utils = { path = "../nu-utils", version = "0.98.0" }
itertools = { workspace = true } itertools = { workspace = true }
shadow-rs = { version = "0.31", default-features = false } shadow-rs = { version = "0.34", default-features = false }
[build-dependencies] [build-dependencies]
shadow-rs = { version = "0.31", default-features = false } shadow-rs = { version = "0.34", default-features = false }
[features] [features]
mimalloc = [] mimalloc = []

View File

@ -9,7 +9,7 @@ impl Command for Alias {
"alias" "alias"
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Alias a command (with optional flags) to a new name." "Alias a command (with optional flags) to a new name."
} }
@ -25,7 +25,7 @@ impl Command for Alias {
.category(Category::Core) .category(Category::Core)
} }
fn extra_usage(&self) -> &str { fn extra_description(&self) -> &str {
r#"This command is a parser keyword. For details, check: r#"This command is a parser keyword. For details, check:
https://www.nushell.sh/book/thinking_in_nu.html"# https://www.nushell.sh/book/thinking_in_nu.html"#
} }

View File

@ -9,7 +9,7 @@ impl Command for Break {
"break" "break"
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Break a loop." "Break a loop."
} }
@ -19,7 +19,7 @@ impl Command for Break {
.category(Category::Core) .category(Category::Core)
} }
fn extra_usage(&self) -> &str { fn extra_description(&self) -> &str {
r#"This command is a parser keyword. For details, check: r#"This command is a parser keyword. For details, check:
https://www.nushell.sh/book/thinking_in_nu.html https://www.nushell.sh/book/thinking_in_nu.html

View File

@ -25,11 +25,11 @@ impl Command for Collect {
.category(Category::Filters) .category(Category::Filters)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Collect a stream into a value." "Collect a stream into a value."
} }
fn extra_usage(&self) -> &str { fn extra_description(&self) -> &str {
r#"If provided, run a closure with the collected value as input. r#"If provided, run a closure with the collected value as input.
The entire stream will be collected into one value in memory, so if the stream The entire stream will be collected into one value in memory, so if the stream

View File

@ -9,7 +9,7 @@ impl Command for Const {
"const" "const"
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Create a parse-time constant." "Create a parse-time constant."
} }
@ -26,7 +26,7 @@ impl Command for Const {
.category(Category::Core) .category(Category::Core)
} }
fn extra_usage(&self) -> &str { fn extra_description(&self) -> &str {
r#"This command is a parser keyword. For details, check: r#"This command is a parser keyword. For details, check:
https://www.nushell.sh/book/thinking_in_nu.html"# https://www.nushell.sh/book/thinking_in_nu.html"#
} }

View File

@ -9,7 +9,7 @@ impl Command for Continue {
"continue" "continue"
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Continue a loop from the next iteration." "Continue a loop from the next iteration."
} }
@ -19,7 +19,7 @@ impl Command for Continue {
.category(Category::Core) .category(Category::Core)
} }
fn extra_usage(&self) -> &str { fn extra_description(&self) -> &str {
r#"This command is a parser keyword. For details, check: r#"This command is a parser keyword. For details, check:
https://www.nushell.sh/book/thinking_in_nu.html https://www.nushell.sh/book/thinking_in_nu.html

View File

@ -9,7 +9,7 @@ impl Command for Def {
"def" "def"
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Define a custom command." "Define a custom command."
} }
@ -24,7 +24,7 @@ impl Command for Def {
.category(Category::Core) .category(Category::Core)
} }
fn extra_usage(&self) -> &str { fn extra_description(&self) -> &str {
r#"This command is a parser keyword. For details, check: r#"This command is a parser keyword. For details, check:
https://www.nushell.sh/book/thinking_in_nu.html"# https://www.nushell.sh/book/thinking_in_nu.html"#
} }

View File

@ -9,7 +9,7 @@ impl Command for Describe {
"describe" "describe"
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Describe the type and structure of the value(s) piped in." "Describe the type and structure of the value(s) piped in."
} }
@ -70,7 +70,7 @@ impl Command for Describe {
Example { Example {
description: "Describe the type of a record in a detailed way", description: "Describe the type of a record in a detailed way",
example: example:
"{shell:'true', uwu:true, features: {bugs:false, multiplatform:true, speed: 10}, fib: [1 1 2 3 5 8], on_save: {|x| print $'Saving ($x)'}, first_commit: 2019-05-10, my_duration: (4min + 20sec)} | describe -d", "{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!( result: Some(Value::test_record(record!(
"type" => Value::test_string("record"), "type" => Value::test_string("record"),
"columns" => Value::test_record(record!( "columns" => Value::test_record(record!(

View File

@ -1,7 +1,7 @@
use nu_engine::{command_prelude::*, get_eval_block_with_early_return, redirect_env}; use nu_engine::{command_prelude::*, get_eval_block_with_early_return, redirect_env};
use nu_protocol::{ use nu_protocol::{
engine::Closure, engine::Closure,
process::{ChildPipe, ChildProcess, ExitStatus}, process::{ChildPipe, ChildProcess},
ByteStream, ByteStreamSource, OutDest, ByteStream, ByteStreamSource, OutDest,
}; };
use std::{ use std::{
@ -17,7 +17,7 @@ impl Command for Do {
"do" "do"
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Run a closure, providing it with the pipeline input." "Run a closure, providing it with the pipeline input."
} }
@ -83,7 +83,7 @@ impl Command for Do {
let eval_block_with_early_return = get_eval_block_with_early_return(engine_state); let eval_block_with_early_return = get_eval_block_with_early_return(engine_state);
// Applies to all block evaluation once set true // Applies to all block evaluation once set true
callee_stack.use_ir = caller_stack.has_env_var(engine_state, "NU_USE_IR"); callee_stack.use_ir = !caller_stack.has_env_var(engine_state, "NU_DISABLE_IR");
let result = eval_block_with_early_return(engine_state, &mut callee_stack, block, input); let result = eval_block_with_early_return(engine_state, &mut callee_stack, block, input);
@ -147,13 +147,7 @@ impl Command for Do {
None None
}; };
if child.wait()? != ExitStatus::Exited(0) { child.wait()?;
return Err(ShellError::ExternalCommand {
label: "External command failed".to_string(),
help: stderr_msg,
span,
});
}
let mut child = ChildProcess::from_raw(None, None, None, span); let mut child = ChildProcess::from_raw(None, None, None, span);
if let Some(stdout) = stdout { if let Some(stdout) = stdout {

View File

@ -8,7 +8,7 @@ impl Command for Echo {
"echo" "echo"
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Returns its arguments, ignoring the piped-in value." "Returns its arguments, ignoring the piped-in value."
} }
@ -19,7 +19,7 @@ impl Command for Echo {
.category(Category::Core) .category(Category::Core)
} }
fn extra_usage(&self) -> &str { fn extra_description(&self) -> &str {
r#"Unlike `print`, which prints unstructured text to stdout, `echo` is like an r#"Unlike `print`, which prints unstructured text to stdout, `echo` is like an
identity function and simply returns its arguments. When given no arguments, identity function and simply returns its arguments. When given no arguments,
it returns an empty string. When given one argument, it returns it as a it returns an empty string. When given one argument, it returns it as a

View File

@ -25,7 +25,7 @@ impl Command for ErrorMake {
.category(Category::Core) .category(Category::Core)
} }
fn usage(&self) -> &str { fn description(&self) -> &str {
"Create an error." "Create an error."
} }

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