Compare commits

...

89 Commits

Author SHA1 Message Date
60769ac1ba Bump version to 0.97.1 (#13659)
# Description

Bump version to `0.97.1`, which will be the actual next major release.
(`0.97.0` had a bug.)
2024-08-20 20:21:12 -07:00
34e7bd861c Fix bug introduced by #13595 (#13658)
<!--
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.
-->

@devyn found that https://github.com/nushell/nushell/pull/13595, which
made ranges be type-checked at parse time, introduced a bug that caused
`../foo` to be parsed as a string rather than a command call. This was
caused by `parse_range` returning a `Some` despite there being parse
errors (`/foo` doesn't match `SyntaxShape::Number`). To go back to the
old behavior, `parse_range` now returns `None` anytime there's any parse
errors met while parsing the range.

Unfortunately, this means that something like `..$foo` will be parsed as
a string if `$foo` isn't defined and as a range if it is defined. That
was the behavior before #13595, and it should probably be fixed at some
point, but I'm just trying to quickly fix the bug.

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

Things should go back to the way they were before #13595, except the
type-checking stuff from that PR is still here.

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

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

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

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

Added a test. Reverted another test that tests that `0..<$day` is parsed
successfully as a string if the variable isn't defined.

# 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-20 19:35:13 -07:00
d667b3c0bc bumped version number to 0.97 (#13655) 2024-08-20 16:28:19 -07:00
b63c3514c4 Fix clippy lints (#13645) 2024-08-19 11:12:45 +02:00
7e9d32d64e Drop outdated touch -d example (#13631)
Fixes nushell/nushell#8723

# Description

The example was showing the flag that no longer exists.

# User-Facing Changes

Help no longer shows the example with `-d` flag.

# Tests + Formatting

I trust in CI.

# After Submitting

Nothing.
2024-08-15 23:57:25 +02:00
621fb25670 update to latest reedline f2b4 (#13629)
# Description

Update to the latest reedline comment. BTW `f2b4` sounds like a new star
wars droid. 😆
2024-08-15 21:03:13 +02:00
a80273bd7b Drop unused fs_extra and hamcrest2 dependencies (#13628)
Fixes nushell/nushell#7995

# Description

This dependency is no longer used by nushell itself.

# User-Facing Changes

None.

# Tests + Formatting

Pased.

# After Submitting

None.
2024-08-15 19:25:50 +02:00
5473def7ef Prefer process name over executable path (#13618)
# Description
Prefer process name over executable path. This in practice causes the
`name` column to use just the base executable name.

Also set start_time to nothing on error, because why not.

# User-Facing Changes

Before:

> /opt/google/chrome/chrome

After:

> chrome

Also picks up changes due to `echo test-proc > /proc/$$/comm`.

# Tests + Formatting

No new coverage.
2024-08-15 13:44:01 +08:00
04746b8e2d add osc633e (#13625)
# Description

This PR adds OSC 633E for vscode users to enable `Terminal: Run Recent
Command` with ctrl-shift-p.


![image](https://github.com/user-attachments/assets/21b92206-3c44-4060-aa0b-78718c099336)
2024-08-15 13:40:34 +08:00
31b3104af7 Remove code duplication in glob (#13626) 2024-08-14 23:11:00 +02:00
803bc9c63f Incrementing the eager dataframe cache value before returning it (#13624)
# Description

Fixes issue [12828](https://github.com/nushell/nushell/issues/12828).

When attempting a `polars collect` on an eager dataframe, we return
dataframe as is. However, before this fix I failed to increment the
internal cache reference count. This caused the value to be dropped from
the internal cache when the references were decremented again.

This fix adds a call to cache.get to increment the value before
returning.
2024-08-14 15:38:46 -05:00
e690e7aac0 Fallback to extension-based content type detection when parsing Content-Type header fails (#13610)
# Description

Previously when nushell failed to parse the content type header, it
would emit an error instead of returning the response. Now it will fall
back to `text/plain` (which, in turn, will trigger type detection based
on file extension).

May fix (potentially) nushell/nushell#11927

Refs:
https://discord.com/channels/601130461678272522/614593951969574961/1272895236489613366

Supercedes: #13609 

# User-Facing Changes

It's now possible to fetch content even if the server returns an invalid
content type header. Users may need to parse the response manually, but
it's still better than not getting the response at all.

# Tests + Formatting

Added a test for the new behaviour.

# After Submitting
2024-08-14 09:47:01 -05:00
e841fce0f9 Bump indexmap from 2.3.0 to 2.4.0 (#13617)
Bumps [indexmap](https://github.com/indexmap-rs/indexmap) from 2.3.0 to
2.4.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.4.0</h2>
<ul>
<li>Added methods <code>IndexMap::append</code> and
<code>IndexSet::append</code>, moving all items from
one map or set into another, and leaving the original capacity for
reuse.</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="b66bbfe282"><code>b66bbfe</code></a>
Merge pull request <a
href="https://redirect.github.com/indexmap-rs/indexmap/issues/337">#337</a>
from cuviper/append</li>
<li><a
href="a288bf3b3a"><code>a288bf3</code></a>
Add a README note for <code>ordermap</code></li>
<li><a
href="0b2b4b9a78"><code>0b2b4b9</code></a>
Release 2.4.0</li>
<li><a
href="8c0a1cd4be"><code>8c0a1cd</code></a>
Add <code>append</code> methods</li>
<li>See full diff in <a
href="https://github.com/indexmap-rs/indexmap/compare/2.3.0...2.4.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.3.0&new-version=2.4.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-08-14 15:21:39 +08:00
d7b0dc1275 Bump shadow-rs from 0.30.0 to 0.31.1 (#13616)
Bumps [shadow-rs](https://github.com/baoyachi/shadow-rs) from 0.30.0 to
0.31.1.
<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>[Improvement] Correct git command directory</h2>
<p>ref: <a
href="https://redirect.github.com/baoyachi/shadow-rs/issues/170">#170</a></p>
<p>Thx <a
href="https://github.com/MichaelScofield"><code>@​MichaelScofield</code></a></p>
<h2>Make build_with function public</h2>
<p>ref:<a
href="https://redirect.github.com/baoyachi/shadow-rs/issues/169">#169</a></p>
<p>Thx <a
href="https://github.com/MichaelScofield"><code>@​MichaelScofield</code></a></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="aa804ec8a2"><code>aa804ec</code></a>
Update Cargo.toml</li>
<li><a
href="b3fbe36403"><code>b3fbe36</code></a>
Merge pull request <a
href="https://redirect.github.com/baoyachi/shadow-rs/issues/170">#170</a>
from MichaelScofield/find-right-branch</li>
<li><a
href="fe6f940f8b"><code>fe6f940</code></a>
execute &quot;git&quot; command in the right path</li>
<li><a
href="458be25e74"><code>458be25</code></a>
Merge pull request <a
href="https://redirect.github.com/baoyachi/shadow-rs/issues/169">#169</a>
from MichaelScofield/flexible-for-submodule</li>
<li><a
href="1521a288b4"><code>1521a28</code></a>
Expose the &quot;build&quot; function to let projects with submodules
control where to ...</li>
<li><a
href="ee12741fa0"><code>ee12741</code></a>
Merge pull request <a
href="https://redirect.github.com/baoyachi/shadow-rs/issues/168">#168</a>
from baoyachi/issue/149</li>
<li><a
href="dfb8b24adb"><code>dfb8b24</code></a>
cargo fmt</li>
<li><a
href="a3be8680aa"><code>a3be868</code></a>
fix clippy</li>
<li><a
href="c8e7cd5704"><code>c8e7cd5</code></a>
Fix compilation failures caused by unwrap</li>
<li>See full diff in <a
href="https://github.com/baoyachi/shadow-rs/compare/v0.30.0...v0.31.1">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.30.0&new-version=0.31.1)](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-08-14 14:41:12 +08:00
5627c95916 Bump sysinfo from 0.30.11 to 0.30.13 (#13615)
Bumps [sysinfo](https://github.com/GuillaumeGomez/sysinfo) from 0.30.11
to 0.30.13.
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/GuillaumeGomez/sysinfo/blob/master/CHANGELOG.md">sysinfo's
changelog</a>.</em></p>
<blockquote>
<h1>0.30.13</h1>
<ul>
<li>macOS: Fix segfault when calling
<code>Components::refresh_list</code> multiple times.</li>
<li>Windows: Fix CPU arch retrieval.</li>
</ul>
<h1>0.30.12</h1>
<ul>
<li>FreeBSD: Fix network interfaces retrieval (one was always
missing).</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="1639d74765"><code>1639d74</code></a>
Merge pull request <a
href="https://redirect.github.com/GuillaumeGomez/sysinfo/issues/1306">#1306</a>
from GuillaumeGomez/update</li>
<li><a
href="4bcded7fa7"><code>4bcded7</code></a>
Update crate version to 0.30.13</li>
<li><a
href="9feeff00a3"><code>9feeff0</code></a>
Add CHANGELOG for 0.30.13</li>
<li><a
href="3e7c8f23d2"><code>3e7c8f2</code></a>
Merge pull request <a
href="https://redirect.github.com/GuillaumeGomez/sysinfo/issues/1305">#1305</a>
from GuillaumeGomez/backport</li>
<li><a
href="5ec06633a0"><code>5ec0663</code></a>
Fix new clippy lints</li>
<li><a
href="53d066ebf1"><code>53d066e</code></a>
Fix fmt</li>
<li><a
href="6a6838bc81"><code>6a6838b</code></a>
Fix minor typo in a doc comment</li>
<li><a
href="0662e60ac4"><code>0662e60</code></a>
Fix CPU arch retrieval on Windows (<a
href="https://redirect.github.com/GuillaumeGomez/sysinfo/issues/1296">#1296</a>)</li>
<li><a
href="57ea114d10"><code>57ea114</code></a>
Fix segfault when call calling Components::refresh_list multiple times
on M-...</li>
<li><a
href="57d6b32300"><code>57d6b32</code></a>
Merge pull request <a
href="https://redirect.github.com/GuillaumeGomez/sysinfo/issues/1271">#1271</a>
from GuillaumeGomez/update</li>
<li>Additional commits viewable in <a
href="https://github.com/GuillaumeGomez/sysinfo/compare/v0.30.11...v0.30.13">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=sysinfo&package-manager=cargo&previous-version=0.30.11&new-version=0.30.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-08-14 14:41:00 +08:00
f122065772 create a better error message for bad glob patterns (#13613)
# Description

@sholderbach pointed out that I could've made this error message better.
So, here's my attempt to make it better.

This should work. I had a hard time figuring out how to trigger the
error anyway because the type checker doesn't allow "bad" parameters to
begin with.

### Before

![image](https://github.com/user-attachments/assets/ac60ce27-4b9a-49ca-910c-74422ae31bc4)


### After

![image](https://github.com/user-attachments/assets/fe939339-67df-4d30-a8dd-5ce3fe623a95)


# 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-13 18:40:17 -05:00
4732507f46 allow glob to take a glob or a string as the input (#13612)
# Description

This PR changes glob to take either a string or a glob as a parameter.

Closes #13611

# 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-13 14:27:42 -05:00
5f45f6c223 add more helpful error with text/xml (#13609)
# Description

This PR is meant to provide a more helpful error message when using http
get and the content type can't be parsed.

### Before

![image](https://github.com/user-attachments/assets/4e6176e2-ec35-48d8-acb3-af5d1cda4327)

### After

![image](https://github.com/user-attachments/assets/aa498ef7-f1ca-495b-8790-484593f02e35)
The span isn't perfect but there's no way to get the span of the content
type that I can see.

In the middle of fixing this error, I also discovered how to fix the
problem in general. Since you can now see the error message complaining
about double quotes (char 22 at position 0. 22 hex is `"`). The fix is
just to remove all the double quotes from the content_type and then you
get this.

### After After

![image](https://github.com/user-attachments/assets/2223d34f-4563-4dea-90eb-83326e808af1)

The discussion on Discord about this is that `--raw` or
`--ignore-errors` should eat this error and it "just work" as well as
default to text or binary when the mime parsing fails. I agree but this
PR does not implement that.

# 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-13 14:27:28 -05:00
a55d172e52 make ls -lf outputs full path in symbolic target (#13605)
# Description
Fixes: #13479 

# User-Facing Changes
Given the following setup:
```
cd /tmp
touch src_file.txt
ln -s src_file.txt link1
```
### Before 
```
ls -lf link1 | get target.0  # It outputs src_file.txt
```
### After
```
ls -lf link1 | get target.0  # It outputs /tmp/src_file.txt
```
# Tests + Formatting
Added a test for the change
2024-08-13 06:34:10 -05:00
48e401834d Fix handling of spaces in executable names (#13596)
# Description
The original code assumed a full single-string command line could be
split by space to get the original argv.

# User-Facing Changes
Fixes an issue where `ps` would display incomplete process name if it
contained space(s).

# Tests + Formatting
Fixes existing code, no new coverage. Existing code doesn't seem to be
covered, we could be it would be somewhat involved and the fix was
simple, so didn't bother..
2024-08-13 06:29:40 -05:00
d5946a9667 Parse time type checking for range (#13595)
# Description

As part of fixing https://github.com/nushell/nushell/issues/13586, this
PR checks the types of the operands when creating a range. Stuff like
`0..(glob .)` will be rejected at parse time. Additionally, `0..$x` will
be treated as a range and rejected if `x` is not defined, rather than
being treated as a string. A separate PR will need to be made to do
reject streams at runtime, so that stuff like `0..(open /dev/random)`
doesn't hang.

Internally, this PR adds a `ParseError::UnsupportedOperationTernary`
variant, for when you have a range like `1..2..(glob .)`.

# User-Facing Changes

Users will now receive an error if any of the operands in the ranges
they construct have types that aren't compatible with `Type::Number`.

Additionally, if a piece of code looks like a range but some parse error
is encountered while parsing it, that piece of code will still be
treated as a range and the user will be shown the parse error. This
means that a piece of code like `0..$x` will be treated as a range no
matter what. Previously, if `x` weren't the expression would've been
treated as a string `"0..$x"`. I feel like it makes the language less
complicated if we make it less context-sensitive.

Here's an example of the error you get:
```
> 0..(glob .)
Error: nu::parser::unsupported_operation

  × range is not supported between int and any.
   ╭─[entry #1:1:1]
 1 │ 0..(glob .)
   · ─────┬─────┬┬
   ·      │     │╰── any
   ·      │     ╰── int
   ·      ╰── doesn't support these values
   ╰────
```

And as an image:

![image](https://github.com/user-attachments/assets/5c76168d-27db-481b-b541-861dac899dbf)

Note: I made the operands themselves (above, `(glob .)`) be garbage,
rather than the `..` operator itself. This doesn't match the behavior of
the math operators (if you do `1 + "foo"`, `+` gets highlighted red).
This is because with ranges, the range operators aren't `Expression`s
themselves, so they can't be turned into garbage. I felt like here, it
makes more sense to highlight the individual operand anyway.
2024-08-13 15:05:34 +08:00
a432bf94ec support SyntaxShape::OneOf in named args (#13553)
# Description
Fixes: #13253

The issue is because nushell use `parse_value` to parse named args, but
`parse_value` doesn't parse `OneOf` syntax shape.

# User-Facing Changes
`OneOf` in named args should works again.

# Tests + Formatting
I think it's hard to add a test, because nushell doesn't support `oneof`
syntax in custom command yet.

# After Submitting
NaN
2024-08-13 06:50:12 +08:00
0eabbb88dd Replace only leading home path with ~ in the title (#13600)
# Description :
- This pull request addresses issue #13594 where any substring of the
path that matches the home directory is replaced with `~` in the title
bar. This was problematic because partial matches within the path were
also being replaced.


---------

Signed-off-by: Aakash788 <aakashparmar788@gmail.com>
Co-authored-by: sholderbach <sholderbach@users.noreply.github.com>
2024-08-12 16:43:59 +02:00
80c8edcfb4 Include only *.nu files in the vendor autoload (#13599)
# Description
Fixes #13587

# User-Facing Changes
Files without ending or non-`*.nu` files will not be loaded as
vendor/configuration files.

# Tests + Formatting
So far we don't have any tests for that..
2024-08-12 22:02:57 +08:00
059167ac96 Make error-message more helpful when user invokes a non-executable file (#13589)
# Description

Fixes Issue #13477 
This adds a check to see if a user is trying to invoke a
(non-executable) file as a command and returns a helpful error if so.
EDIT: this will not work on Windows, and is arguably not relevant there,
because of the different semantics of executables. I think the
equivalent on Windows would be if a user tries to invoke `./foo`, we
should look for `foo.exe` or `foo.bat` in the directory and recommend
that if it exists.

# User-Facing Changes

When a user invokes an unrecognized command that is the path to an
existing file, the error used to say:
`{name} is neither a Nushell built-in or a known external command` 
This PR proposes to change the message to:
`{name} refers to a file that is not executable. Did you forget to to
set execute permissions?`

# Tests + Formatting
Ran cargo fmt, clippy and test on the workspace. 
EDIT: added test asserting the new behavior
2024-08-12 14:21:08 +02:00
4e205cd9a7 Add --raw switch to print for binary data (#13597)
# Description

Something I meant to add a long time ago. We currently don't have a
convenient way to print raw binary data intentionally. You can pipe it
through `cat` to turn it into an unknown stream, or write it to a file
and read it again, but we can't really just e.g. generate msgpack and
write it to stdout without this. For example:

```nushell
[abc def] | to msgpack | print --raw
```

This is useful for nushell scripts that will be piped into something
else. It also means that `nu_plugin_nu_example` probably doesn't need to
do this anymore, but I haven't adjusted it yet:

```nushell
def tell_nushell_encoding [] {
  print -n "\u{0004}json"
}
```

This happens to work because 0x04 is a valid UTF-8 character, but it
wouldn't be possible if it were something above 0x80.

`--raw` also formats other things without `table`, I figured the two
things kind of go together. The output is kind of like `to text`.
Debatable whether that should share the same flag, but it was easier
that way and seemed reasonable.

# User-Facing Changes
- `print` new flag: `--raw`

# Tests + Formatting
Added tests.

# After Submitting
- [ ] release notes (command modified)
2024-08-12 17:29:25 +08:00
18772b73b3 Add parse error for external commands used in assignment without caret (#13585)
# Description

As per our Wednesday meeting, this adds a parse error when something
that would be parsed as an external call is present at the top level,
unless the head of the external call begins with a caret (to make it
explicit).

I tried to make the error quite descriptive about what should be done.

# User-Facing Changes
These now cause a parse error:

```nushell
$foo = bar
$foo = `bar`
```

These would have been interpreted as strings before this version, but
now they'd be interpreted as external calls. This behavior is consistent
with `let`/`mut` (which is unaffected by this change).

Here is an example of the error:

```
Error:   × External command calls must be explicit in assignments
   ╭─[entry #3:1:8]
 1 │ $foo = bar
   ·        ─┬─
   ·         ╰── add a caret (^) before the command name if you intended to run and capture its output
   ╰────
  help: the parsing of assignments was changed in 0.97.0, and this would have previously been treated as a string.
        Alternatively, quote the string with single or double quotes to avoid it being interpreted as a command name. This
        restriction may be removed in a future release.
```

# Tests + Formatting

Tests added to cover the change. Note made about it being temporary.
2024-08-12 10:24:23 +02:00
983014cc40 Clean up key event handling (#13574)
# Description
Cleanups:
 - Add "key_press" to event reading function names to match reality
- Move the relevant comment about why only key press events are
interesting one layer up
 - Remove code duplication in handle_events
- Make `try_next` try harder (instead of bail on a boring event); I
think that was the original intention
- Remove recursion from `next` (I think that's clearer? but maybe just
what I'm used to)

# User-Facing Changes
None

# Tests + Formatting
This cleans up existing code, no new test coverage.
2024-08-09 18:07:50 -07:00
4ff33933dd Merge polars sink and polars to-* to polars save (#13568)
# Description
This pull request merges `polars sink` and `polars to-*` into one
command `polars save`.


# User-Facing Changes
- `polars to-*` commands have all been replaced with `polars save`. When
saving a lazy frame to a type that supports a polars sink operation, a
sink operation will be performed. Sink operations are much more
performant, performing a collect while streaming to the file system.
2024-08-08 09:46:45 -07:00
035308bb1d Bump typo with new ignore (#13563)
Supersedes #13554

(not sure how to narrow the word ignore to a file, maybe the better
course of action would be to mark this file as an ignore with all the
cryptic fileendings)
2024-08-08 06:50:28 +08:00
e530e7d654 Make the math commands const (#13566)
This PR closes [Issue
#13482](https://github.com/nushell/nushell/issues/13482)

# Description
This PR tend to make all math function to be constant. 

# User-Facing Changes
The math commands now can be used as constant methods.

### Some Example
```
> const MODE = [3 3 9 12 12 15] | math mode
> $MODE
╭───┬────╮
│ 0 │  3 │
│ 1 │ 12 │
╰───┴────╯

> const LOG = [16 8 4] | math log 2
> $LOG
╭───┬──────╮
│ 0 │ 4.00 │
│ 1 │ 3.00 │
│ 2 │ 2.00 │
╰───┴──────╯

> const VAR = [1 3 5] | math variance
> $VAR
2.6666666666666665
```

# Tests + Formatting
Tests are added for all of the math command to test there constant
behavior.

I mostly focused on the actual user experience, not the correctness of
the methods and algorithms.

# After Submitting
I think this change don't require any additional documentation. Feel
free to correct me in this topic please.
2024-08-07 22:20:33 +02:00
7d4449f021 Added polars sink command, that performs and streaming collect to t… (#13562)
# Description
This exposes the `LazyFrame::sink_*` functionality to allow a streaming
collect directly to the filesystem. This useful when working with data
that is too large to fit into memory.

# User-Facing Changes
- Introduction of the `polars sink` command
2024-08-07 10:59:49 -05:00
ec3e0e593d polars first and polars last will now handle lazy frames natively (#13555)
# Description
Prior this pull request `polars first` and `polars last` would collect a
lazy frame into an eager frame before performing operations. Now `polars
first` will to a `LazyFrame::limit` and `polars last` will perform a
`LazyFrame::tail`. This is really useful in working with very large
datasets.
2024-08-07 06:36:52 -05:00
ff09c7964e polars open will now open a lazy frame by default (#13556)
# Description
When opening a dataframe the default operation will be to create a lazy
frame if possible. This works much better with large datasets and
supports hive format.

# User-Facing Changes
- `--lazy` is nolonger a valid option. `--eager` must be used to
explicitly open an eager dataframe.
2024-08-07 06:36:08 -05:00
ce13ecfd10 Bump mockito from 1.4.0 to 1.5.0 (#13558)
Bumps [mockito](https://github.com/lipanski/mockito) from 1.4.0 to
1.5.0.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/lipanski/mockito/releases">mockito's
releases</a>.</em></p>
<blockquote>
<h2>1.5.0</h2>
<ul>
<li><strong>[Breaking]</strong> <a
href="https://redirect.github.com/lipanski/mockito/pull/198">Upgrade</a>
to hyper v1</li>
</ul>
<p>Thanks to <a
href="https://github.com/tottoto"><code>@​tottoto</code></a></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="f1c3fe1b7f"><code>f1c3fe1</code></a>
Bump to 1.5.0</li>
<li><a
href="08f2fa322d"><code>08f2fa3</code></a>
Merge pull request <a
href="https://redirect.github.com/lipanski/mockito/issues/199">#199</a>
from tottoto/refactor-response-body</li>
<li><a
href="42e3efe734"><code>42e3efe</code></a>
Refactor response body</li>
<li><a
href="f477e54857"><code>f477e54</code></a>
Merge pull request <a
href="https://redirect.github.com/lipanski/mockito/issues/198">#198</a>
from tottoto/update-to-hyper-1</li>
<li><a
href="e8694ae991"><code>e8694ae</code></a>
Update to hyper 1</li>
<li><a
href="b152b76130"><code>b152b76</code></a>
Depend on some crate directly</li>
<li>See full diff in <a
href="https://github.com/lipanski/mockito/compare/1.4.0...1.5.0">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=mockito&package-manager=cargo&previous-version=1.4.0&new-version=1.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-08-07 11:09:23 +08:00
c18e6bfca0 Add type signature example for def command (#13561)
# Description

By popular demand (a.k.a.
https://github.com/nushell/nushell.github.io/issues/1035), provide an
example of a type signature in the `def` help.

# User-Facing Changes

Help/Doc

# Tests + Formatting

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

# After Submitting

N/A
2024-08-06 21:40:30 -05:00
bc6947cd09 Bump quick-xml from 0.31.0 to 0.32.0 (#13560)
Bumps [quick-xml](https://github.com/tafia/quick-xml) from 0.31.0 to
0.32.0.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/tafia/quick-xml/releases">quick-xml's
releases</a>.</em></p>
<blockquote>
<h2>v0.32.0</h2>
<h2>Significant Changes</h2>
<p>The method of reporting positions of errors has changed - use
<code>error_position()</code> to get an offset of the error position.
For <code>SyntaxError</code>s the range
<code>error_position()..buffer_position()</code> also will represent a
span of error.</p>
<h3>⚠️ Breaking Changes</h3>
<p>The way to configure parser has changed. Now all configuration is
contained in the <code>Config</code> struct and can be applied at once.
When <code>serde-types</code> feature is enabled, configuration is
serializable.</p>
<p>The way of resolve entities with <code>unescape_with</code> has
changed. Those methods no longer resolve predefined entities
(<code>lt</code>, <code>gt</code>, <code>apos</code>, <code>quot</code>,
<code>amp</code>). <code>NoEntityResolver</code> renamed to
<code>PredefinedEntityResolver</code>.</p>
<p><code>Writer::create_element</code> now accepts <code>impl
Into&lt;Cow&lt;str&gt;&gt;</code> instead of <code>&amp;impl
AsRef&lt;str&gt;</code>.</p>
<p>Minimum supported version of serde raised to 1.0.139</p>
<p>The full changelog is below.</p>
<h2>What's Changed</h2>
<h3>New Features</h3>
<ul>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/513">#513</a>:
Allow to continue parsing after getting new
<code>Error::IllFormed</code>.</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/677">#677</a>:
Added methods <code>config()</code> and <code>config_mut()</code> to
inspect and change the parser configuration. Previous builder methods on
<code>Reader</code> / <code>NsReader</code> was replaced by direct
access to fields of config using
<code>reader.config_mut().&lt;...&gt;</code>.</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/684">#684</a>:
Added a method <code>Config::enable_all_checks</code> to turn on or off
all well-formedness checks.</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/362">#362</a>:
Added <code>escape::minimal_escape()</code> which escapes only
<code>&amp;</code> and <code>&lt;</code>.</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/362">#362</a>:
Added <code>BytesCData::minimal_escape()</code> which escapes only
<code>&amp;</code> and <code>&lt;</code>.</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/362">#362</a>:
Added <code>Serializer::set_quote_level()</code> which allow to set
desired level of escaping.</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/705">#705</a>:
Added <code>NsReader::prefixes()</code> to list all the prefixes
currently declared.</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/629">#629</a>:
Added a default case to
<code>impl_deserialize_for_internally_tagged_enum</code> macro so that
it can handle every attribute that does not match existing cases within
an enum variant.</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/722">#722</a>:
Allow to pass owned strings to <code>Writer::create_element</code>. This
is breaking change!</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/275">#275</a>:
Added <code>ElementWriter::new_line()</code> which enables pretty
printing elements with multiple attributes.</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/743">#743</a>:
Added <code>Deserializer::get_ref()</code> to get XML Reader from serde
Deserializer</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/734">#734</a>:
Added helper functions to resolve predefined XML and HTML5 entities:
<ul>
<li><code>quick_xml::escape::resolve_predefined_entity</code></li>
<li><code>quick_xml::escape::resolve_xml_entity</code></li>
<li><code>quick_xml::escape::resolve_html5_entity</code></li>
</ul>
</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/753">#753</a>:
Added parser for processing instructions:
<code>quick_xml::reader::PiParser</code>.</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/754">#754</a>:
Added parser for elements:
<code>quick_xml::reader::ElementParser</code>.</li>
</ul>
<h3>Bug Fixes</h3>
<ul>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/622">#622</a>:
Fix wrong disregarding of not closed markup, such as lone
<code>&lt;</code>.</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/684">#684</a>:
Fix incorrect position reported for
<code>Error::IllFormed(DoubleHyphenInComment)</code>.</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/684">#684</a>:
Fix incorrect position reported for
<code>Error::IllFormed(MissingDoctypeName)</code>.</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/704">#704</a>:
Fix empty tags with attributes not being expanded when
<code>expand_empty_elements</code> is set to true.</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/683">#683</a>:
Use local tag name when check tag name against possible names for
field.</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/753">#753</a>:
Correctly determine end of processing instructions and XML
declaration.</li>
</ul>
<h3>Misc Changes</h3>
<ul>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/675">#675</a>:
Minimum supported version of serde raised to 1.0.139</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/675">#675</a>:
Rework the <code>quick_xml::Error</code> type to provide more accurate
information:</li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/tafia/quick-xml/blob/master/Changelog.md">quick-xml's
changelog</a>.</em></p>
<blockquote>
<h2>0.32.0 -- 2024-06-10</h2>
<p>The way to configure parser is changed. Now all configuration is
contained in the
<code>Config</code> struct and can be applied at once. When
<code>serde-types</code> feature is enabled,
configuration is serializable.</p>
<p>The method of reporting positions of errors has changed - use
<code>error_position()</code>
to get an offset of the error position. For <code>SyntaxError</code>s
the range
<code>error_position()..buffer_position()</code> also will represent a
span of error.</p>
<p>The way of resolve entities with <code>unescape_with</code> are
changed. Those methods no longer
resolve predefined entities.</p>
<h3>New Features</h3>
<ul>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/513">#513</a>:
Allow to continue parsing after getting new
<code>Error::IllFormed</code>.</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/677">#677</a>:
Added methods <code>config()</code> and <code>config_mut()</code> to
inspect and change the parser
configuration. Previous builder methods on <code>Reader</code> /
<code>NsReader</code> was replaced by
direct access to fields of config using
<code>reader.config_mut().&lt;...&gt;</code>.</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/684">#684</a>:
Added a method <code>Config::enable_all_checks</code> to turn on or off
all
well-formedness checks.</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/362">#362</a>:
Added <code>escape::minimal_escape()</code> which escapes only
<code>&amp;</code> and <code>&lt;</code>.</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/362">#362</a>:
Added <code>BytesCData::minimal_escape()</code> which escapes only
<code>&amp;</code> and <code>&lt;</code>.</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/362">#362</a>:
Added <code>Serializer::set_quote_level()</code> which allow to set
desired level of escaping.</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/705">#705</a>:
Added <code>NsReader::prefixes()</code> to list all the prefixes
currently declared.</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/629">#629</a>:
Added a default case to
<code>impl_deserialize_for_internally_tagged_enum</code> macro so that
it can handle every attribute that does not match existing cases within
an enum variant.</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/722">#722</a>:
Allow to pass owned strings to <code>Writer::create_element</code>. This
is breaking change!</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/275">#275</a>:
Added <code>ElementWriter::new_line()</code> which enables pretty
printing elements with multiple attributes.</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/743">#743</a>:
Added <code>Deserializer::get_ref()</code> to get XML Reader from serde
Deserializer</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/734">#734</a>:
Added helper functions to resolve predefined XML and HTML5 entities:
<ul>
<li><code>quick_xml::escape::resolve_predefined_entity</code></li>
<li><code>quick_xml::escape::resolve_xml_entity</code></li>
<li><code>quick_xml::escape::resolve_html5_entity</code></li>
</ul>
</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/753">#753</a>:
Added parser for processing instructions:
<code>quick_xml::reader::PiParser</code>.</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/754">#754</a>:
Added parser for elements:
<code>quick_xml::reader::ElementParser</code>.</li>
</ul>
<h3>Bug Fixes</h3>
<ul>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/622">#622</a>:
Fix wrong disregarding of not closed markup, such as lone
<code>&lt;</code>.</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/684">#684</a>:
Fix incorrect position reported for
<code>Error::IllFormed(DoubleHyphenInComment)</code>.</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/684">#684</a>:
Fix incorrect position reported for
<code>Error::IllFormed(MissingDoctypeName)</code>.</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/704">#704</a>:
Fix empty tags with attributes not being expanded when
<code>expand_empty_elements</code> is set to true.</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/683">#683</a>:
Use local tag name when check tag name against possible names for
field.</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/753">#753</a>:
Correctly determine end of processing instructions and XML
declaration.</li>
</ul>
<h3>Misc Changes</h3>
<ul>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/675">#675</a>:
Minimum supported version of serde raised to 1.0.139</li>
<li><a
href="https://redirect.github.com/tafia/quick-xml/issues/675">#675</a>:
Rework the <code>quick_xml::Error</code> type to provide more accurate
information:</li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="8d38e4cc14"><code>8d38e4c</code></a>
Release 0.32.0</li>
<li><a
href="e6f7be47a7"><code>e6f7be4</code></a>
Add #[inline] to methods implementing XmlSource</li>
<li><a
href="33b9dc59c7"><code>33b9dc5</code></a>
Increase position outside of XmlSource::skip_one</li>
<li><a
href="704ce89239"><code>704ce89</code></a>
Generalize reading methods of PI and element</li>
<li><a
href="6f1a644dcc"><code>6f1a644</code></a>
Rewrite read_element like read_pi</li>
<li><a
href="0a6ecd6498"><code>0a6ecd6</code></a>
Add reusable parser for XML element and use it internally</li>
<li><a
href="02de8a51bf"><code>02de8a5</code></a>
Remove unnecessary block</li>
<li><a
href="0cb09fbda9"><code>0cb09fb</code></a>
Use <code>if let</code> instead of <code>match</code></li>
<li><a
href="6c58bef3ab"><code>6c58bef</code></a>
Implement XmlSource::read_pi like XmlSource::read_element</li>
<li><a
href="79b2fda9fe"><code>79b2fda</code></a>
Stop at the <code>&gt;</code> in PiParser which is consistent with other
search functions</li>
<li>Additional commits viewable in <a
href="https://github.com/tafia/quick-xml/compare/v0.31.0...v0.32.0">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=quick-xml&package-manager=cargo&previous-version=0.31.0&new-version=0.32.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-08-07 09:16:03 +08:00
faaa12838e Bump scraper from 0.19.0 to 0.20.0 (#13559)
Bumps [scraper](https://github.com/causal-agent/scraper) from 0.19.0 to
0.20.0.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/causal-agent/scraper/releases">scraper's
releases</a>.</em></p>
<blockquote>
<h2>0.20.0</h2>
<h2>What's Changed</h2>
<ul>
<li><code>is</code> and <code>has</code> support by <a
href="https://github.com/cfvescovo"><code>@​cfvescovo</code></a> in <a
href="https://redirect.github.com/causal-agent/scraper/pull/187">causal-agent/scraper#187</a></li>
<li>Make ElementRef Debug impl use Element by <a
href="https://github.com/gfaster"><code>@​gfaster</code></a> in <a
href="https://redirect.github.com/causal-agent/scraper/pull/190">causal-agent/scraper#190</a></li>
<li>Bump indexmap from 2.2.6 to 2.3.0 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a> in <a
href="https://redirect.github.com/causal-agent/scraper/pull/194">causal-agent/scraper#194</a></li>
</ul>
<h2>New Contributors</h2>
<ul>
<li><a href="https://github.com/gfaster"><code>@​gfaster</code></a> made
their first contribution in <a
href="https://redirect.github.com/causal-agent/scraper/pull/190">causal-agent/scraper#190</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/causal-agent/scraper/compare/v0.19.1...v0.20.0">https://github.com/causal-agent/scraper/compare/v0.19.1...v0.20.0</a></p>
<h2>0.19.1</h2>
<h2>What's Changed</h2>
<ul>
<li>Bump ahash from 0.8.9 to 0.8.11 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a> in <a
href="https://redirect.github.com/causal-agent/scraper/pull/174">causal-agent/scraper#174</a></li>
<li>Bump indexmap from 2.2.3 to 2.2.5 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a> in <a
href="https://redirect.github.com/causal-agent/scraper/pull/173">causal-agent/scraper#173</a></li>
<li>Bump html5ever from 0.26.0 to 0.27.0 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a> in <a
href="https://redirect.github.com/causal-agent/scraper/pull/176">causal-agent/scraper#176</a></li>
<li>Bump indexmap from 2.2.5 to 2.2.6 by <a
href="https://github.com/dependabot"><code>@​dependabot</code></a> in <a
href="https://redirect.github.com/causal-agent/scraper/pull/177">causal-agent/scraper#177</a></li>
<li>Select and Text are not fused iterators by <a
href="https://github.com/Noname-Official"><code>@​Noname-Official</code></a>
in <a
href="https://redirect.github.com/causal-agent/scraper/pull/184">causal-agent/scraper#184</a></li>
</ul>
<h2>New Contributors</h2>
<ul>
<li><a
href="https://github.com/Noname-Official"><code>@​Noname-Official</code></a>
made their first contribution in <a
href="https://redirect.github.com/causal-agent/scraper/pull/184">causal-agent/scraper#184</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/causal-agent/scraper/compare/v0.19.0...v0.19.1">https://github.com/causal-agent/scraper/compare/v0.19.0...v0.19.1</a></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="4d33a55f59"><code>4d33a55</code></a>
Version 0.20.0</li>
<li><a
href="5b6703e83a"><code>5b6703e</code></a>
Merge pull request <a
href="https://redirect.github.com/causal-agent/scraper/issues/194">#194</a>
from causal-agent/dependabot/cargo/indexmap-2.3.0</li>
<li><a
href="fd01b100ea"><code>fd01b10</code></a>
Bump indexmap from 2.2.6 to 2.3.0</li>
<li><a
href="9242d09e7d"><code>9242d09</code></a>
Merge pull request <a
href="https://redirect.github.com/causal-agent/scraper/issues/190">#190</a>
from gfaster/master</li>
<li><a
href="f5cc684a06"><code>f5cc684</code></a>
Make ElementRef Debug impl use Element</li>
<li><a
href="27dd786c06"><code>27dd786</code></a>
Merge pull request <a
href="https://redirect.github.com/causal-agent/scraper/issues/187">#187</a>
from causal-agent/support-has-selector</li>
<li><a
href="b3570f31e1"><code>b3570f3</code></a>
<code>is</code> and <code>has</code> support</li>
<li><a
href="e8e3cc4edb"><code>e8e3cc4</code></a>
Version 0.19.1</li>
<li><a
href="37b062ec65"><code>37b062e</code></a>
Merge pull request <a
href="https://redirect.github.com/causal-agent/scraper/issues/184">#184</a>
from Noname-Official/patch-1</li>
<li><a
href="3b8383dcc5"><code>3b8383d</code></a>
Text isn't a fused iterator</li>
<li>Additional commits viewable in <a
href="https://github.com/causal-agent/scraper/compare/v0.19.0...v0.20.0">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=scraper&package-manager=cargo&previous-version=0.19.0&new-version=0.20.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-08-07 09:07:19 +08:00
edee2a3c15 Bump indexmap from 2.2.6 to 2.3.0 (#13557)
Bumps [indexmap](https://github.com/indexmap-rs/indexmap) from 2.2.6 to
2.3.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.3.0</h2>
<ul>
<li>Added trait <code>MutableEntryKey</code> for opt-in mutable access
to map entry keys.</li>
<li>Added method <code>MutableKeys::iter_mut2</code> for opt-in mutable
iteration of map
keys and values.</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="22c0b4e0f3"><code>22c0b4e</code></a>
Merge pull request <a
href="https://redirect.github.com/indexmap-rs/indexmap/issues/335">#335</a>
from epage/mut</li>
<li><a
href="39f7cc097a"><code>39f7cc0</code></a>
Release 2.3.0</li>
<li><a
href="6049d518a0"><code>6049d51</code></a>
feat(map): Add MutableKeys::iter_mut2</li>
<li><a
href="65c3c46e37"><code>65c3c46</code></a>
feat(map): Add MutableEntryKey</li>
<li><a
href="7f7d39f734"><code>7f7d39f</code></a>
Merge pull request <a
href="https://redirect.github.com/indexmap-rs/indexmap/issues/332">#332</a>
from waywardmonkeys/missing-indentation-in-doc-comment</li>
<li><a
href="8222a59a85"><code>8222a59</code></a>
Fix missing indentation in doc comment.</li>
<li><a
href="1a71dde63d"><code>1a71dde</code></a>
Merge pull request <a
href="https://redirect.github.com/indexmap-rs/indexmap/issues/327">#327</a>
from waywardmonkeys/dep-update-dev-dep-itertools</li>
<li><a
href="ac2a8a5a40"><code>ac2a8a5</code></a>
deps(dev): Update <code>itertools</code></li>
<li>See full diff in <a
href="https://github.com/indexmap-rs/indexmap/compare/2.2.6...2.3.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.2.6&new-version=2.3.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-08-07 09:02:56 +08:00
2ced9e4d19 Add multipart/form-data uploads (#13532)
Fixes nushell/nushell#11046

# Description
This adds support for `multipart/form-data` (RFC 7578) uploads to
nushell.

Binary data is uploaded as files (`application/octet-stream`),
everything else is uploaded as plain text.

```console
$ http post https://echo.free.beeceptor.com --content-type multipart/form-data {cargo: (open -r Cargo.toml | into binary ), description: "It's some TOML"} | upsert ip "<redacted>"
╭───────────────────┬─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ method            │ POST                                                                                                                                                                    │
│ protocol          │ https                                                                                                                                                                   │
│ host              │ echo.free.beeceptor.com                                                                                                                                                 │
│ path              │ /                                                                                                                                                                       │
│ ip                │ <redacted>                                                                                                                                                              │
│                   │ ╭─────────────────┬────────────────────────────────────────────────────────────────────╮                                                                                │
│ headers           │ │ Host            │ echo.free.beeceptor.com                                            │                                                                                │
│                   │ │ User-Agent      │ nushell                                                            │                                                                                │
│                   │ │ Content-Length  │ 9453                                                               │                                                                                │
│                   │ │ Accept          │ */*                                                                │                                                                                │
│                   │ │ Accept-Encoding │ gzip                                                               │                                                                                │
│                   │ │ Content-Type    │ multipart/form-data; boundary=a15f6a14-5768-4a6a-b3a4-686a112d9e27 │                                                                                │
│                   │ ╰─────────────────┴────────────────────────────────────────────────────────────────────╯                                                                                │
│ parsedQueryParams │ {record 0 fields}                                                                                                                                                       │
│                   │ ╭─────────────────┬───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │
│ parsedBody        │ │                 │ ╭─────────────┬────────────────╮                                                                                                                  │ │
│                   │ │ textFields      │ │ description │ It's some TOML │                                                                                                                  │ │
│                   │ │                 │ ╰─────────────┴────────────────╯                                                                                                                  │ │
│                   │ │                 │ ╭───┬───────┬──────────┬──────────────────────────┬───────────────────────────┬───────────────────────────────────────────┬────────────────╮      │ │
│                   │ │ files           │ │ # │ name  │ fileName │       Content-Type       │ Content-Transfer-Encoding │            Content-Disposition            │ Content-Length │      │ │
│                   │ │                 │ ├───┼───────┼──────────┼──────────────────────────┼───────────────────────────┼───────────────────────────────────────────┼────────────────┤      │ │
│                   │ │                 │ │ 0 │ cargo │ cargo    │ application/octet-stream │ binary                    │ form-data; name="cargo"; filename="cargo" │ 9101           │      │ │
│                   │ │                 │ ╰───┴───────┴──────────┴──────────────────────────┴───────────────────────────┴───────────────────────────────────────────┴────────────────╯      │ │
│                   │ ╰─────────────────┴───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ │
╰───────────────────┴─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
```
# User-Facing Changes
`http post --content-type multipart/form-data` now accepts a record
which is uploaded as `multipart/form-data`.
Binary data is uploaded as files (`application/octet-stream`),
everything else is uploaded as plain text.

Previously `http post --content-type multipart/form-data` rejected
records, so there's no BC break.

# Tests + Formatting

Added.

# After Submitting
- [ ] update docs to showcase new functionality
2024-08-06 15:28:38 -05:00
926331dbfb chore: Add nu_plugin_polars to build and install scripts (#13550)
- Add `nu_plugin_polars` to the list of plugins in
`build-all-maclin.sh`.
- Add `nu_plugin_polars` to the list of plugins in `build-all.nu`.
- Add `nu_plugin_polars` to the list of plugins in `install-all.ps1`.
- Add `nu_plugin_polars` to the list of plugins in `install-all.sh`.
- Add `nu_plugin_polars` to the list of plugins in `uninstall-all.sh`.

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

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

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

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

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

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

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

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

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

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
2024-08-06 15:23:56 -05:00
eca2975b3d Fix a typo in an example (#13548)
Accidentally used the old name of the command, `random bytes`, instead
of the correct one.

Co-authored-by: Andrej Kolčin <self@kaathewise.net>
2024-08-06 13:18:49 +02:00
1cd0544a3f fix: relay Signals reset to plugins (#13510)
This PR will close #13501

# Description

This PR expands on [the relay of signals to running plugin
processes](https://github.com/nushell/nushell/pull/13181). The Ctrlc
relay has been generalized to SignalAction::Interrupt and when
reset_signal is called on the main EngineState, a SignalAction::Reset is
now relayed to running plugins.

# User-Facing Changes

The signal handler closure now takes a `signals::SignalAction`, while
previously it took no arguments. The handler will now be called on both
interrupt and reset. The method to register a handler on the plugin side
is now called `register_signal_handler` instead of
`register_ctrlc_handler`
[example](https://github.com/nushell/nushell/pull/13510/files#diff-3e04dff88fd0780a49778a3d1eede092ec729a1264b4ef07ca0d2baa859dad05L38).
This will only affect plugin authors who have started making use of
https://github.com/nushell/nushell/pull/13181, which isn't currently
part of an official release.

The change will also require all of user's plugins to be recompiled in
order that they don't error when a signal is received on the
PluginInterface.

# Testing

```
: example ctrlc
interrupt status: false
waiting for interrupt signal...
^Cinterrupt status: true
peace.
Error:   × Operation interrupted
   ╭─[display_output hook:1:1]
 1 │ if (term size).columns >= 100 { table -e } else { table }
   · ─┬
   ·  ╰── This operation was interrupted
   ╰────

: example ctrlc
interrupt status: false   <-- NOTE status is false
waiting for interrupt signal...
^Cinterrupt status: true
peace.
Error:   × Operation interrupted
   ╭─[display_output hook:1:1]
 1 │ if (term size).columns >= 100 { table -e } else { table }
   · ─┬
   ·  ╰── This operation was interrupted
   ╰────
   ```
2024-08-06 03:35:40 -07:00
73e8de9753 Attempt to guess the content type of a file when opening with --raw (#13521)
# Description
Attempt to guess the content type of a file when opening with --raw and
set it in the pipeline metadata.

<img width="644" alt="Screenshot 2024-08-02 at 11 30 10"
src="https://github.com/user-attachments/assets/071f0967-c4dd-405a-b8c8-f7aa073efa98">


# User-Facing Changes
- Content of files can be directly piped into commands like `http post`
with the content type set appropriately when using `--raw`.
2024-08-06 11:36:24 +02:00
4e83ccdf86 Allow int input when using a formatstring in into datetime (#13541)
# Description

When using a format string, `into datetime` would disallow an `int` even
when it logically made sense. This was mainly a problem when attempting
to convert a Unix epoch to Nushell `datetime`. Unix epochs are often
stored or returned as `int` in external data sources.

```nu
1722821463 | into datetime -f '%s'
Error: nu:🐚:only_supports_this_input_type

  × Input type not supported.
   ╭─[entry #3:1:1]
 1 │ 1722821463 | into datetime -f '%s'
   · ─────┬────   ──────┬──────
   ·      │             ╰── only string input data is supported
   ·      ╰── input type: int
   ╰────
```

While the solution was simply to `| to text` the `int`, this PR handles
the use-case automatically.

Essentially a ~5 line change that just moves the current parsing to a
closure that is called for both Strings and Ints-converted-to-Strings.

# User-Facing Changes

After the change:

```nu
[
  1722821463
  "1722821463"
  0
] | each { into datetime -f '%s' }
╭───┬──────────────╮
│ 0 │ 10 hours ago │
│ 1 │ 10 hours ago │
│ 2 │ 54 years ago │
╰───┴──────────────╯
```

# Tests + Formatting

Test case added.

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

# After Submitting
2024-08-05 20:05:32 -05:00
6d36941e55 Add completions.sort option (#13311) 2024-08-05 20:30:10 -04:00
2f44801414 Adding plist support (#13545)
# Description
Provides the ability convert from and to plist format.

<img width="1250" alt="Screenshot 2024-08-05 at 10 21 26"
src="https://github.com/user-attachments/assets/970f3366-eb70-4d74-a396-649374556f66">

<img width="730" alt="Screenshot 2024-08-05 at 10 22 38"
src="https://github.com/user-attachments/assets/6ec317d0-686e-47c6-bf35-8ab6e5d802db">

# User-Facing Changes
- Introduction of `from plist` command
- Introduction of `to plist`command

---------

Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com>
2024-08-05 14:07:15 -07:00
9172b22985 Rework help generation internals (#13531)
Reworking some of the sprawling code we use to generate the `help cmd`
or `cmd --help` output.

This touches mainly the rendering and not the gathering of the necessary
data (see open bugs under
[label:help-system](https://github.com/nushell/nushell/issues?q=sort%3Aupdated-desc+is%3Aopen+label%3Ahelp-system))

Fixes #9076 
Fixes the syntax shape output on flags to be consistent.

## Example
```nushell
def test [
  positional: int,
  documented: float, # this has documentation
  default = 50,
  optional?,
  --a = "bla",
  --bla (-b) = "bla", # named with default
] {}
```

### before

![grafik](https://github.com/user-attachments/assets/1867984f-1289-4ad0-bdf5-c49ec56dfddb)


### after


![grafik](https://github.com/user-attachments/assets/8fca526f-d878-4d52-b970-fc41c7e8859c)
2024-08-05 22:44:24 +02:00
1c37f4b958 Create random binary command (#13542)
# Description/User-Facing Changes

Creates a new `random binary <LENGTH>` command, which returns random
bytes.

Resolve #13500
2024-08-05 21:07:12 +02:00
56ed532038 update to latest reedline commit 919292e (#13540)
# Description

This PR updates nushell to the latest reedline commit which has some vi
keyboard mode changes.

# 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-05 07:59:34 -05:00
b974f8f7e3 Include empty table data cells in query web tables (#13538)
# Description

Empty cells were being skipped, causing data to appear in the wrong
columns. By including the cells, data should appear in the correct
columns now. Fixes #10194.

Before:

```
$ [[a b c]; [1 null 3] [4 5 6]] | to html --partial | query web --as-table [a b c]
╭───┬───┬───┬─────────────────────╮
│ # │ a │ b │          c          │
├───┼───┼───┼─────────────────────┤
│ 0 │ 1 │ 3 │ Missing column: 'c' │
│ 1 │ 4 │ 5 │ 6                   │
╰───┴───┴───┴─────────────────────╯
```

After:

```
$ [[a b c]; [1 null 3] [4 5 6]] | to html --partial | query web --as-table [a b c]
╭───┬───┬───┬───╮
│ # │ a │ b │ c │
├───┼───┼───┼───┤
│ 0 │ 1 │   │ 3 │
│ 1 │ 4 │ 5 │ 6 │
╰───┴───┴───┴───╯
```

Co-authored-by: James Chen-Smith <jameschensmith@gmail.com>
2024-08-05 06:20:14 -05:00
802bfed173 feat: prefer exact match when completion mode is prefix (#13302)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

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

Fixes #13204

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

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

When the completion mode is set to `prefix`, path completions explicitly
check for and prefer an exact match for a basename instead of longer or
similar names.

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

Exact match is inactive since there's no trailing slash

```
~/Public/nushell| ls crates/nu-plugin<tab>
crates/nu-plugin/               crates/nu-plugin-core/          crates/nu-plugin-engine/        crates/nu-plugin-protocol/      
crates/nu-plugin-test-support/
```

Exact match is active

```
~/Public/nushell| ls crates/nu-plugin/<tab>
crates/nu-plugin/Cargo.toml  crates/nu-plugin/LICENSE     crates/nu-plugin/README.md   crates/nu-plugin/src/
```

Fuzzy matching persists its behavior

```
~/Public/nushell> $env.config.completions.algorithm = "fuzzy";
~/Public/nushell| ls crates/nu-plugin/car
crates/nu-cmd-plugin/Cargo.toml           crates/nu-plugin/Cargo.toml               crates/nu-plugin-core/Cargo.toml          crates/nu-plugin-engine/Cargo.toml        
crates/nu-plugin-protocol/Cargo.toml      crates/nu-plugin-test-support/Cargo.toml
```

# 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-04 06:06:10 -05:00
07e7c8c81f Fixup #13526 width flag for example (#13529)
# Description
This seems to be a minor copy paste mistake. cc @Embers-of-the-Fire

Followup to #13526

# User-Facing Changes
(-)

# Tests + Formatting
(-)
2024-08-03 16:42:30 +02:00
20b53067cd Fix overflow table display in command documentation (#13526)
# Description

Check and set table width beforehand.

Closes #13520.

# User-Facing Changes
Before:
```plain
❯ help net cmd1
network

Usage:
  > net cmd1

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

Input/output types:
  ╭───┬─────────┬─────────────────────────────────────────────────────────╮
  │ # │  input  │                         output                          │
  ├───┼─────────┼─────────────────────────────────────────────────────────┤
  │ 0 │ nothing │ table<name: string, description: string, mac: string,   │
  │   │         │ ips: table<type: string, addr: string, prefix: int>,
 │
  │   │         │ flags: record<is_up: bool, is_broadcast: bool,
 │
  │   │         │ is_loopback: bool, is_point_to_point: bool,
 │
  │   │         │ is_multicast: bool>>
 │
  ╰───┴─────────┴─────────────────────────────────────────────────────────╯
```

After:
```plain
❯ help net cmd1
network

Usage:
  > net cmd1

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

Input/output types:
  ╭───┬─────────┬───────────────────────────────────────────────────────╮
  │ # │  input  │                        output                         │
  ├───┼─────────┼───────────────────────────────────────────────────────┤
  │ 0 │ nothing │ table<name: string, description: string, mac: string, │
  │   │         │  ips: table<type: string, addr: string, prefix: int>, │
  │   │         │  flags: record<is_up: bool, is_broadcast: bool,       │
  │   │         │ is_loopback: bool, is_point_to_point: bool,           │
  │   │         │ is_multicast: bool>>                                  │
  ╰───┴─────────┴───────────────────────────────────────────────────────╯
```

# Tests + Formatting

- [x] `cargo fmt --all -- --check` to check standard code formatting
(`cargo fmt --all` applies these changes)
- [x] `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used`
to check that you're using the standard code style
- [x] `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))
- [x] `cargo run -- -c "use toolkit.nu; toolkit test stdlib"` to run the
tests for the standard library


# After Submitting
- [x] Bug fix, no doc update.
2024-08-03 10:55:35 +02:00
f4c0d9d45b Path migration part 4: various tests (#13373)
# Description
Part 4 of replacing std::path types with nu_path types added in
https://github.com/nushell/nushell/pull/13115. This PR migrates various
tests throughout the code base.
2024-08-03 10:09:13 +02:00
85b06b22d9 Replace manual Record::get implementation (#13525)
Let's simplify here
2024-08-03 01:14:44 +02:00
63f00e78d1 Lift SharedCow::to_mut out of if let branches (#13524)
In some `if let`s we ran the `SharedCow::to_mut` for the test and to get
access to a mutable reference in the happy path. Internally
`Arc::into_mut` has to read atomics and if necessary clone.
For else branches, where we still want to modify the record we
previously called this again (not just in rust, confirmed in the asm).

This would have introduced a `call` instruction and its cost (even if it
would be guaranteed to take the short path in `Arc::into_mut`).
Lifting it get's rid of this.
2024-08-03 00:26:48 +02:00
ff1ad77130 Simplify column look-up in default (#13522)
# Description
Since we make the promise that record keys/columns are exclusice we
don't have to go through all columns after we have found the first one.
Should permit some short-circuiting if the column is found early.

# User-Facing Changes
(-)

# Tests + Formatting
(-)
2024-08-03 00:26:35 +02:00
af34d5c062 Fix internal panic for query web (#13507)
<!--
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.
-->
Original implementation contains multiple `expect` which can cause
internal runtime panic.

This pr forks the `css` selector impl and make it return an error that
nushell can recognize.

**Note:** The original impl is still used in pre-defined selector
implementations, but they
should never fail, so the `css` fn is preserved.

Closes #13496.

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->
Now `query web` will not panic when the `query` parameter is not given
or has syntax error.

```plain
❯ .\target\debug\nu.exe -c "http get https://www.rust-lang.org | query web"
Error:   × CSS query parse error
   ╭─[source:1:38]
 1 │ http get https://www.rust-lang.org | query web
   ·                                      ────┬────
   ·                                          ╰─┤ Unexpected error occurred. Please report this to the developer
   ·                                            │ EmptySelector
   ╰────
  help: cannot parse query as a valid CSS selector
```

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

Make sure you've run and fixed any issues with these commands:
-->
- [x] `cargo fmt --all -- --check` to check standard code formatting
(`cargo fmt --all` applies these changes)
- [x] `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used`
to check that you're using the standard code style
- [x] `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))
- [x] `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.
-->
- [x] Impl change, no doc update.

---------

Co-authored-by: Stefan Holderbach <sholderbach@users.noreply.github.com>
2024-08-02 21:47:18 +02:00
ed82f9ee18 Clarify default command help (#13519)
# Description

Updates `default` command description to be more clear and adds an
example for a missing values in a list-of-records.

# User-Facing Changes

Help/doc only

# Tests + Formatting

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

# After Submitting

- Update `nothing` doc in Book to reference `default` per
https://github.com/nushell/nushell.github.io/issues/1073 - This was a
bit of a rabbit trail on the path to that update. ;-)

---------

Co-authored-by: Stefan Holderbach <sholderbach@users.noreply.github.com>
2024-08-02 21:23:25 +02:00
d081e3386f Make pipeline metadata available to plugins (#13495)
# Description
Fixes an issue with pipeline metadata not being passed to plugins.
2024-08-02 11:01:20 -07:00
ca8eb856e8 Doc and examples for multi-dot directory traversal (#13513)
# Description

With this PR, we should be able to close
https://github.com/nushell/nushell.github.io/issues/1225

Help/doc/examples updated for:

* `cd` to show multi-dot traversal
* `cd` to show implicit `cd` with bare directory path
* Fixed/clarified another example that mentioned `$OLDPATH` while I was
in there
* `mv` and `cp` examples for multi-dot traversal
* Updated `cp` examples to use more consistent (and clear) filenames

# User-Facing Changes

Help/doc only

# Tests + Formatting

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

# After Submitting

N/A
2024-08-01 15:22:25 -05:00
168835ecd2 random chars doc clarifications (#13511)
# Description

Clarified `random chars` help/doc:

* Default string length in absence of a `--length` arg is 25
* Characters are *"uniformly distributed over ASCII letters and numbers:
a-z, A-Z and 0-9"* (copied from the [`rand` crate
doc](https://docs.rs/rand/latest/rand/distributions/struct.Alphanumeric.html).

# User-Facing Changes

Help/Doc only
2024-08-01 21:21:39 +02:00
4157ca711d Factor out style-setting code (#13406)
# Description
This is mainly cleanup, but introduces a slight (positive, if anything)
behavior change:

Some menu layouts support only a subset of styles, but with this change
the user will still be able to configure them. This seems strictly
better - if reedline starts supporting one of the existing styles for a
particular layout, there won't be any need to update nushell code.


# User-Facing Changes
None

# Tests + Formatting
This is simply factoring out existing code, old tests should still cover
it.

---------

Co-authored-by: sholderbach <sholderbach@users.noreply.github.com>
2024-08-01 11:17:58 +02:00
d34a24db33 setting content type metadata on all core to * commands (#13506)
# Description

All core `to *` set content type pipeline metadata. 

# User-Facing Changes
- For consistency, `from json` no longer sets the content type metadata

# Tests + Formatting
- 🟢 `toolkit fmt`
- 🟢 `toolkit clippy`
- 🟢 `toolkit test`
- 🟢 `toolkit test stdlib
2024-08-01 11:10:52 +02:00
2c6b1471e1 Contentious clippy fixes (#13498)
Lints from stable or nightly toolchain that may have questionable added
value.

- **Contentious lint to contract into single `if let`**
- **Potential false positive around `AsRef`/`Deref` fun**
2024-08-01 11:02:55 +02:00
ae5fed41ed Path migration part 3: $nu paths (#13368)
# Description
Part 3 of replacing `std::path` types with `nu_path` types added in
#13115. This PR targets the paths listed in `$nu`. That is, the home,
config, data, and cache directories.
2024-08-01 10:16:31 +02:00
ca73d85c09 Add --upgrade switch for mv command (#13505)
<!--
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.
-->
Add `--upgrade, -u` switch for `mv` command, corresponding to `cp`.

Closes #13458.

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->
```plain
❯ help mv | find update
╭──────────┬───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│        0 │   -u, --update - move and overwite only when the SOURCE file is newer than the destination file or when the destination file is missing       │
╰──────────┴───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
```

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

Make sure you've run and fixed any issues with these commands:
-->
- [x] `cargo fmt --all -- --check` to check standard code formatting
(`cargo fmt --all` applies these changes)
- [x] `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used`
to check that you're using the standard code style
- [x] `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))
- [x] `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
> ```
-->

P.S.  
The standard test kit (`nu-test-support`) doesn't provide utility to
create file with modification timestamp, and I didn't find any test for
this in `cp` command. I had tested on my local machine but I'm not sure
how to integrate it into ci. If unit testing is required, I may need
your guidance.

# 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.
-->
- [x] Command docs are auto generated.
2024-07-31 20:43:06 -05:00
f82c43f850 Consider numbers to be part of a word in split words (#13502)
# Description

Before this change, `"hash sha256 123 ok" | split words` would return
`[hash sha ok]` - which is surprising to say the least.

Now it will return `[hash sha256 123 ok]`.

Refs:
https://discord.com/channels/601130461678272522/615253963645911060/1268151658572025856

# User-Facing Changes
`split words` will no longer remove digits.

# Tests + Formatting
Added a test for this specific case.

# After Submitting
2024-07-31 16:35:41 -05:00
3dc9691aaa Clarify random int help (#13503)
# Description

Minor nitpicks, but the `random int` help and examples were a bit
ambiguous in several aspects. Updated to clarify that:

* An unconstrained `random int` returns a non-negative integer. That is,
the smallest potential value is 0. Technically integers include negative
numbers as well, and `random int` will never return one unless you pass
it a range with a negative lower-bound.

* To that end, changed the final example to demonstrate a negative
lower-bound.

* The range is inclusive. While most people would probably assume this,
the changes make this explicit in the examples and argument description.

# User-Facing Changes

Help only

# Tests + Formatting

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

# After Submitting

N/A
2024-07-31 16:34:38 -05:00
42531e017c Clippy fixes from stable and nightly (#13455)
- **Doccomment style fixes**
- **Forgotten stuff in `nu-pretty-hex`**
- **Don't `for` around an `Option`**
- and more

I think the suggestions here are a net positive, some of the suggestions
moved into #13498 feel somewhat arbitrary, I also raised
https://github.com/rust-lang/rust-clippy/issues/13188 as the nightly
`byte_char_slices` would require either a global allow or otherwise a
ton of granular allows or possibly confusing bytestring literals.
2024-07-31 20:37:40 +02:00
928c57db41 save: print to stderr for bytestream (#13422)
# Description
Fixes: #13260 

When user run a command like this:
```nushell
$env.FOO = " New";
$env.BAZ = " New Err";
do -i {nu -n -c 'nu --testbin echo_env FOO; nu --testbin echo_env_stderr BAZ'} | save -a -r save_test_22/log.txt
```

`save` command sinks the output of previous commands' stderr output. I
think it should be `stderr`.

# User-Facing Changes
```nushell
$env.FOO = " New";
$env.BAZ = " New Err";
do -i {nu -n -c 'nu --testbin echo_env FOO; nu --testbin echo_env_stderr BAZ'} | save -a -r save_test_22/log.txt
```
The command will output ` New Err` to stderr.

# Tests + Formatting
Added 2 cases.
2024-07-31 18:19:35 +02:00
d880241102 Bump rust toolchain (#13499)
Following the Rust 1.80 release update our supported Rust version to
1.78.0

Necessary clippy fixes in #13497
2024-07-31 18:14:50 +02:00
813aac89bd Clippy fixes for toolchain bump (#13497)
- **Suggested default impl for the new `*Stack`s**
- **Change a hashmap to make clippy happy**
- **Clone from fix**
- **Fix conditional unused in test**
- then **Bump rust toolchain**
2024-07-31 14:49:22 +02:00
d2bf82d22b Bump similar from 2.5.0 to 2.6.0 (#13492) 2024-07-31 08:10:33 +00:00
3f12b14053 Bump crate-ci/typos from 1.23.3 to 1.23.5 (#13491) 2024-07-31 02:12:50 +00:00
8e2917b9ae Make assignment and const consistent with let/mut (#13385)
# Description

This makes assignment operations and `const` behave the same way `let`
and `mut` do, absorbing the rest of the pipeline.

Changes the lexer to be able to recognize assignment operators as a
separate token, and then makes the lite parser continue to push spans
into the same command regardless of any redirections or pipes if an
assignment operator is encountered. Because the pipeline is no longer
split up by the lite parser at this point, it's trivial to just parse
the right hand side as if it were a subexpression not contained within
parentheses.

# User-Facing Changes
Big breaking change. These are all now possible:

```nushell
const path = 'a' | path join 'b'

mut x = 2
$x = random int
$x = [1 2 3] | math sum

$env.FOO = random chars
```

In the past, these would have led to (an attempt at) bare word string
parsing. So while `$env.FOO = bar` would have previously set the
environment variable `FOO` to the string `"bar"`, it now tries to run
the command named `bar`, hence the major breaking change.

However, this is desirable because it is very consistent - if you see
the `=`, you can just assume it absorbs everything else to the right of
it.

# Tests + Formatting
Added tests for the new behaviour. Adjusted some existing tests that
depended on the right hand side of assignments being parsed as
barewords.

# After Submitting
- [ ] release notes (breaking change!)
2024-07-30 18:55:22 -05:00
3c3ec7891c Links to security contacts (#13488)
# Description
Added links to the Discord server and the GitHub vulnerability report
form
2024-07-30 17:05:56 +02:00
6b839c3c32 Create security policy (#13486) 2024-07-30 16:08:24 +02:00
ea22c319b6 make math sqrt const (#13487)
# Description

Just a quick PR to demonstrate one way to make commands const.
related to https://github.com/nushell/nushell/issues/13482

# 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-07-30 08:53:41 -05:00
7432e67da1 don't force stripping ansi codes from strings in stor (#13464)
# Description

The current version of `stor` forces stripping ansi code coloring from
all the strings.
In this PR, I propose to keep strings unchanged.

The logic behind the proposed changes was best described in the
[discord](https://discord.com/channels/601130461678272522/601130461678272524/1266387441074442272):
<img width="773" alt="image"
src="https://github.com/user-attachments/assets/063cdebd-684f-46f1-aca1-faeb4827723d">

with proposed changes we can store colored output:
```
stor reset; stor create --table-name test --columns {a: str};
ls | table | {a: $in} | stor insert --table-name test | null;
stor open | query db 'select a from test' | get a.0 
```

<img width="704" alt="image"
src="https://github.com/user-attachments/assets/8f062808-18fc-498b-a77e-a118f6b9953a">


# User-Facing Changes

If one was using `stor` together with ansi colored input, and then was
querying `stor` with search operations, they might break. But I don't
think that it is a big problem, as one will just need to use `ansi
reset` before storing data.

# Tests + Formatting

Tests are okay.

Thanks to @fdncred for spending time to help me write these changes 🙏
2024-07-30 08:52:28 -05:00
0576794e74 reduce: supply <acc> to the closure as pipeline input as well (#13461)
<!--
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!
-->

resolve #13459

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

Make `reduce` supply the accumulator value to closure as pipeline input.

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

Mostly described in #13459

- Should not be a breaking change.
- Allows cleaner patterns like `... | reduce {|it| merge $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
> ```
-->
`cargo test --package nu-cli --test main -- commands::reduce` and
`toolkit test stdlib` report no issues
2024-07-30 08:51:51 -05:00
12f57dbc62 Add "--as-columns" flag to polars into-df (#13449)
<!--
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!
-->
Per discussion on
[Discord](https://discord.com/channels/601130461678272522/864228801851949077/1265718178927870045)
# 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.
-->

To facilitate column-oriented dataframe construction, this PR added a
`--as-columns` flag to `polars into-df` command so that when specified,
and when input shape is record of lists, each list will be treated as a
column rather than a cell value, i.e. `{a: [1 3], b: [2 4]} | polars
into-df --as-columns` returns the same dataframe as `[[a b];[1 2] [3 4]]
| polars into-df`


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

A new flag `--as-columns`, no change of semantics if this flag is
unspecified.

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

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

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

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

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

---------

Co-authored-by: Ben Yang <ben@ya.ng>
2024-07-30 08:50:50 -05:00
fe57c5c22e fix: Make log respect use_ansi_coloring setting. (#13442)
# Very briefly
Fixes: #13317 
- Ignore ansi coloring on logs if this setting is true.
- Add a reset after the default left prompt (before prompt character)
which fixes all-red text when `use_ansi_coloring` is false.

# Description

## Firstly,
argumentation about the changes to `crates/nu-std/std/log.nu`

Previous behavior colored the output of all log, even when the setting
`use_ansi_coloring` was false.

![image](https://github.com/user-attachments/assets/a82991c4-ff46-455d-8dac-248de2456d78)

Current behavior honors the setting.

![image](https://github.com/user-attachments/assets/6d5365db-e05d-4d2a-8981-f22303dff081)

## Second,
While testing different scenarios, I found out that the default setting
on both (`0.95`, arch linux) and the source (`0.96`) all text was
displayed in red (the color used for the present-working-directory part
of the prompt) after setting `use_ansi_coloring` to `false` ([comment
with picture of the issue and reproduction
steps](https://github.com/nushell/nushell/issues/13317#issuecomment-2247439894)).
To which my response was adding a `(ansi reset)` at the end of the
directory part of the prompt in the default config
(`crates/nu-utils/src/sample_config/default_env.nu`) file. All later
parts follow the `use_ansi_coloring` setting and their assigned colors.

# User-Facing Changes
I would say the color, but don't know if that counts as "user-facing".

# Tests + Formatting
- Formatting was applied as advised.
- 1314 tests passed and 24 ignored, none failed.
- Clippy  did not pass due to an error on the following files:
`crates/nu-protocol/src/engine/argument.rs:81:5` and
`crates/nu-protocol/src/engine/error_handler.rs:19:5`
throwing the error `you should consider adding a 'Default'
implementation for 'ErrorHandlerStack'`.
As those files are out of the scope of the current issue, they have
**not** been changed.
2024-07-30 08:34:11 -05:00
18161e5707 Bump shadow-rs from 0.29.0 to 0.30.0 (#13436) 2024-07-30 13:33:21 +00:00
466b3899e0 Use the Default implementation of Suggestion (#13409)
# Description

Take advantage of the `Default` implementation of `Suggestion`. This in
particular should make code compatible forward-compatible with
https://github.com/nushell/reedline/pull/798.

# User-Facing Changes
None

# Tests + Formatting

Existing coverage.
2024-07-30 08:32:40 -05:00
7b82c6b482 feat: make ctrlc available to plugins (#13181)
# Description

This PR adds a new method to `EngineInterface`: `register_ctrlc_handler`
which takes a closure to run when the plugin's driving engine receives a
ctrlc-signal. It also adds a mirror of the `signals` attribute from the
main shell `EngineState`.

This is an example of how a plugin which makes a long poll http request
can end the request on ctrlc:
https://github.com/cablehead/nu_plugin_http/blob/main/src/commands/request.rs#L68-L77

To facilitate the feature, a new attribute has been added to
`EngineState`: `ctrlc_handlers`. This is a Vec of closures that will be
run when the engine's process receives a ctrlc signal.

When plugins are added to an `engine_state` during a `merge_delta`, the
engine passes the ctrlc_handlers to the plugin's
`.configure_ctrlc_handler` method, which gives the plugin a chance to
register a handler that sends a ctrlc packet through the
`PluginInterface`, if an instance of the plugin is currently running.

On the plugin side: `EngineInterface` also has a ctrlc_handlers Vec of
closures. Plugin calls can use `register_ctrlc_handler` to register a
closure that will be called in the plugin process when the
PluginInput::Ctrlc command is received.

For future reference these are some alternate places that were
investigated for tying the ctrlc trigger to transmitting a Ctrlc packet
through the `PluginInterface`:

- Directly from `src/signals.rs`: the handler there would need a
reference to the Vec<Arc<RegisteredPlugins>>, which would require us to
wrap the plugins in a Mutex, which we don't want to do.

- have `PersistentPlugin.get_plugin` pass down the engine's
CtrlcHandlers to .get and then to .spawn (if the plugin isn't already
running). Once we have CtrlcHandlers in spawn, we can register a handler
to write directly to PluginInterface. We don't want to double down on
passing engine_state to spawn this way though, as it's unpredictable
because it would depend on whether the plugin has already been spawned
or not.

- pass `ctrlc_handlers` to PersistentPlugin::new so it can store it on
itself so it's available to spawn.

- in `PersistentPlugin.spawn`, create a handler that sends to a clone of
the GC event loop's tx. this has the same issues with regards to how to
get CtrlcHandlers to the spawn method, and is more complicated than a
handler that writes directly to PluginInterface

# User-Facing Changes

No breaking changes

---------

Co-authored-by: Ian Manske <ian.manske@pm.me>
2024-07-30 08:29:18 -05:00
e3f78b8793 Keep forward slash when autocomplete on Windows (#13321)
Related #7044 

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

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

When autocomplete path with `/` on Windows, paths keep with slash
instead of backslash(`\`).

If mixed both, path completion uses a last path seperator.


![image](https://github.com/nushell/nushell/assets/4014016/b09633fd-0e4a-4cd9-9c14-2bca30625804)


![image](https://github.com/nushell/nushell/assets/4014016/e1f228f8-4cce-43eb-a34a-dfa54efd2ebb)


![image](https://github.com/nushell/nushell/assets/4014016/0694443a-3017-4828-be60-5f39ffd96440)

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


![completion](https://github.com/nushell/nushell/assets/4014016/03626544-6a14-4d8b-a607-21a4472f8037)

# 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-07-30 08:28:41 -05:00
c31291753c Bump version to 0.96.2 (#13485)
This should be the new development version. We most likely don't need a
0.96.2 patch release. Should be free to merge PRs after this.
2024-07-29 17:20:55 -07:00
264 changed files with 5704 additions and 2992 deletions

View File

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

274
Cargo.lock generated
View File

@ -297,6 +297,12 @@ version = "0.15.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ae037714f313c1353189ead58ef9eec30a8e8dc101b2622d461418fd59e28a9"
[[package]]
name = "atomic-waker"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
[[package]]
name = "autocfg"
version = "1.2.0"
@ -605,7 +611,7 @@ dependencies = [
"encoding_rs",
"log",
"once_cell",
"quick-xml",
"quick-xml 0.31.0",
"serde",
"zip",
]
@ -1796,15 +1802,15 @@ dependencies = [
[[package]]
name = "h2"
version = "0.3.26"
version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81fe527a889e1532da5c525686d96d4c2e74cdd345badf8dfef9f6b39dd5f5e8"
checksum = "fa82e28a107a8cc405f0839610bdc9b15f1e25ec7d696aa5cf173edbcb1486ab"
dependencies = [
"atomic-waker",
"bytes",
"fnv",
"futures-core",
"futures-sink",
"futures-util",
"http",
"indexmap",
"slab",
@ -1905,20 +1911,6 @@ dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "html5ever"
version = "0.26.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bea68cab48b8459f17cf1c944c67ddc572d272d9f2b274140f223ecb1da4a3b7"
dependencies = [
"log",
"mac",
"markup5ever 0.11.0",
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]]
name = "html5ever"
version = "0.27.0"
@ -1927,7 +1919,7 @@ checksum = "c13771afe0e6e846f1e67d038d4cb29998a6779f93c809212e4e9c32efd244d4"
dependencies = [
"log",
"mac",
"markup5ever 0.12.1",
"markup5ever",
"proc-macro2",
"quote",
"syn 2.0.60",
@ -1935,9 +1927,9 @@ dependencies = [
[[package]]
name = "http"
version = "0.2.12"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1"
checksum = "21b9ddb458710bc376481b842f5da65cdf31522de232c1ca8146abce2a358258"
dependencies = [
"bytes",
"fnv",
@ -1946,12 +1938,24 @@ dependencies = [
[[package]]
name = "http-body"
version = "0.4.6"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2"
checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184"
dependencies = [
"bytes",
"http",
]
[[package]]
name = "http-body-util"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "793429d76616a256bcb62c2a2ec2bed781c8307e797e2598c50010f2bee2544f"
dependencies = [
"bytes",
"futures-util",
"http",
"http-body",
"pin-project-lite",
]
@ -1987,13 +1991,12 @@ checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4"
[[package]]
name = "hyper"
version = "0.14.28"
version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf96e135eb83a2a8ddf766e426a841d8ddd7449d5f00d34ea02b41d2f19eef80"
checksum = "50dfd22e0e76d0f662d429a5f80fcaf3855009297eab6a0a9f8543834744ba05"
dependencies = [
"bytes",
"futures-channel",
"futures-core",
"futures-util",
"h2",
"http",
@ -2002,10 +2005,23 @@ dependencies = [
"httpdate",
"itoa",
"pin-project-lite",
"smallvec",
"tokio",
]
[[package]]
name = "hyper-util"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cde7055719c54e36e95e8719f95883f22072a48ede39db7fc17a4e1d5281e9b9"
dependencies = [
"bytes",
"futures-util",
"http",
"http-body",
"hyper",
"pin-project-lite",
"tokio",
"tower-service",
"tracing",
"want",
]
[[package]]
@ -2052,9 +2068,9 @@ dependencies = [
[[package]]
name = "indexmap"
version = "2.2.6"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "168fb715dda47215e360912c096649d23d58bf392ac62f73919e831745e40f26"
checksum = "93ead53efc7ea8ed3cfb0c79fc8023fbb782a5432b52830b6518941cebe6505c"
dependencies = [
"equivalent",
"hashbrown 0.14.5",
@ -2582,20 +2598,6 @@ dependencies = [
"libc",
]
[[package]]
name = "markup5ever"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a2629bb1404f3d34c2e921f21fd34ba00b206124c81f65c50b43b6aaefeb016"
dependencies = [
"log",
"phf 0.10.1",
"phf_codegen 0.10.0",
"string_cache",
"string_cache_codegen",
"tendril",
]
[[package]]
name = "markup5ever"
version = "0.12.1"
@ -2616,8 +2618,8 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "edaa21ab3701bfee5099ade5f7e1f84553fd19228cf332f13cd6e964bf59be18"
dependencies = [
"html5ever 0.27.0",
"markup5ever 0.12.1",
"html5ever",
"markup5ever",
"tendril",
"xml5ever",
]
@ -2732,13 +2734,18 @@ dependencies = [
[[package]]
name = "mockito"
version = "1.4.0"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2f6e023aa5bdf392aa06c78e4a4e6d498baab5138d0c993503350ebbc37bf1e"
checksum = "09b34bd91b9e5c5b06338d392463e1318d683cf82ec3d3af4014609be6e2108d"
dependencies = [
"assert-json-diff",
"futures-core",
"bytes",
"futures-util",
"http",
"http-body",
"http-body-util",
"hyper",
"hyper-util",
"log",
"rand",
"regex",
@ -2748,6 +2755,20 @@ dependencies = [
"tokio",
]
[[package]]
name = "multipart-rs"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22ea34e5c0fa65ba84707cfaf5bf43d500f1c5a4c6c36327bf5541c5bcd17e98"
dependencies = [
"bytes",
"futures-core",
"futures-util",
"memchr",
"mime",
"uuid",
]
[[package]]
name = "multiversion"
version = "0.7.4"
@ -2868,7 +2889,7 @@ dependencies = [
[[package]]
name = "nu"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"assert_cmd",
"crossterm",
@ -2877,6 +2898,7 @@ dependencies = [
"log",
"miette",
"mimalloc",
"multipart-rs",
"nix",
"nu-cli",
"nu-cmd-base",
@ -2922,7 +2944,7 @@ dependencies = [
[[package]]
name = "nu-cli"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"chrono",
"crossterm",
@ -2957,7 +2979,7 @@ dependencies = [
[[package]]
name = "nu-cmd-base"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"indexmap",
"miette",
@ -2969,7 +2991,7 @@ dependencies = [
[[package]]
name = "nu-cmd-extra"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"fancy-regex",
"heck 0.5.0",
@ -2994,7 +3016,7 @@ dependencies = [
[[package]]
name = "nu-cmd-lang"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"itertools 0.12.1",
"nu-engine",
@ -3006,7 +3028,7 @@ dependencies = [
[[package]]
name = "nu-cmd-plugin"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"itertools 0.12.1",
"nu-engine",
@ -3017,7 +3039,7 @@ dependencies = [
[[package]]
name = "nu-color-config"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"nu-ansi-term",
"nu-engine",
@ -3029,7 +3051,7 @@ dependencies = [
[[package]]
name = "nu-command"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"alphanumeric-sort",
"base64 0.22.1",
@ -3053,7 +3075,6 @@ dependencies = [
"fancy-regex",
"filesize",
"filetime",
"fs_extra",
"human-date-parser",
"indexmap",
"indicatif",
@ -3064,6 +3085,7 @@ dependencies = [
"mime",
"mime_guess",
"mockito",
"multipart-rs",
"native-tls",
"nix",
"notify-debouncer-full",
@ -3094,7 +3116,7 @@ dependencies = [
"pretty_assertions",
"print-positions",
"procfs",
"quick-xml",
"quick-xml 0.32.0",
"quickcheck",
"quickcheck_macros",
"rand",
@ -3139,7 +3161,7 @@ dependencies = [
[[package]]
name = "nu-derive-value"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"convert_case",
"proc-macro-error",
@ -3150,18 +3172,19 @@ dependencies = [
[[package]]
name = "nu-engine"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"log",
"nu-glob",
"nu-path",
"nu-protocol",
"nu-utils",
"terminal_size",
]
[[package]]
name = "nu-explore"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"ansi-str",
"anyhow",
@ -3186,14 +3209,14 @@ dependencies = [
[[package]]
name = "nu-glob"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"doc-comment",
]
[[package]]
name = "nu-json"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"fancy-regex",
"linked-hash-map",
@ -3206,7 +3229,7 @@ dependencies = [
[[package]]
name = "nu-lsp"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"assert-json-diff",
"crossbeam-channel",
@ -3227,7 +3250,7 @@ dependencies = [
[[package]]
name = "nu-parser"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"bytesize",
"chrono",
@ -3243,7 +3266,7 @@ dependencies = [
[[package]]
name = "nu-path"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"dirs",
"omnipath",
@ -3252,7 +3275,7 @@ dependencies = [
[[package]]
name = "nu-plugin"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"log",
"nix",
@ -3268,7 +3291,7 @@ dependencies = [
[[package]]
name = "nu-plugin-core"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"interprocess",
"log",
@ -3282,7 +3305,7 @@ dependencies = [
[[package]]
name = "nu-plugin-engine"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"log",
"nu-engine",
@ -3298,7 +3321,7 @@ dependencies = [
[[package]]
name = "nu-plugin-protocol"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"bincode",
"nu-protocol",
@ -3310,7 +3333,7 @@ dependencies = [
[[package]]
name = "nu-plugin-test-support"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"nu-ansi-term",
"nu-cmd-lang",
@ -3328,7 +3351,7 @@ dependencies = [
[[package]]
name = "nu-pretty-hex"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"heapless",
"nu-ansi-term",
@ -3337,7 +3360,7 @@ dependencies = [
[[package]]
name = "nu-protocol"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"brotli",
"byte-unit",
@ -3374,7 +3397,7 @@ dependencies = [
[[package]]
name = "nu-std"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"log",
"miette",
@ -3385,7 +3408,7 @@ dependencies = [
[[package]]
name = "nu-system"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"chrono",
"itertools 0.12.1",
@ -3403,7 +3426,7 @@ dependencies = [
[[package]]
name = "nu-table"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"fancy-regex",
"nu-ansi-term",
@ -3417,7 +3440,7 @@ dependencies = [
[[package]]
name = "nu-term-grid"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"nu-utils",
"unicode-width",
@ -3425,7 +3448,7 @@ dependencies = [
[[package]]
name = "nu-test-support"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"nu-glob",
"nu-path",
@ -3437,7 +3460,7 @@ dependencies = [
[[package]]
name = "nu-utils"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"crossterm_winapi",
"log",
@ -3463,7 +3486,7 @@ dependencies = [
[[package]]
name = "nu_plugin_example"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"nu-cmd-lang",
"nu-plugin",
@ -3473,20 +3496,22 @@ dependencies = [
[[package]]
name = "nu_plugin_formats"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"chrono",
"eml-parser",
"ical",
"indexmap",
"nu-plugin",
"nu-plugin-test-support",
"nu-protocol",
"plist",
"rust-ini",
]
[[package]]
name = "nu_plugin_gstat"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"git2",
"nu-plugin",
@ -3495,7 +3520,7 @@ dependencies = [
[[package]]
name = "nu_plugin_inc"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"nu-plugin",
"nu-protocol",
@ -3504,7 +3529,7 @@ dependencies = [
[[package]]
name = "nu_plugin_polars"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"chrono",
"chrono-tz 0.9.0",
@ -3538,7 +3563,7 @@ dependencies = [
[[package]]
name = "nu_plugin_query"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"gjson",
"nu-plugin",
@ -3553,7 +3578,7 @@ dependencies = [
[[package]]
name = "nu_plugin_stress_internals"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"interprocess",
"serde",
@ -3679,7 +3704,7 @@ checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3"
[[package]]
name = "nuon"
version = "0.96.1"
version = "0.97.1"
dependencies = [
"chrono",
"fancy-regex",
@ -4147,6 +4172,19 @@ dependencies = [
"winapi",
]
[[package]]
name = "plist"
version = "1.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42cf17e9a1800f5f396bc67d193dc9411b59012a5876445ef450d449881e1016"
dependencies = [
"base64 0.22.1",
"indexmap",
"quick-xml 0.32.0",
"serde",
"time",
]
[[package]]
name = "polars"
version = "0.41.2"
@ -4815,6 +4853,15 @@ dependencies = [
"memchr",
]
[[package]]
name = "quick-xml"
version = "0.32.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d3a6e5838b60e0e8fa7a43f22ade549a37d61f8bdbe636d0d7816191de969c2"
dependencies = [
"memchr",
]
[[package]]
name = "quickcheck"
version = "1.0.3"
@ -5004,9 +5051,9 @@ dependencies = [
[[package]]
name = "reedline"
version = "0.33.0"
version = "0.34.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f8c676a3f3814a23c6a0fc9dff6b6c35b2e04df8134aae6f3929cc34de21a53"
checksum = "dc271368d0d3f395745b40fababc0c9061f3fc2978189a8bc76f889e47255b01"
dependencies = [
"arboard",
"chrono",
@ -5366,14 +5413,14 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "scraper"
version = "0.19.0"
version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b80b33679ff7a0ea53d37f3b39de77ea0c75b12c5805ac43ec0c33b3051af1b"
checksum = "b90460b31bfe1fc07be8262e42c665ad97118d4585869de9345a84d501a9eaf0"
dependencies = [
"ahash 0.8.11",
"cssparser",
"ego-tree",
"html5ever 0.26.0",
"html5ever",
"once_cell",
"selectors",
"tendril",
@ -5589,9 +5636,9 @@ dependencies = [
[[package]]
name = "shadow-rs"
version = "0.29.0"
version = "0.31.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0a600f795d0894cda22235b44eea4b85c2a35b405f65523645ac8e35b306817a"
checksum = "02c282402d25101f9c893e9cd7e4cae535fe7db18b81291de973026c219ddf1e"
dependencies = [
"const_format",
"is_debug",
@ -5666,9 +5713,9 @@ checksum = "f27f6278552951f1f2b8cf9da965d10969b2efdea95a6ec47987ab46edfe263a"
[[package]]
name = "similar"
version = "2.5.0"
version = "2.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa42c91313f1d05da9b26f267f931cf178d4aba455b4c4622dd7355eb80c6640"
checksum = "1de1d4f81173b03af4c0cbed3c898f6bff5b870e4a7f5d6f4057d62a7a4b686e"
[[package]]
name = "simplelog"
@ -5967,9 +6014,9 @@ dependencies = [
[[package]]
name = "sysinfo"
version = "0.30.11"
version = "0.30.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87341a165d73787554941cd5ef55ad728011566fe714e987d1b976c15dbc3a83"
checksum = "0a5b4ddaee55fb2bea2bf0e5000747e5f5c0de765e5a5ff87f4cd106439f4bb3"
dependencies = [
"cfg-if",
"core-foundation-sys",
@ -6284,12 +6331,6 @@ dependencies = [
"winnow 0.6.7",
]
[[package]]
name = "tower-service"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52"
[[package]]
name = "tracing"
version = "0.1.40"
@ -6345,12 +6386,6 @@ version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "343e926fc669bc8cde4fa3129ab681c63671bae288b1f1081ceee6d9d37904fc"
[[package]]
name = "try-lock"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]]
name = "typed-arena"
version = "1.7.0"
@ -6730,15 +6765,6 @@ dependencies = [
"winapi-util",
]
[[package]]
name = "want"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"
dependencies = [
"try-lock",
]
[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"
@ -6872,7 +6898,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b3a62929287001986fb58c789dce9b67604a397c15c611ad9f747300b6c283"
dependencies = [
"proc-macro2",
"quick-xml",
"quick-xml 0.31.0",
"quote",
]
@ -6894,7 +6920,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70862efc041d46e6bbaa82bb9c34ae0596d090e86cbd14bd9e93b36ee6802eac"
dependencies = [
"curl",
"html5ever 0.27.0",
"html5ever",
"markup5ever_rcdom",
"serde",
"serde_json",
@ -7321,7 +7347,7 @@ checksum = "9bbb26405d8e919bc1547a5aa9abc95cbfa438f04844f5fdd9dc7596b748bf69"
dependencies = [
"log",
"mac",
"markup5ever 0.12.1",
"markup5ever",
]
[[package]]

View File

@ -10,8 +10,8 @@ homepage = "https://www.nushell.sh"
license = "MIT"
name = "nu"
repository = "https://github.com/nushell/nushell"
rust-version = "1.77.2"
version = "0.96.1"
rust-version = "1.78.0"
version = "0.97.1"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@ -90,12 +90,10 @@ encoding_rs = "0.8"
fancy-regex = "0.13"
filesize = "0.2"
filetime = "0.2"
fs_extra = "1.3"
fuzzy-matcher = "0.3"
hamcrest2 = "0.3"
heck = "0.5.0"
human-date-parser = "0.1.1"
indexmap = "2.2"
indexmap = "2.4"
indicatif = "0.17"
interprocess = "2.2.0"
is_executable = "1.0"
@ -110,9 +108,10 @@ lsp-types = "0.95.0"
mach2 = "0.4"
md5 = { version = "0.10", package = "md-5" }
miette = "7.2"
mime = "0.3"
mime = "0.3.17"
mime_guess = "2.0"
mockito = { version = "1.4", default-features = false }
mockito = { version = "1.5", default-features = false }
multipart-rs = "0.1.11"
native-tls = "0.2"
nix = { version = "0.28", default-features = false }
notify-debouncer-full = { version = "0.3", default-features = false }
@ -131,14 +130,14 @@ proc-macro-error = { version = "1.0", default-features = false }
proc-macro2 = "1.0"
procfs = "0.16.0"
pwd = "1.3"
quick-xml = "0.31.0"
quick-xml = "0.32.0"
quickcheck = "1.0"
quickcheck_macros = "1.0"
quote = "1.0"
rand = "0.8"
ratatui = "0.26"
rayon = "1.10"
reedline = "0.33.0"
reedline = "0.34.0"
regex = "1.9.5"
rmp = "0.8"
rmp-serde = "1.3"
@ -183,22 +182,22 @@ windows-sys = "0.48"
winreg = "0.52"
[dependencies]
nu-cli = { path = "./crates/nu-cli", version = "0.96.1" }
nu-cmd-base = { path = "./crates/nu-cmd-base", version = "0.96.1" }
nu-cmd-lang = { path = "./crates/nu-cmd-lang", version = "0.96.1" }
nu-cmd-plugin = { path = "./crates/nu-cmd-plugin", version = "0.96.1", optional = true }
nu-cmd-extra = { path = "./crates/nu-cmd-extra", version = "0.96.1" }
nu-command = { path = "./crates/nu-command", version = "0.96.1" }
nu-engine = { path = "./crates/nu-engine", version = "0.96.1" }
nu-explore = { path = "./crates/nu-explore", version = "0.96.1" }
nu-lsp = { path = "./crates/nu-lsp/", version = "0.96.1" }
nu-parser = { path = "./crates/nu-parser", version = "0.96.1" }
nu-path = { path = "./crates/nu-path", version = "0.96.1" }
nu-plugin-engine = { path = "./crates/nu-plugin-engine", optional = true, version = "0.96.1" }
nu-protocol = { path = "./crates/nu-protocol", version = "0.96.1" }
nu-std = { path = "./crates/nu-std", version = "0.96.1" }
nu-system = { path = "./crates/nu-system", version = "0.96.1" }
nu-utils = { path = "./crates/nu-utils", version = "0.96.1" }
nu-cli = { path = "./crates/nu-cli", version = "0.97.1" }
nu-cmd-base = { path = "./crates/nu-cmd-base", version = "0.97.1" }
nu-cmd-lang = { path = "./crates/nu-cmd-lang", version = "0.97.1" }
nu-cmd-plugin = { path = "./crates/nu-cmd-plugin", version = "0.97.1", optional = true }
nu-cmd-extra = { path = "./crates/nu-cmd-extra", version = "0.97.1" }
nu-command = { path = "./crates/nu-command", version = "0.97.1" }
nu-engine = { path = "./crates/nu-engine", version = "0.97.1" }
nu-explore = { path = "./crates/nu-explore", version = "0.97.1" }
nu-lsp = { path = "./crates/nu-lsp/", version = "0.97.1" }
nu-parser = { path = "./crates/nu-parser", version = "0.97.1" }
nu-path = { path = "./crates/nu-path", version = "0.97.1" }
nu-plugin-engine = { path = "./crates/nu-plugin-engine", optional = true, version = "0.97.1" }
nu-protocol = { path = "./crates/nu-protocol", version = "0.97.1" }
nu-std = { path = "./crates/nu-std", version = "0.97.1" }
nu-system = { path = "./crates/nu-system", version = "0.97.1" }
nu-utils = { path = "./crates/nu-utils", version = "0.97.1" }
reedline = { workspace = true, features = ["bashisms", "sqlite"] }
crossterm = { workspace = true }
@ -207,6 +206,7 @@ dirs = { workspace = true }
log = { workspace = true }
miette = { workspace = true, features = ["fancy-no-backtrace", "fancy"] }
mimalloc = { version = "0.1.42", default-features = false, optional = true }
multipart-rs = { workspace = true }
serde_json = { workspace = true }
simplelog = "0.12"
time = "0.3"
@ -227,9 +227,9 @@ nix = { workspace = true, default-features = false, features = [
] }
[dev-dependencies]
nu-test-support = { path = "./crates/nu-test-support", version = "0.96.1" }
nu-plugin-protocol = { path = "./crates/nu-plugin-protocol", version = "0.96.1" }
nu-plugin-core = { path = "./crates/nu-plugin-core", version = "0.96.1" }
nu-test-support = { path = "./crates/nu-test-support", version = "0.97.1" }
nu-plugin-protocol = { path = "./crates/nu-plugin-protocol", version = "0.97.1" }
nu-plugin-core = { path = "./crates/nu-plugin-core", version = "0.97.1" }
assert_cmd = "2.0"
dirs = { workspace = true }
tango-bench = "0.5"
@ -305,7 +305,7 @@ bench = false
# To use a development version of a dependency please use a global override here
# changing versions in each sub-crate of the workspace is tedious
# [patch.crates-io]
[patch.crates-io]
# reedline = { git = "https://github.com/nushell/reedline", branch = "main" }
# nu-ansi-term = {git = "https://github.com/nushell/nu-ansi-term.git", branch = "main"}
@ -313,4 +313,4 @@ bench = false
# Run individual benchmarks like `cargo bench -- <regex>` e.g. `cargo bench -- parse`
[[bench]]
name = "benchmarks"
harness = false
harness = false

29
SECURITY.md Normal file
View File

@ -0,0 +1,29 @@
# Security Policy
As a shell and programming language Nushell provides you with great powers and the potential to do dangerous things to your computer and data. Whenever there is a risk that a malicious actor can abuse a bug or a violation of documented behavior/assumptions in Nushell to harm you this is a *security* risk.
We want to fix those issues without exposing our users to unnecessary risk. Thus we want to explain our security policy.
Additional issues may be part of *safety* where the behavior of Nushell as designed and implemented can cause unintended harm or a bug causes damage without the involvement of a third party.
## Supported Versions
As Nushell is still under very active pre-stable development, the only version the core team prioritizes for security and safety fixes is the [most recent version as published on GitHub](https://github.com/nushell/nushell/releases/latest).
Only if you provide a strong reasoning and the necessary resources, will we consider blessing a backported fix with an official patch release for a previous version.
## Reporting a Vulnerability
If you suspect that a bug or behavior of Nushell can affect security or may be potentially exploitable, please report the issue to us in private.
Either reach out to the core team on [our Discord server](https://discord.gg/NtAbbGn) to arrange a private channel or use the [GitHub vulnerability reporting form](https://github.com/nushell/nushell/security/advisories/new).
Please try to answer the following questions:
- How can we reach you for further questions?
- What is the bug? Which system of Nushell may be affected?
- Do you have proof-of-concept for a potential exploit or have you observed an exploit in the wild?
- What is your assessment of the severity based on what could be impacted should the bug be exploited?
- Are additional people aware of the issue or deserve credit for identifying the issue?
We will try to get back to you within a week with:
- acknowledging the receipt of the report
- an initial plan of how we want to address this including the primary points of contact for further communication
- our preliminary assessment of how severe we judge the issue
- a proposal for how we can coordinate responsible disclosure (e.g. how we ship the bugfix, if we need to coordinate with distribution maintainers, when you can release a blog post if you want to etc.)
For purely *safety* related issues where the impact is severe by direct user action instead of malicious input or third parties, feel free to open a regular issue. If we deem that there may be an additional *security* risk on a *safety* issue we may continue discussions in a restricted forum.

View File

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

View File

@ -67,7 +67,7 @@ impl Command for History {
} else {
let history_reader: Option<Box<dyn ReedlineHistory>> = match history.file_format {
HistoryFileFormat::Sqlite => {
SqliteBackedHistory::with_file(history_path.clone(), None, None)
SqliteBackedHistory::with_file(history_path.clone().into(), None, None)
.map(|inner| {
let boxed: Box<dyn ReedlineHistory> = Box::new(inner);
boxed
@ -77,7 +77,7 @@ impl Command for History {
HistoryFileFormat::PlainText => FileBackedHistory::with_file(
history.max_size as usize,
history_path.clone(),
history_path.clone().into(),
)
.map(|inner| {
let boxed: Box<dyn ReedlineHistory> = Box::new(inner);
@ -156,58 +156,34 @@ fn create_history_record(idx: usize, entry: HistoryItem, long: bool, head: Span)
//2. Create a record of either short or long columns and values
let item_id_value = Value::int(
match entry.id {
Some(id) => {
let ids = id.to_string();
match ids.parse::<i64>() {
Ok(i) => i,
_ => 0i64,
}
}
None => 0i64,
},
entry
.id
.and_then(|id| id.to_string().parse::<i64>().ok())
.unwrap_or_default(),
head,
);
let start_timestamp_value = Value::string(
match entry.start_timestamp {
Some(time) => time.to_string(),
None => "".into(),
},
entry
.start_timestamp
.map(|time| time.to_string())
.unwrap_or_default(),
head,
);
let command_value = Value::string(entry.command_line, head);
let session_id_value = Value::int(
match entry.session_id {
Some(sid) => {
let sids = sid.to_string();
match sids.parse::<i64>() {
Ok(i) => i,
_ => 0i64,
}
}
None => 0i64,
},
head,
);
let hostname_value = Value::string(
match entry.hostname {
Some(host) => host,
None => "".into(),
},
head,
);
let cwd_value = Value::string(
match entry.cwd {
Some(cwd) => cwd,
None => "".into(),
},
entry
.session_id
.and_then(|id| id.to_string().parse::<i64>().ok())
.unwrap_or_default(),
head,
);
let hostname_value = Value::string(entry.hostname.unwrap_or_default(), head);
let cwd_value = Value::string(entry.cwd.unwrap_or_default(), head);
let duration_value = Value::duration(
match entry.duration {
Some(d) => d.as_nanos().try_into().unwrap_or(0),
None => 0,
},
entry
.duration
.and_then(|d| d.as_nanos().try_into().ok())
.unwrap_or(0),
head,
);
let exit_status_value = Value::int(entry.exit_status.unwrap_or(0), head);

View File

@ -1,5 +1,5 @@
use crate::{
completions::{Completer, CompletionOptions, MatchAlgorithm, SortBy},
completions::{Completer, CompletionOptions, MatchAlgorithm},
SuggestionKind,
};
use nu_parser::FlatShape;
@ -99,10 +99,9 @@ impl CommandCompletion {
suggestion: Suggestion {
value: String::from_utf8_lossy(&x.0).to_string(),
description: x.1,
style: None,
extra: None,
span: reedline::Span::new(span.start - offset, span.end - offset),
append_whitespace: true,
..Suggestion::default()
},
kind: Some(SuggestionKind::Command(x.2)),
})
@ -118,11 +117,9 @@ impl CommandCompletion {
.map(move |x| SemanticSuggestion {
suggestion: Suggestion {
value: x,
description: None,
style: None,
extra: None,
span: reedline::Span::new(span.start - offset, span.end - offset),
append_whitespace: true,
..Suggestion::default()
},
// TODO: is there a way to create a test?
kind: None,
@ -136,11 +133,9 @@ impl CommandCompletion {
results.push(SemanticSuggestion {
suggestion: Suggestion {
value: format!("^{}", external.suggestion.value),
description: None,
style: None,
extra: None,
span: external.suggestion.span,
append_whitespace: true,
..Suggestion::default()
},
kind: external.kind,
})
@ -198,11 +193,7 @@ impl Completer for CommandCompletion {
};
if !subcommands.is_empty() {
return sort_suggestions(
&String::from_utf8_lossy(&prefix),
subcommands,
SortBy::LevenshteinDistance,
);
return sort_suggestions(&String::from_utf8_lossy(&prefix), subcommands, options);
}
let config = working_set.get_config();
@ -227,11 +218,7 @@ impl Completer for CommandCompletion {
vec![]
};
sort_suggestions(
&String::from_utf8_lossy(&prefix),
commands,
SortBy::LevenshteinDistance,
)
sort_suggestions(&String::from_utf8_lossy(&prefix), commands, options)
}
}

View File

@ -48,6 +48,7 @@ impl NuCompleter {
let options = CompletionOptions {
case_sensitive: config.case_sensitive_completions,
match_algorithm: config.completion_algorithm.into(),
sort: config.completion_sort,
..Default::default()
};
@ -443,14 +444,11 @@ pub fn map_value_completions<'a>(
return Some(SemanticSuggestion {
suggestion: Suggestion {
value: s,
description: None,
style: None,
extra: None,
span: reedline::Span {
start: span.start - offset,
end: span.end - offset,
},
append_whitespace: false,
..Suggestion::default()
},
kind: Some(SuggestionKind::Type(x.get_type())),
});
@ -460,14 +458,11 @@ pub fn map_value_completions<'a>(
if let Ok(record) = x.as_record() {
let mut suggestion = Suggestion {
value: String::from(""), // Initialize with empty string
description: None,
style: None,
extra: None,
span: reedline::Span {
start: span.start - offset,
end: span.end - offset,
},
append_whitespace: false,
..Suggestion::default()
};
// Iterate the cols looking for `value` and `description`

View File

@ -2,19 +2,18 @@ use crate::{
completions::{matches, CompletionOptions},
SemanticSuggestion,
};
use fuzzy_matcher::{skim::SkimMatcherV2, FuzzyMatcher};
use nu_ansi_term::Style;
use nu_engine::env_to_string;
use nu_path::{expand_to_real_path, home_dir};
use nu_protocol::{
engine::{EngineState, Stack, StateWorkingSet},
levenshtein_distance, Span,
CompletionSort, Span,
};
use nu_utils::get_ls_colors;
use std::path::{
is_separator, Component, Path, PathBuf, MAIN_SEPARATOR as SEP, MAIN_SEPARATOR_STR,
};
use std::path::{is_separator, Component, Path, PathBuf, MAIN_SEPARATOR as SEP};
use super::SortBy;
use super::MatchAlgorithm;
#[derive(Clone, Default)]
pub struct PathBuiltFromString {
@ -22,12 +21,21 @@ pub struct PathBuiltFromString {
isdir: bool,
}
fn complete_rec(
/// Recursively goes through paths that match a given `partial`.
/// built: State struct for a valid matching path built so far.
///
/// `isdir`: whether the current partial path has a trailing slash.
/// Parsing a path string into a pathbuf loses that bit of information.
///
/// want_directory: Whether we want only directories as completion matches.
/// Some commands like `cd` can only be run on directories whereas others
/// like `ls` can be run on regular files as well.
pub fn complete_rec(
partial: &[&str],
built: &PathBuiltFromString,
cwd: &Path,
options: &CompletionOptions,
dir: bool,
want_directory: bool,
isdir: bool,
) -> Vec<PathBuiltFromString> {
let mut completions = vec![];
@ -37,7 +45,7 @@ fn complete_rec(
let mut built = built.clone();
built.parts.push(base.to_string());
built.isdir = true;
return complete_rec(rest, &built, cwd, options, dir, isdir);
return complete_rec(rest, &built, cwd, options, want_directory, isdir);
}
}
@ -58,24 +66,41 @@ fn complete_rec(
built.parts.push(entry_name.clone());
built.isdir = entry_isdir;
if !dir || entry_isdir {
if !want_directory || entry_isdir {
entries.push((entry_name, built));
}
}
let prefix = partial.first().unwrap_or(&"");
let sorted_entries = sort_completions(prefix, entries, SortBy::Ascending, |(entry, _)| entry);
let sorted_entries = sort_completions(prefix, entries, options, |(entry, _)| entry);
for (entry_name, built) in sorted_entries {
match partial.split_first() {
Some((base, rest)) => {
if matches(base, &entry_name, options) {
// We use `isdir` to confirm that the current component has
// at least one next component or a slash.
// Serves as confirmation to ignore longer completions for
// components in between.
if !rest.is_empty() || isdir {
completions.extend(complete_rec(rest, &built, cwd, options, dir, isdir));
completions.extend(complete_rec(
rest,
&built,
cwd,
options,
want_directory,
isdir,
));
} else {
completions.push(built);
}
}
if entry_name.eq(base)
&& matches!(options.match_algorithm, MatchAlgorithm::Prefix)
&& isdir
{
break;
}
}
None => {
completions.push(built);
@ -93,16 +118,16 @@ enum OriginalCwd {
}
impl OriginalCwd {
fn apply(&self, mut p: PathBuiltFromString) -> String {
fn apply(&self, mut p: PathBuiltFromString, path_separator: char) -> String {
match self {
Self::None => {}
Self::Home => p.parts.insert(0, "~".to_string()),
Self::Prefix(s) => p.parts.insert(0, s.clone()),
};
let mut ret = p.parts.join(MAIN_SEPARATOR_STR);
let mut ret = p.parts.join(&path_separator.to_string());
if p.isdir {
ret.push(SEP);
ret.push(path_separator);
}
ret
}
@ -133,6 +158,14 @@ pub fn complete_item(
) -> Vec<(nu_protocol::Span, String, Option<Style>)> {
let partial = surround_remove(partial);
let isdir = partial.ends_with(is_separator);
#[cfg(unix)]
let path_separator = SEP;
#[cfg(windows)]
let path_separator = partial
.chars()
.rfind(|c: &char| is_separator(*c))
.unwrap_or(SEP);
let cwd_pathbuf = Path::new(cwd).to_path_buf();
let ls_colors = (engine_state.config.use_ls_colors_completions
&& engine_state.config.use_ansi_coloring)
@ -170,7 +203,7 @@ pub fn complete_item(
}
Some(Component::Normal(home)) if home.to_string_lossy() == "~" => {
components.next();
cwd = home_dir().unwrap_or(cwd_pathbuf);
cwd = home_dir().map(Into::into).unwrap_or(cwd_pathbuf);
prefix_len = 1;
original_cwd = OriginalCwd::Home;
}
@ -195,7 +228,7 @@ pub fn complete_item(
)
.into_iter()
.map(|p| {
let path = original_cwd.apply(p);
let path = original_cwd.apply(p, path_separator);
let style = ls_colors.as_ref().map(|lsc| {
lsc.style_for_path_with_metadata(
&path,
@ -273,33 +306,37 @@ pub fn adjust_if_intermediate(
pub fn sort_suggestions(
prefix: &str,
items: Vec<SemanticSuggestion>,
sort_by: SortBy,
options: &CompletionOptions,
) -> Vec<SemanticSuggestion> {
sort_completions(prefix, items, sort_by, |it| &it.suggestion.value)
sort_completions(prefix, items, options, |it| &it.suggestion.value)
}
/// # Arguments
/// * `prefix` - What the user's typed, for sorting by Levenshtein distance
/// * `prefix` - What the user's typed, for sorting by fuzzy matcher score
pub fn sort_completions<T>(
prefix: &str,
mut items: Vec<T>,
sort_by: SortBy,
options: &CompletionOptions,
get_value: fn(&T) -> &str,
) -> Vec<T> {
// Sort items
match sort_by {
SortBy::LevenshteinDistance => {
items.sort_by(|a, b| {
let a_distance = levenshtein_distance(prefix, get_value(a));
let b_distance = levenshtein_distance(prefix, get_value(b));
a_distance.cmp(&b_distance)
});
}
SortBy::Ascending => {
items.sort_by(|a, b| get_value(a).cmp(get_value(b)));
}
SortBy::None => {}
};
if options.sort == CompletionSort::Smart && options.match_algorithm == MatchAlgorithm::Fuzzy {
let mut matcher = SkimMatcherV2::default();
if options.case_sensitive {
matcher = matcher.respect_case();
} else {
matcher = matcher.ignore_case();
};
items.sort_by(|a, b| {
let a_str = get_value(a);
let b_str = get_value(b);
let a_score = matcher.fuzzy_match(a_str, prefix).unwrap_or_default();
let b_score = matcher.fuzzy_match(b_str, prefix).unwrap_or_default();
b_score.cmp(&a_score).then(a_str.cmp(b_str))
});
} else {
items.sort_by(|a, b| get_value(a).cmp(get_value(b)));
}
items
}

View File

@ -1,17 +1,10 @@
use fuzzy_matcher::{skim::SkimMatcherV2, FuzzyMatcher};
use nu_parser::trim_quotes_str;
use nu_protocol::CompletionAlgorithm;
use nu_protocol::{CompletionAlgorithm, CompletionSort};
use std::fmt::Display;
#[derive(Copy, Clone)]
pub enum SortBy {
LevenshteinDistance,
Ascending,
None,
}
/// Describes how suggestions should be matched.
#[derive(Copy, Clone, Debug)]
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum MatchAlgorithm {
/// Only show suggestions which begin with the given input
///
@ -96,6 +89,7 @@ pub struct CompletionOptions {
pub case_sensitive: bool,
pub positional: bool,
pub match_algorithm: MatchAlgorithm,
pub sort: CompletionSort,
}
impl Default for CompletionOptions {
@ -104,6 +98,7 @@ impl Default for CompletionOptions {
case_sensitive: true,
positional: true,
match_algorithm: MatchAlgorithm::Prefix,
sort: Default::default(),
}
}
}

View File

@ -1,13 +1,13 @@
use crate::completions::{
completer::map_value_completions, Completer, CompletionOptions, MatchAlgorithm,
SemanticSuggestion, SortBy,
SemanticSuggestion,
};
use nu_engine::eval_call;
use nu_protocol::{
ast::{Argument, Call, Expr, Expression},
debugger::WithoutDebug,
engine::{Stack, StateWorkingSet},
PipelineData, Span, Type, Value,
CompletionSort, PipelineData, Span, Type, Value,
};
use nu_utils::IgnoreCaseExt;
use std::collections::HashMap;
@ -18,7 +18,6 @@ pub struct CustomCompletion {
stack: Stack,
decl_id: usize,
line: String,
sort_by: SortBy,
}
impl CustomCompletion {
@ -27,7 +26,6 @@ impl CustomCompletion {
stack,
decl_id,
line,
sort_by: SortBy::None,
}
}
}
@ -93,10 +91,6 @@ impl Completer for CustomCompletion {
.and_then(|val| val.as_bool().ok())
.unwrap_or(false);
if should_sort {
self.sort_by = SortBy::Ascending;
}
custom_completion_options = Some(CompletionOptions {
case_sensitive: options
.get("case_sensitive")
@ -114,6 +108,11 @@ impl Completer for CustomCompletion {
.unwrap_or(MatchAlgorithm::Prefix),
None => completion_options.match_algorithm,
},
sort: if should_sort {
CompletionSort::Alphabetical
} else {
CompletionSort::Smart
},
});
}
@ -124,12 +123,11 @@ impl Completer for CustomCompletion {
})
.unwrap_or_default();
let suggestions = if let Some(custom_completion_options) = custom_completion_options {
filter(&prefix, suggestions, &custom_completion_options)
} else {
filter(&prefix, suggestions, completion_options)
};
sort_suggestions(&String::from_utf8_lossy(&prefix), suggestions, self.sort_by)
let options = custom_completion_options
.as_ref()
.unwrap_or(completion_options);
let suggestions = filter(&prefix, suggestions, completion_options);
sort_suggestions(&String::from_utf8_lossy(&prefix), suggestions, options)
}
}

View File

@ -48,14 +48,12 @@ impl Completer for DirectoryCompletion {
.map(move |x| SemanticSuggestion {
suggestion: Suggestion {
value: x.1,
description: None,
style: x.2,
extra: None,
span: reedline::Span {
start: x.0.start - offset,
end: x.0.end - offset,
},
append_whitespace: false,
..Suggestion::default()
},
// TODO????
kind: None,

View File

@ -6,7 +6,7 @@ use nu_protocol::{
use reedline::Suggestion;
use std::path::{is_separator, Path, MAIN_SEPARATOR as SEP, MAIN_SEPARATOR_STR};
use super::{completion_common::sort_suggestions, SemanticSuggestion, SortBy};
use super::{completion_common::sort_suggestions, SemanticSuggestion};
#[derive(Clone, Default)]
pub struct DotNuCompletion {}
@ -116,14 +116,13 @@ impl Completer for DotNuCompletion {
.map(move |x| SemanticSuggestion {
suggestion: Suggestion {
value: x.1,
description: None,
style: x.2,
extra: None,
span: reedline::Span {
start: x.0.start - offset,
end: x.0.end - offset,
},
append_whitespace: true,
..Suggestion::default()
},
// TODO????
kind: None,
@ -131,6 +130,6 @@ impl Completer for DotNuCompletion {
})
.collect();
sort_suggestions(&prefix_str, output, SortBy::Ascending)
sort_suggestions(&prefix_str, output, options)
}
}

View File

@ -53,14 +53,12 @@ impl Completer for FileCompletion {
.map(move |x| SemanticSuggestion {
suggestion: Suggestion {
value: x.1,
description: None,
style: x.2,
extra: None,
span: reedline::Span {
start: x.0.start - offset,
end: x.0.end - offset,
},
append_whitespace: false,
..Suggestion::default()
},
// TODO????
kind: None,

View File

@ -1,6 +1,4 @@
use crate::completions::{
completion_common::sort_suggestions, Completer, CompletionOptions, SortBy,
};
use crate::completions::{completion_common::sort_suggestions, Completer, CompletionOptions};
use nu_protocol::{
ast::{Expr, Expression},
engine::{Stack, StateWorkingSet},
@ -51,13 +49,12 @@ impl Completer for FlagCompletion {
suggestion: Suggestion {
value: String::from_utf8_lossy(&named).to_string(),
description: Some(flag_desc.to_string()),
style: None,
extra: None,
span: reedline::Span {
start: span.start - offset,
end: span.end - offset,
},
append_whitespace: true,
..Suggestion::default()
},
// TODO????
kind: None,
@ -78,13 +75,12 @@ impl Completer for FlagCompletion {
suggestion: Suggestion {
value: String::from_utf8_lossy(&named).to_string(),
description: Some(flag_desc.to_string()),
style: None,
extra: None,
span: reedline::Span {
start: span.start - offset,
end: span.end - offset,
},
append_whitespace: true,
..Suggestion::default()
},
// TODO????
kind: None,
@ -92,7 +88,7 @@ impl Completer for FlagCompletion {
}
}
return sort_suggestions(&String::from_utf8_lossy(&prefix), output, SortBy::Ascending);
return sort_suggestions(&String::from_utf8_lossy(&prefix), output, options);
}
vec![]

View File

@ -13,7 +13,7 @@ mod variable_completions;
pub use base::{Completer, SemanticSuggestion, SuggestionKind};
pub use command_completions::CommandCompletion;
pub use completer::NuCompleter;
pub use completion_options::{CompletionOptions, MatchAlgorithm, SortBy};
pub use completion_options::{CompletionOptions, MatchAlgorithm};
pub use custom_completions::CustomCompletion;
pub use directory_completions::DirectoryCompletion;
pub use dotnu_completions::DotNuCompletion;

View File

@ -9,7 +9,7 @@ use nu_protocol::{
use reedline::Suggestion;
use std::str;
use super::{completion_common::sort_suggestions, SortBy};
use super::completion_common::sort_suggestions;
#[derive(Clone)]
pub struct VariableCompletion {
@ -72,7 +72,7 @@ impl Completer for VariableCompletion {
}
}
return sort_suggestions(&prefix_str, output, SortBy::Ascending);
return sort_suggestions(&prefix_str, output, options);
}
} else {
// No nesting provided, return all env vars
@ -85,18 +85,15 @@ impl Completer for VariableCompletion {
output.push(SemanticSuggestion {
suggestion: Suggestion {
value: env_var.0,
description: None,
style: None,
extra: None,
span: current_span,
append_whitespace: false,
..Suggestion::default()
},
kind: Some(SuggestionKind::Type(env_var.1.get_type())),
});
}
}
return sort_suggestions(&prefix_str, output, SortBy::Ascending);
return sort_suggestions(&prefix_str, output, options);
}
}
@ -120,7 +117,7 @@ impl Completer for VariableCompletion {
}
}
return sort_suggestions(&prefix_str, output, SortBy::Ascending);
return sort_suggestions(&prefix_str, output, options);
}
}
@ -142,7 +139,7 @@ impl Completer for VariableCompletion {
}
}
return sort_suggestions(&prefix_str, output, SortBy::Ascending);
return sort_suggestions(&prefix_str, output, options);
}
}
}
@ -157,11 +154,8 @@ impl Completer for VariableCompletion {
output.push(SemanticSuggestion {
suggestion: Suggestion {
value: builtin.to_string(),
description: None,
style: None,
extra: None,
span: current_span,
append_whitespace: false,
..Suggestion::default()
},
// TODO is there a way to get the VarId to get the type???
kind: None,
@ -184,11 +178,8 @@ impl Completer for VariableCompletion {
output.push(SemanticSuggestion {
suggestion: Suggestion {
value: String::from_utf8_lossy(v.0).to_string(),
description: None,
style: None,
extra: None,
span: current_span,
append_whitespace: false,
..Suggestion::default()
},
kind: Some(SuggestionKind::Type(
working_set.get_variable(*v.1).ty.clone(),
@ -215,11 +206,8 @@ impl Completer for VariableCompletion {
output.push(SemanticSuggestion {
suggestion: Suggestion {
value: String::from_utf8_lossy(v.0).to_string(),
description: None,
style: None,
extra: None,
span: current_span,
append_whitespace: false,
..Suggestion::default()
},
kind: Some(SuggestionKind::Type(
working_set.get_variable(*v.1).ty.clone(),
@ -229,7 +217,7 @@ impl Completer for VariableCompletion {
}
}
output = sort_suggestions(&prefix_str, output, SortBy::Ascending);
output = sort_suggestions(&prefix_str, output, options);
output.dedup(); // TODO: Removes only consecutive duplicates, is it intended?
@ -255,11 +243,8 @@ fn nested_suggestions(
output.push(SemanticSuggestion {
suggestion: Suggestion {
value: col.clone(),
description: None,
style: None,
extra: None,
span: current_span,
append_whitespace: false,
..Suggestion::default()
},
kind: Some(kind.clone()),
});
@ -272,11 +257,8 @@ fn nested_suggestions(
output.push(SemanticSuggestion {
suggestion: Suggestion {
value: column_name,
description: None,
style: None,
extra: None,
span: current_span,
append_whitespace: false,
..Suggestion::default()
},
kind: Some(kind.clone()),
});

View File

@ -192,7 +192,8 @@ pub fn add_plugin_file(
} else if let Some(mut plugin_path) = nu_path::config_dir() {
// Path to store plugins signatures
plugin_path.push(storage_path);
let mut plugin_path = canonicalize_with(&plugin_path, &cwd).unwrap_or(plugin_path);
let mut plugin_path =
canonicalize_with(&plugin_path, &cwd).unwrap_or(plugin_path.into());
plugin_path.push(PLUGIN_FILE);
let plugin_path = canonicalize_with(&plugin_path, &cwd).unwrap_or(plugin_path);
engine_state.plugin_path = Some(plugin_path);
@ -247,7 +248,7 @@ pub(crate) fn get_history_path(storage_path: &str, mode: HistoryFileFormat) -> O
HistoryFileFormat::PlainText => HISTORY_FILE_TXT,
HistoryFileFormat::Sqlite => HISTORY_FILE_SQLITE,
});
history_path
history_path.into()
})
}

View File

@ -1,4 +1,4 @@
use nu_engine::documentation::get_flags_section;
use nu_engine::documentation::{get_flags_section, HelpStyle};
use nu_protocol::{engine::EngineState, levenshtein_distance, Config};
use nu_utils::IgnoreCaseExt;
use reedline::{Completer, Suggestion};
@ -20,6 +20,9 @@ impl NuHelpCompleter {
fn completion_helper(&self, line: &str, pos: usize) -> Vec<Suggestion> {
let folded_line = line.to_folded_case();
let mut help_style = HelpStyle::default();
help_style.update_from_config(&self.engine_state, &self.config);
let mut commands = self
.engine_state
.get_decls_sorted(false)
@ -60,12 +63,9 @@ impl NuHelpCompleter {
let _ = write!(long_desc, "Usage:\r\n > {}\r\n", sig.call_signature());
if !sig.named.is_empty() {
long_desc.push_str(&get_flags_section(
Some(&self.engine_state),
Some(&self.config),
&sig,
|v| v.to_parsable_string(", ", &self.config),
))
long_desc.push_str(&get_flags_section(&sig, &help_style, |v| {
v.to_parsable_string(", ", &self.config)
}))
}
if !sig.required_positional.is_empty()
@ -110,13 +110,12 @@ impl NuHelpCompleter {
Suggestion {
value: decl.name().into(),
description: Some(long_desc),
style: None,
extra: Some(extra),
span: reedline::Span {
start: pos - line.len(),
end: pos,
},
append_whitespace: false,
..Suggestion::default()
}
})
.collect()

View File

@ -142,10 +142,9 @@ fn convert_to_suggestions(
vec![Suggestion {
value: text,
description,
style: None,
extra,
span,
append_whitespace: false,
..Suggestion::default()
}]
}
Value::List { vals, .. } => vals
@ -154,9 +153,6 @@ fn convert_to_suggestions(
.collect(),
_ => vec![Suggestion {
value: format!("Not a record: {value:?}"),
description: None,
style: None,
extra: None,
span: reedline::Span {
start: if only_buffer_difference {
pos - line.len()
@ -169,7 +165,7 @@ fn convert_to_suggestions(
line.len()
},
},
append_whitespace: false,
..Suggestion::default()
}],
}
}

View File

@ -22,6 +22,11 @@ impl Command for Print {
Some('n'),
)
.switch("stderr", "print to stderr instead of stdout", Some('e'))
.switch(
"raw",
"print without formatting (including binary data)",
Some('r'),
)
.category(Category::Strings)
}
@ -50,15 +55,25 @@ Since this command has no output, there is no point in piping it with other comm
let args: Vec<Value> = call.rest(engine_state, stack, 0)?;
let no_newline = call.has_flag(engine_state, stack, "no-newline")?;
let to_stderr = call.has_flag(engine_state, stack, "stderr")?;
let raw = call.has_flag(engine_state, stack, "raw")?;
// This will allow for easy printing of pipelines as well
if !args.is_empty() {
for arg in args {
arg.into_pipeline_data()
.print(engine_state, stack, no_newline, to_stderr)?;
if raw {
arg.into_pipeline_data()
.print_raw(engine_state, no_newline, to_stderr)?;
} else {
arg.into_pipeline_data()
.print(engine_state, stack, no_newline, to_stderr)?;
}
}
} else if !input.is_nothing() {
input.print(engine_state, stack, no_newline, to_stderr)?;
if raw {
input.print_raw(engine_state, no_newline, to_stderr)?;
} else {
input.print(engine_state, stack, no_newline, to_stderr)?;
}
}
Ok(PipelineData::empty())
@ -76,6 +91,11 @@ Since this command has no output, there is no point in piping it with other comm
example: r#"print (2 + 3)"#,
result: None,
},
Example {
description: "Print 'ABC' from binary data",
example: r#"0x[41 42 43] | print --raw"#,
result: None,
},
]
}
}

View File

@ -46,7 +46,10 @@ pub(crate) const VSCODE_POST_EXECUTION_MARKER_PREFIX: &str = "\x1b]633;D;";
#[allow(dead_code)]
pub(crate) const VSCODE_POST_EXECUTION_MARKER_SUFFIX: &str = "\x1b\\";
#[allow(dead_code)]
pub(crate) const VSCODE_COMMANDLINE_MARKER: &str = "\x1b]633;E\x1b\\";
//"\x1b]633;E;{}\x1b\\"
pub(crate) const VSCODE_COMMANDLINE_MARKER_PREFIX: &str = "\x1b]633;E;";
#[allow(dead_code)]
pub(crate) const VSCODE_COMMANDLINE_MARKER_SUFFIX: &str = "\x1b\\";
#[allow(dead_code)]
// "\x1b]633;P;Cwd={}\x1b\\"
pub(crate) const VSCODE_CWD_PROPERTY_MARKER_PREFIX: &str = "\x1b]633;P;Cwd=";

View File

@ -193,6 +193,29 @@ fn get_style(record: &Record, name: &str, span: Span) -> Option<Style> {
})
}
fn set_menu_style<M: MenuBuilder>(mut menu: M, style: &Value) -> M {
let span = style.span();
let Value::Record { val, .. } = &style else {
return menu;
};
if let Some(style) = get_style(val, "text", span) {
menu = menu.with_text_style(style);
}
if let Some(style) = get_style(val, "selected_text", span) {
menu = menu.with_selected_text_style(style);
}
if let Some(style) = get_style(val, "description_text", span) {
menu = menu.with_description_text_style(style);
}
if let Some(style) = get_style(val, "match_text", span) {
menu = menu.with_match_text_style(style);
}
if let Some(style) = get_style(val, "selected_match_text", span) {
menu = menu.with_selected_match_text_style(style);
}
menu
}
// Adds a columnar menu to the editor engine
pub(crate) fn add_columnar_menu(
line_editor: Reedline,
@ -231,24 +254,7 @@ pub(crate) fn add_columnar_menu(
};
}
let span = menu.style.span();
if let Value::Record { val, .. } = &menu.style {
if let Some(style) = get_style(val, "text", span) {
columnar_menu = columnar_menu.with_text_style(style);
}
if let Some(style) = get_style(val, "selected_text", span) {
columnar_menu = columnar_menu.with_selected_text_style(style);
}
if let Some(style) = get_style(val, "description_text", span) {
columnar_menu = columnar_menu.with_description_text_style(style);
}
if let Some(style) = get_style(val, "match_text", span) {
columnar_menu = columnar_menu.with_match_text_style(style);
}
if let Some(style) = get_style(val, "selected_match_text", span) {
columnar_menu = columnar_menu.with_selected_match_text_style(style);
}
}
columnar_menu = set_menu_style(columnar_menu, &menu.style);
let marker = menu.marker.to_expanded_string("", config);
columnar_menu = columnar_menu.with_marker(&marker);
@ -304,18 +310,7 @@ pub(crate) fn add_list_menu(
};
}
let span = menu.style.span();
if let Value::Record { val, .. } = &menu.style {
if let Some(style) = get_style(val, "text", span) {
list_menu = list_menu.with_text_style(style);
}
if let Some(style) = get_style(val, "selected_text", span) {
list_menu = list_menu.with_selected_text_style(style);
}
if let Some(style) = get_style(val, "description_text", span) {
list_menu = list_menu.with_description_text_style(style);
}
}
list_menu = set_menu_style(list_menu, &menu.style);
let marker = menu.marker.to_expanded_string("", &config);
list_menu = list_menu.with_marker(&marker);
@ -496,24 +491,7 @@ pub(crate) fn add_ide_menu(
};
}
let span = menu.style.span();
if let Value::Record { val, .. } = &menu.style {
if let Some(style) = get_style(val, "text", span) {
ide_menu = ide_menu.with_text_style(style);
}
if let Some(style) = get_style(val, "selected_text", span) {
ide_menu = ide_menu.with_selected_text_style(style);
}
if let Some(style) = get_style(val, "description_text", span) {
ide_menu = ide_menu.with_description_text_style(style);
}
if let Some(style) = get_style(val, "match_text", span) {
ide_menu = ide_menu.with_match_text_style(style);
}
if let Some(style) = get_style(val, "selected_match_text", span) {
ide_menu = ide_menu.with_selected_match_text_style(style);
}
}
ide_menu = set_menu_style(ide_menu, &menu.style);
let marker = menu.marker.to_expanded_string("", &config);
ide_menu = ide_menu.with_marker(&marker);
@ -601,18 +579,7 @@ pub(crate) fn add_description_menu(
};
}
let span = menu.style.span();
if let Value::Record { val, .. } = &menu.style {
if let Some(style) = get_style(val, "text", span) {
description_menu = description_menu.with_text_style(style);
}
if let Some(style) = get_style(val, "selected_text", span) {
description_menu = description_menu.with_selected_text_style(style);
}
if let Some(style) = get_style(val, "description_text", span) {
description_menu = description_menu.with_description_text_style(style);
}
}
description_menu = set_menu_style(description_menu, &menu.style);
let marker = menu.marker.to_expanded_string("", &config);
description_menu = description_menu.with_marker(&marker);

View File

@ -1,6 +1,7 @@
use crate::prompt_update::{
POST_EXECUTION_MARKER_PREFIX, POST_EXECUTION_MARKER_SUFFIX, PRE_EXECUTION_MARKER,
RESET_APPLICATION_MODE, VSCODE_CWD_PROPERTY_MARKER_PREFIX, VSCODE_CWD_PROPERTY_MARKER_SUFFIX,
RESET_APPLICATION_MODE, VSCODE_COMMANDLINE_MARKER_PREFIX, VSCODE_COMMANDLINE_MARKER_SUFFIX,
VSCODE_CWD_PROPERTY_MARKER_PREFIX, VSCODE_CWD_PROPERTY_MARKER_SUFFIX,
VSCODE_POST_EXECUTION_MARKER_PREFIX, VSCODE_POST_EXECUTION_MARKER_SUFFIX,
VSCODE_PRE_EXECUTION_MARKER,
};
@ -131,7 +132,26 @@ pub fn evaluate_repl(
run_shell_integration_osc9_9(engine_state, &mut unique_stack, use_color);
}
if shell_integration_osc633 {
run_shell_integration_osc633(engine_state, &mut unique_stack, use_color);
// escape a few things because this says so
// https://code.visualstudio.com/docs/terminal/shell-integration#_vs-code-custom-sequences-osc-633-st
let cmd_text = line_editor.current_buffer_contents().to_string();
let replaced_cmd_text = cmd_text
.chars()
.map(|c| match c {
'\n' => '\x0a',
'\r' => '\x0d',
'\x1b' => '\x1b',
_ => c,
})
.collect();
run_shell_integration_osc633(
engine_state,
&mut unique_stack,
use_color,
replaced_cmd_text,
);
}
engine_state.set_startup_time(entire_start_time.elapsed().as_nanos() as i64);
@ -452,14 +472,19 @@ fn loop_iteration(ctx: LoopContext) -> (bool, Stack, Reedline) {
let line_editor_input_time = std::time::Instant::now();
match input {
Ok(Signal::Success(s)) => {
Ok(Signal::Success(repl_cmd_line_text)) => {
let history_supports_meta = matches!(
engine_state.history_config().map(|h| h.file_format),
Some(HistoryFileFormat::Sqlite)
);
if history_supports_meta {
prepare_history_metadata(&s, hostname, engine_state, &mut line_editor);
prepare_history_metadata(
&repl_cmd_line_text,
hostname,
engine_state,
&mut line_editor,
);
}
// For pre_exec_hook
@ -470,7 +495,7 @@ fn loop_iteration(ctx: LoopContext) -> (bool, Stack, Reedline) {
if let Some(hook) = config.hooks.pre_execution.clone() {
// Set the REPL buffer to the current command for the "pre_execution" hook
let mut repl = engine_state.repl_state.lock().expect("repl state mutex");
repl.buffer = s.to_string();
repl.buffer = repl_cmd_line_text.to_string();
drop(repl);
if let Err(err) = eval_hook(
@ -531,7 +556,7 @@ fn loop_iteration(ctx: LoopContext) -> (bool, Stack, Reedline) {
// Actual command execution logic starts from here
let cmd_execution_start_time = Instant::now();
match parse_operation(s.clone(), engine_state, &stack) {
match parse_operation(repl_cmd_line_text.clone(), engine_state, &stack) {
Ok(operation) => match operation {
ReplOperation::AutoCd { cwd, target, span } => {
do_auto_cd(target, cwd, &mut stack, engine_state, span);
@ -577,7 +602,7 @@ fn loop_iteration(ctx: LoopContext) -> (bool, Stack, Reedline) {
if history_supports_meta {
if let Err(e) = fill_in_result_related_history_metadata(
&s,
&repl_cmd_line_text,
engine_state,
cmd_duration,
&mut stack,
@ -597,7 +622,12 @@ fn loop_iteration(ctx: LoopContext) -> (bool, Stack, Reedline) {
run_shell_integration_osc9_9(engine_state, &mut stack, use_color);
}
if shell_integration_osc633 {
run_shell_integration_osc633(engine_state, &mut stack, use_color);
run_shell_integration_osc633(
engine_state,
&mut stack,
use_color,
repl_cmd_line_text,
);
}
if shell_integration_reset_application_mode {
run_shell_integration_reset_application_mode();
@ -911,7 +941,12 @@ fn run_shell_integration_osc2(
// Try to abbreviate string for windows title
let maybe_abbrev_path = if let Some(p) = nu_path::home_dir() {
path.replace(&p.as_path().display().to_string(), "~")
let home_dir_str = p.as_path().display().to_string();
if path.starts_with(&home_dir_str) {
path.replacen(&home_dir_str, "~", 1)
} else {
path
}
} else {
path
};
@ -988,7 +1023,12 @@ fn run_shell_integration_osc9_9(engine_state: &EngineState, stack: &mut Stack, u
}
}
fn run_shell_integration_osc633(engine_state: &EngineState, stack: &mut Stack, use_color: bool) {
fn run_shell_integration_osc633(
engine_state: &EngineState,
stack: &mut Stack,
use_color: bool,
repl_cmd_line_text: String,
) {
#[allow(deprecated)]
if let Ok(path) = current_dir_str(engine_state, stack) {
// Supported escape sequences of Microsoft's Visual Studio Code (vscode)
@ -1008,6 +1048,27 @@ fn run_shell_integration_osc633(engine_state: &EngineState, stack: &mut Stack, u
start_time,
use_color
);
// escape a few things because this says so
// https://code.visualstudio.com/docs/terminal/shell-integration#_vs-code-custom-sequences-osc-633-st
let replaced_cmd_text: String = repl_cmd_line_text
.chars()
.map(|c| match c {
'\n' => '\x0a',
'\r' => '\x0d',
'\x1b' => '\x1b',
_ => c,
})
.collect();
//OSC 633 ; E ; <commandline> [; <nonce] ST - Explicitly set the command line with an optional nonce.
run_ansi_sequence(&format!(
"{}{}{}",
VSCODE_COMMANDLINE_MARKER_PREFIX,
replaced_cmd_text,
VSCODE_COMMANDLINE_MARKER_SUFFIX
));
}
}
}
@ -1337,20 +1398,26 @@ fn are_session_ids_in_sync() {
#[cfg(test)]
mod test_auto_cd {
use super::{do_auto_cd, parse_operation, ReplOperation};
use nu_path::AbsolutePath;
use nu_protocol::engine::{EngineState, Stack};
use std::path::Path;
use tempfile::tempdir;
/// Create a symlink. Works on both Unix and Windows.
#[cfg(any(unix, windows))]
fn symlink(original: impl AsRef<Path>, link: impl AsRef<Path>) -> std::io::Result<()> {
fn symlink(
original: impl AsRef<AbsolutePath>,
link: impl AsRef<AbsolutePath>,
) -> std::io::Result<()> {
let original = original.as_ref();
let link = link.as_ref();
#[cfg(unix)]
{
std::os::unix::fs::symlink(original, link)
}
#[cfg(windows)]
{
if original.as_ref().is_dir() {
if original.is_dir() {
std::os::windows::fs::symlink_dir(original, link)
} else {
std::os::windows::fs::symlink_file(original, link)
@ -1362,11 +1429,11 @@ mod test_auto_cd {
/// `before`, and after `input` is parsed and evaluated, PWD should be
/// changed to `after`.
#[track_caller]
fn check(before: impl AsRef<Path>, input: &str, after: impl AsRef<Path>) {
fn check(before: impl AsRef<AbsolutePath>, input: &str, after: impl AsRef<AbsolutePath>) {
// Setup EngineState and Stack.
let mut engine_state = EngineState::new();
let mut stack = Stack::new();
stack.set_cwd(before).unwrap();
stack.set_cwd(before.as_ref()).unwrap();
// Parse the input. It must be an auto-cd operation.
let op = parse_operation(input.to_string(), &engine_state, &stack).unwrap();
@ -1382,54 +1449,66 @@ mod test_auto_cd {
// don't have to be byte-wise equal (on Windows, the 8.3 filename
// conversion messes things up),
let updated_cwd = std::fs::canonicalize(updated_cwd).unwrap();
let after = std::fs::canonicalize(after).unwrap();
let after = std::fs::canonicalize(after.as_ref()).unwrap();
assert_eq!(updated_cwd, after);
}
#[test]
fn auto_cd_root() {
let tempdir = tempdir().unwrap();
let root = if cfg!(windows) { r"C:\" } else { "/" };
check(&tempdir, root, root);
let tempdir = AbsolutePath::try_new(tempdir.path()).unwrap();
let input = if cfg!(windows) { r"C:\" } else { "/" };
let root = AbsolutePath::try_new(input).unwrap();
check(tempdir, input, root);
}
#[test]
fn auto_cd_tilde() {
let tempdir = tempdir().unwrap();
let tempdir = AbsolutePath::try_new(tempdir.path()).unwrap();
let home = nu_path::home_dir().unwrap();
check(&tempdir, "~", home);
check(tempdir, "~", home);
}
#[test]
fn auto_cd_dot() {
let tempdir = tempdir().unwrap();
check(&tempdir, ".", &tempdir);
let tempdir = AbsolutePath::try_new(tempdir.path()).unwrap();
check(tempdir, ".", tempdir);
}
#[test]
fn auto_cd_double_dot() {
let tempdir = tempdir().unwrap();
let dir = tempdir.path().join("foo");
let tempdir = AbsolutePath::try_new(tempdir.path()).unwrap();
let dir = tempdir.join("foo");
std::fs::create_dir_all(&dir).unwrap();
check(dir, "..", &tempdir);
check(dir, "..", tempdir);
}
#[test]
fn auto_cd_triple_dot() {
let tempdir = tempdir().unwrap();
let dir = tempdir.path().join("foo").join("bar");
let tempdir = AbsolutePath::try_new(tempdir.path()).unwrap();
let dir = tempdir.join("foo").join("bar");
std::fs::create_dir_all(&dir).unwrap();
check(dir, "...", &tempdir);
check(dir, "...", tempdir);
}
#[test]
fn auto_cd_relative() {
let tempdir = tempdir().unwrap();
let foo = tempdir.path().join("foo");
let bar = tempdir.path().join("bar");
let tempdir = AbsolutePath::try_new(tempdir.path()).unwrap();
let foo = tempdir.join("foo");
let bar = tempdir.join("bar");
std::fs::create_dir_all(&foo).unwrap();
std::fs::create_dir_all(&bar).unwrap();
let input = if cfg!(windows) { r"..\bar" } else { "../bar" };
check(foo, input, bar);
}
@ -1437,32 +1516,35 @@ mod test_auto_cd {
#[test]
fn auto_cd_trailing_slash() {
let tempdir = tempdir().unwrap();
let dir = tempdir.path().join("foo");
std::fs::create_dir_all(&dir).unwrap();
let tempdir = AbsolutePath::try_new(tempdir.path()).unwrap();
let dir = tempdir.join("foo");
std::fs::create_dir_all(&dir).unwrap();
let input = if cfg!(windows) { r"foo\" } else { "foo/" };
check(&tempdir, input, dir);
check(tempdir, input, dir);
}
#[test]
fn auto_cd_symlink() {
let tempdir = tempdir().unwrap();
let dir = tempdir.path().join("foo");
std::fs::create_dir_all(&dir).unwrap();
let link = tempdir.path().join("link");
symlink(&dir, &link).unwrap();
let tempdir = AbsolutePath::try_new(tempdir.path()).unwrap();
let dir = tempdir.join("foo");
std::fs::create_dir_all(&dir).unwrap();
let link = tempdir.join("link");
symlink(&dir, &link).unwrap();
let input = if cfg!(windows) { r".\link" } else { "./link" };
check(&tempdir, input, link);
check(tempdir, input, link);
}
#[test]
#[should_panic(expected = "was not parsed into an auto-cd operation")]
fn auto_cd_nonexistent_directory() {
let tempdir = tempdir().unwrap();
let dir = tempdir.path().join("foo");
let tempdir = AbsolutePath::try_new(tempdir.path()).unwrap();
let dir = tempdir.join("foo");
let input = if cfg!(windows) { r"foo\" } else { "foo/" };
check(&tempdir, input, dir);
check(tempdir, input, dir);
}
}

View File

@ -321,16 +321,10 @@ mod test {
let env = engine_state.render_env_vars();
assert!(
matches!(env.get(&"FOO".to_string()), Some(&Value::String { val, .. }) if val == "foo")
);
assert!(
matches!(env.get(&"SYMBOLS".to_string()), Some(&Value::String { val, .. }) if val == symbols)
);
assert!(
matches!(env.get(&symbols.to_string()), Some(&Value::String { val, .. }) if val == "symbols")
);
assert!(env.get(&"PWD".to_string()).is_some());
assert!(matches!(env.get("FOO"), Some(&Value::String { val, .. }) if val == "foo"));
assert!(matches!(env.get("SYMBOLS"), Some(&Value::String { val, .. }) if val == symbols));
assert!(matches!(env.get(symbols), Some(&Value::String { val, .. }) if val == "symbols"));
assert!(env.contains_key("PWD"));
assert_eq!(env.len(), 4);
}
}

View File

@ -32,7 +32,6 @@ fn completer() -> NuCompleter {
fn completer_strings() -> NuCompleter {
// Create a new engine
let (dir, _, mut engine, mut stack) = new_engine();
// Add record value as example
let record = r#"def animals [] { ["cat", "dog", "eel" ] }
def my-command [animal: string@animals] { print $animal }"#;
@ -90,14 +89,12 @@ fn subcommand_completer() -> NuCompleter {
// Create a new engine
let (dir, _, mut engine, mut stack) = new_engine();
// Use fuzzy matching, because subcommands are sorted by Levenshtein distance,
// and that's not very useful with prefix matching
let commands = r#"
$env.config.completions.algorithm = "fuzzy"
def foo [] {}
def "foo bar" [] {}
def "foo abaz" [] {}
def "foo aabrr" [] {}
def "foo aabcrr" [] {}
def food [] {}
"#;
assert!(support::merge_input(commands.as_bytes(), &mut engine, &mut stack, dir).is_ok());
@ -106,6 +103,22 @@ fn subcommand_completer() -> NuCompleter {
NuCompleter::new(Arc::new(engine), Arc::new(stack))
}
/// Use fuzzy completions but sort in alphabetical order
#[fixture]
fn fuzzy_alpha_sort_completer() -> NuCompleter {
// Create a new engine
let (dir, _, mut engine, mut stack) = new_engine();
let config = r#"
$env.config.completions.algorithm = "fuzzy"
$env.config.completions.sort = "alphabetical"
"#;
assert!(support::merge_input(config.as_bytes(), &mut engine, &mut stack, dir).is_ok());
// Instantiate a new completer
NuCompleter::new(Arc::new(engine), Arc::new(stack))
}
#[test]
fn variables_dollar_sign_with_variablecompletion() {
let (_, _, engine, stack) = new_engine();
@ -123,28 +136,28 @@ fn variables_double_dash_argument_with_flagcompletion(mut completer: NuCompleter
let suggestions = completer.complete("tst --", 6);
let expected: Vec<String> = vec!["--help".into(), "--mod".into()];
// dbg!(&expected, &suggestions);
match_suggestions(expected, suggestions);
match_suggestions(&expected, &suggestions);
}
#[rstest]
fn variables_single_dash_argument_with_flagcompletion(mut completer: NuCompleter) {
let suggestions = completer.complete("tst -", 5);
let expected: Vec<String> = vec!["--help".into(), "--mod".into(), "-h".into(), "-s".into()];
match_suggestions(expected, suggestions);
match_suggestions(&expected, &suggestions);
}
#[rstest]
fn variables_command_with_commandcompletion(mut completer_strings: NuCompleter) {
let suggestions = completer_strings.complete("my-c ", 4);
let expected: Vec<String> = vec!["my-command".into()];
match_suggestions(expected, suggestions);
match_suggestions(&expected, &suggestions);
}
#[rstest]
fn variables_subcommands_with_customcompletion(mut completer_strings: NuCompleter) {
let suggestions = completer_strings.complete("my-command ", 11);
let expected: Vec<String> = vec!["cat".into(), "dog".into(), "eel".into()];
match_suggestions(expected, suggestions);
match_suggestions(&expected, &suggestions);
}
#[rstest]
@ -153,7 +166,7 @@ fn variables_customcompletion_subcommands_with_customcompletion_2(
) {
let suggestions = completer_strings.complete("my-command ", 11);
let expected: Vec<String> = vec!["cat".into(), "dog".into(), "eel".into()];
match_suggestions(expected, suggestions);
match_suggestions(&expected, &suggestions);
}
#[test]
@ -182,19 +195,19 @@ fn dotnu_completions() {
let completion_str = "source-env ".to_string();
let suggestions = completer.complete(&completion_str, completion_str.len());
match_suggestions(expected.clone(), suggestions);
match_suggestions(&expected, &suggestions);
// Test use completion
let completion_str = "use ".to_string();
let suggestions = completer.complete(&completion_str, completion_str.len());
match_suggestions(expected.clone(), suggestions);
match_suggestions(&expected, &suggestions);
// Test overlay use completion
let completion_str = "overlay use ".to_string();
let suggestions = completer.complete(&completion_str, completion_str.len());
match_suggestions(expected, suggestions);
match_suggestions(&expected, &suggestions);
}
#[test]
@ -258,8 +271,22 @@ fn file_completions() {
folder(dir.join(".hidden_folder")),
];
#[cfg(windows)]
{
let separator = '/';
let target_dir = format!("cp {dir_str}{separator}");
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);
match_suggestions(&expected_paths, &suggestions);
// Test completions for a file
let target_dir = format!("cp {}", folder(dir.join("another")));
@ -269,17 +296,91 @@ fn file_completions() {
let expected_paths: Vec<String> = vec![file(dir.join("another").join("newfile"))];
// Match the results
match_suggestions(expected_paths, suggestions);
match_suggestions(&expected_paths, &suggestions);
// Test completions for hidden files
let target_dir = format!("ls {}/.", folder(dir.join(".hidden_folder")));
let target_dir = format!("ls {}{MAIN_SEPARATOR}.", folder(dir.join(".hidden_folder")));
let suggestions = completer.complete(&target_dir, target_dir.len());
let expected_paths: Vec<String> =
vec![file(dir.join(".hidden_folder").join(".hidden_subfile"))];
#[cfg(windows)]
{
let target_dir = format!("ls {}/.", folder(dir.join(".hidden_folder")));
let slash_suggestions = completer.complete(&target_dir, target_dir.len());
let expected_slash: Vec<String> = expected_paths
.iter()
.map(|s| s.replace('\\', "/"))
.collect();
match_suggestions(&expected_slash, &slash_suggestions);
}
// Match the results
match_suggestions(expected_paths, suggestions);
match_suggestions(&expected_paths, &suggestions);
}
#[cfg(windows)]
#[test]
fn file_completions_with_mixed_separators() {
// Create a new engine
let (dir, dir_str, engine, stack) = new_dotnu_engine();
// Instantiate a new completer
let mut completer = NuCompleter::new(Arc::new(engine), Arc::new(stack));
// Create Expected values
let expected_paths: Vec<String> = vec![
file(dir.join("lib-dir1").join("bar.nu")),
file(dir.join("lib-dir1").join("baz.nu")),
file(dir.join("lib-dir1").join("xyzzy.nu")),
];
let expecetd_slash_paths: Vec<String> = expected_paths
.iter()
.map(|s| s.replace(MAIN_SEPARATOR, "/"))
.collect();
let target_dir = format!("ls {dir_str}/lib-dir1/");
let suggestions = completer.complete(&target_dir, target_dir.len());
match_suggestions(&expecetd_slash_paths, &suggestions);
let target_dir = format!("cp {dir_str}\\lib-dir1/");
let suggestions = completer.complete(&target_dir, target_dir.len());
match_suggestions(&expecetd_slash_paths, &suggestions);
let target_dir = format!("ls {dir_str}/lib-dir1\\/");
let suggestions = completer.complete(&target_dir, target_dir.len());
match_suggestions(&expecetd_slash_paths, &suggestions);
let target_dir = format!("ls {dir_str}\\lib-dir1\\/");
let suggestions = completer.complete(&target_dir, target_dir.len());
match_suggestions(&expecetd_slash_paths, &suggestions);
let target_dir = format!("ls {dir_str}\\lib-dir1\\");
let suggestions = completer.complete(&target_dir, target_dir.len());
match_suggestions(&expected_paths, &suggestions);
let target_dir = format!("ls {dir_str}/lib-dir1\\");
let suggestions = completer.complete(&target_dir, target_dir.len());
match_suggestions(&expected_paths, &suggestions);
let target_dir = format!("ls {dir_str}/lib-dir1/\\");
let suggestions = completer.complete(&target_dir, target_dir.len());
match_suggestions(&expected_paths, &suggestions);
let target_dir = format!("ls {dir_str}\\lib-dir1/\\");
let suggestions = completer.complete(&target_dir, target_dir.len());
match_suggestions(&expected_paths, &suggestions);
}
#[test]
@ -303,7 +404,7 @@ fn partial_completions() {
];
// Match the results
match_suggestions(expected_paths, suggestions);
match_suggestions(&expected_paths, &suggestions);
// Test completions for the files whose name begin with "h"
// and are present under directories whose names begin with "pa"
@ -324,7 +425,7 @@ fn partial_completions() {
];
// Match the results
match_suggestions(expected_paths, suggestions);
match_suggestions(&expected_paths, &suggestions);
// Test completion for all files under directories whose names begin with "pa"
let dir_str = folder(dir.join("pa"));
@ -345,7 +446,7 @@ fn partial_completions() {
];
// Match the results
match_suggestions(expected_paths, suggestions);
match_suggestions(&expected_paths, &suggestions);
// Test completion for a single file
let dir_str = file(dir.join("fi").join("so"));
@ -356,7 +457,7 @@ fn partial_completions() {
let expected_paths: Vec<String> = vec![file(dir.join("final_partial").join("somefile"))];
// Match the results
match_suggestions(expected_paths, suggestions);
match_suggestions(&expected_paths, &suggestions);
// Test completion where there is a sneaky `..` in the path
let dir_str = file(dir.join("par").join("..").join("fi").join("so"));
@ -392,7 +493,7 @@ fn partial_completions() {
];
// Match the results
match_suggestions(expected_paths, suggestions);
match_suggestions(&expected_paths, &suggestions);
// Test completion for all files under directories whose names begin with "pa"
let file_str = file(dir.join("partial-a").join("have"));
@ -406,7 +507,7 @@ fn partial_completions() {
];
// Match the results
match_suggestions(expected_paths, suggestions);
match_suggestions(&expected_paths, &suggestions);
// Test completion for all files under directories whose names begin with "pa"
let file_str = file(dir.join("partial-a").join("have_ext."));
@ -420,7 +521,7 @@ fn partial_completions() {
];
// Match the results
match_suggestions(expected_paths, suggestions);
match_suggestions(&expected_paths, &suggestions);
}
#[test]
@ -455,15 +556,16 @@ fn command_ls_with_filecompletion() {
".hidden_folder/".to_string(),
];
match_suggestions(expected_paths, suggestions);
match_suggestions(&expected_paths, &suggestions);
let target_dir = "ls custom_completion.";
let suggestions = completer.complete(target_dir, target_dir.len());
let expected_paths: Vec<String> = vec!["custom_completion.nu".to_string()];
match_suggestions(expected_paths, suggestions)
match_suggestions(&expected_paths, &suggestions);
}
#[test]
fn command_open_with_filecompletion() {
let (_, _, engine, stack) = new_engine();
@ -496,14 +598,14 @@ fn command_open_with_filecompletion() {
".hidden_folder/".to_string(),
];
match_suggestions(expected_paths, suggestions);
match_suggestions(&expected_paths, &suggestions);
let target_dir = "open custom_completion.";
let suggestions = completer.complete(target_dir, target_dir.len());
let expected_paths: Vec<String> = vec!["custom_completion.nu".to_string()];
match_suggestions(expected_paths, suggestions)
match_suggestions(&expected_paths, &suggestions);
}
#[test]
@ -538,7 +640,7 @@ fn command_rm_with_globcompletion() {
".hidden_folder/".to_string(),
];
match_suggestions(expected_paths, suggestions)
match_suggestions(&expected_paths, &suggestions)
}
#[test]
@ -573,7 +675,7 @@ fn command_cp_with_globcompletion() {
".hidden_folder/".to_string(),
];
match_suggestions(expected_paths, suggestions)
match_suggestions(&expected_paths, &suggestions)
}
#[test]
@ -608,7 +710,7 @@ fn command_save_with_filecompletion() {
".hidden_folder/".to_string(),
];
match_suggestions(expected_paths, suggestions)
match_suggestions(&expected_paths, &suggestions)
}
#[test]
@ -643,7 +745,7 @@ fn command_touch_with_filecompletion() {
".hidden_folder/".to_string(),
];
match_suggestions(expected_paths, suggestions)
match_suggestions(&expected_paths, &suggestions)
}
#[test]
@ -678,7 +780,7 @@ fn command_watch_with_filecompletion() {
".hidden_folder/".to_string(),
];
match_suggestions(expected_paths, suggestions)
match_suggestions(&expected_paths, &suggestions)
}
#[rstest]
@ -686,19 +788,19 @@ fn subcommand_completions(mut subcommand_completer: NuCompleter) {
let prefix = "foo br";
let suggestions = subcommand_completer.complete(prefix, prefix.len());
match_suggestions(
vec!["foo bar".to_string(), "foo aabrr".to_string()],
suggestions,
&vec!["foo bar".to_string(), "foo aabcrr".to_string()],
&suggestions,
);
let prefix = "foo b";
let suggestions = subcommand_completer.complete(prefix, prefix.len());
match_suggestions(
vec![
&vec![
"foo bar".to_string(),
"foo aabcrr".to_string(),
"foo abaz".to_string(),
"foo aabrr".to_string(),
],
suggestions,
&suggestions,
);
}
@ -724,7 +826,7 @@ fn file_completion_quoted() {
format!("`{}`", folder("test dir")),
];
match_suggestions(expected_paths, suggestions);
match_suggestions(&expected_paths, &suggestions);
let dir: PathBuf = "test dir".into();
let target_dir = format!("open '{}'", folder(dir.clone()));
@ -735,7 +837,7 @@ fn file_completion_quoted() {
format!("`{}`", file(dir.join("single quote"))),
];
match_suggestions(expected_paths, suggestions)
match_suggestions(&expected_paths, &suggestions)
}
#[test]
@ -770,7 +872,7 @@ fn flag_completions() {
];
// Match results
match_suggestions(expected, suggestions);
match_suggestions(&expected, &suggestions);
}
#[test]
@ -794,8 +896,21 @@ fn folder_with_directorycompletions() {
folder(dir.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);
match_suggestions(&expected_paths, &suggestions);
}
#[test]
@ -837,7 +952,7 @@ fn variables_completions() {
];
// Match results
match_suggestions(expected, suggestions);
match_suggestions(&expected, &suggestions);
// Test completions for $nu.h (filter)
let suggestions = completer.complete("$nu.h", 5);
@ -851,7 +966,7 @@ fn variables_completions() {
];
// Match results
match_suggestions(expected, suggestions);
match_suggestions(&expected, &suggestions);
// Test completions for $nu.os-info
let suggestions = completer.complete("$nu.os-info.", 12);
@ -863,7 +978,7 @@ fn variables_completions() {
"name".into(),
];
// Match results
match_suggestions(expected, suggestions);
match_suggestions(&expected, &suggestions);
// Test completions for custom var
let suggestions = completer.complete("$actor.", 7);
@ -873,7 +988,7 @@ fn variables_completions() {
let expected: Vec<String> = vec!["age".into(), "name".into()];
// Match results
match_suggestions(expected, suggestions);
match_suggestions(&expected, &suggestions);
// Test completions for custom var (filtering)
let suggestions = completer.complete("$actor.n", 8);
@ -883,7 +998,7 @@ fn variables_completions() {
let expected: Vec<String> = vec!["name".into()];
// Match results
match_suggestions(expected, suggestions);
match_suggestions(&expected, &suggestions);
// Test completions for $env
let suggestions = completer.complete("$env.", 5);
@ -896,7 +1011,7 @@ fn variables_completions() {
let expected: Vec<String> = vec!["PATH".into(), "PWD".into(), "TEST".into()];
// Match results
match_suggestions(expected, suggestions);
match_suggestions(&expected, &suggestions);
// Test completions for $env
let suggestions = completer.complete("$env.T", 6);
@ -906,12 +1021,12 @@ fn variables_completions() {
let expected: Vec<String> = vec!["TEST".into()];
// Match results
match_suggestions(expected, suggestions);
match_suggestions(&expected, &suggestions);
let suggestions = completer.complete("$", 1);
let expected: Vec<String> = vec!["$actor".into(), "$env".into(), "$in".into(), "$nu".into()];
match_suggestions(expected, suggestions);
match_suggestions(&expected, &suggestions);
}
#[test]
@ -930,7 +1045,7 @@ fn alias_of_command_and_flags() {
#[cfg(not(windows))]
let expected_paths: Vec<String> = vec!["test_a/".to_string(), "test_b/".to_string()];
match_suggestions(expected_paths, suggestions)
match_suggestions(&expected_paths, &suggestions)
}
#[test]
@ -949,7 +1064,7 @@ fn alias_of_basic_command() {
#[cfg(not(windows))]
let expected_paths: Vec<String> = vec!["test_a/".to_string(), "test_b/".to_string()];
match_suggestions(expected_paths, suggestions)
match_suggestions(&expected_paths, &suggestions)
}
#[test]
@ -971,7 +1086,7 @@ fn alias_of_another_alias() {
#[cfg(not(windows))]
let expected_paths: Vec<String> = vec!["test_a/".to_string(), "test_b/".to_string()];
match_suggestions(expected_paths, suggestions)
match_suggestions(&expected_paths, &suggestions)
}
fn run_external_completion(completer: &str, input: &str) -> Vec<Suggestion> {
@ -1034,35 +1149,35 @@ fn unknown_command_completion() {
".hidden_folder/".to_string(),
];
match_suggestions(expected_paths, suggestions)
match_suggestions(&expected_paths, &suggestions)
}
#[rstest]
fn flagcompletion_triggers_after_cursor(mut completer: NuCompleter) {
let suggestions = completer.complete("tst -h", 5);
let expected: Vec<String> = vec!["--help".into(), "--mod".into(), "-h".into(), "-s".into()];
match_suggestions(expected, suggestions);
match_suggestions(&expected, &suggestions);
}
#[rstest]
fn customcompletion_triggers_after_cursor(mut completer_strings: NuCompleter) {
let suggestions = completer_strings.complete("my-command c", 11);
let expected: Vec<String> = vec!["cat".into(), "dog".into(), "eel".into()];
match_suggestions(expected, suggestions);
match_suggestions(&expected, &suggestions);
}
#[rstest]
fn customcompletion_triggers_after_cursor_piped(mut completer_strings: NuCompleter) {
let suggestions = completer_strings.complete("my-command c | ls", 11);
let expected: Vec<String> = vec!["cat".into(), "dog".into(), "eel".into()];
match_suggestions(expected, suggestions);
match_suggestions(&expected, &suggestions);
}
#[rstest]
fn flagcompletion_triggers_after_cursor_piped(mut completer: NuCompleter) {
let suggestions = completer.complete("tst -h | ls", 5);
let expected: Vec<String> = vec!["--help".into(), "--mod".into(), "-h".into(), "-s".into()];
match_suggestions(expected, suggestions);
match_suggestions(&expected, &suggestions);
}
#[test]
@ -1096,77 +1211,88 @@ fn filecompletions_triggers_after_cursor() {
".hidden_folder/".to_string(),
];
match_suggestions(expected_paths, suggestions);
match_suggestions(&expected_paths, &suggestions);
}
#[rstest]
fn extern_custom_completion_positional(mut extern_completer: NuCompleter) {
let suggestions = extern_completer.complete("spam ", 5);
let expected: Vec<String> = vec!["cat".into(), "dog".into(), "eel".into()];
match_suggestions(expected, suggestions);
match_suggestions(&expected, &suggestions);
}
#[rstest]
fn extern_custom_completion_long_flag_1(mut extern_completer: NuCompleter) {
let suggestions = extern_completer.complete("spam --foo=", 11);
let expected: Vec<String> = vec!["cat".into(), "dog".into(), "eel".into()];
match_suggestions(expected, suggestions);
match_suggestions(&expected, &suggestions);
}
#[rstest]
fn extern_custom_completion_long_flag_2(mut extern_completer: NuCompleter) {
let suggestions = extern_completer.complete("spam --foo ", 11);
let expected: Vec<String> = vec!["cat".into(), "dog".into(), "eel".into()];
match_suggestions(expected, suggestions);
match_suggestions(&expected, &suggestions);
}
#[rstest]
fn extern_custom_completion_long_flag_short(mut extern_completer: NuCompleter) {
let suggestions = extern_completer.complete("spam -f ", 8);
let expected: Vec<String> = vec!["cat".into(), "dog".into(), "eel".into()];
match_suggestions(expected, suggestions);
match_suggestions(&expected, &suggestions);
}
#[rstest]
fn extern_custom_completion_short_flag(mut extern_completer: NuCompleter) {
let suggestions = extern_completer.complete("spam -b ", 8);
let expected: Vec<String> = vec!["cat".into(), "dog".into(), "eel".into()];
match_suggestions(expected, suggestions);
match_suggestions(&expected, &suggestions);
}
#[rstest]
fn extern_complete_flags(mut extern_completer: NuCompleter) {
let suggestions = extern_completer.complete("spam -", 6);
let expected: Vec<String> = vec!["--foo".into(), "-b".into(), "-f".into()];
match_suggestions(expected, suggestions);
match_suggestions(&expected, &suggestions);
}
#[rstest]
fn custom_completer_triggers_cursor_before_word(mut custom_completer: NuCompleter) {
let suggestions = custom_completer.complete("cmd foo bar", 8);
let expected: Vec<String> = vec!["cmd".into(), "foo".into(), "".into()];
match_suggestions(expected, suggestions);
match_suggestions(&expected, &suggestions);
}
#[rstest]
fn custom_completer_triggers_cursor_on_word_left_boundary(mut custom_completer: NuCompleter) {
let suggestions = custom_completer.complete("cmd foo bar", 8);
let expected: Vec<String> = vec!["cmd".into(), "foo".into(), "".into()];
match_suggestions(expected, suggestions);
match_suggestions(&expected, &suggestions);
}
#[rstest]
fn custom_completer_triggers_cursor_next_to_word(mut custom_completer: NuCompleter) {
let suggestions = custom_completer.complete("cmd foo bar", 11);
let expected: Vec<String> = vec!["cmd".into(), "foo".into(), "bar".into()];
match_suggestions(expected, suggestions);
match_suggestions(&expected, &suggestions);
}
#[rstest]
fn custom_completer_triggers_cursor_after_word(mut custom_completer: NuCompleter) {
let suggestions = custom_completer.complete("cmd foo bar ", 12);
let expected: Vec<String> = vec!["cmd".into(), "foo".into(), "bar".into(), "".into()];
match_suggestions(expected, suggestions);
match_suggestions(&expected, &suggestions);
}
#[rstest]
fn sort_fuzzy_completions_in_alphabetical_order(mut fuzzy_alpha_sort_completer: NuCompleter) {
let suggestions = fuzzy_alpha_sort_completer.complete("ls nu", 5);
// Even though "nushell" is a better match, it should come second because
// the completions should be sorted in alphabetical order
match_suggestions(
&vec!["custom_completion.nu".into(), "nushell".into()],
&suggestions,
);
}
#[ignore = "was reverted, still needs fixing"]

View File

@ -186,7 +186,7 @@ pub fn new_partial_engine() -> (AbsolutePathBuf, String, EngineState, Stack) {
}
// match a list of suggestions with the expected values
pub fn match_suggestions(expected: Vec<String>, suggestions: Vec<Suggestion>) {
pub fn match_suggestions(expected: &Vec<String>, suggestions: &Vec<Suggestion>) {
let expected_len = expected.len();
let suggestions_len = suggestions.len();
if expected_len != suggestions_len {
@ -196,13 +196,13 @@ pub fn match_suggestions(expected: Vec<String>, suggestions: Vec<Suggestion>) {
Expected: {expected:#?}\n"
)
}
assert_eq!(
expected,
suggestions
.into_iter()
.map(|it| it.value)
.collect::<Vec<_>>()
);
let suggestoins_str = suggestions
.iter()
.map(|it| it.value.clone())
.collect::<Vec<_>>();
assert_eq!(expected, &suggestoins_str);
}
// append the separator to the converted path

View File

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

View File

@ -3,21 +3,26 @@ use nu_protocol::{
engine::{EngineState, Stack},
Range, ShellError, Span, Value,
};
use std::{ops::Bound, path::PathBuf};
use std::ops::Bound;
pub fn get_init_cwd() -> PathBuf {
std::env::current_dir().unwrap_or_else(|_| {
std::env::var("PWD")
.map(Into::into)
.unwrap_or_else(|_| nu_path::home_dir().unwrap_or_default())
})
pub fn get_init_cwd() -> AbsolutePathBuf {
std::env::current_dir()
.ok()
.and_then(|path| AbsolutePathBuf::try_from(path).ok())
.or_else(|| {
std::env::var("PWD")
.ok()
.and_then(|path| AbsolutePathBuf::try_from(path).ok())
})
.or_else(nu_path::home_dir)
.expect("Failed to get current working directory")
}
pub fn get_guaranteed_cwd(engine_state: &EngineState, stack: &Stack) -> PathBuf {
pub fn get_guaranteed_cwd(engine_state: &EngineState, stack: &Stack) -> AbsolutePathBuf {
engine_state
.cwd(Some(stack))
.map(AbsolutePathBuf::into_std_path_buf)
.unwrap_or(crate::util::get_init_cwd())
.ok()
.unwrap_or_else(get_init_cwd)
}
type MakeRangeError = fn(&str, Span) -> ShellError;

View File

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

View File

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

View File

@ -70,6 +70,11 @@ impl Command for Def {
example: r#"def --wrapped my-echo [...rest] { ^echo ...$rest }; my-echo -e 'spam\tspam'"#,
result: Some(Value::test_string("spam\tspam")),
},
Example {
description: "Define a custom command with a type signature. Passing a non-int value will result in an error",
example: r#"def only_int []: int -> int { $in }; 42 | only_int"#,
result: Some(Value::test_int(42)),
},
]
}
}

View File

@ -72,7 +72,7 @@ pub fn check_example_input_and_output_types_match_command_signature(
witnessed_type_transformations
}
fn eval_pipeline_without_terminal_expression(
pub fn eval_pipeline_without_terminal_expression(
src: &str,
cwd: &std::path::Path,
engine_state: &mut Box<EngineState>,

View File

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

View File

@ -5,18 +5,18 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu-color-confi
edition = "2021"
license = "MIT"
name = "nu-color-config"
version = "0.96.1"
version = "0.97.1"
[lib]
bench = false
[dependencies]
nu-protocol = { path = "../nu-protocol", version = "0.96.1" }
nu-engine = { path = "../nu-engine", version = "0.96.1" }
nu-json = { path = "../nu-json", version = "0.96.1" }
nu-protocol = { path = "../nu-protocol", version = "0.97.1" }
nu-engine = { path = "../nu-engine", version = "0.97.1" }
nu-json = { path = "../nu-json", version = "0.97.1" }
nu-ansi-term = { workspace = true }
serde = { workspace = true, features = ["derive"] }
[dev-dependencies]
nu-test-support = { path = "../nu-test-support", version = "0.96.1" }
nu-test-support = { path = "../nu-test-support", version = "0.97.1" }

View File

@ -5,7 +5,7 @@ edition = "2021"
license = "MIT"
name = "nu-command"
repository = "https://github.com/nushell/nushell/tree/main/crates/nu-command"
version = "0.96.1"
version = "0.97.1"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@ -13,21 +13,21 @@ version = "0.96.1"
bench = false
[dependencies]
nu-cmd-base = { path = "../nu-cmd-base", version = "0.96.1" }
nu-color-config = { path = "../nu-color-config", version = "0.96.1" }
nu-engine = { path = "../nu-engine", version = "0.96.1" }
nu-glob = { path = "../nu-glob", version = "0.96.1" }
nu-json = { path = "../nu-json", version = "0.96.1" }
nu-parser = { path = "../nu-parser", version = "0.96.1" }
nu-path = { path = "../nu-path", version = "0.96.1" }
nu-pretty-hex = { path = "../nu-pretty-hex", version = "0.96.1" }
nu-protocol = { path = "../nu-protocol", version = "0.96.1" }
nu-system = { path = "../nu-system", version = "0.96.1" }
nu-table = { path = "../nu-table", version = "0.96.1" }
nu-term-grid = { path = "../nu-term-grid", version = "0.96.1" }
nu-utils = { path = "../nu-utils", version = "0.96.1" }
nu-cmd-base = { path = "../nu-cmd-base", version = "0.97.1" }
nu-color-config = { path = "../nu-color-config", version = "0.97.1" }
nu-engine = { path = "../nu-engine", version = "0.97.1" }
nu-glob = { path = "../nu-glob", version = "0.97.1" }
nu-json = { path = "../nu-json", version = "0.97.1" }
nu-parser = { path = "../nu-parser", version = "0.97.1" }
nu-path = { path = "../nu-path", version = "0.97.1" }
nu-pretty-hex = { path = "../nu-pretty-hex", version = "0.97.1" }
nu-protocol = { path = "../nu-protocol", version = "0.97.1" }
nu-system = { path = "../nu-system", version = "0.97.1" }
nu-table = { path = "../nu-table", version = "0.97.1" }
nu-term-grid = { path = "../nu-term-grid", version = "0.97.1" }
nu-utils = { path = "../nu-utils", version = "0.97.1" }
nu-ansi-term = { workspace = true }
nuon = { path = "../nuon", version = "0.96.1" }
nuon = { path = "../nuon", version = "0.97.1" }
alphanumeric-sort = { workspace = true }
base64 = { workspace = true }
@ -50,7 +50,6 @@ encoding_rs = { workspace = true }
fancy-regex = { workspace = true }
filesize = { workspace = true }
filetime = { workspace = true }
fs_extra = { workspace = true }
human-date-parser = { workspace = true }
indexmap = { workspace = true }
indicatif = { workspace = true }
@ -60,6 +59,7 @@ lscolors = { workspace = true, default-features = false, features = ["nu-ansi-te
md5 = { workspace = true }
mime = { workspace = true }
mime_guess = { workspace = true }
multipart-rs = { workspace = true }
native-tls = { workspace = true }
notify-debouncer-full = { workspace = true, default-features = false }
num-format = { workspace = true }
@ -87,7 +87,7 @@ sysinfo = { workspace = true }
tabled = { workspace = true, features = ["color"], default-features = false }
terminal_size = { workspace = true }
titlecase = { workspace = true }
toml = { workspace = true, features = ["preserve_order"]}
toml = { workspace = true, features = ["preserve_order"] }
unicode-segmentation = { workspace = true }
ureq = { workspace = true, default-features = false, features = ["charset", "gzip", "json", "native-tls"] }
url = { workspace = true }
@ -137,8 +137,8 @@ sqlite = ["rusqlite"]
trash-support = ["trash"]
[dev-dependencies]
nu-cmd-lang = { path = "../nu-cmd-lang", version = "0.96.1" }
nu-test-support = { path = "../nu-test-support", version = "0.96.1" }
nu-cmd-lang = { path = "../nu-cmd-lang", version = "0.97.1" }
nu-test-support = { path = "../nu-test-support", version = "0.97.1" }
dirs = { workspace = true }
mockito = { workspace = true, default-features = false }

View File

@ -177,11 +177,9 @@ fn run_histogram(
match v {
// parse record, and fill valid value to actual input.
Value::Record { val, .. } => {
for (c, v) in val.iter() {
if c == col_name {
if let Ok(v) = HashableValue::from_value(v.clone(), head_span) {
inputs.push(v);
}
if let Some(v) = val.get(col_name) {
if let Ok(v) = HashableValue::from_value(v.clone(), head_span) {
inputs.push(v);
}
}
}

View File

@ -150,13 +150,9 @@ fn fill(
FillAlignment::Left
};
let width = if let Some(arg) = width_arg { arg } else { 1 };
let width = width_arg.unwrap_or(1);
let character = if let Some(arg) = character_arg {
arg
} else {
" ".to_string()
};
let character = character_arg.unwrap_or_else(|| " ".to_string());
let arg = Arguments {
width,

View File

@ -379,42 +379,47 @@ fn action(input: &Value, args: &Arguments, head: Span) -> Value {
// If input is not a timestamp, try parsing it as a string
let span = input.span();
match input {
Value::String { val, .. } => {
match dateformat {
Some(dt) => match DateTime::parse_from_str(val, &dt.0) {
Ok(d) => Value::date ( d, head ),
Err(reason) => {
match NaiveDateTime::parse_from_str(val, &dt.0) {
Ok(d) => Value::date (
DateTime::from_naive_utc_and_offset(
d,
*Local::now().offset(),
),
head,
let parse_as_string = |val: &str| {
match dateformat {
Some(dt) => match DateTime::parse_from_str(val, &dt.0) {
Ok(d) => Value::date ( d, head ),
Err(reason) => {
match NaiveDateTime::parse_from_str(val, &dt.0) {
Ok(d) => Value::date (
DateTime::from_naive_utc_and_offset(
d,
*Local::now().offset(),
),
Err(_) => {
Value::error (
ShellError::CantConvert { to_type: format!("could not parse as datetime using format '{}'", dt.0), from_type: reason.to_string(), span: head, help: Some("you can use `into datetime` without a format string to enable flexible parsing".to_string()) },
head,
)
}
head,
),
Err(_) => {
Value::error (
ShellError::CantConvert { to_type: format!("could not parse as datetime using format '{}'", dt.0), from_type: reason.to_string(), span: head, help: Some("you can use `into datetime` without a format string to enable flexible parsing".to_string()) },
head,
)
}
}
},
}
},
// Tries to automatically parse the date
// (i.e. without a format string)
// and assumes the system's local timezone if none is specified
None => match parse_date_from_string(val, span) {
Ok(date) => Value::date (
date,
span,
),
Err(err) => err,
},
}
// Tries to automatically parse the date
// (i.e. without a format string)
// and assumes the system's local timezone if none is specified
None => match parse_date_from_string(val, span) {
Ok(date) => Value::date (
date,
span,
),
Err(err) => err,
},
}
};
match input {
Value::String { val, .. } => parse_as_string(val),
Value::Int { val, .. } => parse_as_string(&val.to_string()),
// Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => input.clone(),
other => Value::error(
@ -575,6 +580,24 @@ mod tests {
assert_eq!(actual, expected)
}
#[test]
fn takes_int_with_formatstring() {
let date_int = Value::test_int(1_614_434_140);
let fmt_options = Some(DatetimeFormat("%s".to_string()));
let args = Arguments {
zone_options: None,
format_options: fmt_options,
cell_paths: None,
};
let actual = action(&date_int, &args, Span::test_data());
let expected = Value::date(
DateTime::parse_from_str("2021-02-27 21:55:40 +08:00", "%Y-%m-%d %H:%M:%S %z").unwrap(),
Span::test_data(),
);
assert_eq!(actual, expected)
}
#[test]
fn takes_timestamp() {
let date_str = Value::test_string("1614434140000000000");

View File

@ -424,11 +424,7 @@ pub fn value_to_sql(value: Value) -> Result<Box<dyn rusqlite::ToSql>, ShellError
Value::Filesize { val, .. } => Box::new(val),
Value::Duration { val, .. } => Box::new(val),
Value::Date { val, .. } => Box::new(val),
Value::String { val, .. } => {
// don't store ansi escape sequences in the database
// escape single quotes
Box::new(nu_utils::strip_ansi_unlikely(&val).into_owned())
}
Value::String { val, .. } => Box::new(val),
Value::Binary { val, .. } => Box::new(val),
Value::Nothing { .. } => Box::new(rusqlite::types::Null),
val => {

View File

@ -397,6 +397,7 @@ pub fn add_shell_command_context(mut engine_state: EngineState) -> EngineState {
RandomFloat,
RandomInt,
RandomUuid,
RandomBinary
};
// Generators

View File

@ -1,6 +1,5 @@
use nu_cmd_base::util::get_init_cwd;
use nu_engine::command_prelude::*;
use nu_path::AbsolutePathBuf;
use nu_utils::filesystem::{have_permission, PermissionResult};
#[derive(Clone)]
@ -46,8 +45,8 @@ impl Command for Cd {
// user can use `cd` to recover PWD to a good state.
let cwd = engine_state
.cwd(Some(stack))
.map(AbsolutePathBuf::into_std_path_buf)
.unwrap_or(get_init_cwd());
.ok()
.unwrap_or_else(get_init_cwd);
let path_val = {
if let Some(path) = path_val {
@ -66,7 +65,7 @@ impl Command for Cd {
if let Some(oldpwd) = stack.get_env_var(engine_state, "OLDPWD") {
oldpwd.to_path()?
} else {
cwd
cwd.into()
}
} else {
// Trim whitespace from the end of path.
@ -135,7 +134,7 @@ impl Command for Cd {
result: None,
},
Example {
description: "Change to the previous working directory ($OLDPWD)",
description: r#"Change to the previous working directory (same as "cd $env.OLDPWD")"#,
example: r#"cd -"#,
result: None,
},
@ -144,6 +143,16 @@ impl Command for Cd {
example: r#"def --env gohome [] { cd ~ }"#,
result: None,
},
Example {
description: "Move two directories up in the tree (the parent directory's parent). Additional dots can be added for additional levels.",
example: r#"cd ..."#,
result: None,
},
Example {
description: "The cd command itself is often optional. Simply entering a path to a directory will cd to it.",
example: r#"/home"#,
result: None,
},
]
}
}

View File

@ -13,7 +13,7 @@ impl Command for Glob {
fn signature(&self) -> Signature {
Signature::build("glob")
.input_output_types(vec![(Type::Nothing, Type::List(Box::new(Type::String)))])
.required("glob", SyntaxShape::String, "The glob expression.")
.required("glob", SyntaxShape::OneOf(vec![SyntaxShape::String, SyntaxShape::GlobPattern]), "The glob expression.")
.named(
"depth",
SyntaxShape::Int,
@ -126,12 +126,12 @@ impl Command for Glob {
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let span = call.head;
let glob_pattern: Spanned<String> = call.req(engine_state, stack, 0)?;
let glob_pattern_input: Value = call.req(engine_state, stack, 0)?;
let glob_span = glob_pattern_input.span();
let depth = call.get_flag(engine_state, stack, "depth")?;
let no_dirs = call.has_flag(engine_state, stack, "no-dir")?;
let no_files = call.has_flag(engine_state, stack, "no-file")?;
let no_symlinks = call.has_flag(engine_state, stack, "no-symlink")?;
let paths_to_exclude: Option<Value> = call.get_flag(engine_state, stack, "exclude")?;
let (not_patterns, not_pattern_span): (Vec<String>, Span) = match paths_to_exclude {
@ -148,11 +148,22 @@ impl Command for Glob {
}
};
if glob_pattern.item.is_empty() {
let glob_pattern =
match glob_pattern_input {
Value::String { val, .. } | Value::Glob { val, .. } => val,
_ => return Err(ShellError::IncorrectValue {
msg: "Incorrect glob pattern supplied to glob. Please use string or glob only."
.to_string(),
val_span: call.head,
call_span: glob_span,
}),
};
if glob_pattern.is_empty() {
return Err(ShellError::GenericError {
error: "glob pattern must not be empty".into(),
msg: "glob pattern is empty".into(),
span: Some(glob_pattern.span),
span: Some(glob_span),
help: Some("add characters to the glob pattern".into()),
inner: vec![],
});
@ -164,13 +175,13 @@ impl Command for Glob {
usize::MAX
};
let (prefix, glob) = match WaxGlob::new(&glob_pattern.item) {
let (prefix, glob) = match WaxGlob::new(&glob_pattern) {
Ok(p) => p.partition(),
Err(e) => {
return Err(ShellError::GenericError {
error: "error with glob pattern".into(),
msg: format!("{e}"),
span: Some(glob_pattern.span),
span: Some(glob_span),
help: None,
inner: vec![],
})
@ -189,7 +200,7 @@ impl Command for Glob {
return Err(ShellError::GenericError {
error: "error in canonicalize".into(),
msg: format!("{e}"),
span: Some(glob_pattern.span),
span: Some(glob_span),
help: None,
inner: vec![],
})

View File

@ -5,7 +5,7 @@ use nu_engine::glob_from;
#[allow(deprecated)]
use nu_engine::{command_prelude::*, env::current_dir};
use nu_glob::MatchOptions;
use nu_path::expand_to_real_path;
use nu_path::{expand_path_with, expand_to_real_path};
use nu_protocol::{DataSource, NuGlob, PipelineMetadata, Signals};
use pathdiff::diff_paths;
@ -412,6 +412,7 @@ fn ls_for_one_pattern(
du,
&signals,
use_mime_type,
args.full_paths,
);
match entry {
Ok(value) => Some(value),
@ -522,6 +523,7 @@ pub(crate) fn dir_entry_dict(
du: bool,
signals: &Signals,
use_mime_type: bool,
full_symlink_target: bool,
) -> Result<Value, ShellError> {
#[cfg(windows)]
if metadata.is_none() {
@ -551,7 +553,23 @@ pub(crate) fn dir_entry_dict(
"target",
if md.file_type().is_symlink() {
if let Ok(path_to_link) = filename.read_link() {
Value::string(path_to_link.to_string_lossy(), span)
// Actually `filename` should always have a parent because it's a symlink.
// But for safety, we check `filename.parent().is_some()` first.
if full_symlink_target && filename.parent().is_some() {
Value::string(
expand_path_with(
path_to_link,
filename
.parent()
.expect("already check the filename have a parent"),
true,
)
.to_string_lossy(),
span,
)
} else {
Value::string(path_to_link.to_string_lossy(), span)
}
} else {
Value::string("Could not obtain target file's path", span)
}

View File

@ -146,11 +146,19 @@ impl Command for Open {
}
};
let content_type = if raw {
path.extension()
.map(|ext| ext.to_string_lossy().to_string())
.and_then(|ref s| detect_content_type(s))
} else {
None
};
let stream = PipelineData::ByteStream(
ByteStream::file(file, call_span, engine_state.signals().clone()),
Some(PipelineMetadata {
data_source: DataSource::FilePath(path.to_path_buf()),
content_type: None,
content_type,
}),
);
@ -268,3 +276,22 @@ fn extract_extensions(filename: &str) -> Vec<String> {
extensions
}
fn detect_content_type(extension: &str) -> Option<String> {
// This will allow the overriding of metadata to be consistent with
// the content type
match extension {
// Per RFC-9512, application/yaml should be used
"yaml" | "yml" => Some("application/yaml".to_string()),
_ => mime_guess::from_ext(extension)
.first()
.map(|mime| mime.to_string()),
}
}
#[cfg(test)]
mod test {
#[test]
fn test_content_type() {}
}

View File

@ -135,12 +135,9 @@ fn rm(
let home: Option<String> = nu_path::home_dir().map(|path| {
{
if path.exists() {
match nu_path::canonicalize_with(&path, &currentdir_path) {
Ok(canon_path) => canon_path,
Err(_) => path,
}
nu_path::canonicalize_with(&path, &currentdir_path).unwrap_or(path.into())
} else {
path
path.into()
}
}
.to_string_lossy()

View File

@ -121,9 +121,11 @@ impl Command for Save {
} else {
match stderr {
ChildPipe::Pipe(mut pipe) => {
io::copy(&mut pipe, &mut io::sink())
io::copy(&mut pipe, &mut io::stderr())
}
ChildPipe::Tee(mut tee) => {
io::copy(&mut tee, &mut io::stderr())
}
ChildPipe::Tee(mut tee) => io::copy(&mut tee, &mut io::sink()),
}
.err_span(span)?;
}

View File

@ -179,11 +179,6 @@ impl Command for Touch {
example: "touch -m fixture.json",
result: None,
},
Example {
description: "Changes the last modified time of files a, b and c to a date",
example: r#"touch -m -d "yesterday" a b c"#,
result: None,
},
Example {
description: r#"Changes the last modified time of file d and e to "fixture.json"'s last modified time"#,
example: r#"touch -m -r fixture.json d e"#,

View File

@ -86,17 +86,22 @@ impl Command for UCp {
},
Example {
description: "Copy only if source file is newer than target file",
example: "cp -u a b",
example: "cp -u myfile newfile",
result: None,
},
Example {
description: "Copy file preserving mode and timestamps attributes",
example: "cp --preserve [ mode timestamps ] a b",
example: "cp --preserve [ mode timestamps ] myfile newfile",
result: None,
},
Example {
description: "Copy file erasing all attributes",
example: "cp --preserve [] a b",
example: "cp --preserve [] myfile newfile",
result: None,
},
Example {
description: "Copy file to a directory three levels above its current location",
example: "cp myfile ....",
result: None,
},
]
@ -235,7 +240,7 @@ impl Command for UCp {
for (sources, need_expand_tilde) in sources.iter_mut() {
for src in sources.iter_mut() {
if !src.is_absolute() {
*src = nu_path::expand_path_with(&src, &cwd, *need_expand_tilde);
*src = nu_path::expand_path_with(&*src, &cwd, *need_expand_tilde);
}
}
}

View File

@ -30,11 +30,21 @@ impl Command for UMv {
example: "mv test.txt my/subdirectory",
result: None,
},
Example {
description: "Move only if source file is newer than target file",
example: "mv -u new/test.txt old/",
result: None,
},
Example {
description: "Move many files into a directory",
example: "mv *.txt my/subdirectory",
result: None,
},
Example {
description: r#"Move a file into the "my" directory two levels up in the directory tree"#,
example: "mv test.txt .../my/",
result: None,
},
]
}
@ -49,6 +59,11 @@ impl Command for UMv {
.switch("verbose", "explain what is being done.", Some('v'))
.switch("progress", "display a progress bar", Some('p'))
.switch("interactive", "prompt before overwriting", Some('i'))
.switch(
"update",
"move and overwrite only when the SOURCE file is newer than the destination file or when the destination file is missing",
Some('u')
)
.switch("no-clobber", "do not overwrite an existing file", Some('n'))
.rest(
"paths",
@ -77,6 +92,11 @@ impl Command for UMv {
} else {
uu_mv::OverwriteMode::Force
};
let update = if call.has_flag(engine_state, stack, "update")? {
UpdateMode::ReplaceIfOlder
} else {
UpdateMode::ReplaceAll
};
#[allow(deprecated)]
let cwd = current_dir(engine_state, stack)?;
@ -141,7 +161,7 @@ impl Command for UMv {
for (files, need_expand_tilde) in files.iter_mut() {
for src in files.iter_mut() {
if !src.is_absolute() {
*src = nu_path::expand_path_with(&src, &cwd, *need_expand_tilde);
*src = nu_path::expand_path_with(&*src, &cwd, *need_expand_tilde);
}
}
}
@ -164,7 +184,7 @@ impl Command for UMv {
verbose,
suffix: String::from("~"),
backup: BackupMode::NoBackup,
update: UpdateMode::ReplaceAll,
update,
target_dir: None,
no_target_dir: false,
strip_slashes: false,

View File

@ -27,7 +27,7 @@ impl Command for Default {
}
fn usage(&self) -> &str {
"Sets a default row's column if missing."
"Sets a default value if a row's column is missing or null."
}
fn run(
@ -66,6 +66,20 @@ impl Command for Default {
Span::test_data(),
)),
},
Example {
description: r#"Replace the missing value in the "a" column of a list"#,
example: "[{a:1 b:2} {b:1}] | default 'N/A' a",
result: Some(Value::test_list(vec![
Value::test_record(record! {
"a" => Value::test_int(1),
"b" => Value::test_int(2),
}),
Value::test_record(record! {
"a" => Value::test_string("N/A"),
"b" => Value::test_int(1),
}),
])),
},
]
}
}
@ -88,19 +102,13 @@ fn default(
val: ref mut record,
..
} => {
let mut found = false;
for (col, val) in record.to_mut().iter_mut() {
if *col == column.item {
found = true;
if matches!(val, Value::Nothing { .. }) {
*val = value.clone();
}
let record = record.to_mut();
if let Some(val) = record.get_mut(&column.item) {
if matches!(val, Value::Nothing { .. }) {
*val = value.clone();
}
}
if !found {
record.to_mut().push(column.item.clone(), value.clone());
} else {
record.push(column.item.clone(), value.clone());
}
item

View File

@ -120,8 +120,7 @@ impl Command for Reduce {
engine_state.signals().check(head)?;
acc = closure
.add_arg(value)
.add_arg(acc)
.run_with_input(PipelineData::Empty)?
.run_with_value(acc)?
.into_value(head)?;
}

View File

@ -1,7 +1,7 @@
use std::io::{BufRead, Cursor};
use nu_engine::command_prelude::*;
use nu_protocol::{ListStream, PipelineMetadata, Signals};
use nu_protocol::{ListStream, Signals};
#[derive(Clone)]
pub struct FromJson;
@ -83,7 +83,7 @@ impl Command for FromJson {
strict,
engine_state.signals().clone(),
),
update_metadata(metadata),
metadata,
))
}
PipelineData::ByteStream(stream, metadata)
@ -92,7 +92,7 @@ impl Command for FromJson {
if let Some(reader) = stream.reader() {
Ok(PipelineData::ListStream(
read_json_lines(reader, span, strict, Signals::empty()),
update_metadata(metadata),
metadata,
))
} else {
Ok(PipelineData::Empty)
@ -115,10 +115,10 @@ impl Command for FromJson {
if strict {
Ok(convert_string_to_value_strict(&string_input, span)?
.into_pipeline_data_with_metadata(update_metadata(metadata)))
.into_pipeline_data_with_metadata(metadata))
} else {
Ok(convert_string_to_value(&string_input, span)?
.into_pipeline_data_with_metadata(update_metadata(metadata)))
.into_pipeline_data_with_metadata(metadata))
}
}
}
@ -265,14 +265,6 @@ fn convert_string_to_value_strict(string_input: &str, span: Span) -> Result<Valu
}
}
fn update_metadata(metadata: Option<PipelineMetadata>) -> Option<PipelineMetadata> {
metadata
.map(|md| md.with_content_type(Some("application/json".into())))
.or_else(|| {
Some(PipelineMetadata::default().with_content_type(Some("application/json".into())))
})
}
#[cfg(test)]
mod test {
use super::*;

View File

@ -4,6 +4,8 @@ use crate::formats::to::delimited::to_delimited_data;
use nu_engine::command_prelude::*;
use nu_protocol::Config;
use super::delimited::ToDelimitedDataArgs;
#[derive(Clone)]
pub struct ToCsv;
@ -116,17 +118,62 @@ fn to_csv(
},
};
to_delimited_data(noheaders, sep, columns, "CSV", input, head, config)
to_delimited_data(
ToDelimitedDataArgs {
noheaders,
separator: sep,
columns,
format_name: "CSV",
input,
head,
content_type: Some(mime::TEXT_CSV.to_string()),
},
config,
)
}
#[cfg(test)]
mod test {
use nu_cmd_lang::eval_pipeline_without_terminal_expression;
use crate::Metadata;
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(ToCsv {})
}
#[test]
fn test_content_type_metadata() {
let mut engine_state = Box::new(EngineState::new());
let delta = {
// Base functions that are needed for testing
// Try to keep this working set small to keep tests running as fast as possible
let mut working_set = StateWorkingSet::new(&engine_state);
working_set.add_decl(Box::new(ToCsv {}));
working_set.add_decl(Box::new(Metadata {}));
working_set.render()
};
engine_state
.merge_delta(delta)
.expect("Error merging delta");
let cmd = "{a: 1 b: 2} | to csv | metadata | get content_type";
let result = eval_pipeline_without_terminal_expression(
cmd,
std::env::temp_dir().as_ref(),
&mut engine_state,
);
assert_eq!(
Value::test_record(record!("content_type" => Value::test_string("text/csv"))),
result.expect("There should be a result")
);
}
}

View File

@ -69,18 +69,36 @@ fn make_cant_convert_error(value: &Value, format_name: &'static str) -> ShellErr
}
}
pub struct ToDelimitedDataArgs {
pub noheaders: bool,
pub separator: Spanned<char>,
pub columns: Option<Vec<String>>,
pub format_name: &'static str,
pub input: PipelineData,
pub head: Span,
pub content_type: Option<String>,
}
pub fn to_delimited_data(
noheaders: bool,
separator: Spanned<char>,
columns: Option<Vec<String>>,
format_name: &'static str,
input: PipelineData,
head: Span,
ToDelimitedDataArgs {
noheaders,
separator,
columns,
format_name,
input,
head,
content_type,
}: ToDelimitedDataArgs,
config: Arc<Config>,
) -> Result<PipelineData, ShellError> {
let mut input = input;
let span = input.span().unwrap_or(head);
let metadata = input.metadata();
let metadata = Some(
input
.metadata()
.unwrap_or_default()
.with_content_type(content_type),
);
let separator = u8::try_from(separator.item).map_err(|_| ShellError::IncorrectValue {
msg: "separator must be an ASCII character".into(),

View File

@ -64,7 +64,7 @@ impl Command for ToJson {
let res = Value::string(serde_json_string, span);
let metadata = PipelineMetadata {
data_source: nu_protocol::DataSource::None,
content_type: Some("application/json".to_string()),
content_type: Some(mime::APPLICATION_JSON.to_string()),
};
Ok(PipelineData::Value(res, Some(metadata)))
}
@ -159,6 +159,10 @@ fn json_list(input: &[Value]) -> Result<Vec<nu_json::Value>, ShellError> {
#[cfg(test)]
mod test {
use nu_cmd_lang::eval_pipeline_without_terminal_expression;
use crate::Metadata;
use super::*;
#[test]
@ -167,4 +171,34 @@ mod test {
test_examples(ToJson {})
}
#[test]
fn test_content_type_metadata() {
let mut engine_state = Box::new(EngineState::new());
let delta = {
// Base functions that are needed for testing
// Try to keep this working set small to keep tests running as fast as possible
let mut working_set = StateWorkingSet::new(&engine_state);
working_set.add_decl(Box::new(ToJson {}));
working_set.add_decl(Box::new(Metadata {}));
working_set.render()
};
engine_state
.merge_delta(delta)
.expect("Error merging delta");
let cmd = "{a: 1 b: 2} | to json | metadata | get content_type";
let result = eval_pipeline_without_terminal_expression(
cmd,
std::env::temp_dir().as_ref(),
&mut engine_state,
);
assert_eq!(
Value::test_record(record!("content_type" => Value::test_string("application/json"))),
result.expect("There should be a result")
);
}
}

View File

@ -82,6 +82,12 @@ fn to_md(
config: &Config,
head: Span,
) -> Result<PipelineData, ShellError> {
// text/markdown became a valid mimetype with rfc7763
let metadata = input
.metadata()
.unwrap_or_default()
.with_content_type(Some("text/markdown".into()));
let (grouped_input, single_list) = group_by(input, head, config);
if per_element || single_list {
return Ok(Value::string(
@ -95,9 +101,10 @@ fn to_md(
.join(""),
head,
)
.into_pipeline_data());
.into_pipeline_data_with_metadata(Some(metadata)));
}
Ok(Value::string(table(grouped_input, pretty, config), head).into_pipeline_data())
Ok(Value::string(table(grouped_input, pretty, config), head)
.into_pipeline_data_with_metadata(Some(metadata)))
}
fn fragment(input: Value, pretty: bool, config: &Config) -> String {
@ -328,7 +335,10 @@ fn get_padded_string(text: String, desired_length: usize, padding_character: cha
#[cfg(test)]
mod tests {
use crate::Metadata;
use super::*;
use nu_cmd_lang::eval_pipeline_without_terminal_expression;
use nu_protocol::{record, Config, IntoPipelineData, Value};
fn one(string: &str) -> String {
@ -453,4 +463,35 @@ mod tests {
"#)
);
}
#[test]
fn test_content_type_metadata() {
let mut engine_state = Box::new(EngineState::new());
let state_delta = {
// Base functions that are needed for testing
// Try to keep this working set small to keep tests running as fast as possible
let mut working_set = StateWorkingSet::new(&engine_state);
working_set.add_decl(Box::new(ToMd {}));
working_set.add_decl(Box::new(Metadata {}));
working_set.render()
};
let delta = state_delta;
engine_state
.merge_delta(delta)
.expect("Error merging delta");
let cmd = "{a: 1 b: 2} | to md | metadata | get content_type";
let result = eval_pipeline_without_terminal_expression(
cmd,
std::env::temp_dir().as_ref(),
&mut engine_state,
);
assert_eq!(
Value::test_record(record!("content_type" => Value::test_string("text/markdown"))),
result.expect("There should be a result")
);
}
}

View File

@ -74,13 +74,18 @@ MessagePack: https://msgpack.org/
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let metadata = input
.metadata()
.unwrap_or_default()
.with_content_type(Some("application/x-msgpack".into()));
let value_span = input.span().unwrap_or(call.head);
let value = input.into_value(value_span)?;
let mut out = vec![];
write_value(&mut out, &value, 0)?;
Ok(Value::binary(out, call.head).into_pipeline_data())
Ok(Value::binary(out, call.head).into_pipeline_data_with_metadata(Some(metadata)))
}
}
@ -268,6 +273,10 @@ where
#[cfg(test)]
mod test {
use nu_cmd_lang::eval_pipeline_without_terminal_expression;
use crate::Metadata;
use super::*;
#[test]
@ -276,4 +285,36 @@ mod test {
test_examples(ToMsgpack {})
}
#[test]
fn test_content_type_metadata() {
let mut engine_state = Box::new(EngineState::new());
let delta = {
// Base functions that are needed for testing
// Try to keep this working set small to keep tests running as fast as possible
let mut working_set = StateWorkingSet::new(&engine_state);
working_set.add_decl(Box::new(ToMsgpack {}));
working_set.add_decl(Box::new(Metadata {}));
working_set.render()
};
engine_state
.merge_delta(delta)
.expect("Error merging delta");
let cmd = "{a: 1 b: 2} | to msgpack | metadata | get content_type";
let result = eval_pipeline_without_terminal_expression(
cmd,
std::env::temp_dir().as_ref(),
&mut engine_state,
);
assert_eq!(
Value::test_record(
record!("content_type" => Value::test_string("application/x-msgpack"))
),
result.expect("There should be a result")
);
}
}

View File

@ -42,6 +42,11 @@ impl Command for ToNuon {
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let metadata = input
.metadata()
.unwrap_or_default()
.with_content_type(Some("application/x-nuon".into()));
let style = if call.has_flag(engine_state, stack, "raw")? {
nuon::ToStyle::Raw
} else if let Some(t) = call.get_flag(engine_state, stack, "tabs")? {
@ -56,9 +61,8 @@ impl Command for ToNuon {
let value = input.into_value(span)?;
match nuon::to_nuon(&value, style, Some(span)) {
Ok(serde_nuon_string) => {
Ok(Value::string(serde_nuon_string, span).into_pipeline_data())
}
Ok(serde_nuon_string) => Ok(Value::string(serde_nuon_string, span)
.into_pipeline_data_with_metadata(Some(metadata))),
_ => Ok(Value::error(
ShellError::CantConvert {
to_type: "NUON".into(),
@ -68,7 +72,7 @@ impl Command for ToNuon {
},
span,
)
.into_pipeline_data()),
.into_pipeline_data_with_metadata(Some(metadata))),
}
}
@ -100,10 +104,45 @@ impl Command for ToNuon {
#[cfg(test)]
mod test {
use super::*;
use nu_cmd_lang::eval_pipeline_without_terminal_expression;
use crate::Metadata;
#[test]
fn test_examples() {
use super::ToNuon;
use crate::test_examples;
test_examples(ToNuon {})
}
#[test]
fn test_content_type_metadata() {
let mut engine_state = Box::new(EngineState::new());
let delta = {
// Base functions that are needed for testing
// Try to keep this working set small to keep tests running as fast as possible
let mut working_set = StateWorkingSet::new(&engine_state);
working_set.add_decl(Box::new(ToNuon {}));
working_set.add_decl(Box::new(Metadata {}));
working_set.render()
};
engine_state
.merge_delta(delta)
.expect("Error merging delta");
let cmd = "{a: 1 b: 2} | to nuon | metadata | get content_type";
let result = eval_pipeline_without_terminal_expression(
cmd,
std::env::temp_dir().as_ref(),
&mut engine_state,
);
assert_eq!(
Value::test_record(record!("content_type" => Value::test_string("application/x-nuon"))),
result.expect("There should be a result")
);
}
}

View File

@ -134,14 +134,18 @@ fn local_into_string(value: Value, separator: &str, config: &Config) -> String {
fn update_metadata(metadata: Option<PipelineMetadata>) -> Option<PipelineMetadata> {
metadata
.map(|md| md.with_content_type(Some("text/plain".to_string())))
.map(|md| md.with_content_type(Some(mime::TEXT_PLAIN.to_string())))
.or_else(|| {
Some(PipelineMetadata::default().with_content_type(Some("text/plain".to_string())))
Some(PipelineMetadata::default().with_content_type(Some(mime::TEXT_PLAIN.to_string())))
})
}
#[cfg(test)]
mod test {
use nu_cmd_lang::eval_pipeline_without_terminal_expression;
use crate::Metadata;
use super::*;
#[test]
@ -150,4 +154,34 @@ mod test {
test_examples(ToText {})
}
#[test]
fn test_content_type_metadata() {
let mut engine_state = Box::new(EngineState::new());
let delta = {
// Base functions that are needed for testing
// Try to keep this working set small to keep tests running as fast as possible
let mut working_set = StateWorkingSet::new(&engine_state);
working_set.add_decl(Box::new(ToText {}));
working_set.add_decl(Box::new(Metadata {}));
working_set.render()
};
engine_state
.merge_delta(delta)
.expect("Error merging delta");
let cmd = "{a: 1 b: 2} | to text | metadata | get content_type";
let result = eval_pipeline_without_terminal_expression(
cmd,
std::env::temp_dir().as_ref(),
&mut engine_state,
);
assert_eq!(
Value::test_record(record!("content_type" => Value::test_string("text/plain"))),
result.expect("There should be a result")
);
}
}

View File

@ -1,6 +1,6 @@
use chrono::{DateTime, Datelike, FixedOffset, Timelike};
use nu_engine::command_prelude::*;
use nu_protocol::ast::PathMember;
use nu_protocol::{ast::PathMember, PipelineMetadata};
#[derive(Clone)]
pub struct ToToml;
@ -100,9 +100,18 @@ fn toml_into_pipeline_data(
toml_value: &toml::Value,
value_type: Type,
span: Span,
metadata: Option<PipelineMetadata>,
) -> Result<PipelineData, ShellError> {
let new_md = Some(
metadata
.unwrap_or_default()
.with_content_type(Some("text/x-toml".into())),
);
match toml::to_string_pretty(&toml_value) {
Ok(serde_toml_string) => Ok(Value::string(serde_toml_string, span).into_pipeline_data()),
Ok(serde_toml_string) => {
Ok(Value::string(serde_toml_string, span).into_pipeline_data_with_metadata(new_md))
}
_ => Ok(Value::error(
ShellError::CantConvert {
to_type: "TOML".into(),
@ -112,7 +121,7 @@ fn toml_into_pipeline_data(
},
span,
)
.into_pipeline_data()),
.into_pipeline_data_with_metadata(new_md)),
}
}
@ -139,6 +148,7 @@ fn to_toml(
input: PipelineData,
span: Span,
) -> Result<PipelineData, ShellError> {
let metadata = input.metadata();
let value = input.into_value(span)?;
let toml_value = value_to_toml_value(engine_state, &value, span)?;
@ -148,10 +158,11 @@ fn to_toml(
vec.iter().next().expect("this should never trigger"),
value.get_type(),
span,
metadata,
),
_ => toml_into_pipeline_data(&toml_value, value.get_type(), span),
_ => toml_into_pipeline_data(&toml_value, value.get_type(), span, metadata),
},
_ => toml_into_pipeline_data(&toml_value, value.get_type(), span),
_ => toml_into_pipeline_data(&toml_value, value.get_type(), span, metadata),
}
}

View File

@ -4,6 +4,8 @@ use crate::formats::to::delimited::to_delimited_data;
use nu_engine::command_prelude::*;
use nu_protocol::Config;
use super::delimited::ToDelimitedDataArgs;
#[derive(Clone)]
pub struct ToTsv;
@ -82,11 +84,26 @@ fn to_tsv(
item: '\t',
span: head,
};
to_delimited_data(noheaders, sep, columns, "TSV", input, head, config)
to_delimited_data(
ToDelimitedDataArgs {
noheaders,
separator: sep,
columns,
format_name: "TSV",
input,
head,
content_type: Some(mime::TEXT_TAB_SEPARATED_VALUES.to_string()),
},
config,
)
}
#[cfg(test)]
mod test {
use nu_cmd_lang::eval_pipeline_without_terminal_expression;
use crate::Metadata;
use super::*;
#[test]
@ -95,4 +112,36 @@ mod test {
test_examples(ToTsv {})
}
#[test]
fn test_content_type_metadata() {
let mut engine_state = Box::new(EngineState::new());
let delta = {
// Base functions that are needed for testing
// Try to keep this working set small to keep tests running as fast as possible
let mut working_set = StateWorkingSet::new(&engine_state);
working_set.add_decl(Box::new(ToTsv {}));
working_set.add_decl(Box::new(Metadata {}));
working_set.render()
};
engine_state
.merge_delta(delta)
.expect("Error merging delta");
let cmd = "{a: 1 b: 2} | to tsv | metadata | get content_type";
let result = eval_pipeline_without_terminal_expression(
cmd,
std::env::temp_dir().as_ref(),
&mut engine_state,
);
assert_eq!(
Value::test_record(
record!("content_type" => Value::test_string("text/tab-separated-values"))
),
result.expect("There should be a result")
);
}
}

View File

@ -132,6 +132,10 @@ impl Job {
}
fn run(mut self, input: PipelineData, head: Span) -> Result<PipelineData, ShellError> {
let metadata = input
.metadata()
.unwrap_or_default()
.with_content_type(Some("application/xml".into()));
let value = input.into_value(head)?;
self.write_xml_entry(value, true).and_then(|_| {
@ -141,7 +145,7 @@ impl Job {
} else {
return Err(ShellError::NonUtf8 { span: head });
};
Ok(Value::string(s, head).into_pipeline_data())
Ok(Value::string(s, head).into_pipeline_data_with_metadata(Some(metadata)))
})
}
@ -508,6 +512,10 @@ impl Job {
#[cfg(test)]
mod test {
use nu_cmd_lang::eval_pipeline_without_terminal_expression;
use crate::Metadata;
use super::*;
#[test]
@ -516,4 +524,34 @@ mod test {
test_examples(ToXml {})
}
#[test]
fn test_content_type_metadata() {
let mut engine_state = Box::new(EngineState::new());
let delta = {
// Base functions that are needed for testing
// Try to keep this working set small to keep tests running as fast as possible
let mut working_set = StateWorkingSet::new(&engine_state);
working_set.add_decl(Box::new(ToXml {}));
working_set.add_decl(Box::new(Metadata {}));
working_set.render()
};
engine_state
.merge_delta(delta)
.expect("Error merging delta");
let cmd = "{tag: note attributes: {} content : [{tag: remember attributes: {} content : [{tag: null attributes: null content : Event}]}]} | to xml | metadata | get content_type";
let result = eval_pipeline_without_terminal_expression(
cmd,
std::env::temp_dir().as_ref(),
&mut engine_state,
);
assert_eq!(
Value::test_record(record!("content_type" => Value::test_string("application/xml"))),
result.expect("There should be a result")
);
}
}

View File

@ -95,11 +95,19 @@ pub fn value_to_yaml_value(v: &Value) -> Result<serde_yaml::Value, ShellError> {
}
fn to_yaml(input: PipelineData, head: Span) -> Result<PipelineData, ShellError> {
let metadata = input
.metadata()
.unwrap_or_default()
// Per RFC-9512, application/yaml should be used
.with_content_type(Some("application/yaml".into()));
let value = input.into_value(head)?;
let yaml_value = value_to_yaml_value(&value)?;
match serde_yaml::to_string(&yaml_value) {
Ok(serde_yaml_string) => Ok(Value::string(serde_yaml_string, head).into_pipeline_data()),
Ok(serde_yaml_string) => {
Ok(Value::string(serde_yaml_string, head)
.into_pipeline_data_with_metadata(Some(metadata)))
}
_ => Ok(Value::error(
ShellError::CantConvert {
to_type: "YAML".into(),
@ -109,12 +117,16 @@ fn to_yaml(input: PipelineData, head: Span) -> Result<PipelineData, ShellError>
},
head,
)
.into_pipeline_data()),
.into_pipeline_data_with_metadata(Some(metadata))),
}
}
#[cfg(test)]
mod test {
use nu_cmd_lang::eval_pipeline_without_terminal_expression;
use crate::Metadata;
use super::*;
#[test]
@ -123,4 +135,34 @@ mod test {
test_examples(ToYaml {})
}
#[test]
fn test_content_type_metadata() {
let mut engine_state = Box::new(EngineState::new());
let delta = {
// Base functions that are needed for testing
// Try to keep this working set small to keep tests running as fast as possible
let mut working_set = StateWorkingSet::new(&engine_state);
working_set.add_decl(Box::new(ToYaml {}));
working_set.add_decl(Box::new(Metadata {}));
working_set.render()
};
engine_state
.merge_delta(delta)
.expect("Error merging delta");
let cmd = "{a: 1 b: 2} | to yaml | metadata | get content_type";
let result = eval_pipeline_without_terminal_expression(
cmd,
std::env::temp_dir().as_ref(),
&mut engine_state,
);
assert_eq!(
Value::test_record(record!("content_type" => Value::test_string("application/yaml"))),
result.expect("There should be a result")
);
}
}

View File

@ -34,6 +34,10 @@ impl Command for SubCommand {
vec!["absolute", "modulus", "positive", "distance"]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
engine_state: &EngineState,
@ -45,6 +49,19 @@ impl Command for SubCommand {
input.map(move |value| abs_helper(value, head), engine_state.signals())
}
fn run_const(
&self,
working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
input.map(
move |value| abs_helper(value, head),
working_set.permanent().signals(),
)
}
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Compute absolute value of each number in a list of numbers",

View File

@ -38,6 +38,10 @@ impl Command for SubCommand {
vec!["average", "mean", "statistics"]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
_engine_state: &EngineState,
@ -48,6 +52,15 @@ impl Command for SubCommand {
run_with_function(call, input, average)
}
fn run_const(
&self,
_working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
run_with_function(call, input, average)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {

View File

@ -29,6 +29,10 @@ impl Command for SubCommand {
vec!["ceiling", "round up", "rounding", "integer"]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
engine_state: &EngineState,
@ -44,6 +48,23 @@ impl Command for SubCommand {
input.map(move |value| operate(value, head), engine_state.signals())
}
fn run_const(
&self,
working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
// This doesn't match explicit nulls
if matches!(input, PipelineData::Empty) {
return Err(ShellError::PipelineEmpty { dst_span: head });
}
input.map(
move |value| operate(value, head),
working_set.permanent().signals(),
)
}
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Apply the ceil function to a list of numbers",

View File

@ -29,6 +29,10 @@ impl Command for SubCommand {
vec!["round down", "rounding", "integer"]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
engine_state: &EngineState,
@ -44,6 +48,23 @@ impl Command for SubCommand {
input.map(move |value| operate(value, head), engine_state.signals())
}
fn run_const(
&self,
working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
// This doesn't match explicit nulls
if matches!(input, PipelineData::Empty) {
return Err(ShellError::PipelineEmpty { dst_span: head });
}
input.map(
move |value| operate(value, head),
working_set.permanent().signals(),
)
}
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Apply the floor function to a list of numbers",

View File

@ -34,6 +34,10 @@ impl Command for SubCommand {
vec!["base", "exponent", "inverse", "euler"]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
engine_state: &EngineState,
@ -63,6 +67,34 @@ impl Command for SubCommand {
)
}
fn run_const(
&self,
working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let base: Spanned<f64> = call.req_const(working_set, 0)?;
if base.item <= 0.0f64 {
return Err(ShellError::UnsupportedInput {
msg: "Base has to be greater 0".into(),
input: "value originates from here".into(),
msg_span: head,
input_span: base.span,
});
}
// This doesn't match explicit nulls
if matches!(input, PipelineData::Empty) {
return Err(ShellError::PipelineEmpty { dst_span: head });
}
let base = base.item;
input.map(
move |value| operate(value, head, base),
working_set.permanent().signals(),
)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {

View File

@ -35,6 +35,10 @@ impl Command for SubCommand {
vec!["maximum", "largest"]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
_engine_state: &EngineState,
@ -45,6 +49,15 @@ impl Command for SubCommand {
run_with_function(call, input, maximum)
}
fn run_const(
&self,
_working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
run_with_function(call, input, maximum)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {

View File

@ -32,6 +32,10 @@ impl Command for SubCommand {
vec!["middle", "statistics"]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
_engine_state: &EngineState,
@ -42,6 +46,15 @@ impl Command for SubCommand {
run_with_function(call, input, median)
}
fn run_const(
&self,
_working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
run_with_function(call, input, median)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {

View File

@ -35,6 +35,10 @@ impl Command for SubCommand {
vec!["minimum", "smallest"]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
_engine_state: &EngineState,
@ -45,6 +49,15 @@ impl Command for SubCommand {
run_with_function(call, input, minimum)
}
fn run_const(
&self,
_working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
run_with_function(call, input, minimum)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {

View File

@ -62,6 +62,10 @@ impl Command for SubCommand {
vec!["common", "often"]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
_engine_state: &EngineState,
@ -72,6 +76,15 @@ impl Command for SubCommand {
run_with_function(call, input, mode)
}
fn run_const(
&self,
_working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
run_with_function(call, input, mode)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {

View File

@ -32,6 +32,10 @@ impl Command for SubCommand {
vec!["times", "multiply", "x", "*"]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
_engine_state: &EngineState,
@ -42,6 +46,15 @@ impl Command for SubCommand {
run_with_function(call, input, product)
}
fn run_const(
&self,
_working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
run_with_function(call, input, product)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {

View File

@ -35,6 +35,10 @@ impl Command for SubCommand {
vec!["approx", "closest", "nearest"]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
engine_state: &EngineState,
@ -54,6 +58,24 @@ impl Command for SubCommand {
)
}
fn run_const(
&self,
working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let precision_param: Option<i64> = call.get_flag_const(working_set, "precision")?;
let head = call.head;
// This doesn't match explicit nulls
if matches!(input, PipelineData::Empty) {
return Err(ShellError::PipelineEmpty { dst_span: head });
}
input.map(
move |value| operate(value, head, precision_param),
working_set.permanent().signals(),
)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {

View File

@ -29,6 +29,10 @@ impl Command for SubCommand {
vec!["square", "root"]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
engine_state: &EngineState,
@ -44,6 +48,23 @@ impl Command for SubCommand {
input.map(move |value| operate(value, head), engine_state.signals())
}
fn run_const(
&self,
working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
// This doesn't match explicit nulls
if matches!(input, PipelineData::Empty) {
return Err(ShellError::PipelineEmpty { dst_span: head });
}
input.map(
move |value| operate(value, head),
working_set.permanent().signals(),
)
}
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Compute the square root of each number in a list",

View File

@ -41,6 +41,10 @@ impl Command for SubCommand {
]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
engine_state: &EngineState,
@ -52,6 +56,16 @@ impl Command for SubCommand {
run_with_function(call, input, compute_stddev(sample))
}
fn run_const(
&self,
working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let sample = call.has_flag_const(working_set, "sample")?;
run_with_function(call, input, compute_stddev(sample))
}
fn examples(&self) -> Vec<Example> {
vec![
Example {

View File

@ -34,6 +34,10 @@ impl Command for SubCommand {
vec!["plus", "add", "total", "+"]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
_engine_state: &EngineState,
@ -44,6 +48,15 @@ impl Command for SubCommand {
run_with_function(call, input, summation)
}
fn run_const(
&self,
_working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
run_with_function(call, input, summation)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {

View File

@ -33,6 +33,10 @@ impl Command for SubCommand {
vec!["deviation", "dispersion", "variation", "statistics"]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
engine_state: &EngineState,
@ -44,6 +48,16 @@ impl Command for SubCommand {
run_with_function(call, input, compute_variance(sample))
}
fn run_const(
&self,
working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let sample = call.has_flag_const(working_set, "sample")?;
run_with_function(call, input, compute_variance(sample))
}
fn examples(&self) -> Vec<Example> {
vec![
Example {

View File

@ -4,10 +4,12 @@ use base64::{
engine::{general_purpose::PAD, GeneralPurpose},
Engine,
};
use multipart_rs::MultipartWriter;
use nu_engine::command_prelude::*;
use nu_protocol::{ByteStream, Signals};
use nu_protocol::{ByteStream, LabeledError, Signals};
use std::{
collections::HashMap,
io::Cursor,
path::PathBuf,
str::FromStr,
sync::mpsc::{self, RecvTimeoutError},
@ -20,6 +22,7 @@ use url::Url;
pub enum BodyType {
Json,
Form,
Multipart,
Unknown,
}
@ -141,17 +144,17 @@ pub fn request_add_authorization_header(
let login = match (user, password) {
(Some(user), Some(password)) => {
let mut enc_str = String::new();
base64_engine.encode_string(&format!("{user}:{password}"), &mut enc_str);
base64_engine.encode_string(format!("{user}:{password}"), &mut enc_str);
Some(enc_str)
}
(Some(user), _) => {
let mut enc_str = String::new();
base64_engine.encode_string(&format!("{user}:"), &mut enc_str);
base64_engine.encode_string(format!("{user}:"), &mut enc_str);
Some(enc_str)
}
(_, Some(password)) => {
let mut enc_str = String::new();
base64_engine.encode_string(&format!(":{password}"), &mut enc_str);
base64_engine.encode_string(format!(":{password}"), &mut enc_str);
Some(enc_str)
}
_ => None,
@ -210,6 +213,7 @@ pub fn send_request(
let (body_type, req) = match content_type {
Some(it) if it == "application/json" => (BodyType::Json, request),
Some(it) if it == "application/x-www-form-urlencoded" => (BodyType::Form, request),
Some(it) if it == "multipart/form-data" => (BodyType::Multipart, request),
Some(it) => {
let r = request.clone().set("Content-Type", &it);
(BodyType::Unknown, r)
@ -265,6 +269,48 @@ pub fn send_request(
};
send_cancellable_request(&request_url, Box::new(request_fn), span, signals)
}
// multipart form upload
Value::Record { val, .. } if body_type == BodyType::Multipart => {
let mut builder = MultipartWriter::new();
let err = |e| {
ShellErrorOrRequestError::ShellError(ShellError::IOError {
msg: format!("failed to build multipart data: {}", e),
})
};
for (col, val) in val.into_owned() {
if let Value::Binary { val, .. } = val {
let headers = [
"Content-Type: application/octet-stream".to_string(),
"Content-Transfer-Encoding: binary".to_string(),
format!(
"Content-Disposition: form-data; name=\"{}\"; filename=\"{}\"",
col, col
),
format!("Content-Length: {}", val.len()),
];
builder
.add(&mut Cursor::new(val), &headers.join("\n"))
.map_err(err)?;
} else {
let headers =
format!(r#"Content-Disposition: form-data; name="{}""#, col);
builder
.add(val.coerce_into_string()?.as_bytes(), &headers)
.map_err(err)?;
}
}
builder.finish();
let (boundary, data) = (builder.boundary, builder.data);
let content_type = format!("multipart/form-data; boundary={}", boundary);
let request_fn =
move || req.set("Content-Type", &content_type).send_bytes(&data);
send_cancellable_request(&request_url, Box::new(request_fn), span, signals)
}
Value::List { vals, .. } if body_type == BodyType::Form => {
if vals.len() % 2 != 0 {
return Err(ShellErrorOrRequestError::ShellError(ShellError::IOError {
@ -514,23 +560,23 @@ fn transform_response_using_content_type(
resp: Response,
content_type: &str,
) -> Result<PipelineData, ShellError> {
let content_type =
mime::Mime::from_str(content_type).map_err(|_| ShellError::GenericError {
error: format!("MIME type unknown: {content_type}"),
msg: "".into(),
span: None,
help: Some("given unknown MIME type".into()),
inner: vec![],
})?;
let content_type = mime::Mime::from_str(content_type)
// there are invalid content types in the wild, so we try to recover
// Example: `Content-Type: "text/plain"; charset="utf8"` (note the quotes)
.or_else(|_| mime::Mime::from_str(&content_type.replace('"', "")))
.or_else(|_| mime::Mime::from_str("text/plain"))
.expect("Failed to parse content type, and failed to default to text/plain");
let ext = match (content_type.type_(), content_type.subtype()) {
(mime::TEXT, mime::PLAIN) => {
let path_extension = url::Url::parse(requested_url)
.map_err(|_| ShellError::GenericError {
error: format!("Cannot parse URL: {requested_url}"),
msg: "".into(),
span: None,
help: Some("cannot parse".into()),
inner: vec![],
.map_err(|err| {
LabeledError::new(err.to_string())
.with_help("cannot parse")
.with_label(
format!("Cannot parse URL: {requested_url}"),
Span::unknown(),
)
})?
.path_segments()
.and_then(|segments| segments.last())

View File

@ -127,6 +127,11 @@ impl Command for SubCommand {
example: "open foo.json | http post https://www.example.com",
result: None,
},
Example {
description: "Upload a file to example.com",
example: "http post --content-type multipart/form-data https://www.example.com { audio: (open -r file.mp3) }",
result: None,
},
]
}
}

View File

@ -0,0 +1,64 @@
use nu_engine::command_prelude::*;
use rand::{thread_rng, RngCore};
#[derive(Clone)]
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"random binary"
}
fn signature(&self) -> Signature {
Signature::build("random binary")
.input_output_types(vec![(Type::Nothing, Type::Binary)])
.allow_variants_without_examples(true)
.required("length", SyntaxShape::Int, "Length of the output binary.")
.category(Category::Random)
}
fn usage(&self) -> &str {
"Generate random bytes."
}
fn search_terms(&self) -> Vec<&str> {
vec!["generate", "bytes"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let length = call.req(engine_state, stack, 0)?;
let mut rng = thread_rng();
let mut out = vec![0u8; length];
rng.fill_bytes(&mut out);
Ok(Value::binary(out, call.head).into_pipeline_data())
}
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Generate 16 random bytes",
example: "random binary 16",
result: None,
}]
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SubCommand {})
}
}

View File

@ -19,12 +19,17 @@ impl Command for SubCommand {
Signature::build("random chars")
.input_output_types(vec![(Type::Nothing, Type::String)])
.allow_variants_without_examples(true)
.named("length", SyntaxShape::Int, "Number of chars", Some('l'))
.named(
"length",
SyntaxShape::Int,
"Number of chars (default 25)",
Some('l'),
)
.category(Category::Random)
}
fn usage(&self) -> &str {
"Generate random chars."
"Generate random chars uniformly distributed over ASCII letters and numbers: a-z, A-Z and 0-9."
}
fn search_terms(&self) -> Vec<&str> {
@ -44,7 +49,7 @@ impl Command for SubCommand {
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Generate random chars",
description: "Generate a string with 25 random chars",
example: "random chars",
result: None,
},

View File

@ -15,7 +15,11 @@ impl Command for SubCommand {
Signature::build("random int")
.input_output_types(vec![(Type::Nothing, Type::Int)])
.allow_variants_without_examples(true)
.optional("range", SyntaxShape::Range, "Range of values.")
.optional(
"range",
SyntaxShape::Range,
"Range of potential values, inclusive of both start and end values.",
)
.category(Category::Random)
}
@ -40,12 +44,12 @@ impl Command for SubCommand {
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Generate an unconstrained random integer",
description: "Generate a non-negative random integer",
example: "random int",
result: None,
},
Example {
description: "Generate a random integer less than or equal to 500",
description: "Generate a random integer between 0 (inclusive) and 500 (inclusive)",
example: "random int ..500",
result: None,
},
@ -55,8 +59,8 @@ impl Command for SubCommand {
result: None,
},
Example {
description: "Generate a random integer between 1 and 10",
example: "random int 1..10",
description: "Generate a random integer between -10 (inclusive) and 10 (inclusive)",
example: "random int (-10)..10",
result: None,
},
]

View File

@ -1,3 +1,4 @@
mod binary;
mod bool;
mod chars;
mod dice;
@ -6,6 +7,7 @@ mod int;
mod random_;
mod uuid;
pub use self::binary::SubCommand as RandomBinary;
pub use self::bool::SubCommand as RandomBool;
pub use self::chars::SubCommand as RandomChars;
pub use self::dice::SubCommand as RandomDice;

View File

@ -187,7 +187,7 @@ fn split_words_helper(v: &Value, word_length: Option<usize>, span: Span, graphem
// [^[:alpha:]\'] = do not match any uppercase or lowercase letters or apostrophes
// [^\p{L}\'] = do not match any unicode uppercase or lowercase letters or apostrophes
// Let's go with the unicode one in hopes that it works on more than just ascii characters
let regex_replace = Regex::new(r"[^\p{L}\']").expect("regular expression error");
let regex_replace = Regex::new(r"[^\p{L}\p{N}\']").expect("regular expression error");
let v_span = v.span();
match v {
@ -422,4 +422,9 @@ mod test {
test_examples(SubCommand {})
}
#[test]
fn mixed_letter_number() {
let actual = nu!(r#"echo "a1 b2 c3" | split words | str join ','"#);
assert_eq!(actual.out, "a1,b2,c3");
}
}

View File

@ -115,12 +115,13 @@ fn run_ps(
help: None,
inner: vec![],
})?;
// If we can't get the start time, just use the current time
let proc_start = proc_stat
.starttime()
.get()
.unwrap_or_else(|_| chrono::Local::now());
record.push("start_time", Value::date(proc_start.into(), span));
record.push(
"start_time",
match proc_stat.starttime().get() {
Ok(ts) => Value::date(ts.into(), span),
Err(_) => Value::nothing(span),
},
);
record.push("user_id", Value::int(proc.curr_proc.owner() as i64, span));
// These work and may be helpful, but it just seemed crowded
// record.push("group_id", Value::int(proc_stat.pgrp as i64, span));
@ -180,7 +181,5 @@ fn run_ps(
output.push(Value::record(record, span));
}
Ok(output
.into_iter()
.into_pipeline_data(span, engine_state.signals().clone()))
Ok(output.into_pipeline_data(span, engine_state.signals().clone()))
}

View File

@ -473,6 +473,15 @@ pub fn command_not_found(
};
}
// If we find a file, it's likely that the user forgot to set permissions
if Path::new(name).is_file() {
return ShellError::ExternalCommand {
label: format!("Command `{name}` not found"),
help: format!("`{name}` refers to a file that is not executable. Did you forget to to set execute permissions?"),
span,
};
}
// We found nothing useful. Give up and return a generic error message.
ShellError::ExternalCommand {
label: format!("Command `{name}` not found"),

View File

@ -1,7 +1,7 @@
use nu_path::Path;
use nu_test_support::fs::Stub::EmptyFile;
use nu_test_support::nu;
use nu_test_support::playground::Playground;
use std::path::PathBuf;
#[test]
fn cd_works_with_in_var() {
@ -22,7 +22,7 @@ fn filesystem_change_from_current_directory_using_relative_path() {
Playground::setup("cd_test_1", |dirs, _| {
let actual = nu!( cwd: dirs.root(), "cd cd_test_1; $env.PWD");
assert_eq!(PathBuf::from(actual.out), *dirs.test());
assert_eq!(Path::new(&actual.out), dirs.test());
})
}
@ -32,7 +32,7 @@ fn filesystem_change_from_current_directory_using_relative_path_with_trailing_sl
// Intentionally not using correct path sep because this should work on Windows
let actual = nu!( cwd: dirs.root(), "cd cd_test_1_slash/; $env.PWD");
assert_eq!(PathBuf::from(actual.out), *dirs.test());
assert_eq!(Path::new(&actual.out), *dirs.test());
})
}
@ -48,7 +48,7 @@ fn filesystem_change_from_current_directory_using_absolute_path() {
dirs.formats().display()
);
assert_eq!(PathBuf::from(actual.out), dirs.formats());
assert_eq!(Path::new(&actual.out), dirs.formats());
})
}
@ -65,7 +65,7 @@ fn filesystem_change_from_current_directory_using_absolute_path_with_trailing_sl
std::path::MAIN_SEPARATOR_STR,
);
assert_eq!(PathBuf::from(actual.out), dirs.formats());
assert_eq!(Path::new(&actual.out), dirs.formats());
})
}
@ -84,7 +84,7 @@ fn filesystem_switch_back_to_previous_working_directory() {
dirs.test().display()
);
assert_eq!(PathBuf::from(actual.out), dirs.test().join("odin"));
assert_eq!(Path::new(&actual.out), dirs.test().join("odin"));
})
}
@ -101,10 +101,7 @@ fn filesystem_change_from_current_directory_using_relative_path_and_dash() {
"
);
assert_eq!(
PathBuf::from(actual.out),
dirs.test().join("odin").join("-")
);
assert_eq!(Path::new(&actual.out), dirs.test().join("odin").join("-"));
})
}
@ -119,7 +116,7 @@ fn filesystem_change_current_directory_to_parent_directory() {
"
);
assert_eq!(PathBuf::from(actual.out), *dirs.root());
assert_eq!(Path::new(&actual.out), *dirs.root());
})
}
@ -136,7 +133,7 @@ fn filesystem_change_current_directory_to_two_parents_up_using_multiple_dots() {
"
);
assert_eq!(PathBuf::from(actual.out), *dirs.test());
assert_eq!(Path::new(&actual.out), *dirs.test());
})
}
@ -151,7 +148,7 @@ fn filesystem_change_to_home_directory() {
"
);
assert_eq!(Some(PathBuf::from(actual.out)), dirs::home_dir());
assert_eq!(Path::new(&actual.out), dirs::home_dir().unwrap());
})
}
@ -169,7 +166,7 @@ fn filesystem_change_to_a_directory_containing_spaces() {
);
assert_eq!(
PathBuf::from(actual.out),
Path::new(&actual.out),
dirs.test().join("robalino turner katz")
);
})
@ -234,7 +231,7 @@ fn filesystem_change_directory_to_symlink_relative() {
$env.PWD
"
);
assert_eq!(PathBuf::from(actual.out), dirs.test().join("foo_link"));
assert_eq!(Path::new(&actual.out), dirs.test().join("foo_link"));
let actual = nu!(
cwd: dirs.test().join("boo"),
@ -243,7 +240,7 @@ fn filesystem_change_directory_to_symlink_relative() {
$env.PWD
"
);
assert_eq!(PathBuf::from(actual.out), dirs.test().join("foo"));
assert_eq!(Path::new(&actual.out), dirs.test().join("foo"));
})
}

View File

@ -95,13 +95,13 @@ fn capture_error_with_both_stdout_stderr_messages_not_hang_nushell() {
#[test]
fn combined_pipe_redirection() {
let actual = nu!("$env.FOO = hello; $env.BAR = world; nu --testbin echo_env_mixed out-err FOO BAR o+e>| complete | get stdout");
let actual = nu!("$env.FOO = 'hello'; $env.BAR = 'world'; nu --testbin echo_env_mixed out-err FOO BAR o+e>| complete | get stdout");
assert_eq!(actual.out, "helloworld");
}
#[test]
fn err_pipe_redirection() {
let actual =
nu!("$env.FOO = hello; nu --testbin echo_env_stderr FOO e>| complete | get stdout");
nu!("$env.FOO = 'hello'; nu --testbin echo_env_stderr FOO e>| complete | get stdout");
assert_eq!(actual.out, "hello");
}

View File

@ -1,6 +1,5 @@
use std::{io::Write, path::PathBuf};
use chrono::{DateTime, FixedOffset};
use nu_path::AbsolutePathBuf;
use nu_protocol::{ast::PathMember, record, Span, Value};
use nu_test_support::{
fs::{line_ending, Stub},
@ -13,6 +12,7 @@ use rand::{
rngs::StdRng,
Rng, SeedableRng,
};
use std::io::Write;
#[test]
fn into_sqlite_schema() {
@ -453,7 +453,7 @@ impl Distribution<TestRow> for Standard {
}
}
fn make_sqlite_db(dirs: &Dirs, nu_table: &str) -> PathBuf {
fn make_sqlite_db(dirs: &Dirs, nu_table: &str) -> AbsolutePathBuf {
let testdir = dirs.test();
let testdb_path =
testdir.join(testdir.file_name().unwrap().to_str().unwrap().to_owned() + ".db");
@ -465,7 +465,7 @@ fn make_sqlite_db(dirs: &Dirs, nu_table: &str) -> PathBuf {
);
assert!(nucmd.status.success());
testdb_path.into()
testdb_path
}
fn insert_test_rows(dirs: &Dirs, nu_table: &str, sql_query: Option<&str>, expected: Vec<TestRow>) {

View File

@ -23,6 +23,13 @@ fn let_takes_pipeline() {
assert_eq!(actual.out, "11");
}
#[test]
fn let_takes_pipeline_with_declared_type() {
let actual = nu!(r#"let x: list<string> = [] | append "hello world"; print $x.0"#);
assert_eq!(actual.out, "hello world");
}
#[test]
fn let_pipeline_allows_in() {
let actual =
@ -38,6 +45,13 @@ fn mut_takes_pipeline() {
assert_eq!(actual.out, "11");
}
#[test]
fn mut_takes_pipeline_with_declared_type() {
let actual = nu!(r#"mut x: list<string> = [] | append "hello world"; print $x.0"#);
assert_eq!(actual.out, "hello world");
}
#[test]
fn mut_pipeline_allows_in() {
let actual =

View File

@ -808,3 +808,28 @@ fn list_inside_tilde_glob_metachars_dir() {
},
);
}
#[test]
fn list_symlink_with_full_path() {
Playground::setup("list_symlink_with_full_path", |dirs, sandbox| {
sandbox.with_files(&[EmptyFile("test_file.txt")]);
#[cfg(unix)]
let _ = std::os::unix::fs::symlink("test_file.txt", dirs.test().join("test_link1"));
#[cfg(windows)]
let _ = std::os::windows::fs::symlink_file("test_file.txt", dirs.test().join("test_link1"));
let actual = nu!(
cwd: dirs.test(),
"ls -l test_link1 | get target.0"
);
assert_eq!(actual.out, "test_file.txt");
let actual = nu!(
cwd: dirs.test(),
"ls -lf test_link1 | get target.0"
);
assert_eq!(
actual.out,
dirs.test().join("test_file.txt").to_string_lossy()
);
})
}

View File

@ -0,0 +1,7 @@
use nu_test_support::nu;
#[test]
fn const_abs() {
let actual = nu!("const ABS = -5.5 | math abs; $ABS");
assert_eq!(actual.out, "5.5");
}

View File

@ -20,3 +20,9 @@ fn can_average_bytes() {
assert_eq!(actual.out, "34985870");
}
#[test]
fn const_avg() {
let actual = nu!("const AVG = [1 3 5] | math avg; $AVG");
assert_eq!(actual.out, "3");
}

View File

@ -0,0 +1,7 @@
use nu_test_support::nu;
#[test]
fn const_ceil() {
let actual = nu!("const CEIL = 1.5 | math ceil; $CEIL");
assert_eq!(actual.out, "2");
}

View File

@ -0,0 +1,7 @@
use nu_test_support::nu;
#[test]
fn const_floor() {
let actual = nu!("const FLOOR = 15.5 | math floor; $FLOOR");
assert_eq!(actual.out, "15");
}

View File

@ -0,0 +1,7 @@
use nu_test_support::nu;
#[test]
fn const_log() {
let actual = nu!("const LOG = 16 | math log 2; $LOG");
assert_eq!(actual.out, "4");
}

View File

@ -0,0 +1,7 @@
use nu_test_support::nu;
#[test]
fn const_max() {
let actual = nu!("const MAX = [1 3 5] | math max; $MAX");
assert_eq!(actual.out, "5");
}

View File

@ -35,3 +35,9 @@ fn median_mixed_numbers() {
assert_eq!(actual.out, "-11.5")
}
#[test]
fn const_median() {
let actual = nu!("const MEDIAN = [1 3 5] | math median; $MEDIAN");
assert_eq!(actual.out, "3");
}

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