6881 Commits

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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


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

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

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

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

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

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

Before

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

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

# Tests + Formatting
added `generate_inf`

# After Submitting

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

Edit history
1. Updated `After Submitting` section

---------

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

# Description


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

Hello, this PR proposes a solution for some requested features mentioned
in https://github.com/nushell/nushell/issues/10957. I personally think
these are very simple changes that bring significant quality of life
improvements.
It gives the possibility to do `http get google.com` instead of `http
get http://google.com` and `http get :8080` instead of `http get
http://localhost:8080`.
I did not address the other part of the issue (data management) as those
are more controversial.
2025-05-24 19:53:59 +02:00
Piepmatz
ea97229688
Fix: use ring as a crypto provider instead of aws_lc (#15812) 2025-05-24 15:01:29 +02:00
Julian Amarilla
6bf955a5a5
Fix #15571 panic on write to source parquet file (#15601)
Fixes #15571 

# Description

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

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

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

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

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

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

closes #14041

# Description

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

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

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

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

# User-Facing Changes

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

No changes to the Nushell API.

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

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

// common case
CRYPTO_PROVIDER.default();

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

# Tests + Formatting

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

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

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

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

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

# After Submitting

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

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

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

# Tests + Formatting
Added 1 test

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

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

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

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->
Bump dev version to 0.104.2
2025-05-24 00:54:33 +08:00
Ville Vainio
88d421dcb6
std-rfc/kv: optimize kv get by only selecting one row from the stor db (#15792)
Optimize std-rfc/kv, kv get to only read one row from the sqlite db.
2025-05-22 21:14:31 -04:00
Stefan Holderbach
7c50f7c714
Clean public API of EngineState and friends (#15636)
# Description
`pub` has been overused in many parts of `nu-protocol`. This exposes
implementation details in ways that things could break should we involve
the internals. Also each public member can slow down the decisions to
improve a certain implementation. Furthermore dead code can't be
detected if things are marked as `pub`. Thus we need to judiciously
remove more accidentally `pub` markings and eliminate the dead code if
we come across it.

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

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

# API User-Facing Changes
Removal of several formerly public members that potentially give
intrusive access to the engine. We will button up some of our public
API, feel free to explicitly complain so we can figure out what access
should be granted. We want to evolve to stable APIs as much as possible
which means hiding more implementation details and committing to a
select few well defined and documented interfaces
2025-05-23 07:26:34 +08:00
Bahex
6906a0ca50
fix: implicitly running .ps1 scripts with spaces in path (#15781)
- this PR should close #15757

# Description

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

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

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

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

# User-Facing Changes

# Tests + Formatting

# After Submitting

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

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

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

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

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

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

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

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

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

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

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

> What about `$env`?

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

> `$env.ENV_CONVERSIONS`?

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

# User-Facing Changes

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

# Tests + Formatting

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

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

# After Submitting

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

# User-Facing Changes

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

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

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

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

# User-Facing Changes

None

# Tests + Formatting

None

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

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

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

For example:

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

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

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

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

# User-Facing Changes

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

# Tests + Formatting

All tests pass.

# After Submitting

---------

Co-authored-by: 132ikl <132@ikl.sh>
2025-05-15 10:10:56 -04:00
Darren Schroeder
8c2b1a22d4
allow powershell scripts in the path to be executed (#15760)
# Description

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

closes #15759

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

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

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

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

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

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

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

- fixes #14896
- related to #15163

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

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

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

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

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

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

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

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

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

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

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

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

# User-Facing Changes

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

# After Submitting

---------

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

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

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

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

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

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

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

# User-Facing Changes

# Tests + Formatting

Added examples and tests.

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


# After Submitting

---------

Co-authored-by: Bahex <17417311+Bahex@users.noreply.github.com>
2025-05-13 22:24:45 +03:00
Jack Wright
c2ac8f730e
Rust 1.85, edition=2024 (#15741) 2025-05-13 16:49:30 +02:00
Jack Wright
1a0986903f
Minor DataType refactor (#15728)
# Description
This is needed for the enum work. The recent polars changes have broken
my enum work, so I am breaking it into smaller pull requests.
2025-05-12 08:11:17 -07:00
Firegem
7d6d48f3f7
Allow path join to read ByteStream input (#15128) (#15736)
# Description
Fixes #15128. Allows `path join` to use ByteStream pipeline data to join
on if it's coercible to string. Binary ByteStream input still results in
an error. Tested with `^$nu.current-exe -c '$nu.config-path' | path join
foo` and `^tar.exe -c assets/nu_logo.ico | path join foo`

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

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

Add both of these examples.

# User-Facing Changes

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

* simple value matching
* alternative value matching
2025-05-11 05:41:24 -05:00
zc he
8352a09117
fix: inefficient select with large row number (#15730)
Fixes #15716

# Description

Returns None early if the input iterator is depleted.

# User-Facing Changes

Should be none

# Tests + Formatting

+1

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

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

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

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

# User-Facing Changes

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

Thanks for reproducible.

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

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

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

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

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

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

Cc @132ikl 

# User-Facing Changes
None

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

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

> _Syntax updated after discussion on discord._

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

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

Parameters:
  param <oneof<binary, string>>

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

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

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

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

</p>
</details> 


# User-Facing Changes

# Tests + Formatting
Added some test cases.

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

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

---------

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


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

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

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

---

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

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


</details>

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

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

# User-Facing Changes

None

# Tests + Formatting

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

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

# User-Facing Changes
* Added `polars struct-encode-json`, providing the ability to encode
structs as json
2025-05-06 13:58:51 -07:00
Bruce Weirdan
39b95fc59e
Environment-aware help for open and save (#15651)
# Description

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

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

# User-Facing Changes

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

## `help open`

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

## `help save`

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


# Tests + Formatting

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

# After Submitting

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

New config option:

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

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

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

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

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

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

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

# Description

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

# User-Facing Changes

# Tests + Formatting

~todo!~

adjusted

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

# User-Facing Changes

# Tests + Formatting

# After Submitting

---------

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

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

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

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

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


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

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

cc: @fdncred
2025-05-01 09:43:30 -05:00