Commit Graph

6677 Commits

Author SHA1 Message Date
Matthias Meschede
966cebec34
Adds polars list-contains command (#15304)
# Description

This  PR adds the `polars list-contains` command. It works like this:

```
~/Projects/nushell/nushell> let df = [[a]; [[a,b,c]] [[b,c,d]] [[c,d,f]]] | polars into-df -s {a: list<str>};
~/Projects/nushell/nushell> $df | polars with-column [(polars col a | polars list-contains (polars lit a) | polars as b)] | polars collect
╭───┬───────────┬───────╮
│ # │     a     │   b   │
├───┼───────────┼───────┤
│ 0 │ ╭───┬───╮ │ true  │
│   │ │ 0 │ a │ │       │
│   │ │ 1 │ b │ │       │
│   │ │ 2 │ c │ │       │
│   │ ╰───┴───╯ │       │
│ 1 │ ╭───┬───╮ │ false │
│   │ │ 0 │ b │ │       │
│   │ │ 1 │ c │ │       │
│   │ │ 2 │ d │ │       │
│   │ ╰───┴───╯ │       │
│ 2 │ ╭───┬───╮ │ false │
│   │ │ 0 │ c │ │       │
│   │ │ 1 │ d │ │       │
│   │ │ 2 │ f │ │       │
│   │ ╰───┴───╯ │       │
╰───┴───────────┴───────╯
```

or 

```
~/Projects/nushell/nushell> let df = [[a, b]; [[a,b,c], a] [[b,c,d], f] [[c,d,f], f]] | polars into-df -s {a: list<str>, b: str}
~/Projects/nushell/nushell> $df | polars with-column [(polars col a | polars list-contains b | polars as c)] | polars collect
╭───┬───────────┬───┬───────╮
│ # │     a     │ b │   c   │
├───┼───────────┼───┼───────┤
│ 0 │ ╭───┬───╮ │ a │ true  │
│   │ │ 0 │ a │ │   │       │
│   │ │ 1 │ b │ │   │       │
│   │ │ 2 │ c │ │   │       │
│   │ ╰───┴───╯ │   │       │
│ 1 │ ╭───┬───╮ │ f │ false │
│   │ │ 0 │ b │ │   │       │
│   │ │ 1 │ c │ │   │       │
│   │ │ 2 │ d │ │   │       │
│   │ ╰───┴───╯ │   │       │
│ 2 │ ╭───┬───╮ │ f │ true  │
│   │ │ 0 │ c │ │   │       │
│   │ │ 1 │ d │ │   │       │
│   │ │ 2 │ f │ │   │       │
│   │ ╰───┴───╯ │   │       │
╰───┴───────────┴───┴───────╯
```

or

```
~/Projects/nushell/nushell> let df = [[a, b]; [[1,2,3], 4] [[2,4,1], 2] [[2,1,6], 3]] | polars into-df -s {a: list<i64>, b: i64}
~/Projects/nushell/nushell> $df | polars with-column [(polars col a | polars list-contains ((polars col b) * 2) | polars as c)] | polars collect
╭───┬───────────┬───┬───────╮
│ # │     a     │ b │   c   │
├───┼───────────┼───┼───────┤
│ 0 │ ╭───┬───╮ │ 4 │ false │
│   │ │ 0 │ 1 │ │   │       │
│   │ │ 1 │ 2 │ │   │       │
│   │ │ 2 │ 3 │ │   │       │
│   │ ╰───┴───╯ │   │       │
│ 1 │ ╭───┬───╮ │ 2 │ true  │
│   │ │ 0 │ 2 │ │   │       │
│   │ │ 1 │ 4 │ │   │       │
│   │ │ 2 │ 1 │ │   │       │
│   │ ╰───┴───╯ │   │       │
│ 2 │ ╭───┬───╮ │ 3 │ true  │
│   │ │ 0 │ 2 │ │   │       │
│   │ │ 1 │ 1 │ │   │       │
│   │ │ 2 │ 6 │ │   │       │
│   │ ╰───┴───╯ │   │       │
╰───┴───────────┴───┴───────╯
```

Let me know what you think. I'm a bit surprised that a list by default
seems to get converted to "object" when doing `into-df` which is why I
added the extra `-s` flag every time to explicitly force it into a list.
2025-03-12 08:25:03 -07:00
zc he
44b7cfd696
refactor: tree-sitter-nu friendly alternative expressions (#15301)
# Description

Choose more tree-sitter-nu-friendly (if not better) expressions in nu
scripts.
The changes made in this PR all come from known issues of
`tree-sitter-nu`.

1. nested single/double quotes:
https://github.com/nushell/tree-sitter-nu/issues/125
2. module path of `use` command:
https://github.com/nushell/tree-sitter-nu/issues/165
3. where predicates of boolean column:
https://github.com/nushell/tree-sitter-nu/issues/177
4. `error make` keyword:
https://github.com/nushell/tree-sitter-nu/issues/179

Those issues are either hard to fix or "not planned" for syntactical
precision considerations ATM.

# User-Facing Changes

Should be none

# Tests + Formatting

# After Submitting
2025-03-12 08:48:19 -05:00
Yash Thakur
a17ffdfe56
Include symlinks in directory completions (#15268)
Fixes #15077

# Description

Symlinks are currently not shown in directory completions. #14667
modified completions so that symlinks wouldn't be suggested with
trailing slashes, but it did this by treating symlinks as files. This PR
includes symlinks to directories when completing directories, but still
suggests them without trailing slashes.

# User-Facing Changes

Directory completions will once again include symlinks.

# Tests + Formatting

# After Submitting
2025-03-12 08:13:41 -05:00
132ikl
430b2746b8
Parse XML documents with DTDs by default, and add --disallow-dtd flag (#15272)
<!--
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 allows `from xml` to parse XML documents with [document type
declarations](https://en.wikipedia.org/wiki/Document_type_declaration)
by default. This is especially notable since many HTML documents start
with `<!DOCTYPE html>`, and `roxmltree` should be able to parse some
simple HTML documents. The security concerns with DTDs are [XXE
attacks](https://en.wikipedia.org/wiki/XML_external_entity_attack), and
[exponential entity expansion
attacks](https://en.wikipedia.org/wiki/Billion_laughs_attack).
`roxmltree` [doesn't
support](d2c7801624/src/tokenizer.rs (L535-L547))
external entities (it parses them, but doesn't do anything with them),
so it is not vulnerable to XXE attacks. Additionally, `roxmltree` has
[some
safeguards](d2c7801624/src/parse.rs (L424-L452))
in place to prevent exponential entity expansion, so enabling DTDs by
default is relatively safe. The worst case is no worse than running
`loop {}`, so I think allowing DTDs by default is best, and DTDs can
still be disabled with `--disallow-dtd` if needed.

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->
* Allows `from xml` to parse XML documents with [document type
declarations](https://en.wikipedia.org/wiki/Document_type_declaration)
by default, and adds a `--disallow-dtd` flag to disallow parsing
documents with DTDs.

This PR also improves the errors in `from xml` by pointing at the issue
in the XML source. Example:

```
$ open --raw foo.xml | from xml 
Error:   × Failed to parse XML
   ╭─[2:7]
 1 │ <html>
 2 │     <p<>hi</p>
   ·       ▲
   ·       ╰── Unexpected character <, expected a whitespace
 3 │ </html>
   ╰────
```

# 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
> ```
-->
N/A

# 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.
-->
N/A
2025-03-12 08:09:55 -05:00
zc he
1e566adcfc
fix(completion): full set of operators for type any (#15303)
# Description

As elaborated
[here](https://github.com/nushell/nushell/issues/13676#issuecomment-2717096417),
a full set probably is a more thoughtful approximation for unknown
types.

# User-Facing Changes

# Tests + Formatting

Adjusted

# After Submitting
2025-03-12 08:04:20 -05:00
zc he
789781665d
fix(lsp): find_id for custom def in custom def (#15289)
# Description

Enables hover/rename/references for:

```nushell
def foo [] {
  def bar [] { }
     # |____________ this custom command
}
```

# User-Facing Changes

# Tests + Formatting

+1

# After Submitting
2025-03-12 07:35:28 -05:00
Jack Wright
e926919582
polars open: exposing the ability to configure hive settings. (#15255)
# Description
Exposes parameters for working with
[hive](https://docs.pola.rs/user-guide/io/hive/#scanning-hive-partitioned-data)
partitioning.

# User-Facing Changes
- Added flags `--hive-enabled`, `--hive-start-idx`, `--hive-schema`,
`--hive-try-parse-dates` to `polars open`
2025-03-11 14:18:36 -07:00
Douglas
8d5d01bbc9
Fix improper application of local timezone offset to Unix epochs (#15283)
Fix failing test by ignoring the local offset when converting times, but still displaying the
resulting date in the local timezone (including applicable DST offset).

# User-Facing Changes

Fix: Unix Epochs now convert consistently regardless of whether DST is
in effect in the local timezone or not.
2025-03-11 11:57:37 -04:00
Loïc Riegel
b432866dc9
bugfix: math commands now return error with infinite range [#15135] (#15236)
### Description
Fixes issue #15135

Result

![image](https://github.com/user-attachments/assets/9ff4397f-db79-46df-b1da-2d09f50dd63f)

Also this works with other commands: min, max, sum, product, avg...

### User-Facing Changes
Error is returned, instead of console completely blocked and having to
be killed
I chose "Incorrect value", because commands accept inputs of range type,
just cannot work with unbounded ranges.

### Tests + Formatting
- ran cargo fmt, clippy
- added tests
2025-03-11 14:40:26 +01:00
zc he
81e496673e
refactor(lsp): span fix made easy by bumping lsp-textdocument to 0.4.2 (#15287)
# Description

The upstream crate fixed a bug of position calc, which made some extra
checking in lsp unnecessary.
Also moved some follow-up fixing of #15238 from #15270 here, as it has
something to do with previous position calc bug.

# User-Facing Changes

# Tests + Formatting

Adjusted

# After Submitting
2025-03-11 06:13:58 -05:00
Jack Wright
2dab65f852
Polars: Map pq extension to parquet files (#15284)
# Description
Files with the extension pq will automatically be treated as parquet
files.

closes #15282
2025-03-10 16:25:34 -05:00
Ian Manske
95dcb2fd6c
Add filesize.show_unit config option (#15276)
# Description

Continuation of #15271. This PR adds the
`$env.config.filesize.show_unit` option to allow the ability to omit the
filesize unit. Useful if `$env.config.filesize.unit` is set to a fixed
unit, and you don't want the same unit repeated over and over.

# User-Facing Changes

- Adds the `$env.config.filesize.show_unit` option.
2025-03-09 17:34:55 -05:00
Ian Manske
d97b2e3c60
Respect system locale when formatting file sizes via config (#15271)
# Description

Commands and other pieces of code using `$env.config.format.filesize` to
format filesizes now respect the system locale when formatting the
numeric portion of a file size.

# User-Facing Changes

- System locale is respected when using `$env.config.format.filesize` to
format file sizes.
- Formatting a file size with a binary unit is now exact for large file
sizes and units.
- The output of `to text` is no longer dependent on the config.
2025-03-09 15:43:02 -05:00
Darren Schroeder
4fe7865ad0
allow --group-digits to be used in into string (#15265)
# Description

This PR allows the `into string` command to pass the `--group-digits`
flag which already existed in this code but was hard coded to `false`.

Now you can do things like
```nushell
❯ 1234567890 | into string --group-digits
1,234,567,890
❯ ls | into string size --group-digits | last 5
╭─#─┬────────name─────────┬─type─┬──size──┬───modified───╮
│ 0 │ README.md           │ file │ 12,606 │ 4 weeks ago  │
│ 1 │ rust-toolchain.toml │ file │ 1,125  │ 2 weeks ago  │
│ 2 │ SECURITY.md         │ file │ 2,712  │ 7 months ago │
│ 3 │ toolkit.nu          │ file │ 21,929 │ 2 months ago │
│ 4 │ typos.toml          │ file │ 542    │ 7 months ago │
╰─#─┴────────name─────────┴─type─┴──size──┴───modified───╯
❯ "12345" | into string --group-digits
12,345
```
# 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-03-07 12:43:35 -06:00
Wind
7d17c2eb5e
add a helpful msg to indicate a job has been frozen (#15206)
# Description
As stated in the title, when pressing ctrl-z, I sometimes feel confused
because I return to the REPL without any message. I don't know if the
process has been killed or suspended.

This PR aims to add a message to notify the user that the process has
been frozen.

# User-Facing Changes
After pressing `ctrl-z`.  A message will be printed in repl.


![图片](https://github.com/user-attachments/assets/5fe502eb-439e-4022-889f-64ba52cc2825)

# Tests + Formatting
NaN

# After Submitting
NaN
2025-03-06 11:20:58 -05:00
Loïc Riegel
0e6e9abc12
bugfix: add "to yml" command (#15254)
# Description
This fixes #15240, which can be closed after merge.

# User-Facing Changes
- user get now use `to yml` -> exactly the same as `to yaml`


![2025-03-06_00h01_27](https://github.com/user-attachments/assets/e002a96a-26dd-4f9c-9b45-b456a95be158)

# Tests + Formatting
Cargo fmt and clippy 🆗 
I added a test in the only place I could find where `to yaml` was
already tested.

I didn't see the `save.rs::convert_to_extension` function tested
anywhere, but maybe I missed it.

# After Submitting

Not sure this needs an update on the documentation  What do you
suggest?

---------

Co-authored-by: Stefan Holderbach <sholderbach@users.noreply.github.com>
2025-03-06 14:32:36 +01:00
Ayam Dobhal
f3982278e8
feat(random uuid): add support for uuid versions other than 4. (#15239)
This PR implements the changes proposed in #15112 without any breaking
changes. Should close #15112 post the review.

# Description

Added functionality to generate `uuid` versions 1, 3, 4, 5, 7 instead of
just the version 4.
- Users can now add a `-v n` flag to specify the version of uuid they
want to generate and it maintains backward compatibility by returning a
v4 uuid by default if no flags are passed.
- Versions 3 and 5 have the additional but required namespace (`-s`) and
name (`-n`) arguments too. Version 1 requires a mac address (`-m`).
# User-Facing Changes
- Added support for uuid versions 1, 3, 5 and 7.
- For v3 and v5, the namespace and name arguments are required and hence
there will be an error if those are not passed. Similarly the mac
address for v1.
- Full backward compatibility by setting v4 as default.
# Tests + Formatting

Tests added:
in `nu-command::commands::random`
- generates_valid_uuid4_by_default
- generates_valid_uuid1
- generates_valid_uuid3_with_namespace_and_name
- generates_valid_uuid4
- generates_valid_uuid5_with_namespace_and_name
- generates_valid_uuid7
2025-03-06 14:21:52 +01:00
Yash Thakur
b1e591f84c
Fix unterminated loop in parse_record (#15246)
Fixes #15243

# Description

As noted in #15243, a record with more characters after it (e.g.,
`{a:b}/`) will cause an OOM due to an infinite loop, introduced by
#15023. This happens because the entire string `{a:b}/` is lexed as one
token and passed to `parse_record`, where it repeatedly lexes until it
hits the closing `}`. This PR detects such extra characters and reports
an error.

# User-Facing Changes

`{a:b}/` and other such constructions will no longer cause infinite
loops. Before #15023, you would've seen an "Unclosed delimiter" error
message, but this PR changes that to "Invalid characters."

```
Error: nu::parser::extra_token_after_closing_delimiter

  × Invalid characters after closing delimiter
   ╭─[entry #5:1:7]
 1 │  {a:b}/
   ·       ┬
   ·       ╰── invalid characters
   ╰────
  help: Try removing them.
```

# Tests + Formatting

# After Submitting
2025-03-05 21:02:03 +01:00
Wind
122bcff356
fix $env.FILE_PWD and $env.CURRENT_FILE inside overlay use (#15126)
# Description
Fixes: #14540
The change is similar to #14101

User input can be a directory, in this case, we need to use the return
value of find_in_dirs_env carefully, so in case, I renamed
maybe_file_path to maybe_file_path_or_dir to emphasize it.

# User-Facing Changes
NaN

# Tests + Formatting
Added 2 test cases

# After Submitting
2025-03-05 21:13:44 +02:00
Matthias Meschede
087fe484f6
Enhance polars plugin documentation (#15250)
This PR (based on #15249 and #15248 because it mentions them) adds extra
documentation to the main polars command outlining the main datatypes
that are used by the plugin. The lack of a description of the types
involved in `polars xxx` commands was quite confusing to me when I
started using the plugin and this is a first try improving it.

I didn't find a better place but please let me know what you think.
2025-03-05 08:22:21 -08:00
Matthias Meschede
88bbe4abaa
Add Xor to polars plugin nu_expressions (#15249)
solution for #15242 ,  based on PR #15248 .

Allows doing this:

```
~/Projects/nushell> [[a, b]; [1., 2.], [3.,3.], [4., 6.]] | polars into-df | polars filter (((polars col a) < 2) xor ((polars col b) > 5))
╭───┬──────┬──────╮
│ # │  a   │  b   │
├───┼──────┼──────┤
│ 0 │ 1.00 │ 2.00 │
│ 1 │ 4.00 │ 6.00 │
╰───┴──────┴──────╯
```
2025-03-05 08:03:35 -08:00
zc he
49f92e9090
feat(lsp): completion items now respect the append_whitespace flag (#15247)
# Description

Append space if marked as required.
Aligned behavior as the REPL completion.

# User-Facing Changes

# Tests + Formatting

Adjusted

# After Submitting
2025-03-05 05:45:27 -06:00
Solomon
4779d69de6
prevent panic when parsing incomplete multi-expr (|) matches (#15230)
Fixes #14971, fixes #15229

# User-Facing Changes

Fixes a panic when variable data is accessed after invalid usage of the
`|` separator, which made it impossible to type certain match arms:

```nushell
> match $in { 1 |
Error:   x Main thread panicked.
  |-> at crates/nu-protocol/src/engine/state_delta.rs💯14
  `-> internal error: missing required scope frame
```

# Description

Removes duplicative calls to `exit_scope` from an inner loop when `|`
parse errors are encountered. The outer loop creates and exits scopes
for each match arm.
2025-03-04 05:34:34 -06:00
zc he
de7b000505
fix(lsp): completion on command with following text (#15238)
# Description

Fixes a bug introduced by #15188 

# User-Facing Changes

Before:

<img width="216" alt="image"
src="https://github.com/user-attachments/assets/5846a844-d88e-4d9f-b9e2-e2478c7acb37"
/>

And will crash the lsp server.

After:

<img width="454" alt="image"
src="https://github.com/user-attachments/assets/85e727d6-fef5-426b-818c-e554d3c49c7d"
/>

# Tests + Formatting

adjusted

# After Submitting
2025-03-04 05:33:55 -06:00
Loïc Riegel
9eaa8908d2
doc: clarify trailing line ending in 'to json -r' documentation (#15234)
# Description

Fixes issue  #15215

# User-Facing Changes

Change in help msg in "to json" command with -r flag

# Tests + Formatting
cargo fmt 🆗 

# After Submitting
Doc for that is generated from code I think, so 🆗
2025-03-03 16:49:29 -06:00
zc he
fc72aa6abe
feat(lsp): signature help (manually triggered) (#15233)
# Description

To check for missing parameters

<img width="417" alt="image"
src="https://github.com/user-attachments/assets/5e2a8356-5fd9-4d15-8ae6-08321f9d6e0b"
/>

# User-Facing Changes

For other languages, the help request can be triggered by the `(`
character of the function call.
Editors like nvim refuse to set the trigger character to space, and
space is probably way too common for that.

So this kind of request has to be triggered manually for now.
example of nvim config:

```lua
vim.api.nvim_create_autocmd("FileType", {
  pattern = "nu",
  callback = function(event)
    vim.bo[event.buf].commentstring = "# %s"
    vim.api.nvim_buf_set_keymap(event.buf, "i", "<C-f>", "", {
      callback = function()
        vim.lsp.buf.signature_help()
      end,
    })
  end,
})
```

# Tests + Formatting

+2

# After Submitting
2025-03-03 06:54:42 -06:00
zc he
8e1385417e
fix(lsp): completion label descriptions for cell_path and external values (#15226)
# Description

The type shown in the completion description is 1 level higher than the
actual entry.
Also cleans some TODOs for `SuggetionKind`.

# User-Facing Changes

## Before

<img width="409" alt="image"
src="https://github.com/user-attachments/assets/c7d7df02-aed9-4ea9-892a-0bca707352eb"
/>

<img width="491" alt="image"
src="https://github.com/user-attachments/assets/9b9394d4-62ee-4924-9840-402f00d88a8a"
/>

## After

<img width="425" alt="image"
src="https://github.com/user-attachments/assets/d8f41059-2c68-4902-9c32-d789f91b6d77"
/>

<img width="425" alt="image"
src="https://github.com/user-attachments/assets/ce03afb9-6c1f-4a65-a1cc-cbba4655abb3"
/>

# Tests + Formatting

Adjusted accordingly

# After Submitting
2025-03-02 16:17:12 -06:00
Justin Ma
95f89a093a
Add ansi codes to move cursor position (#15221)
<!--
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 ansi codes to move cursor position: `ansi cursor_left`, `ansi
cursor_right`, `ansi cursor_up`, `ansi cursor_down`
Why I add these? I'm trying to add a spinner to the message end for a
long running task, just to find that I need to move the cursor left to
make it work as expected: `with-progress 'Waiting for the task to
finish' { sleep 10sec }`
```nu
def with-progress [
  message: string,         # Message to display
  action: closure,         # Action to perform
  --success: string,       # Success message
  --error: string          # Error message
] {
  print -n $'($message)   '
  # ASCII spinner frames
  let frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']

  # Start the spinner in the background
  let spinner_pid = job spawn {
    mut i = 0
    print -n (ansi cursor_off)
    loop {
      print -n (ansi cursor_left)
      print -n ($frames | get $i)
      sleep 100ms
      $i = ($i + 1) mod ($frames | length)
    }
  }

  # Run the action and capture result
  let result = try {
    do $action
    { success: true }
  } catch {
    { success: false }
  }

  # Stop the spinner
  job kill $spinner_pid
  print "\r                                                  \r"

  # Show appropriate message
  if $result.success {
    print ($success | default '✓ Done!')
  } else {
    print ($error | default '✗ Failed!')
    exit 1
  }
}
```

# 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-03-01 11:30:00 -06:00
hardfault
e9b677a9e9
fix compact to handle empty list or record in column (#15213)
If a table contains an empty list or record in one column and both column
and -e flags are used, then skip that row.

`compact -e` now skips empty values in a column where as before they were
ignored. Example:

 ```nu
[["a", "b"]; ["c", "d"], ["h", []]] 
| compact -e b
```
before

```plain
 #   a         b
────────────────────────
 0   c   d
 1   h   [list 0 items]
```
after
```plain
 #   a   b
───────────
 0   c   d
```
2025-03-01 07:47:55 -05:00
zc he
7555743ccc
fix(lsp): completion of commands defined after the cursor (#15188)
# Description

Completion feature in LSP can't deal with commands defined after the
cursor before this PR.
This PR adds an alternative completion route where text is not truncated
and no extra `a` appended.

This will also ease future implementation of [signature
help](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_signatureHelp).

# User-Facing Changes

# Tests + Formatting

+6

# After Submitting
2025-03-01 06:21:53 -06:00
hardfault
93612974e0
fix(test-support): use CARGO_BUILD_TARGET_DIR env var (#15212)
# Description

cargo uses both CARGO_BUILD_TARGET_DIR and CARGO_TARGET_DIR, so check
for CARGO_BUILD_TARGET_DIR if CARGO_TARGET_DIR is not found

https://doc.rust-lang.org/cargo/reference/config.html#buildtarget-dir
2025-02-28 20:08:44 +01:00
zc he
52a35827c7
fix(completion): edge cases of operator completions (#15169)
# Description

Improves the completeness of operator completions.
Check the new test cases for details.

# User-Facing Changes

# Tests + Formatting

+4

# After Submitting
2025-02-28 19:39:59 +01:00
Solomon
c5a14bb8ff
check signals in nu-glob and ls (#15140)
Fixes #10144

# User-Facing Changes

Long running glob expansions and `ls` runs (e.g. `ls /**/*`) can now be
interrupted with ctrl-c.
2025-02-28 19:36:39 +01:00
Darren Schroeder
48bdcc71f4
update reedline editcommands in nushell (#15191)
# Description

This PR tries to update the EditCommands and ReedlineEvents by adding
missing items and ordering them to the same order that the reedline enum
has them listed.

@sholderbach When you have time, would you mind looking at this please.
I left some TODOs because I wasn't sure how to implement them. I also
guessed at some of the other implementations. I don't use vim much so
I'm not really sure how these are supposed to act. I was really just
trying to fill in the blanks.

# User-Facing Changes
Closes #15167

# 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: sholderbach <sholderbach@users.noreply.github.com>
2025-02-28 17:41:27 +01:00
132ikl
78c93e5ae0
Run-time pipeline input type checking performance optimizations (#15192)
# Description

Avoids cloning custom command signatures during run-time pipeline input
type checking

# User-Facing Changes

N/A

# Tests + Formatting

N/A
2025-02-27 14:29:25 +01:00
zc he
96af27fb4c
fix: new clippy warnings from rust 1.85.0 (#15203)
# Description
Mainly some cleanup of `map_or`.
2025-02-27 14:11:47 +01:00
Darren Schroeder
1616acd124
update query json help and examples (#15190)
# Description

This PR adds extra_description stating what syntax query json is with
links. It also adds some examples since query json was written before
examples existed for plugins.

# 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-02-26 09:15:14 -06:00
Stefan Holderbach
6f6ad23072
Bump ratatui to 0.29.0 (#15187)
This is the most recent version

Deduplicates the `crossterm` dependency, brings `itertools` in line with
the majority of dependencies.

In the fight against compile times this sadly introduces a
proc-macro-crate for writing proc-macros (`darling`) as a transitive
dependency. So may not lead to a compile time improvement (or could make
it even slightly worse)

Observation: Cargo changed the `Cargo.lock` file version when running
this. (this should still be the specified toolchain, so don't expect a
risk of locking out the expected `cargo` versions)
2025-02-26 06:22:47 -06:00
Jack Wright
7939fb05ea
polars strip-chars: Allow any polars expression for pattern argument (#15178)
# Description 
Allow any polars expression for pattern argument for `polars
strip-chars`
2025-02-25 17:59:02 -06:00
Matthias Meschede
53d30ee7ea
add polars str strip chars (with --end / --start options) (#15118)
# Description

This PR adds `polars str-strip-chars-end`

# User-Facing Changes

New function that can be used as follows:

```
~/Projects/nushell> [[text]; [hello!!!] [world!!!]] | polars into-df | polars select (polars col text | polars str-strip-chars-end "!") | polars collect
╭───┬───────╮
│ # │ text  │
├───┼───────┤
│ 0 │ hello │
│ 1 │ world │
╰───┴───────╯
```

# Tests + Formatting

tests ran locally.
I ran the formatter.

# 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-02-25 15:37:52 -08:00
Jack Wright
058ce0ed2d
move to polars bigidx (#15177)
Fixes [#15157](https://github.com/nushell/nushell/issues/15157)

# Description
Utilizes the polar's bigidx feature to support massive datasets.
2025-02-25 17:29:56 -06:00
Renan Ribeiro
9bb7f0c7dc
Jobs (#14883)
# Description

This is an attempt to improve the nushell situation with regard to issue
#247.

This PR implements:
- [X] spawning jobs: `job spawn { do_background_thing }`
Jobs will be implemented as threads and not forks, to maintain a
consistent behavior between unix and windows.

- [X] listing running jobs: `job list`
This should allow users to list what background tasks they currently
have running.

- [X] killing jobs: `job kill <id>`
- [X] interupting nushell code in the job's background thread
- [X] interrupting the job's currently-running process, if any.

Things that should be taken into consideration for implementation:
- [X] (unix-only) Handling `TSTP` signals while executing code and
turning the current program into a background job, and unfreezing them
in foreground `job unfreeze`.

- [X] Ensuring processes spawned by background jobs get distinct process
groups from the nushell shell itself

This PR originally aimed to implement some of the following, but it is
probably ideal to be left for another PR (scope creep)
- Disowning external process jobs (`job dispatch`)
- Inter job communication (`job send/recv`)

Roadblocks encountered so far:
- Nushell does some weird terminal sequence magics which make so that
when a background process or thread prints something to stderr and the
prompt is idle, the stderr output ends up showing up weirdly
2025-02-25 12:09:52 -05:00
Darren Schroeder
9521b209d1
allow bench to handle larger numbers (#15162)
# Description

This PR allows `bench` to handle larger numbers by using `into float`
2025-02-25 15:02:42 +01:00
zc he
f51a79181a
feat(lsp): semantic tokens for highlighting internal commands with spaces (#15173)
# Description

We decided to move that specific highlighting task from tree-sitter-nu
to lsp for various reasons.
https://github.com/nushell/tree-sitter-nu/pull/184

# User-Facing Changes

Before:
<img width="404" alt="image"
src="https://github.com/user-attachments/assets/79fad167-e424-4411-8aa2-334f08ecc4ab"
/>

After:
<img width="404" alt="image"
src="https://github.com/user-attachments/assets/8eec7c6c-2f63-4a7d-9e98-9e0c397be6bf"
/>


# Tests + Formatting
+1
# After Submitting
2025-02-25 07:14:48 -06:00
zc he
938fa6ee55
fix(completion): prefix_str should be trimmed to element_expression (#15171)
# Description
Hot fix of  a newly introduced bug by #15086.
Forgot to trim the line str according to the expression span, which will
disable external command completions in many cases.

Also adds the suggestion kind to external commands, for lsp
visualization.

# User-Facing Changes

Before:
<img width="246" alt="image"
src="https://github.com/user-attachments/assets/c62904f6-0dd7-4368-8f0b-aacd6fe590f0"
/>

After:
<img width="291" alt="image"
src="https://github.com/user-attachments/assets/76316649-956f-4828-94cb-41f79d5f94f7"
/>

I find it better to visually distinguish externals from internals, so
`function` for internals and `interface` for externals.
But it's arguably not the best option.

# Tests + Formatting

test case adjusted

# After Submitting
2025-02-25 11:47:10 +01:00
Nguyễn Hồng Quân
1d0d91d5e5
Improve documentation for each command (#15172)
# Description

It is a rework of https://github.com/nushell/nushell.github.io/pull/1819

So, I was wasting time looking for equivalent of `filter_map` in Nu,
unaware that `each` already has it. This PR is to make it clear in the
documentation, saving other user's time.

# User-Facing Changes

No

# Tests + Formatting

No

# After Submitting

No
2025-02-25 11:01:09 +01:00
zc he
be508cbd7f
refactor(completion): flatten_shape -> expression for internal/external/operator (#15086)
# Description

Fixes #14852

As the completion rules are somehow intertwined between internals and
externals,
this PR is relatively messy, and has larger probability to break things,
@fdncred @ysthakur @sholderbach
But I strongly believe this is a better direction to go. Edge cases
should be easier to fix in the dedicated branches.

There're no flattened expression based completion rules left.

# User-Facing Changes

# Tests + Formatting
+7
# After Submitting

---------

Co-authored-by: Yash Thakur <45539777+ysthakur@users.noreply.github.com>
2025-02-23 13:47:49 -05:00
Bahex
fcd1d59abd
split list: add streaming, closure argument, and splitting before/after a separator (#15161)
- this PR addresses most of the points in #13153

# Description

- make `split list` support streaming
- **[BREAKING CHANGE]** if the input is split on consecutive items, the
empty lists between those items are preserved.
  e.g. `[1 1 0 0 3 3 0 4 4] | split list 0` == `[[1 1] [] [2 2] [3 3]]`
- accept a closure as argument, the closure is called for each item, and
if it returns `true` the list is split on that item
- added `--split` flag, which allows keeping the separator items.
`--split=after` splits the list *after* the separator and
`--split=before` splits the list *before* the separator.
  `--split=on` is the default behavior where the separator is lost

# User-Facing Changes

`split list`:
- keeps empty sublists
- allows using a closure to determine items to split on
- allows keeping the separator items with `--split=after` and
`--split=before`

# Tests + Formatting

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

# After Submitting
N/A

---------

Co-authored-by: Bahex <17417311+Bahex@users.noreply.github.com>
2025-02-23 07:53:38 -06:00
Marcel Mukundi
083c534948
Fix insert/upsert creation for nested lists (#15131) (#15133)
# Description
This PR fixes #15131 by allowing the `insert` and `upsert` commands to
create lists where they may be expected based on the cell path provided.
For example, the below would have previously thrown an error, but now
creates lists and list elements where necessary
<img width="173" alt="Screenshot 2025-02-17 at 2 46 12 AM"
src="https://github.com/user-attachments/assets/6d680e7e-6268-42ed-a037-a0795014a7e0"
/>
<img width="200" alt="Screenshot 2025-02-17 at 2 46 16 AM"
src="https://github.com/user-attachments/assets/50d0e8eb-aabb-49fe-b961-5f7489fdc993"
/>
<img width="284" alt="Screenshot 2025-02-17 at 2 45 43 AM"
src="https://github.com/user-attachments/assets/242a2ec6-7e8f-4a51-92ce-9d5ec10f867f"
/>

# User-Facing Changes
This change removes errors that were previously raised by
`insert_data_at_cell_path` and `upsert_data_at_cell_path`. If one of
these commands encountered an unknown cell path in cases such as these,
it would either raise a "Not a list value" as the list index is used on
a record:

<img width="326" alt="Screenshot 2025-02-17 at 2 46 43 AM"
src="https://github.com/user-attachments/assets/39b9b006-388b-49b3-82a0-8cc9b739feaa"
/>


Or a "Row number too large" when required to create a new list element
along the way:
<img width="475" alt="Screenshot 2025-02-17 at 2 46 51 AM"
src="https://github.com/user-attachments/assets/007d1268-7d26-42aa-9bf5-d54c0abf4058"
/>


But both now succeed, which seems to be the intention as it is in parity
with record behavior. Any consumers depending on this specific behavior
will see these errors subside.

This change also includes the static method
`Value::with_data_at_cell_path` that creates a value with a given nested
value at a given cell path, creating records or lists based on the path
member type. 

# Tests + Formatting
In addition to unit tests for the altered behavior, both affected
user-facing commands (`insert` and `upsert`) gained a new command
example to both explain and test this change at the user level.
<img width="382" alt="Screenshot 2025-02-17 at 2 29 26 AM"
src="https://github.com/user-attachments/assets/e6973640-3ce6-4ea7-9ba5-d256fe5cb38b"
/>

Note: A single test did fail locally, due to my config directory
differing from expected, but works where this variable is unset
(`with-env { XDG_CONFIG_HOME: null } {cargo test}`):
```
---- repl::test_config_path::test_default_config_path stdout ----
thread 'repl::test_config_path::test_default_config_path' panicked at tests/repl/test_config_path.rs:101:5:
assertion failed: `(left == right)`

Diff < left / right > :
<[home_dir]/Library/Application Support/nushell
>[home_dir]/.config/nushell
```
2025-02-22 21:53:25 -08:00
Piepmatz
bda3245725
More precise ErrorKind::NotFound errors (#15149)
In this PR, the two new variants for `ErrorKind`, `FileNotFound`
and `DirectoryNotFound` with a nice `not_found_as` method for the
`ErrorKind` to easily specify the `NotFound` errors. I also updated some
places where I could of think of with these new variants and the message
for `NotFound` is no longer "Entity not found" but "Not found" to be
less strange.

closes #15142
closes #15055
2025-02-22 11:42:44 -05:00