Commit Graph

5164 Commits

Author SHA1 Message Date
Darren Schroeder
e290fa0e68
Add stor family of commands (#11170)
# Description

This PR adds the `stor` family of commands. These commands are meant to
create, open, insert, update, delete, reset data in an in-memory sqlite
database. This is really an experiment to see how creatively we can use
an in-memory database.

```
Usage:
  > stor

Subcommands:
  stor create - Create a table in the in-memory sqlite database
  stor delete - Delete a table or specified rows in the in-memory sqlite database
  stor export - Export the in-memory sqlite database to a sqlite database file
  stor import - Import a sqlite database file into the in-memory sqlite database
  stor insert - Insert information into a specified table in the in-memory sqlite database
  stor open - Opens the in-memory sqlite database
  stor reset - Reset the in-memory database by dropping all tables
  stor update - Update information in a specified table in the in-memory sqlite database

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

Input/output types:
  ╭─#─┬──input──┬─output─╮
  │ 0 │ nothing │ string │
  ╰───┴─────────┴────────╯
```

### Examples

## stor create
```nushell
❯ stor create --table-name nudb --columns {bool1: bool, int1: int, float1: float, str1: str, datetime1: datetime}
╭──────┬────────────────╮
│ nudb │ [list 0 items] │
╰──────┴────────────────╯
```
## stor insert
```nushell
❯ stor insert --table-name nudb --data-record {bool1: true, int1: 2, float1: 1.1, str1: fdncred, datetime1: 2023-04-17} 
╭──────┬───────────────╮
│ nudb │ [table 1 row] │
╰──────┴───────────────╯
```
## stor open
```nushell
❯ stor open | table -e 
╭──────┬────────────────────────────────────────────────────────────────────╮
│      │ ╭─#─┬id─┬bool1┬int1┬float1┬──str1───┬─────────datetime1──────────╮ │
│ nudb │ │ 0 │ 1 │   1 │  2 │ 1.10 │ fdncred │ 2023-04-17 00:00:00 +00:00 │ │
│      │ ╰───┴───┴─────┴────┴──────┴─────────┴────────────────────────────╯ │
╰──────┴────────────────────────────────────────────────────────────────────╯
```
## stor update
```nushell
❯ stor update --table-name nudb --update-record {str1: toby datetime1: 2021-04-17} --where-clause "bool1 = 1"
╭──────┬───────────────╮
│ nudb │ [table 1 row] │
╰──────┴───────────────╯
❯ stor open | table -e
╭──────┬─────────────────────────────────────────────────────────────────╮
│      │ ╭─#─┬id─┬bool1┬int1┬float1┬─str1─┬─────────datetime1──────────╮ │
│ nudb │ │ 0 │ 1 │   1 │  2 │ 1.10 │ toby │ 2021-04-17 00:00:00 +00:00 │ │
│      │ ╰───┴───┴─────┴────┴──────┴──────┴────────────────────────────╯ │
╰──────┴─────────────────────────────────────────────────────────────────╯
```
## insert another row
```nushell
❯ stor insert --table-name nudb --data-record {bool1: true, int1: 5, float1: 1.1, str1: fdncred, datetime1: 2023-04-17} 
╭──────┬────────────────╮
│ nudb │ [table 2 rows] │
╰──────┴────────────────╯
❯ stor open | table -e
╭──────┬────────────────────────────────────────────────────────────────────╮
│      │ ╭─#─┬id─┬bool1┬int1┬float1┬──str1───┬─────────datetime1──────────╮ │
│ nudb │ │ 0 │ 1 │   1 │  2 │ 1.10 │ toby    │ 2021-04-17 00:00:00 +00:00 │ │
│      │ │ 1 │ 2 │   1 │  5 │ 1.10 │ fdncred │ 2023-04-17 00:00:00 +00:00 │ │
│      │ ╰───┴───┴─────┴────┴──────┴─────────┴────────────────────────────╯ │
╰──────┴────────────────────────────────────────────────────────────────────╯
```
## stor delete (specific row(s))
```nushell
❯ stor delete --table-name nudb --where-clause "int1 == 5"
╭──────┬───────────────╮
│ nudb │ [table 1 row] │
╰──────┴───────────────╯
```
## insert multiple tables
```nushell
❯ stor create --table-name nudb1 --columns {bool1: bool, int1: int, float1: float, str1: str, datetime1: datetime}
╭───────┬────────────────╮
│ nudb  │ [table 1 row]  │
│ nudb1 │ [list 0 items] │
╰───────┴────────────────╯
❯ stor insert --table-name nudb1 --data-record {bool1: true, int1: 2, float1: 1.1, str1: fdncred, datetime1: 2023-04-17}
╭───────┬───────────────╮
│ nudb  │ [table 1 row] │
│ nudb1 │ [table 1 row] │
╰───────┴───────────────╯
❯ stor create --table-name nudb2 --columns {bool1: bool, int1: int, float1: float, str1: str, datetime1: datetime}
╭───────┬────────────────╮
│ nudb  │ [table 1 row]  │
│ nudb1 │ [table 1 row]  │
│ nudb2 │ [list 0 items] │
╰───────┴────────────────╯
❯ stor insert --table-name nudb2 --data-record {bool1: true, int1: 2, float1: 1.1, str1: fdncred, datetime1: 2023-04-17}
╭───────┬───────────────╮
│ nudb  │ [table 1 row] │
│ nudb1 │ [table 1 row] │
│ nudb2 │ [table 1 row] │
╰───────┴───────────────╯
```
## stor delete (specific table)
```nushell
❯ stor delete --table-name nudb1
╭───────┬───────────────╮
│ nudb  │ [table 1 row] │
│ nudb2 │ [table 1 row] │
╰───────┴───────────────╯
```
## stor reset (all tables are deleted)
```nushell
❯ stor reset
```
## stor export
```nushell
❯ stor export --file-name nudb.sqlite3
╭──────┬───────────────╮
│ nudb │ [table 1 row] │
╰──────┴───────────────╯
❯ open nudb.sqlite3 | table -e
╭──────┬────────────────────────────────────────────────────────────────────╮
│      │ ╭─#─┬id─┬bool1┬int1┬float1┬──str1───┬─────────datetime1──────────╮ │
│ nudb │ │ 0 │ 1 │   1 │  5 │ 1.10 │ fdncred │ 2023-04-17 00:00:00 +00:00 │ │
│      │ ╰───┴───┴─────┴────┴──────┴─────────┴────────────────────────────╯ │
╰──────┴────────────────────────────────────────────────────────────────────╯
❯ open nudb.sqlite3 | schema | table -e
╭────────┬─────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│        │ ╭──────┬──────────────────────────────────────────────────────────────────────────────────────────────────╮ │
│ tables │ │      │ ╭───────────────┬──────────────────────────────────────────────────────────────────────────────╮ │ │
│        │ │ nudb │ │               │ ╭─#─┬─cid─┬───name────┬─────type─────┬─notnull─┬───────default────────┬─pk─╮ │ │ │
│        │ │      │ │ columns       │ │ 0 │ 0   │ id        │ INTEGER      │ 1       │                      │ 1  │ │ │ │
│        │ │      │ │               │ │ 1 │ 1   │ bool1     │ BOOLEAN      │ 0       │                      │ 0  │ │ │ │
│        │ │      │ │               │ │ 2 │ 2   │ int1      │ INTEGER      │ 0       │                      │ 0  │ │ │ │
│        │ │      │ │               │ │ 3 │ 3   │ float1    │ REAL         │ 0       │                      │ 0  │ │ │ │
│        │ │      │ │               │ │ 4 │ 4   │ str1      │ VARCHAR(255) │ 0       │                      │ 0  │ │ │ │
│        │ │      │ │               │ │ 5 │ 5   │ datetime1 │ DATETIME     │ 0       │ STRFTIME('%Y-%m-%d   │ 0  │ │ │ │
│        │ │      │ │               │ │   │     │           │              │         │ %H:%M:%f', 'NOW')    │    │ │ │ │
│        │ │      │ │               │ ╰─#─┴─cid─┴───name────┴─────type─────┴─notnull─┴───────default────────┴─pk─╯ │ │ │
│        │ │      │ │ constraints   │ [list 0 items]                                                               │ │ │
│        │ │      │ │ foreign_keys  │ [list 0 items]                                                               │ │ │
│        │ │      │ │ indexes       │ [list 0 items]                                                               │ │ │
│        │ │      │ ╰───────────────┴──────────────────────────────────────────────────────────────────────────────╯ │ │
│        │ ╰──────┴──────────────────────────────────────────────────────────────────────────────────────────────────╯ │
╰────────┴─────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
```
## Using with `query db`
```nushell
❯ stor open | query db "select * from nudb"
╭─#─┬id─┬bool1┬int1┬float1┬──str1───┬─────────datetime1──────────╮
│ 0 │ 1 │   1 │  5 │ 1.10 │ fdncred │ 2023-04-17 00:00:00 +00:00 │
╰───┴───┴─────┴────┴──────┴─────────┴────────────────────────────╯
```
## stor import
```nushell
❯ stor open
# note, nothing is returned. there is nothing in memory, atm.
❯ stor import --file-name nudb.sqlite3
╭──────┬───────────────╮
│ nudb │ [table 1 row] │
╰──────┴───────────────╯
❯ stor open | table -e 
╭──────┬────────────────────────────────────────────────────────────────────╮
│      │ ╭─#─┬id─┬bool1┬int1┬float1┬──str1───┬─────────datetime1──────────╮ │
│ nudb │ │ 0 │ 1 │   1 │  5 │ 1.10 │ fdncred │ 2023-04-17 00:00:00 +00:00 │ │
│      │ ╰───┴───┴─────┴────┴──────┴─────────┴────────────────────────────╯ │
╰──────┴────────────────────────────────────────────────────────────────────╯
```

TODO:
- [x] `stor export` - Export a fully formed sqlite db file. 
- [x] `stor import` - Imports a specified sqlite db file.
- [x] Perhaps feature-gate it with the sqlite feature
- [x] Update `query db` to work with the in-memory database
- [x] Remove `open --in-memory`

# 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 std testing; testing run-tests --path
crates/nu-std"` 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.
-->
2023-11-29 08:02:46 -08:00
Stefan Holderbach
112306aab5
Revert "Adding support for Polars structs" (#11171)
Reverts nushell/nushell#10943

The current implementation of `arr_to_value` is unsound, as it allows
casts of arbitrary data to arbitrary types without being marked
`unsafe`.
The full safety requirements to perform both the cast and the following
unchecked access are not as clear that a simple change of `fn
arr_to_value` to `unsafe fn arr_to_value` could be blessed without
further investigation.

cc @ayax79
2023-11-29 16:33:27 +01:00
Ian Manske
98952082ae
Build nu-protocol docs with all features enabled (#11180)
# Description
Currently, `PluginSignature` does not appear on
[`docs.rs`](https://docs.rs/nu-protocol/latest/nu_protocol/index.html),
since it is behind the `plugin` feature which is not enabled by default.
This PR adds [metadata](https://docs.rs/about/metadata) to the
Cargo.toml to get `docs.rs` to build docs with all features enabled.
2023-11-29 16:17:22 +01:00
Eric Hodel
8386bc0919
Convert more ShellError variants to named fields (#11173)
# Description

Convert these ShellError variants to named fields:
* CreateNotPossible
* MoveNotPossibleSingle
* DirectoryNotFoundCustom
* DirectoryNotFound
* NotADirectory
* OutOfMemoryError
* PermissionDeniedError
* IOErrorSpanned
* IOError
* IOInterrupted

Also place the `span` field of `DirectoryNotFound` last to match other
errors.

Part of #10700 (almost half done!)

# User-Facing Changes

None

# Tests + Formatting

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

# After Submitting

N/A
2023-11-28 06:43:51 -06:00
WindSoilder
182b0ab4fb
add echo_env_mixed testbin to reduce windows only tests (#11172)
# Description
We have seen some test cases which requires to output message to both
stdout and stderr, especially in redirection scenario.

This pr is going to introduce a new echo_env_mixed testbin, so we can
have less tests which only runs on windows.

# User-Facing Changes
NaN

# Tests + Formatting
NaN

# After Submitting
NaN
2023-11-28 06:42:35 -06:00
Marika Chlebowska
fa83458a6d
Add metadata to some filters (#11160)
<!--
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
This PR preserves metadata when running some filters. As discussed on
discord that helps when running for example `ls | reject modified`
because it keeps colouring and links.
<!--
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 std testing; testing run-tests --path
crates/nu-std"` 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.
-->
2023-11-27 12:16:34 -06:00
WindSoilder
077d1c8125
Support o>>, e>>, o+e>> to append output to an external file (#10764)
# Description
Close: #10278

This pr introduces `o>>`, `e>>`, `o+e>>` to allow redirection to append
to a file.
Examples:
```nushell
echo abc o>> a.txt
echo abc o>> a.txt
cat asdf e>> a.txt
cat asdf e>> a.txt
cat asdf o+e>> a.txt
```

~~TODO:~~
~~1. currently internal commands with `o+e>` redirect to a variable is
broken: `let x = "a.txt"; echo abc o+e> $x`, not sure when it was
introduced...~~
~~2. redirect stdout and stderr with append mode doesn't supported yet:
`cat asdf o>>a.txt e>>b.ext`~~

~~For these 2 items, I'd like to fix them in different prs.~~
Already done in this pr
2023-11-27 07:52:39 -06:00
Artemiy
1ff8c2d81d
Cp target expansion (#11152)
# Description
This PR addresses issue with cp brough up on
[discord](https://discord.com/channels/601130461678272522/614593951969574961/1177669443917189130)
where target of cp is not correctly expanded.
If one has directory `test` with file `file.txt` in it then the
following command (in one line or inside a `do` block):
```nu
cd test; let file = 'copy.txt'; cp file.txt $file
```
will create a `copy.txt` in `.` not in `test` instead. This happens
because target of `cp` is a variable which is not expanded unlike a
string literal

# User-Facing Changes
`cp` will correctly parse realative target paths

# 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 std testing; testing run-tests --path
crates/nu-std"` 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.
-->
2023-11-25 09:42:20 -06:00
Darren Schroeder
d77f1753c2
add shape ExternalResolved to show found externals via syntax highlighting in the repl (#11135)
# Description

This PR enables a new feature that shows which externals are found in
your path via the syntax highlighter as you type.

![external_resolved](https://github.com/nushell/nushell/assets/343840/e5fa91f0-6fac-485c-8afc-5711fc0ed9bc)

This idea could use some improvement where it caches the items in your
path and on some trigger, expires that cache and creates a new on. Right
now, all it does is call the `which` crate on every character you type.
This could be problematic if you have hundreds of paths in your PATH or
if some of your paths in your Path point to extraordinarily slow file
systems. WSL pointing to Windows comes to mind. Either way, I've thrown
it up here for people to try and provide feedback. I think the novelty
of showing what is valid and what isn't is pretty cool. I believe
fish-shell also does this, IIRC.

# 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 std testing; testing run-tests --path
crates/nu-std"` 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.
-->
2023-11-25 09:42:05 -06:00
Antoine Stevan
85c6047b71
fix the link to the nu_scripts in std clip deprecation (#11150)
this is just a simple fix for the link to the `nu_scripts` introduced in
https://github.com/nushell/nushell/pull/11097 😌
2023-11-24 19:03:07 +01:00
Marika Chlebowska
d37893cca0
Add more descriptive error message when passing list to from_csv (#10962)
<!--
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
Added statement catching early List passed to CSV and printing more
helpful error message. This fixes #10081. Similar message might be
useful for other from_* calls but I'm not sure if there aren't any
converters accepting List as input.

# 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 std testing; testing run-tests --path
crates/nu-std"` 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.
-->
2023-11-24 07:45:01 -06:00
WindSoilder
57808ca7cc
Redirect: support redirect stderr with piping stdout to next commands. (#10851)
# Description
Fixes: #10271

Given the following script:
```shell
# test.sh
echo aaaaa
echo bbbbb 1>&2
echo cc
```

This pr makes the following command possible:
```nushell
bash test.sh err> /dev/null | lines | each {|line| $line | str length}
```


## General idea behind the change:
When nushell redirect stderr message to external file
1. it take stdout of external stream, and pass this stream to next
command, so it won't block next pipeline command from running.
2. relative stderr stream are handled by `save` command

These two streams are handled separately, so we need to delegate a
thread to `save` command, or else we'll have a chance to hang nushell,
we have meet a similar before: #5625.

### One case to consider
What if we're failed to save to an external stream? (Like we don't have
a permission to save to a file)?
In this case nushell will just print a waning message, and don't stop
the following scripts from running.

# User-Facing Changes
## Before
```nushell
❯ bash test2.sh err> /dev/null | lines | each {|line| $line | str length}
aaaaa
cc
```

## After
```nushell
❯ bash test2.sh err> /dev/null | lines | each {|line| $line | str length}
╭───┬───╮
│ 0 │ 5 │
│ 1 │ 2 │
╰───┴───╯
```

BTY, after this pr, the following commands are impossible either, it's
important to make sure that the implementation doesn't introduce too
much costs:
```nushell
❯ echo a e> a.txt e> a.txt
Error:   × Can't make stderr redirection twice
   ╭─[entry #1:1:1]
 1 │ echo a e> a.txt e> a.txt
   ·                 ─┬
   ·                  ╰── try to remove one
   ╰────

❯ echo a o> a.txt o> a.txt
Error:   × Can't make stdout redirection twice
   ╭─[entry #2:1:1]
 1 │ echo a o> a.txt o> a.txt
   ·                 ─┬
   ·                  ╰── try to remove one
   ╰────
```
2023-11-23 10:11:00 +08:00
WindSoilder
6cfe35eb7e
enable to pass switch values dynamically (#11057)
# Description
Closes: #7260 

About the change:
When we make an internalcall, and meet a `switch` (Flag.arg is None),
nushell will try to see if the switch is called like `--xyz=false` , if
that is true, `parse_long_flag` will return relative value.

# User-Facing Changes
So after the pr, the following would be possible:
```nushell
def build-imp [--push, --release] {
    echo $"Doing a build with push: ($push) and release: ($release)"
}
def build [--push, --release] {
    build-imp --push=$push --release=$release
}

build --push --release=false
build --push=false --release=true
build --push=false --release=false
build --push --release
build
```

# Tests + Formatting
Done

# After Submitting
Needs to submit a doc update, mentioned about the difference between
`def a [--x] {}` and `def a [--x: bool] {}`
2023-11-23 06:57:37 +08:00
Stefan Holderbach
b2734db015
Move more commands to opaque Record type (#11122)
# Description

Further work towards the goal that we can make `Record`'s field private
and experiment with different internal representations

## Details
- Use inplace record iter in `nu-command/math/utils`
  - Guarantee that existing allocation can be reused
- Use proper record iterators in `path join`
- Remove unnecesary hashmap in `path join`
  - Should minimally reduce the overhead
- Unzip records in `nu-command`
- Refactor `query web` plugin to use record APIs
- Use `Record::into_values` for `values` command
- Use `Record::columns()` in `join` instead.
  - Potential minor pessimisation
  - Not the hot value path
- Use sane `Record` iters in example `Debug` impl
- Avoid layout assumption in `nu-cmd-extra/roll/mod`
  - Potential minor pessimisation
- relegated to `extra`, changing the representation may otherwise break
this op.
- Use record api in `rotate`
- Minor risk that this surfaces some existing invalid behavior as panics
as we now validate column/value lengths
  - `extra` so things are unstable
- Remove unnecessary references in `rotate`
  - Bonus cleanup
# User-Facing Changes
None functional, minor potential differences in runtime. You win some,
you lose some.

# Tests + Formatting
Relying on existing tests
2023-11-22 23:48:48 +01:00
ysthakur
823e578c46
Spread operator for list literals (#11006) 2023-11-22 23:10:08 +02:00
Antoine Stevan
95a745e622
deprecate std clip (#11097)
related to 
- https://github.com/nushell/nushell/issues/11041
- https://github.com/nushell/nu_scripts/pull/674

cc/ @FMotalleb 

# Description
reading the [frontpage of the standard
library](https://github.com/nushell/nushell/blob/main/crates/nu-std/README.md#--welcome-to-the-standard-library-of-nushell--)
and according to the last Nushell meeting, i has been agreed that `std
clip` does not belong to the standard library 😮
- it is not written in pure Nushell and requires external dependencies
which might not even work properly as in
https://github.com/nushell/nushell/issues/11041
- it is not a building block to build more complex applications

this PR deprecates the `std clip` command in favor of [`modules/system
clip`](https://github.com/nushell/nu_scripts/pull/674) for now.

the `std clip` command will be removed in Nushell 0.89.

# User-Facing Changes
the deprecation warning:

![std-clip-deprecation](https://github.com/nushell/nushell/assets/44101798/84bbdf3c-178c-4191-b0bf-9b1b25c229a2)
> **Note**
> the link has been changed to the `nu_scripts` in fa6c17da0 according
to the review comments

# Tests + Formatting

# After Submitting
this will have to be mentionned in the next release note, namely the
slight differences between the two commands.
2023-11-22 18:26:12 +01:00
Eric Hodel
776df7cd93
Convert PluginFailedToDecode to named fields (#11126)
# Description

Part of #10700

# User-Facing Changes

None

# Tests + Formatting
- 🟢 `toolkit fmt`
- 🟢 `toolkit clippy`
- 🟢 `toolkit test`
- 🟢 `toolkit test stdlib`

# After Submitting

N/A
2023-11-22 12:56:04 +01:00
Eric Hodel
d5677625a7
Add is-terminal to determine if stdin/out/err are a terminal (#10970)
# Description

I'm not sure if "is-terminal" is the best name for this command as there
is also "term size". Uses
[`is_terminal()`](https://doc.rust-lang.org/stable/std/io/trait.IsTerminal.html#tymethod.is_terminal)
which is cross-platform.

Possible alternative names:
* `term is-tty --stdout`
* `term is-tty stdout`
* `term is-terminal stdout`

If multiple streams are provided an error is returned. The error span
covers all arguments as the incompatible one is not known. This may be
new?

Fixes #10517

# User-Facing Changes

* Add `is-terminal` to check if stdin, stdout, or stderr are a terminal
(TTY)

# Tests + Formatting

The nu tests always redirect stdin, stdout, and stderr so a positive
test case is not possible without extra work

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

# After Submitting

The new command will be added automatically

---------

Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com>
2023-11-21 20:48:39 -06:00
Eric Hodel
64288b4350
Convert PluginFailedToEncode to named fields (#11125)
# Description

Part of #10700

# User-Facing Changes

None

# Tests + Formatting
- 🟢 `toolkit fmt`
- 🟢 `toolkit clippy`
- 🟢 `toolkit test`
- 🟢 `toolkit test stdlib`

# After Submitting

N/A
2023-11-21 17:38:58 -06:00
Eric Hodel
a42fd3611a
Convert PluginFailedToLoad to named fields (#11124)
# Description

Part of #10700

# User-Facing Changes

None

# Tests + Formatting

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

# After Submitting

N/A
2023-11-21 17:30:52 -06:00
Eric Hodel
e36f69bf3c
Convert FileNotFoundCustom to named fields (#11123)
# Description

Part of #10700

# User-Facing Changes

None

# Tests + Formatting

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

# After Submitting

N/A
2023-11-21 17:30:21 -06:00
Stefan Holderbach
177e800a07
Use record API in describe --detailed (#11075)
For the new stuff from #10795

Added helper to contract `{"type": ...}` records
Use inplace operations if possible for records/lists

Referencing #11027
2023-11-21 17:49:23 +01:00
Eric Hodel
a324a50bb7
Convert FileNotFound to named fields (#11120)
# Description

Part of #10700

# User-Facing Changes

None

# Tests + Formatting

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

# After Submitting

N/A
2023-11-21 17:08:10 +08:00
Eric Hodel
0578cf85ac
Convert ShellError::AliasNotFound to named fields (#11118)
# Description

Part of #10700

# User-Facing Changes

None

# Tests + Formatting

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

# After Submitting

N/A
2023-11-21 16:24:08 +08:00
Eric Hodel
1b54dd5418
Remove ShellError::FlagNotFound (#11119)
# Description

`ShellError::FlagNotFound` had a note that said it may be removable so
this PR removes it instead of updating it to named fields per #10700

I can't see this error being used since it was introduced with #4364. I
can't find why or where it was used before that date, though. There was
a large merge with that PR but I can't penetrate the secrets of git to
find out where its earlier history went.

# User-Facing Changes

None

# Tests + Formatting

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

# After Submitting

N/A
2023-11-21 16:23:09 +08:00
Stefan Holderbach
8ad5d8bb6a
Bump procfs to 0.16.0 (#11115)
Fix the breaking changes.
Get's rid of some outdated transitive dependencies.
Sadly we need to expose more of `procfs` to `nu-command` based on how
the features of `nu-system` are exposed right now.

Conditional compilation/dependencies from hell included

Supersedes #11101
2023-11-20 21:22:35 +01:00
dependabot[bot]
869b01205c
Bump uuid from 1.5.0 to 1.6.0 (#11104) 2023-11-20 19:38:41 +00:00
dependabot[bot]
f5b2f5a9ee
Bump winreg from 0.51.0 to 0.52.0 (#11102) 2023-11-20 19:35:21 +00:00
Stefan Holderbach
adfa4d00c0
Bump version to 0.87.2 (#11114)
Based on the hotfix
https://github.com/nushell/nushell/releases/tag/0.87.1 use this to
disambiguate
2023-11-20 20:31:10 +01:00
Ian Manske
12effd9b4e
Refactor Value cell path functions to fix bugs (#11066)
# Description
Slightly refactors the cell path functions (`insert_data_at_cell_path`,
etc.) for `Value` to fix a few bugs and ensure consistent behavior.
Namely, case (in)sensitivity now applies to lazy records just like it
does for regular `Records`. Also, the insert behavior of `insert` and
`upsert` now match, alongside fixing a few related bugs described below.
Otherwise, a few places were changed to use the `Record` API.

# Tests
Added tests for two bugs:
- `{a: {}} | insert a.b.c 0`: before this PR, doesn't create the
innermost record `c`.
- `{table: [[col]; [{a: 1}], [{a: 1}]]} | insert table.col.b 2`: before
this PR, doesn't add the field `b: 2` to each row.
2023-11-19 21:46:41 +01:00
Eric Hodel
c26fca7419
Add Argument::span() and Call::arguments_span() (#10983)
# Description

These make it easy to make a Span that covers an entire argument and the
span of all arguments in a Call.

Call::arguments_span() is useful for errors where a command may accept
arguments or the pipeline, but not both.

Argument::span() is useful for errors where an arguments is incompatible
with one or more other arguments.

In particular, I wish to use this to create an error for an
implementation of #9563 that either allows arguments to set limits:

```nushell
limits set RLIMIT_NOFILE --soft 255 --hard 1024
```

Or pipeline:

```nushell
{name: RLIMIT_NOFILE, soft: 255} | limits set
```

But not both:

```
❯ [{name: RLIMIT_NOFILE, soft: 255, hard: 1024}] | limits set AS --soft 5 --hard 5
Error: nu:🐚:incompatible_parameters

  × Incompatible parameters.
   ╭─[source:1:1]
 1 │ [{name: RLIMIT_NOFILE, soft: 255, hard: 1024}] | limits set AS --soft 5 --hard 5
   · ───────────────────────┬──────────────────────              ──────────┬─────────
   ·                        │                                              ╰── or arguments, not both
   ·                        ╰── Supply either pipeline
   ╰────
```

# User-Facing Changes

Only nushell Command API changes
2023-11-19 21:43:56 +01:00
Eric Hodel
da59dfe7d2
Convert ShellError::NetworkFailure to named fields (#11093)
# Description

Part of #10700
2023-11-19 21:32:11 +01:00
Eric Hodel
08715e6308
Convert ShellError::CommandNotFound to named fields (#11094)
# Description

Part of #10700
2023-11-19 21:31:28 +01:00
Antoine Stevan
07d7899a97
remove def-env and export def-env (#10999)
follow-up to
- https://github.com/nushell/nushell/pull/10715

> **Important**
> wait for between 0.87 and 0.88 to land this

# Description
it's time for removal again 😋 
this PR removes `def-env` and `export def-env` in favor of `def --env`

# User-Facing Changes
`def-env` and `export def-env` will not be found anymore.

# Tests + Formatting

# After Submitting
2023-11-19 23:25:09 +08:00
Taylor
494a5a5286
Add mktemp command (#11005)
closes #10845 

I've opened this a little prematurely to get some questions answered
before I cleanup the code.

As I started trying to better understand GNUs `mktemp` I've realized its
kind of peculiar and we might want to change its behavior to introduce
it to nushell.

#### quiet and dry run

Does it make sense to keep the `quiet` and `dry_run` flags? I don't
think so. The GNU documentation says this about the dry run flag "Using
the output of this command to create a new file is inherently unsafe, as
there is a window of time between generating the name and using it where
another process can create an object by the same name." So yeah why keep
it? As far as quiet goes, does it make sense to silence the errors in
nushell?

#### other confusing flags

According to the [gnu
docs](https://www.gnu.org/software/coreutils/manual/html_node/mktemp-invocation.html),
the `-t` flag is deprecated and the `-p`/ `--tempdir` are the same flag
with the only difference being `--tempdir` takes an optional path, Given
that, I've broken the `-p` away from `--tempdir`. Now there is one
switch `--tmpdir`/`-t` and one named param `--tmpdir-path`/`-p`.

GNU mktemp
```
  -p DIR, --tmpdir[=DIR]  interpret TEMPLATE relative to DIR; if DIR is not
                        specified, use $TMPDIR if set, else /tmp.  With
                        this option, TEMPLATE must not be an absolute name;
                        unlike with -t, TEMPLATE may contain slashes, but
                        mktemp creates only the final component
  -t                  interpret TEMPLATE as a single file name component,
                        relative to a directory: $TMPDIR, if set; else the
                        directory specified via -p; else /tmp [deprecated]

```
to
nushell mktemp
```
  -p, --tmpdir-path <Filepath> # named param, must provide a path
  -t, --tmpdir                 # a switch
```

Is this a terrible idea?

What should I do?

---------

Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com>
2023-11-17 19:30:53 -06:00
nibon7
f41c93b2d3
Apply nightly clippy fixes (#11083)
<!--
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.
-->
Clippy fixes for rust 1.76.0-nightly

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

N/A
# 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 std testing; testing run-tests --path
crates/nu-std"` 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.
-->
2023-11-17 09:15:55 -06:00
WindSoilder
5063e01c12
std: add cross platform null-device name (#11070)
# Description
We have meet a discord discussion about cross platform `null-device`:
https://discord.com/channels/601130461678272522/988303282931912704/1165966467095875624

I want the same feature too...And I think it's good enough to add it
into `nu-std`.

Different to https://github.com/nushell/nu_scripts/pull/649/files, I
think named it to `null-device`(the name comes from
[wiki](https://en.wikipedia.org/wiki/Null_device)) is better than
`null-stream`.
2023-11-17 14:49:07 +01:00
Jakub Žádník
d1137cc700
Send only absolute paths to uu_cp (#11080)
# Description
Fixes https://github.com/nushell/nushell/issues/10832

Replaces: https://github.com/nushell/nushell/pull/10843
2023-11-17 07:30:57 +08:00
Ian Manske
3966c0a9fd
Fix rm path handling (#11064)
# Description
Fixes issue #11061 where `rm` fails to find a file after a `cd`. It
looks like the new glob functions do not return absolute file paths
which we forgot to account for.

# Tests
Added a test (fails on current main, but passes with this PR).

---------

Co-authored-by: Jakub Žádník <kubouch@gmail.com>
2023-11-17 07:30:15 +08:00
Antoine Stevan
dbdb1f6600
remove the unfold command (#10773)
follow-up to:
- https://github.com/nushell/nushell/pull/10771

> **Important**
> wait for between 0.87 and 0.88 to land this

# Description
after deprecation comes the removal... this PR removes `unfold` in favor
of `generate` 🥳

# User-Facing Changes
users should use `generate` now, `unfold` will stop working.

# Tests + Formatting

# After Submitting
2023-11-17 06:50:20 +08:00
Antoine Stevan
84cdc0d521
remove size command in favor of str stats (#10784)
follow-up to
- https://github.com/nushell/nushell/pull/10798

> **Important**
> wait for between 0.87 and 0.88 to land this

# Description
once again, after deprecation comes removal 😌 

# User-Facing Changes
`size` is now removed and `str size` should be used

# Tests + Formatting

# After Submitting
2023-11-17 06:49:19 +08:00
Antoine Stevan
ab59dab129
remove --not from glob (#10839)
follow-up to
- https://github.com/nushell/nushell/pull/10827

> **Important**  
> wait for between 0.87 and 0.88 to land this

# Description
after deprecation comes removal... this PR removes `glob --not` in favor
of `glob --exclude`.

# User-Facing Changes
`glob --not` will stop working.

# Tests + Formatting

# After Submitting
i didn't find any use of `glob --not` in the `nu_scripts` so no update
required there 👍
2023-11-17 06:46:15 +08:00
Antoine Stevan
e0c8a3d14c
remove extern-wrapped and export extern-wrapped (#11000)
follow-up to
- https://github.com/nushell/nushell/pull/10716

> **Important**
> wait for between 0.87 and 0.88 to land this

# Description
it's time for removal again 😋 
this PR removes `extern-wrapped` and `export extern-wrapped` in favor of
`def --wrapped`

# User-Facing Changes
`extern-wrapped` and `export extern-wrapped` will not be found anymore.

# Tests + Formatting

# After Submitting
2023-11-17 06:44:28 +08:00
Darren Schroeder
e93e51d672
bump rust-toolchain to 1.72.1 (#11079)
# Description

This PR follows our process of staying 2 releases behind rust. 1.74.0
was released today so we update to 1.72.1.

Reference https://releases.rs/

# 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 std testing; testing run-tests --path
crates/nu-std"` 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.
-->
2023-11-16 15:14:45 -06:00
Sophia June Turner
4205edbc70
Fix the output type for 'view files' (#11077)
<!--
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 std testing; testing run-tests --path
crates/nu-std"` 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: JT <547158+jntrnr@users.noreply.github.com>
2023-11-16 11:53:51 -06:00
Darren Schroeder
80bee40807
optimize/clean up a few of the table changes (#11076)
# Description

@sholderbach pointed out some places that I could help improve the code
in the table command changes. This PR tries to implement those.

# 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 std testing; testing run-tests --path
crates/nu-std"` 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.
-->
2023-11-16 11:37:46 -06:00
Darren Schroeder
461837773b
correct table example syntax (#11074)
# Description

Correct an example that had old syntax.

# 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 std testing; testing run-tests --path
crates/nu-std"` 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.
-->
2023-11-16 08:20:52 -06:00
Darren Schroeder
52d4259f58
add "default" table theme (#11072)
# Description

This PR fixes a minor bug that prevented this command from running.
```nushell
table --list | each {|r| print ($r); print (ls | first 3 | table --theme $r)}
```
Here's the output now of the first few themes.

![image](https://github.com/nushell/nushell/assets/343840/21bc8942-5106-4b6a-8905-e90d6cb9a153)

It prevented it from running because "default" wasn't a real table
theme. Now "default" is a synonym of rounded.

Also tweaked the error message when a bad theme name is provided.

# 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 std testing; testing run-tests --path
crates/nu-std"` 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.
-->
2023-11-16 06:14:18 -06:00
Darren Schroeder
274a8366c6
tweak table example/parameter text (#11071)
# Description

This PR just tweaks the `table` example text and some parameter text.

# 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 std testing; testing run-tests --path
crates/nu-std"` 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.
-->
2023-11-16 05:35:55 -06:00
Maxim Zhiburt
a1dfc35968
Fix #11047 (#11054)
close #11047
2023-11-16 05:28:54 -06:00
Skyler Hawthorne
5886a74ccc
into binary -c: return 0 as single byte (#11068)
# Description

The `into binary` command has a `-c` flag which strips any leading 0s in
the most significant digits to represent the minimal number of bytes,
rather than the system's complete in-memory representation of the input.

However, currently giving 0 as input results in eight 0 bytes even with
the `-c` flag, which is inconsistent with the purpose of the flag.

```nu
❯ : 345678 | into binary
Length: 8 (0x8) bytes | printable whitespace ascii_other non_ascii
00000000:   4e 46 05 00  00 00 00 00                             NF•00000

❯ : 345678 | into binary -c
Length: 3 (0x3) bytes | printable whitespace ascii_other non_ascii
00000000:   4e 46 05

❯ : 0 | into binary
Length: 8 (0x8) bytes | printable whitespace ascii_other non_ascii
00000000:   00 00 00 00  00 00 00 00                             00000000

❯ : 0 | into binary -c
Length: 8 (0x8) bytes | printable whitespace ascii_other non_ascii
00000000:   00 00 00 00  00 00 00 00                             00000000
```

This change fixes this behavior so that if the entire input results in
all 0 bytes, only a single 0 byte is returned.

```nu
❯ : ~/src/nushell/target/aarch64-linux-android/debug/nu -c '0 | into binar
y -c'
Length: 1 (0x1) bytes | printable whitespace ascii_other non_ascii
00000000:   00
```

# User-Facing Changes

Values which result in all null bytes will be truncated to a single byte
when `-c` is given. This could potentially be considered a breaking
change if this behavior was relied upon in some way.
2023-11-16 04:09:31 -06:00
Darren Schroeder
4367aa9f58
allow parsing of human readable datetimes (#11051)
# Description

This PR adds the ability to parse human readable datetime strings as
part of the `into datetime` command. I added a new `-n`/`--list-human`
parameter that produces this list to give the user an idea of what is
supported.
```nushell
❯ into datetime --list-human 
╭#─┬parseable human datetime examples┬───result───╮
│0 │Today 18:30                      │in 8 hours  │
│1 │2022-11-07 13:25:30              │a year ago  │
│2 │15:20 Friday                     │in 3 days   │
│3 │This Friday 17:00                │in 3 days   │
│4 │13:25, Next Tuesday              │in a week   │
│5 │Last Friday at 19:45             │3 days ago  │
│6 │In 3 days                        │in 2 days   │
│7 │In 2 hours                       │in 2 hours  │
│8 │10 hours and 5 minutes ago       │10 hours ago│
│9 │1 years ago                      │a year ago  │
│10│A year ago                       │a year ago  │
│11│A month ago                      │a month ago │
│12│A week ago                       │a week ago  │
│13│A day ago                        │a day ago   │
│14│An hour ago                      │an hour ago │
│15│A minute ago                     │a minute ago│
│16│A second ago                     │now         │
│17│Now                              │now         │
╰#─┴parseable human datetime examples┴───result───╯
```

Or with `$env.config.datetime_format.table` set.
```nushell
❯ into datetime --list-human 
╭#─┬parseable human datetime examples┬──────result───────╮
│0 │Today 18:30                      │11/14/23 06:30:00PM│
│1 │2022-11-07 13:25:30              │11/07/22 01:25:30PM│
│2 │15:20 Friday                     │11/17/23 03:20:00PM│
│3 │This Friday 17:00                │11/17/23 05:00:00PM│
│4 │13:25, Next Tuesday              │11/21/23 01:25:00PM│
│5 │Last Friday at 19:45             │11/10/23 07:45:00PM│
│6 │In 3 days                        │11/17/23 10:12:54AM│
│7 │In 2 hours                       │11/14/23 12:12:54PM│
│8 │10 hours and 5 minutes ago       │11/14/23 12:07:54AM│
│9 │1 years ago                      │11/13/22 10:12:54AM│
│10│A year ago                       │11/13/22 10:12:54AM│
│11│A month ago                      │10/15/23 11:12:54AM│
│12│A week ago                       │11/07/23 10:12:54AM│
│13│A day ago                        │11/13/23 10:12:54AM│
│14│An hour ago                      │11/14/23 09:12:54AM│
│15│A minute ago                     │11/14/23 10:11:54AM│
│16│A second ago                     │11/14/23 10:12:53AM│
│17│Now                              │11/14/23 10:12:54AM│
╰#─┴parseable human datetime examples┴──────result───────╯
```
# 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 std testing; testing run-tests --path
crates/nu-std"` 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.
-->
2023-11-15 17:43:37 -06:00
Maxim Zhiburt
e9c298713e
nu-table/ Add -t/theme argument && Replace -n/start-number with -i/index (#11058)
ref #11054

cc: @fdncred 

I've not figured out how to be able to have a flag option as `table -i`
:(

```nu
~/bin/nushell> [[a b, c]; [1 [2 3 3] 3] [4 5 [1 2 [1 2 3]]]] | table -e --width=80 --theme basic -i false

+---+-------+-----------+
| a |   b   |     c     |
+---+-------+-----------+
| 1 | +---+ |         3 |
|   | | 2 | |           |
|   | +---+ |           |
|   | | 3 | |           |
|   | +---+ |           |
|   | | 3 | |           |
|   | +---+ |           |
+---+-------+-----------+
| 4 |     5 | +-------+ |
|   |       | |     1 | |
|   |       | +-------+ |
|   |       | |     2 | |
|   |       | +-------+ |
|   |       | | +---+ | |
|   |       | | | 1 | | |
|   |       | | +---+ | |
|   |       | | | 2 | | |
|   |       | | +---+ | |
|   |       | | | 3 | | |
|   |       | | +---+ | |
|   |       | +-------+ |
+---+-------+-----------+
```

```nu
~/bin/nushell> [[a b, c]; [1 [2 3 3] 3] [4 5 [1 2 [1 2 3]]]] | table -e --width=80 --theme basic -i 100

+-----+---+-------------+-----------------------+
|   # | a |      b      |           c           |
+-----+---+-------------+-----------------------+
| 100 | 1 | +-----+---+ |                     3 |
|     |   | | 100 | 2 | |                       |
|     |   | +-----+---+ |                       |
|     |   | | 101 | 3 | |                       |
|     |   | +-----+---+ |                       |
|     |   | | 102 | 3 | |                       |
|     |   | +-----+---+ |                       |
+-----+---+-------------+-----------------------+
| 101 | 4 |           5 | +-----+-------------+ |
|     |   |             | | 100 |           1 | |
|     |   |             | +-----+-------------+ |
|     |   |             | | 101 |           2 | |
|     |   |             | +-----+-------------+ |
|     |   |             | | 102 | +-----+---+ | |
|     |   |             | |     | | 100 | 1 | | |
|     |   |             | |     | +-----+---+ | |
|     |   |             | |     | | 101 | 2 | | |
|     |   |             | |     | +-----+---+ | |
|     |   |             | |     | | 102 | 3 | | |
|     |   |             | |     | +-----+---+ | |
|     |   |             | +-----+-------------+ |
+-----+---+-------------+-----------------------+
```
2023-11-15 17:41:18 -06:00
Marc Schreiber
c110ddff66
Implement LSP Text Document Synchronization (#10941) 2023-11-15 17:35:48 -06:00
Skyler Hawthorne
a806717f35
Testing support tweaks: exit status in Outcome (#10692)
This PR makes a couple of tweaks to the testing support crate:

Add the `nu` invocation's exit status to the test output so that one
can assert that nu exited with a successful code.

This PR was split off of #10232.
2023-11-15 23:50:43 +01:00
Stefan Holderbach
2b5f1ee5b3
Bump version to 0.87.1 (#11056) 2023-11-15 23:50:11 +01:00
Stefan Holderbach
77a1c3c7b2
Bump version for 0.87.0 release (#11031)
# Release checklist

- [x] reedline
  - [x] released
  - [x] pinned
- [x] crate graph check
- [x] release notes
- [x] release script update (new crate `nu-lsp`)
- [ ] permission management `nu-lsp` on crates.io
2023-11-14 21:01:19 +01:00
Stefan Holderbach
82b3ae826f
Pin reedline to 0.26 release (#11053)
See full release notes:
https://github.com/nushell/reedline/releases/tag/v0.26.0
2023-11-14 20:47:25 +01:00
Stefan Holderbach
1b3092ae7c
Move to clearer reedline keyboard enhancement API (#11045)
Go from the ill-defined `enable/disable` pairs to `.use_...` builders
This alleviates unclear properties when the underlying enhancements are
enabled. Now they are enabed when entering `Reedline::read_line` and
disabled when exiting that.

Furthermore allow setting `$env.config.use_kitty_protocol` to have an
effect when toggling during runtime. Previously it was only enabled when
receiving a value from `config.nu`. I kept the warning code there to not
pollute the log. We could move it into the REPL-loop if desired

Not sure if we should actively block the enabling of `bracketed_paste`
on Windows. Need to test what happens if it just doesn't do anything we
could remove the `cfg!` switch. At least for WSL2 Windows Terminal
already supports bracketed paste. `target_os = windows` is a bad
predictor for `conhost.exe`.

Depends on https://github.com/nushell/reedline/pull/659
(pointing to personal fork)

Closes https://github.com/nushell/nushell/issues/10982
Supersedes https://github.com/nushell/nushell/pull/10998
2023-11-14 20:27:14 +01:00
WindSoilder
942ff7df4d
fix custom command's default value (#11043)
# Description
Fixes: #11033

Sorry for the issue, it's a regression which introduce by this pr:
#10456.
And this pr is going to fix it.

About the change: create a new field named `type_annotated` for
`Arg::Flag` and `Arg::Signature` instead of `arg_explicit_type`
variable.
When we meet a type in `TypeMode`, we set `type_annotated` field of the
argument to be true, then we know that if the arg have a annotated type
easily
2023-11-14 13:46:05 +01:00
Motalleb Fallahnezhad
415b1273b4
Fix (http) get HTTP_PROXY from $env (#11026)
# Description

This PR closes this
[issue](https://github.com/nushell/nushell/issues/11025)

# User-Facing Changes

Setting the environment variable HTTP_PROXY using $env.HTTP_PROXY will
work.

# Before

```bash
~> $env.HTTP_PROXY = http://127.0.0.1:7890 | http get https://lumtest.com/myip.json | get country
IR # (direct)
```

# After

```bash
~> $env.HTTP_PROXY = http://127.0.0.1:7890 | http get https://lumtest.com/myip.json | get country
DE # (with proxy)
```
2023-11-11 10:16:17 -06:00
WindSoilder
6bee80dcd7
make reject support list input directly (#11024)
# Description
Fixes: #10895 

It's because `reject` and `select` command can't handle list of CellPath
input directly.
After this pr, the following should be ok:
```nushell
❯ [{'a': 1, 'b': 2, 'c': 3}, {'a': 1, 'b': 2, 'c': 3}] | reject ['a', 'b']
╭───┬───╮
│ # │ c │
├───┼───┤
│ 0 │ 3 │
│ 1 │ 3 │
╰───┴───╯
❯ [{'a': 1, 'b': 2, 'c': 3}, {'a': 1, 'b': 2, 'c': 3}] | select ['a', 'b']
╭───┬───┬───╮
│ # │ a │ b │
├───┼───┼───┤
│ 0 │ 1 │ 2 │
│ 1 │ 1 │ 2 │
╰───┴───┴───╯
```
2023-11-11 10:15:11 -06:00
Ian Manske
93096a07aa
Implement Display for CellPath (#11023)
# Description
Because `CellPath::into_string` takes a borrowed `self`, I renamed it to
`to_string` to follow Rust [API
guidelines](https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv).
This then triggered the clippy lint
[inherent_to_string](https://rust-lang.github.io/rust-clippy/master/index.html#/inherent_to_string),
which is... correct! The current `CellPath::into_string` is being used
as if it were the `Display` implementation for `CellPath`.

# User-Facing Changes
Breaking API change for `nu-protocol`, since `CellPath::into_string` was
removed.
2023-11-10 21:12:51 +01:00
Ian Manske
523d0bca16
Refactor flatten command (#11017)
# Description
Refactors the `flatten` command to remove a bunch of cloning. This was
down by passing ownership of the `Value` to `flat_value`, removing the
lifetime on `TableInside`, and using `Vec<Record>` in `FlattenedRows`
instead of a pair of `Vec` of columns and values.

For the quick benchmark below, it seems to be twice as fast now:
```nushell
let data = ls crates | where type == dir | each { ls $'($in.name)/**/*' }
timeit { for x in 0..1000 { $data | flatten } }
```
This took 550ms on v0.86.0 and only 230ms on this PR.
But considering that
```nushell
timeit { for x in 0..1000 { $data } }
```
takes 200ms on both versions, then the difference for `flatten` itself
is really 250ms vs 30ms -- 8x faster.
2023-11-10 13:18:02 +01:00
Jack Wright
fe92051bb3
Adding support for Polars structs (#10943)
Provides support for reading Polars structs. This allows opening of
supported files (jsonl, parquet, etc) that contain rows with structured
data.

The following attached json lines
file([receipts.jsonl.gz](https://github.com/nushell/nushell/files/13311476/receipts.jsonl.gz))
contains a customer column with structured data. This json lines file
can now be loaded via `dfr open` and will render as follows:

<img width="525" alt="Screenshot 2023-11-09 at 10 09 18"
src="https://github.com/nushell/nushell/assets/56345/4b26ccdc-c230-43ae-a8d5-8af88a1b72de">


This also addresses some cleanup of date handling and utilizing
timezones where provided.

This pull request only addresses reading data from polars structs. I
will address converting nushell data to polars structs in a future
request as this change is large enough as it is.

---------

Co-authored-by: Jack Wright <jack.wright@disqo.com>
2023-11-09 19:00:59 -06:00
Stefan Holderbach
ee648ecb7d
Refactor transpose and improve perf (#11013)
# Description

Generally elide a bunch of unnecessary clones. Both globally stopping to
clone the whole input data in a bunch of places where we need to read it
but also some minor places where we currently cloned.

As part of that, we can make the overwriting with `keep-all` and
`keep-last` inplace so the items don't need to be removed and repushed
to the record. 

# Benchmarking

```nu
timeit { scope commands | transpose -r }
```

Before ~24 ms now just ~5 ms

# User-Facing Changes
This can change the order of apperance in the transposed record with
`--keep-last`/`--keep-all`. Now the
order is determined by the first appearance and not by the last
appearance in the ingoing columns.
This mirrors the behavior when not passed `keep-all` or `keep-last`.

# Tests + Formatting
Sadly the `transpose` command is so far undertested for more complex
operations.
2023-11-09 22:41:38 +01:00
Ian Manske
33a7bc405f
Refactor drop columns to fix issues (#10903)
# Description
This PR refactors `drop columns` and fixes issues #10902 and #6846.
Tables with "holes" are now handled consistently, although still
somewhat awkwardly. That is, the columns in the first row are used to
determine which columns to drop, meaning that the columns displayed all
the way to the right by `table` may not be the columns actually being
dropped. For example, `[{a: 1}, {b: 2}] | drop column` will drop column
`a` instead of `b`. Before, this would give a list of empty records.

# User-Facing Changes
`drop columns` can now take records as input.
2023-11-09 13:51:46 +01:00
Stefan Holderbach
cd75640a90
Add Record::truncate for trimming based on len (#11004)
# Description
Compatible with `Vec::truncate` and `indexmap::IndexMap::truncate`

Found useful in #10903 for `drop column`

# Tests + Formatting
Doctest with the relevant edge-cases
2023-11-09 00:00:20 +01:00
Christopher Durham
0f600bc3f5
Improve case insensitivity consistency (#10884)
# Description

Add an extension trait `IgnoreCaseExt` to nu_utils which adds some case
insensitivity helpers, and use them throughout nu to improve the
handling of case insensitivity. Proper case folding is done via unicase,
which is already a dependency via mime_guess from nu-command.

In actuality a lot of code still does `to_lowercase`, because unicase
only provides immediate comparison and doesn't expose a `to_folded_case`
yet. And since we do a lot of `contains`/`starts_with`/`ends_with`, it's
not sufficient to just have `eq_ignore_case`. But if we get access in
the future, this makes us ready to use it with a change in one place.

Plus, it's clearer what the purpose is at the call site to call
`to_folded_case` instead of `to_lowercase` if it's exclusively for the
purpose of case insensitive comparison, even if it just does
`to_lowercase` still.

# User-Facing Changes

- Some commands that were supposed to be case insensitive remained only
insensitive to ASCII case (a-z), and now are case insensitive w.r.t.
non-ASCII characters as well.

# Tests + Formatting

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

---------

Co-authored-by: Stefan Holderbach <sholderbach@users.noreply.github.com>
2023-11-08 23:58:54 +01:00
Ian Manske
aed4b626b8
Refactor env conversion, yeet Value::follow_cell_path_not... (#10926)
# Description
Replaces the only usage of `Value::follow_cell_path_not_from_user_input`
with some `Record::get`s.

# User-Facing Changes
Breaking change for `nu-protocol`, since
`Value::follow_cell_path_not_from_user_input` was deleted.

Nushell now reports errors for when environment conversions are not
closures.
2023-11-08 23:57:24 +01:00
Stefan Holderbach
92503e6571
Use record API in more parts of nu-protocol (#10928)
# Description

This is pretty complementary/orthogonal to @IanManske 's changes to
`Value` cellpath accessors in:
- #10925
- to a lesser extent #10926

## Steps
- Use `R.remove` in `Value.remove_data_at_cell_path`
- Pretty sound after #10875 (tests mentioned in commit message have been
removed by that)
- Update `did_you_mean` helper to use iterator
- Change `Value::columns` to return iterator
  - This is not a place of honor
- Use `Record::get` in `Value::get_data_by_key`
# User-Facing Changes
None intentional, potential edge cases on duplicated columns could
change (considered undefined behavior)

# Tests + Formatting
(-)
2023-11-08 23:03:08 +01:00
Stefan Holderbach
44c0db46e1
Add Record::drain to take out elements by range (#11002)
Matches the general behavior of `Vec::drain` or
`indexmap::IndexMap::drain`:
- Drop the remaining elements (implementing the unstable `keep_rest()`
would not be compatible with something like `indexmap`)
- No `AsRef<[T]>` or `Drain::as_slice()` behavior as this would make
layout assumptions.
- `Drain: DoubleEndedIterator`

Found useful in #10903
2023-11-08 22:54:02 +01:00
Ian Manske
1fd3bc1ba6
Add exec command for Windows (#11001)
# Description
Based of the work and discussion in #10844, this PR adds the `exec`
command for Windows. This is done by simply spawning a
`std::process::Command` and then immediately exiting via
`std::process::exit` once the child process is finished. The child
process's exit code is passed to `exit`.

# User-Facing Changes
The `exec` command is now available on Windows, and there should be no
change in behaviour for Unix systems.
2023-11-08 14:50:25 -06:00
Ian Manske
59ea28cf06
Use Record::get instead of Value functions (#10925)
# Description
Where appropriate, this PR replaces instances of
`Value::get_data_by_key` and `Value::follow_cell_path` with
`Record::get`. This avoids some unnecessary clones and simplifies the
code in some places.
2023-11-08 21:47:37 +01:00
Andrej Kolchin
435abadd8a
Add special error case for alias (#10975)
Adds a special error, which is triggered by `alias foo=bar` style
commands. It adds a help string which recommends adding spaces.

Resolve #10958

---------

Co-authored-by: Jakub Žádník <kubouch@gmail.com>
2023-11-08 13:35:40 -06:00
Stefan Holderbach
86cd387439
Refactor and fix Config<->Value mechanism (#10896)
# Description
Our config exists both as a `Config` struct for internal consumption and
as a `Value`. The latter is exposed through `$env.config` and can be
both set and read.
Thus we have a complex bug-prone mechanism, that reads a `Value` and
then tries to plug anything where the value is unrepresentable in
`Config` with the correct state from `Config`.

The parsing involves therefore mutation of the `Value` in a nested
`Record` structure. Previously this was wholy done manually, with
indices.
To enable deletion for example, things had to be iterated over from the
back. Also things were indexed in a bunch of places. This was hard to
read and an invitation for bugs.

With #10876 we can now use `Record::retain_mut` to traverse the records,
modify anything that needs fixing, and drop invalid fields.

# Parts:

- Error messages now consistently use the correct spans pointing to the
problematic value and the paths displayed in some messages are also
aligned with the keys used for lookup.
- Reconstruction of values has been fixed for:
	- `table.padding`
	- `buffer_editor`
	- `hooks.command_not_found`
	- `datetime_format` (partial solution)
- Fix validation of `table.padding` input so value is not set (and
underflows `usize` causing `table` to run forever with negative values)
- New proper types for settings. Fully validated enums instead of
strings:
  - `config.edit_mode` -> `EditMode` 
  	- Don't fall back to vi-mode on invalid string
  - `config.table.mode` -> `TableMode`
- there is still a fall back to `rounded` if given an invalid
`TableMode` as argument to the `nu` binary
  - `config.completions.algorithm` -> `CompletionAlgorithm`
  - `config.error_style` -> `ErrorStyle`
    - don't implicitly fall back to `fancy` when given an invalid value.
- This should also shrink the size of `Config` as instead of 4x24 bytes
those fields now need only 4x1 bytes in `Config`
- Completely removed macros relying on the scope of `Value::into_config`
so we can break it up into smaller parts in the future.
- Factored everything into smaller files with the types and helpers for
particular topics.
- `NuCursorShape` now explicitly expresses the `Inherit` setting.
conversion to option only happens at the interface to `reedline`
2023-11-08 20:31:30 +01:00
Stefan Holderbach
edbf3aaccb
Use Record's public API in a bunch of places (#10927)
# Description
Since #10841 the goal is to remove the implementation details of
`Record` outside of core operations.

To this end use Record iterators and map-like accessors in a bunch of
places. In this PR I try to collect the boring cases where I don't
expect any dramatic performance impacts or don't have doubts about the
correctness afterwards

- Use checked record construction in `nu_plugin_example`
- Use `Record::into_iter` in `columns`
- Use `Record` iterators in `headers` cmd
- Use explicit record iterators in `split-by`
- Use `Record::into_iter` in variable completions
- Use `Record::values` iterator in `into sqlite`
- Use `Record::iter_mut` for-loop in `default`
- Change `nu_engine::nonexistent_column` to use iterator
- Use `Record::columns` iter in `nu-cmd-base`
- Use `Record::get_index` in `nu-command/network/http`
- Use `Record.insert()` in `merge`
- Refactor `move` to use encapsulated record API
- Use `Record.insert()` in `explore`
- Use proper `Record` API in `explore`
- Remove defensiveness around record in `explore`
- Use encapsulated record API in more `nu-command`s

# User-Facing Changes
None intentional

# Tests + Formatting
(-)
2023-11-08 14:24:00 +01:00
Eric Hodel
55316a9f27
Convert ShellError::DatetimeParseError to named fields (#10991)
# Description

Part of #10700

# User-Facing Changes

None

# Tests + Formatting

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

# After Submitting

N/A
2023-11-08 13:04:02 +01:00
Darren Schroeder
d3ec3dc66b
allow vscode-specific ansi escape sequence to set path (#10990)
# Description

This change allows the vscode-specific ansi escape sequence of
633;P;Cwd= to be run when nushell detects that it's running inside of
vscode's terminal. Otherwise the standard OSC7 will run. This is helpful
with ctrl+g inside of vscode terminal as well.

closed #10989 

/cc @CAD97 

# 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 std testing; testing run-tests --path
crates/nu-std"` 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.
-->
2023-11-07 19:38:30 -06:00
Stefan Holderbach
7ebae0b5f7
Refactor table cmd and nu-table with Record API (#10930)
# Description
- Simplify `table` record highlight with `.get_mut`
  - pretty straight forward
- Use record iterators in `table` abbreviation logic
- This required some rework if we go from guaranted contiguous arrays to
iterators
- Refactor `nu-table` internals to new record API
# User-Facing Changes
None intened

# Tests + Formatting
(-)
2023-11-08 01:22:47 +01:00
Stefan Holderbach
f45aed257f
Refactor find in terms of clean Record API (#10929)
# Description
Rewrite `find` internals with the same principles as in #10927.

Here we can remove an unnecessary lookup accross all columns when not
narrowing find to particular columns

- Change `find` internal fns to use iterators
- Remove unnecessary quadratic lookup in `find`
- Refactor `find` record highlight logic
# User-Facing Changes
Should provide a small speedup when not providing `find --columns`

# Tests + Formatting
(-)
2023-11-08 01:06:22 +01:00
Ian Manske
60da7abbc7
Use Vec for Closure captures (#10940)
# Description
Changes the `captures` field in `Closure` from a `HashMap` to a `Vec`
and makes `Stack::captures_to_stack` take an owned `Vec` instead of a
borrowed `HashMap`.

This eliminates the conversion to a `Vec` inside `captures_to_stack` and
makes it possible to avoid clones altogether when using an owned
`Closure` (which is the case for most commands). Additionally, using a
`Vec` reduces the size of `Value` by 8 bytes (down to 72).

# User-Facing Changes
Breaking API change for `nu-protocol`.
2023-11-08 00:43:28 +01:00
Eric Hodel
7a3cbf43e8
Convert ShellError::UnsupportedInput to named fields (#10971)
# Description

This is easy to do with rust-analyzer, but I didn't want to just pump
these all out without feedback.

Part of #10700

# User-Facing Changes

None

# Tests + Formatting

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

# After Submitting

N/A

---------

Co-authored-by: Stefan Holderbach <sholderbach@users.noreply.github.com>
2023-11-07 23:25:32 +01:00
dependabot[bot]
45b02ce2ab
Bump indexmap from 2.0.2 to 2.1.0 (#10969) 2023-11-07 15:36:34 +00:00
Eric Hodel
c039e4b3d0
Update description and error types for split-by (#10865)
# Description

`split-by` only works on a `Record`, the error type was updated to
match, and now uses a more-specific type. (Two type fixes for the price
of one!)

The `usage` was updated to say "record" as well

# User-Facing Changes

* Providing the wrong type to `split-by` now gives an error messages
with the correct required input type

Previously:

```
❯ ls | get name | split-by type
Error:   × unsupported input
   ╭─[entry #267:1:1]
 1 │ ls | get name | split-by type
   ·      ─┬─
   ·       ╰── requires a table with one row for splitting
   ╰────
```

With this PR:

```
❯ ls | get name | split-by type
Error: nu:🐚:type_mismatch

  × Type mismatch.
   ╭─[entry #1:1:1]
 1 │ ls | get name | split-by type
   ·      ─┬─
   ·       ╰── requires a record to split
   ╰────
```

# Tests + Formatting

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

# After Submitting

Only generated commands need to be updated

---------

Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com>
2023-11-07 16:27:10 +01:00
Christopher Durham
9b202d560d
Limit run-external --redirect-combine sh test to not(Windows) (#10905)
# Description

Limit the test `-p nu-command --test main
commands::run_external::redirect_combine` which uses `sh` to running on
`not(Windows)` like is done for other tests assuming unixy CLI items;
`sh` doesn't exist on Windows.

# User-Facing Changes

None; this is a change to tests only.

# Tests + Formatting

- 🟢 `toolkit fmt`
- 🟢 `toolkit clippy`
- 🟢 `toolkit test`
- 🟢 `toolkit test stdlib`
2023-11-07 16:35:24 +08:00
Darren Schroeder
1874082a2c
allow items to properly evaluate block settings (#10980)
# Description

@jntrnr discovered that `items` wasn't properly setting the
`eval_block_with_early_return()` block settings. This change fixes that
which allows `echo` to be redirected and therefore pass data through the
pipeline.

Without `echo`
```nushell
❯ { new: york, san: francisco } | items {|key, value| $'($key) ($value)' }
╭─┬─────────────╮
│0│new york     │
│1│san francisco│
╰─┴─────────────╯
```
With `echo`
```nushell
❯ { new: york, san: francisco } | items {|key, value| echo $'($key) ($value)' }
╭─┬─────────────╮
│0│new york     │
│1│san francisco│
╰─┴─────────────╯
```

# 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 std testing; testing run-tests --path
crates/nu-std"` 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.
-->
2023-11-06 12:15:37 -06:00
Darren Schroeder
1359b26da2
update items example to send data through the pipeline (#10976)
# Description

This PR updates the `items` example so that it doesn't use `echo`.
`echo` now works like print unless it's being redirected, so it doesn't
send values through the pipeline anymore like the example showed.

# 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 std testing; testing run-tests --path
crates/nu-std"` 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.
-->
2023-11-06 06:59:13 -06:00
Eric Hodel
81d00f71a9
Show plugin extra usage and search terms (#10952)
# Description

The `PluginSignature` type supports extra usage but this was not
available in `plugin_name --help`. It also supports search terms but
these did not appear in `help commands`

New behavior show below is the "Extra usage for nu-example-1" line and
the "Search terms:" line

```
❯ nu-example-1 --help
PluginSignature test 1 for plugin. Returns Value::Nothing

Extra usage for nu-example-1

Search terms: example

Usage:
  > nu-example-1 {flags} <a> <b> (opt) ...(rest)

Flags:
  -h, --help - Display the help message for this command
  -f, --flag - a flag for the signature
  -n, --named <String> - named string

Parameters:
  a <int>: required integer value
  b <string>: required string value
  opt <int>: Optional number (optional)
  ...rest <string>: rest value string

Examples:
  running example with an int value and string value
  > nu-example-1 3 bb
```

Search terms are also available in `help commands`:

```
❯ help commands | where name == "nu-example-1" | select name search_terms
╭──────────────┬──────────────╮
│     name     │ search_terms │
├──────────────┼──────────────┤
│ nu-example-1 │ example      │
╰──────────────┴──────────────╯
```

# User-Facing Changes

Users can now see plugin extra usage and search terms 

# Tests + Formatting

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

# After Submitting

N/A
2023-11-04 15:12:58 -05:00
dzorya
77fbf3e2d2
better help message for MissingPositional error (#10949)
Added "Use `--help` for more information." to the help of
MissingPositional error
- this PR should close
[#10946](https://github.com/nushell/nushell/issues/10946)

**Before:**

![image](https://github.com/nushell/nushell/assets/1835944/629aeaae-e985-41aa-a791-05ef062e988e)

**After:**

![image](https://github.com/nushell/nushell/assets/1835944/0bc1868c-ffed-4440-ad98-2cf29aa8c656)



<!--
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 std testing; testing run-tests --path
crates/nu-std"` 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: Denis Zorya <denis.zorya@trafigura.com>
2023-11-04 12:24:21 -05:00
Andrej Kolchin
f565661f42
Fix issues with error make refactor (#10950)
- Replaced one error return `None` with a `help` option.
- Fixed example.
- Added comments highlighting correct early returns.

Fix #10947
2023-11-04 17:23:43 +01:00
Andrej Kolchin
1a864ea6f4
Refactor error make (#10923)
- Replaced `start`/`end` with span.
- Fixed standard library.
- Add `help` option.
- Add a couple more errors for invalid record types.

Resolve #10914


# Description



# User-Facing Changes

- **BREAKING CHANGE:** `error make` now takes in `span` instead of
`start`/`end`:

  ```Nushell
  error make {
      msg: "Message"
      label: {
          text: "Label text"
          span: (metadata $var).span
      }
  }
  ```
- `error make` now has a `help` argument for custom error help.
2023-11-03 10:09:33 -05:00
Darren Schroeder
c1738620e3
remove unwraps in registry_query command (#10936)
# Description

After talking to @CAD97, I decided to change these unwraps to expects.
See the comments. The bigger question is, how did unwrap pass the CI?

# 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 std testing; testing run-tests --path
crates/nu-std"` 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.
-->
2023-11-03 08:12:36 -05:00
Ian Manske
56e35fc3f9
Reduce element shifting in Record::retain_mut (#10915)
# Description
Replaces the `Vec::remove` in `Record::retain_mut` with some swaps which
should eliminate the `O(n^2)` complexity due to repeated shifting of
elements.
2023-11-02 20:01:46 +01:00
stfacc
29591c97a7
Add "shape_keyword" to default config (#10922)
Keep it in sync with Rust code.
Mainly so that people know they can style keywords.

I discovered this while trying to change color of "else".
2023-11-02 19:59:17 +01:00
Andrej Kolchin
697dee6750
Change input list to return null (#10913)
Now the `input list` command, when nothing is selected, will return a
null instead of empty string or an empty list.

Resolves #10909.


# User-Facing Changes

`input list` now returns a `null` when nothing is selected.
2023-11-02 19:57:06 +01:00
Marc Schreiber
0ca8fcf58c
Integrated Language Server (#10723)
# Description

This commit integrates a language server into nushell so that IDEs don't
have to convert CLI option back and forth.

- fixes https://github.com/nushell/vscode-nushell-lang/issues/117
- fixes https://github.com/jokeyrhyme/nuls/issues/8

Tracking tasks


- [x]
[textDocument/hover](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_hover)
-> `nu --ide-hover`
- [x]
[textDocument/completion](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_completion)
-> `nu --ide-complete`
- [x]
[textDocument/definition](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_definition)
-> `nu --ide-goto-def`
- ~~[ ]
[textDocument/didChange](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_didChange),
[textDocument/didClose](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_didClose),
and
[textDocument/didOpen](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_didOpen)~~
(will be done in a follow-up PR)
- ~~[ ]
[textDocument/inlayHint](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_inlayHint)
-> `nu --ide-check`~~ (will be done in a follow-up PR)
- ~~[ ]
[textDocument/publishDiagnostics](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_publishDiagnostics)
-> `nu --ide-check`~~ (will be done in a follow-up PR)
- ~~[ ]
[workspace/configuration](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#workspace_configuration)~~
(will be done in a follow-up PR)
- ~~[ ]
[workspace/didChangeConfiguration](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#workspace_didChangeConfiguration)~~
(will be done in a follow-up PR)


# User-Facing Changes

The command line options `--lsp` will start a LSP server.

# 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 std testing; testing run-tests --path
crates/nu-std"` 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.
-->
2023-11-02 10:18:57 -05:00
Stefan Holderbach
a46048f362
Use Record APIs in nu-protocol/nu-engine (#10917)
# Description
Consequences of #10841

This does not yet make the assumption that columns are always
duplicated. Follow the existing logic here

- Use saner record API in `nu-engine/src/eval.rs`
- Use checked record construction in `nu-engine/src/scope.rs`
- Use `values` iterator in `nu-engine/src/scope.rs`
- Use `columns` iterator in `nu_engine::get_columns()`
- Start using record API in `value/mod.rs`
- Use `.insert` in `eval_const.rs` Record code
- Record API for `eval_const.rs` table code

# User-Facing Changes
None

# Tests + Formatting
None
2023-11-01 23:19:58 +01:00
Stefan Holderbach
0569a9c92e
Disallow duplicated columns in table literals (#10875)
# Description
Pretty much all operations/commands in Nushell assume that the column
names/keys in a record and thus also in a table (which consists of a
list of records) are unique.
Access through a string-like cell path should refer to a single column
or key/value pair and our output through `table` will only show the last
mention of a repeated column name.

```nu
[[a a]; [1 2]]
╭─#─┬─a─╮
│ 0 │ 2 │
╰───┴───╯
```

While the record parsing already either errors with the
`ShellError::ColumnDefinedTwice` or silently overwrites the first
occurence with the second occurence, the table literal syntax `[[header
columns]; [val1 val2]]` currently still allowed the creation of tables
(and internally records with more than one entry with the same name.

This is not only confusing, but also breaks some assumptions around how
we can efficiently perform operations or in the past lead to outright
bugs (e.g. #8431 fixed by #8446).

This PR proposes to make this an error.
After this change another hole which allowed the construction of records
with non-unique column names will be plugged.

## Parts
- Fix `SE::ColumnDefinedTwice` error code
- Remove previous tests permitting duplicate columns
- Deny duplicate column in table literal eval
- Deny duplicate column in const eval
- Deny duplicate column in `from nuon`

# User-Facing Changes
`[[a a]; [1 2]]` will now return an error:

```
Error: nu:🐚:column_defined_twice

  × Record field or table column used twice
   ╭─[entry #2:1:1]
 1 │ [[a a]; [1 2]]
   ·   ┬ ┬
   ·   │ ╰── field redefined here
   ·   ╰── field first defined here
   ╰────
```

this may under rare circumstances block code from evaluating.

Furthermore this makes some NUON files invalid if they previously
contained tables with repeated column names.

# Tests + Formatting
Added tests for each of the different evaluation paths that materialize
tables.
2023-11-01 21:25:35 +01:00
Darren Schroeder
c1ca10ffd1
allow compact to also compact empty strings (#10912)
# Description

This change allows `compact` to also compact things with empty strings,
empty lists, and empty records if the `--empty` switch is used. Let's
add a quality-of-life improvement here to just compact all this mess. If
this is a bad idea, please cite examples demonstrating why.

```
❯ [[name position]; [Francis Lead] [Igor TechLead] [Aya null]] | compact position
╭#┬─name──┬position╮
│0│Francis│Lead    │
│1│Igor   │TechLead│
╰─┴───────┴────────╯
❯ [[name position]; [Francis Lead] [Igor TechLead] [Aya ""]] | compact position --empty
╭#┬─name──┬position╮
│0│Francis│Lead    │
│1│Igor   │TechLead│
╰─┴───────┴────────╯
❯ [1, null, 2, "", 3, [], 4, {}, 5] | compact
╭─┬─────────────────╮
│0│                1│
│1│                2│
│2│                 │
│3│                3│
│4│[list 0 items]   │
│5│                4│
│6│{record 0 fields}│
│7│                5│
╰─┴─────────────────╯
❯ [1, null, 2, "", 3, [], 4, {}, 5] | compact --empty
╭─┬─╮
│0│1│
│1│2│
│2│3│
│3│4│
│4│5│
╰─┴─╯
```

# 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 std testing; testing run-tests --path
crates/nu-std"` 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.
-->
2023-11-01 13:56:25 -05:00
Ian Manske
15c22db8f4
Make FromValue take owned Values (#10900)
# Description
Changes `FromValue` to take owned `Value`s instead of borrowed `Value`s.
This eliminates some unnecessary clones (e.g., in `call_ext.rs`).

# User-Facing Changes
Breaking API change for `nu_protocol`.
2023-10-31 19:47:00 +01:00
Himadri Bhattacharjee
1c52b112c8
Return external file completions if not empty (#10898)
<!--
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.
-->
If an external completer is used and it returns no completions for a
filepath, we fall back to the builtin path completer.

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

Path completions will remain consistent with the use of an external
completer.

# 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 std testing; testing run-tests --path
crates/nu-std"` 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.
-->
2023-10-31 11:32:21 -05:00
Himadri Bhattacharjee
275dba82d5
fix: preserve path when completing intermediate directory (#10831)
<!--
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 #10766

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

If the partial supplied to the completion function is shorter than the
span, the cursor is in between the path, we are trying to complete an
intermediate directory. In such a case we:
- only suggest directory names
- don't append the slash since it is already present
- only complete the path till the component the cursor is on

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

Intermediate directories can be completed without erasing the rest of
the path.

# 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 std testing; testing run-tests --path
crates/nu-std"` 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.
-->
2023-10-31 07:39:14 -05:00
WindSoilder
cf7040a215
Refactor: introduce a gen_save_call function to reduce duplicate code (#10852)
make a little refactor on relative code to make it more
readable.
2023-10-31 10:45:36 +08:00
Ian Manske
72cb4b6032
Reuse Closure type in Value::Closure (#10894)
# Description
Reuses the existing `Closure` type in `Value::Closure`. This will help
with the span refactoring for `Value`. Additionally, this allows us to
more easily box or unbox the `Closure` case should we chose to do so in
the future.

# User-Facing Changes
Breaking API change for `nu_protocol`.
2023-10-30 23:34:23 +01:00
Andrej Kolchin
d4cbab454e
Change category of scope commands to core (#10892)
close #10802
2023-10-30 19:55:40 +01:00
Stefan Holderbach
3645178ff1
Convert "pure" macros to pure fn in config.rs (#10893)
# Description
These macros simply took a `Span` and a shared reference to `Config` and
returned a Value, for better readability and reasoning about their
behavior convert them to simple function as they don't do anything
relevant with their macro powers.


# User-Facing Changes
None

# Tests + Formatting
(-)
2023-10-30 19:54:59 +01:00
Stefan Holderbach
005180f269
Add Record::remove/retain/retain_mut (#10876)
# Description
While we have now a few ways to add items or iterate over the
collection, we don't have a way to cleanly remove items from `Record`.

This PR fixes that:

- Add `Record.remove()` to remove by key
- makes the assumption that keys are unique, so can not be used
universally, yet (see #10875 for an important example)
- Add naive `Record.retain()` for inplace removal
- This follows the two separate `retain`/`retain_mut` in the Rust std
library types, compared to the value-mutating `retain` in `indexmap`
- Add `Record.retain_mut()` for one-pass pruning

Continuation of #10841 

# User-Facing Changes
None yet.

# Tests + Formatting
Doctests for the `retain`ing fun
2023-10-30 19:51:28 +01:00
Andrej Kolchin
72f7b9b7cc
Add umkdir command (#10785)
A `mkdir` command, which uses `uu_mkdir` as backend.

close #10515.
2023-10-30 07:59:48 -05:00
dependabot[bot]
d8c59eddb3
Bump rust-ini from 0.19.0 to 0.20.0 (#10882) 2023-10-30 11:56:13 +00:00
dependabot[bot]
ac43372618
Bump scraper from 0.17.1 to 0.18.1 (#10879) 2023-10-30 11:53:26 +00:00
Darren Schroeder
2e68e6ddbf
allow sort-by to work with records (#10870)
# Description

This PR restores and old functionality that must of been broken with the
input_output_types() updating. It allows commands like this to work
again.

```nushell
open $nu.history-path | 
  get history.command_line | 
  split column ' ' cmd | 
  group-by cmd --to-table | 
  update items {|u| $u.items | length} | 
  sort-by items -r | 
  first 10 | 
  table -n 1
```
output
```
╭#─┬group─┬items╮
│1 │exit  │ 3004│
│2 │ls    │ 2591│
│3 │git   │ 1678│
│4 │help  │ 1549│
│5 │open  │ 1374│
│6 │cd    │ 1186│
│7 │cargo │  944│
│8 │let   │  784│
│9 │source│  755│
│10│z     │  486│
╰#─┴group─┴items╯
```

# 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 std testing; testing run-tests --path
crates/nu-std"` 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.
-->
2023-10-29 08:22:20 -05:00
Eric Hodel
3dfe1a4f0e
group-by now returns a table instead of a record (#10848)
# Description

Previously `group-by` returned a record containing each group as a
column. This data layout is hard to work with for some tasks because you
have to further manipulate the result to do things like determine the
number of items in each group, or the number of groups. `transpose` will
turn the record returned by `group-by` into a table, but this is
expensive when `group-by` is run on a large input.

In a discussion with @fdncred [several
workarounds](https://github.com/nushell/nushell/discussions/10462) to
common tasks were discussed, but they seem unsatisfying in general.

Now when `group-by --to-table` is used a table is returned with the
columns "groups" and "items" making it easier to do things like count
the number of groups (`| length`) or count the number of items in each
group (`| each {|g| $g.items | length`)

# User-Facing Changes

* `group-by` returns a `table` with "group" and "items" columns instead
of a `record` with one column per group name

# Tests + Formatting

Tests for `group-by` were updated

# After Submitting

* No breaking changes were made. The new `--to-table` switch should be
added automatically to the [`group-by`
documentation](https://www.nushell.sh/commands/docs/group-by.html)
2023-10-28 14:15:14 -05:00
Stefan Holderbach
c87bac04c0
Add common map-like API to nu_protocol::Record (#10841)
# Description

> Our `Record` looks like a map, quacks like a map, so let's treat it
with the API for a map

Implement common methods found on e.g. `std::collections::HashMap` or
the insertion-ordered [indexmap](https://docs.rs/indexmap).

This allows contributors to not have to worry about how to get to the
relevant items and not mess up the assumptions of a Nushell record.

## Record assumptions
- `cols` and `vals` are of equal length
- for all practical purposes, keys/columns should be unique

## End goal

The end goal of the upcoming series of PR's is to allow us to make
`cols` and `vals` private.
Then it would be possible to exchange the backing datastructure to best
fit the expected workload.
This could be statically (by finding the best balance) or dynamically by
using an `enum` of potential representations.

## Parts
- Add validating explicit part constructor
`Record::from_raw_cols_vals()`
- Add `Record.columns()` iterator
- Add `Record.values()` iterator
- Add consuming `Record.into_values()` iterator
- Add `Record.contains()` helper
- Add `Record.insert()` that respects existing keys
- Add key-based `.get()`/`.get_mut()` to `Record`
- Add `Record.get_index()` for index-based access
- Implement `Extend` for `Record` naively
- Use checked constructor in `record!` macro
- Add `Record.index_of()` to get index by key

# User-Facing Changes
None directly

# Developer facing changes
You don't have to roll your own record handling and can use a familiar
API

# Tests + Formatting
No explicit unit tests yet. Wouldn't be too tricky to validate core
properties directly.
Will be exercised by the following PRs using the new
methods/traits/iterators.
2023-10-28 15:18:41 +02:00
Stefan Holderbach
4b301710d3
Convert more examples and tests to record! macro (#10840)
# Description
Use `record!` macro instead of defining two separate `vec!` for `cols`
and `vals` when appropriate.
This visually aligns the key with the value.
Further more you don't have to deal with the construction of `Record {
cols, vals }` so we can hide the implementation details in the future.

## State

Not covering all possible commands yet, also some tests/examples are
better expressed by creating cols and vals separately.

# User/Developer-Facing Changes
The examples and tests should read more natural. No relevant functional
change

# Bycatch

Where I noticed it I replaced usage of `Value` constructors with
`Span::test_data()` or `Span::unknown()` to the `Value::test_...`
constructors. This should make things more readable and also simplify
changes to the `Span` system in the future.
2023-10-28 14:52:31 +02:00
Michel Lind (né Salim)
7d67ca3652
[nu-cmd-base] add missing LICENSE text (#10855)
# Description
Adds license text to the `nu-cmd-base` crate, copied from `nu-cmd-lang`

# User-Facing Changes
N/A

# Tests + Formatting
```
$ cargo package --allow-dirty --no-verify
$ bsdtar tf ../../target/package/nu-cmd-base-0.86.1.crate | grep LICENSE
```

# After Submitting
N/A

Signed-off-by: Michel Lind <salimma@fedoraproject.org>
2023-10-27 15:55:03 -05:00
Antoine Stevan
01d8961eb7
use to_lowercase in str downcase (#10850)
# Description
as we can see in the [documentation of
`str.to_lowercase`](https://doc.rust-lang.org/std/primitive.str.html#method.to_lowercase),
not only ASCII symbols have lower and upper variants.

- `str upcase` uses the correct method to convert the string

7ac5a01e2f/crates/nu-command/src/strings/str_/case/upcase.rs (L93)
- `str downcase` incorrectly converts only ASCII characters

7ac5a01e2f/crates/nu-command/src/strings/str_/case/downcase.rs (L124)

this PR uses `str.to_lower_case` instead of `str.to_ascii_lowercase` in
`str downcase`.

# User-Facing Changes
- upcase still works fine
```nushell
~ l> "ὀδυσσεύς" | str upcase
ὈΔΥΣΣΕΎΣ
```
- downcase now works

👉 before
```nushell
~ l> "ὈΔΥΣΣΕΎΣ" | str downcase
ὈΔΥΣΣΕΎΣ
```
👉 after
```nushell
~ l> "ὈΔΥΣΣΕΎΣ" | str downcase
ὀδυσσεύς
```

# Tests + Formatting
- 🟢 `toolkit fmt`
- 🟢 `toolkit clippy`
-  `toolkit test`
-  `toolkit test stdlib`

adds two tests
- `non_ascii_upcase`
- `non_ascii_downcase`

# After Submitting
2023-10-27 19:16:17 +02:00
Antoine Stevan
7ac5a01e2f
deprecate glob --not in favor of glob --exclude (#10827)
# Description
looking at the [Wax documentation about
`wax::Walk.not`](https://docs.rs/wax/latest/wax/struct.Walk.html#examples),
especially
> therefore does not read directory trees from the file system when a
directory matches an [exhaustive glob
expression](https://docs.rs/wax/latest/wax/trait.Pattern.html#tymethod.is_exhaustive)

> **Important**
> in the following of this PR description, i talk about *pruning* and a
`--prune` option, but this has been changed to *exclusion* and
`--exclude` after a discussion with @fdncred.

this looks like a *pruning* operation to me, right? 😮 
i wanted to make the `glob` option `--not` clearer about that, because
>   -n, --not <List(String)> - Patterns to exclude from the results

from `help glob` is not very explicit about whether the search is pruned
when entering a directory matching a pattern in `--not` or just removing
it from the output 😕

## changelog
this PR proposes to rename the `glob --not` option to `glob --prune` and
make it's documentation more explicit 😋

## benchmarking
to support the *pruning* behaviour put forward above, i've run a
benchmark
1. define two closures to compare the behaviour between removing
patterns manually or using `--not`
```nushell
let where = {
    [.*/\.local/.*, .*/documents/.*, .*/\.config/.*]
        | reduce --fold (glob **) {|pat, acc| $acc | where $it !~ $pat}
        | length
}
```
```nushell
let not = { glob ** --not [**/.local/**, **/documents/**, **/.config/**] | length }
```
2. run the two to make sure they give similar results
```nushell
> do $where
33424
```
```nushell
> do $not
33420
```
👌 
3. measure the performance
```nushell
use std bench
```
```nushell
> bench --verbose --pretty --rounds 25 $not
44ms 52µs 285ns +/- 977µs 571ns
```
```nushell
> bench --verbose --pretty --rounds 5 $where
1sec 250ms 187µs 99ns +/- 8ms 538µs 57ns
```

👉 we can see that the results are (almost) the same but
`--not` is much faster, looks like pruning 😋

# User-Facing Changes
- `--not` will give a warning message but still work
- `--prune` will work just as `--not` without warning and with a more
explicit doc
- `--prune` and `--not` at the same time will give an error

# Tests + Formatting
this PR fixes the examples of `glob` using the `--not` option.

# After Submitting
prepare the removal PR and mention in release notes.
2023-10-25 17:11:57 +02:00
Terts Diepraam
e2fb0e5b82
implement whoami using uutils (#10488)
<!--
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.
-->

Implements `whoami` using the `whoami` command from uutils as backend.
This is a draft because it depends on
https://github.com/uutils/coreutils/pull/5310 and a new release of
uutils needs to be made (and the paths in `Cargo.toml` should be
updated). At this point, this is more of a proof of concept 😄

Additionally, this implements a (simple and naive) conversion from the
uutils `UResult` to the nushell `ShellError`, which should help with the
integration of other utils, too. I can split that off into a separate PR
if desired.

I put this command in the "platform" category. If it should go somewhere
else, let me know!

The tests will currently fail, because I've used a local path to uutils.
Once the PR on the uutils side is merged, I'll update it to a git path
so that it can be tested and runs on more machines than just mine.

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

New `whoami` command. This might break some users who expect the system
`whoami` command. However, the result of this new command should be very
close, just with a nicer help message, at least for Linux users. The
default `whoami` on Windows is quite different from this implementation:
https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/whoami

# 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 std testing; testing run-tests --path
crates/nu-std"` to run the tests for the standard library

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

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

---------

Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com>
2023-10-25 09:53:52 -05:00
Antoine Stevan
a11e41332c
expand paths and split PATH in std path add (#10710)
related to
-
https://discord.com/channels/601130461678272522/614593951969574961/1162406310155923626

# Description
this PR
- does a bit of minor refactoring
- makes sure the input paths get expanded
- makes sure the input PATH gets split on ":"
- adds a test
- fixes the other tests

# User-Facing Changes
should give a better overall experience with `std path add`

# Tests + Formatting
adds a new test case to the `path_add` test and fixes the others.

# After Submitting
2023-10-25 16:43:27 +02:00
Antoine Stevan
f3656f7822
sync $env.config.filesize.metric (#10277)
# Description
just noticed `$env.config.filesize.metric` is not the same in
`default_config.nu` and `config.rs`

# User-Facing Changes
filesizes will show in "binary" mode by default when using the default
config files, i.e. `kib` instead of `kb`.

# Tests + Formatting

# After Submitting
2023-10-25 16:42:24 +02:00
WindSoilder
f35741d50e
redirection: fix internal commands error with o+e> redirection (#10816)
# Description
Currently the following command is broken:
```nushell
echo a o+e> 1.txt
```

It's because we don't redirect output of `echo` command. This pr is
trying to fix it.
2023-10-25 16:35:51 +02:00
Gaëtan
d93315d8f5
Fix describe -d for lazy records (#10836)
<!--
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 fixes an overlook from a previous PR. It now correctly returns
the details on lazy records.

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->
Describe detailed now returns the expected result.
2023-10-25 08:04:37 -05:00
Ludwig Austermann
8429aec57f
readd update flag to cp command (#10824)
# Description
- this PR should close #10819


# User-Facing Changes
Behaviour is similar to pre 0.86.0 behaviour of the cp command and
should as such not have a user-facing change, only compared to the
current version, were the option is readded.


# After Submitting
I guess the documentation will be automatically updated and as this
feature is no further highlighted, probably, no more work will be needed
here.

# Considerations
coreutils actually allows a third option:
```
pub enum UpdateMode {
    // --update=`all`,
    ReplaceAll,
    // --update=`none`
    ReplaceNone,
    // --update=`older`
    // -u
    ReplaceIfOlder,
}
```
namely `ReplaceNone`, which I have not added. Also I think that
specifying `--update 'abc'` is non functional.
2023-10-25 11:30:13 +02:00
WindSoilder
f043a8a8ff
redirect should have a target (#10835)
# Description
Fixes:  #10830 

The issue happened during lite-parsing, when we want to put a
`LiteElement` to a `LitePipeline`, we do nothing if relative redirection
target is empty.

So the command `echo aaa o> | ignore` will be interpreted to `echo aaa |
ignore`.

This pr is going to check and return an error if redirection target is
empty.

# User-Facing Changes
## Before
```
❯ echo aaa o> | ignore   # nothing happened
```

## After
```nushell
❯ echo aaa o> | ignore
Error: nu::parser::parse_mismatch

  × Parse mismatch during operation.
   ╭─[entry #1:1:1]
 1 │ echo aaa o> | ignore
   ·          ─┬
   ·           ╰── expected redirection target
   ╰────
```
2023-10-25 11:19:35 +02:00
Jack Wright
c6016d7659
Dataframe support for small int types (#10828)
Turned features to allow signed and unsigned 8 and 16 bit types.

---------

Co-authored-by: Jack Wright <jack.wright@disqo.com>
2023-10-24 21:25:21 -05:00
Hudson Clark
78b4472b32
Support pattern matching null literals (#10829)
# Description
Support pattern matching against the `null` literal.  Fixes #10799 

### Before
```nushell
> match null { null => "success", _ => "failure" }
failure
```

### After
```nushell
> match null { null => "success", _ => "failure" }
success
```

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->
Users can pattern match against a `null` literal.
2023-10-25 06:30:45 +08:00
Hudson Clark
cb754befe9
fix: Ensure consistent vals and cols when parsing with --flexible (#10814)
# Description
`from tsv` and `from csv` both support a `--flexible` flag. This flag
can be used to "allow the number of fields in records to be variable".

Previously, a record's invariant that `rec.cols.len() == rec.vals.len()`
could be broken during parsing. This can cause runtime errors as in
#10693. Other commands, like `select` were also affected.

The inconsistencies are somewhat hard to see, as most nushell code
assumes an equal number of columns and values.

# Before

### Fewer values than columns
```nushell
> let record = (echo "one,two\n1" | from csv --flexible | first)
# There are two columns
> $record | columns | to nuon
[one, two]
# But only one value
> $record | values | to nuon
[1]
# And printing the record doesn't show the second column!
> $record | to nuon
{one: 1}
```

### More values than columns
```nushell
> let record = (echo "one,two\n1,2,3" | from csv --flexible | first)
# There are two columns
> $record | columns | to nuon
[one, two]
# But three values
> $record | values | to nuon
[1, 2, 3]
# And printing the record doesn't show the third value!
> $record | to nuon
{one: 1, two: 2}
```
# After

### Fewer values than columns
```nushell
> let record = (echo "one,two\n1" | from csv --flexible | first)
# There are two columns
> $record | columns | to nuon
[one, two]
# And a matching number of values
> $record | values | to nuon
[1, null]
# And printing the record works as expected
> $record | to nuon
{one: 1, two: null}
```

### More values than columns
```nushell
> let record = (echo "one,two\n1,2,3" | from csv --flexible | first)
# There are two columns
> $record | columns | to nuon
[one, two]
# And a matching number of values
> $record | values | to nuon
[1, 2]
# And printing the record works as expected
> $record | to nuon
{one: 1, two: 2}
```

# User-Facing Changes
Using the `--flexible` flag with `from csv` and `from tsv` will not
result in corrupted record state.

# 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 std testing; testing run-tests --path
crates/nu-std"` 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.
-->
2023-10-24 15:54:26 -05:00
Gaëtan
0588a4fc19
Make debug info lazy (#10728)
<!--
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.
-->

* Makes the `debug info` lazy which greatly improves performance.
* Adds a `thread id` attribute

![Screenshot 2023-10-15
211940](https://github.com/nushell/nushell/assets/25441359/b8457a30-ebf7-4731-9e13-17635501f029)

![image](https://github.com/nushell/nushell/assets/25441359/010ed35b-9f50-4fc6-8650-b68b29d5a9cd)


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

`threadid` column added.

---------

Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com>
2023-10-24 12:48:05 -05:00
Darren Schroeder
ff3a0a0de3
fix main not building due to errors later found in describe (#10821)
# Description

This is just a fixup PR. There was a describe PR that passed CI but then
later didn't pass main. This PR fixes that issue.

# 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 std testing; testing run-tests --path
crates/nu-std"` 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.
-->
2023-10-23 13:22:32 -05:00
Gaëtan
c799f77577
Add detailed flag for describe (#10795)
- Add `detailed` flag for `describe`

- Improve detailed describe and better format when running examples.

# Rationale

For now, neither `describe` nor any of the `debug` commands provide an
easy and structured way of inspecting the data's type and more. This
flag provides a structured way of getting such information. Allows also
to avoid the rather hacky solution
```nu
$in | describe | str replace --regex '<.*' ''
```

# User-facing changes

Adds a new flag to ``describe`.
2023-10-23 09:12:11 -05:00
Stefan Holderbach
d3182a6737
Revert "Bump regex from 1.9.6 to 1.10.2" (#10818)
Reverts nushell/nushell#10812

This goes back to a version of `regex` and its dependencies that is
shared with a lot of our other dependencies. Before this we did not
duplicate big dependencies of `regex` that affect binary size and
compile time.

As there is no known bug or security problem we suffer from, we can wait
on receiving the performance improvements to `regex` with the rest of
our `regex` dependents.
2023-10-23 09:11:32 -05:00
Christopher Durham
b5e09b8a30
Improve registry value return types (#10806)
r? @fdncred
Last one, I hope. At least short of completely redesigning `registry
query`'s interface. (Which I wouldn't implement without asking around
first.)

# Description

User-Facing Changes has the general overview. Inline comments provide a
lot of justification on specific choices. Most of the type conversions
should be reasonably noncontroversial, but expanding `REG_EXPAND_SZ`
needs some justification. First, an example of the behavior there:

```shell
> # release nushell:
> version | select version commit_hash | to md --pretty
| version | commit_hash                              |
| ------- | ---------------------------------------- |
| 0.85.0  | a6f62e05ae |
> registry query --hkcu Environment TEMP | get value
%USERPROFILE%\AppData\Local\Temp

> # with this patch:
> version | select version commit_hash | to md --pretty
| version | commit_hash                              |
| ------- | ---------------------------------------- |
| 0.86.1  | 0c5a4c991f |
> registry query --hkcu Environment TEMP | get value
C:\Users\CAD\AppData\Local\Temp

> # Microsoft CLI tooling behavior:
> ^pwsh -c `(Get-ItemProperty HKCU:\Environment).TEMP`
C:\Users\CAD\AppData\Local\Temp
> ^reg query HKCU\Environment /v TEMP
HKEY_CURRENT_USER\Environment
    TEMP    REG_EXPAND_SZ    %USERPROFILE%\AppData\Local\Temp
```

As noted in the inline comments, I'm arguing that it makes more sense to
eagerly expand the %EnvironmentString% placeholders, as none of
Nushell's path functionality will interpret these placeholders. This
makes the behavior of `registry query` match the behavior of pwsh's
`Get-ItemProperty` registry access, and means that paths (the most
common use of `REG_EXPAND_SZ`) are actually usable.

This does *not* break nu_script's
[`update-path`](https://github.com/nushell/nu_scripts/blob/main/sourced/update-path.nu);
it will just be slightly inefficient as it will not find any
`%Placeholder%`s to manually expand anymore. But also, note that
`update-path` is currently *wrong*, as a path including
`%LocalAppData%Low` is perfectly valid and sometimes used (to go to
`Appdata\LocalLow`); expansion isn't done solely on a path segment
basis, as is implemented by `update-path`.

I believe that the type conversions implemented by this patch are
essentially always desired. But if we want to keep `registry query`
"pure", we could easily introduce a `registry get`[^get] which does the
more complete interpretation of registry types, and leave `registry
query` alone as doing the bare minimum. Or we could teach `path expand`
to do `ExpandEnvironmentStringsW`. But REG_EXPAND_SZ being the odd one
out of not getting its registry type semantics decoded by `registry
query` seems wrong.

[^get]: This is the potential redesign I alluded to at the top. One
potential change could be to make `registry get Environment` produce
`record<Path: string, TEMP: string, TMP: string>` instead of `registry
query`'s `table<name: string, value: string, type: string>`, the idea
being to make it feel as native as possible. We could even translate
between Nu's cell-path and registry paths -- cell paths with spaces do
actually work, if a bit awkwardly -- or even introduce lazy records so
the registry can be traversed with normal data manipulation ... but that
all seems a bit much.

# User-Facing Changes

- `registry query`'s produced `value` has changed. Specifically:
-  Rows `where type == REG_EXPAND_SZ` now expand `%EnvironmentVarable%`
placeholders for you. For example, `registry query --hkcu Environment
TEMP | get value` returns `C:\Users\CAD\AppData\Local\Temp` instead of
`%USERPROFILE%\AppData\Local\Temp`.
- You can restore the old behavior and preserve the placeholders by
passing a new `--no-expand` switch.
- Rows `where type == REG_MULTI_SZ` now provide a `list<string>` value.
They previously had that same list, but `| str join "\n"`.
- Rows `where type == REG_DWORD_BIG_ENDIAN` now provide the correct
numeric value instead of a byte-swapped value.
- Rows `where type == REG_QWORD` now provide the correct numeric
value[^sign] instead of the value modulo 2<sup>32</sup>.
- Rows `where type == REG_LINK` now provide a string value of the link
target registry path instead of an internal debug string representation.
(This should never be visible, as links should be transparently
followed.)
- Rows `where type =~ RESOURCE` now provide a binary value instead of an
internal debug string representation.

[^sign]: Nu's `int` is a signed 64-bit integer. As such, values >=
2<sup>63</sup> will be reported as their negative two's compliment
value. This might sometimes be the correct interpretation -- the
registry does not distinguish between signed and unsigned integer values
-- but regedit and pwsh display all values as unsigned.
2023-10-23 07:21:27 -05:00
dependabot[bot]
05efd735b9
Bump which from 4.4.2 to 5.0.0 (#10811) 2023-10-23 14:14:28 +08:00
dependabot[bot]
5e0499fcf9
Bump uuid from 1.4.1 to 1.5.0 (#10810) 2023-10-23 14:14:08 +08:00
dependabot[bot]
74d3f3c1d6
Bump regex from 1.9.6 to 1.10.2 (#10812) 2023-10-23 14:13:57 +08:00
Jakub Žádník
a35ecb4837
Finish removing profile command and related data (#10807) 2023-10-22 14:06:53 +03:00
Christopher Durham
a01ef85bda
Remove registry clean_string hack (#10804)
# Description

Remove the `clean_string` hack used in `registry query`.

This was a workaround for a [bug][gentoo90/winreg-rs#52] in winreg which
has since [been fixed][edf9eef] and released in [winreg v0.12.0].

winreg now properly displays strings in RegKey's Display impl instead of
outputting their debug representation. We remove our `clean_string` such
that registry entries which happen to start/end with `"` or contain `\\`
won't get mangled. This is very important for entries in UNC path format
as those begin with a double backslash.

[gentoo90/winreg-rs#52]:
<https://github.com/gentoo90/winreg-rs/issues/52>
[edf9eef]:
<edf9eef38f>
[winreg v0.12.0]:
<https://github.com/gentoo90/winreg-rs/releases/tag/v0.12.0>

# User-Facing Changes

- `registry query` used to accidentally mangle values that contain a
literal `\\`, such as UNC paths. It no longer does so.

# Tests + Formatting

- [X] `toolkit check pr`
  - 🟢 `toolkit fmt`
  - 🟢 `toolkit clippy`
  - 🟢 `toolkit test`
  - 🟢 `toolkit test stdlib`
2023-10-21 18:50:34 -05:00
stfacc
6445c4e7de
Do not use white text in the default light theme (#10796)
Use instead 'dark_gray', the default fg color for the other primitives.

fixes #10636
2023-10-21 16:31:46 -05:00
Justin Ma
52e8b0afb2
Deprecate size to str stats (#10798)
<!--
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.
-->

Rename `str size` to `str stats`, for more detail see:
https://github.com/nushell/nushell/pull/10772

# 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 std testing; testing run-tests --path
crates/nu-std"` 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.
-->
2023-10-21 11:21:34 -05:00
Justin Ma
db3f3eaf5a
Move ansi link from extra to default feature, close #10792 (#10801)
<!--
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.
-->

Move `ansi link` from extra to default feature, close #10792

# 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 std testing; testing run-tests --path
crates/nu-std"` 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.
-->
2023-10-21 11:04:37 -05:00
Hofer-Julian
878f0cf6e1
Add long options for viewers (#10787)
![](http://s2.quickmeme.com/img/7f/7f77546945f948560cdc26b12b99d5ccd390c2e39d2849d3423ae7608dac066a.jpg)
2023-10-20 11:43:42 -05:00
Antoine Stevan
6a2539534f
deprecate size to str size (#10772)
related to
-
https://discord.com/channels/601130461678272522/614613939334152217/1164530991931605062

# Description
it appears `size` is a command that operates on `string`s only and gives
the user information about the chars, graphemes and bytes of a string.
this looks like a command that should be a subcommand to `str` 😏 

this PR
- adds `str size`
- deprecates `size`

`size` is planned to be removed in 0.88

# User-Facing Changes
`str size` can be used for the same result as `size`.

# Tests + Formatting

# After Submitting
write a removal PR for `size`
2023-10-20 11:34:55 +02:00
Chinmay Dalal
f310a9be8c
Make hints aware of the current directory (#10780)
This commit uses the new `CwdAwareHinter` in reedline. Closes #8883.

# Description

Currently, the history based hints show results from all directories,
while most commands make sense only in the directory they were run in.
This PR makes hints take the current directory into account.

# User-Facing Changes

Described above.

I haven't yet added a config option for this, because I personally
believe folks won't be against it once they try it out. We can add it if
people complain, there's some time before the next release.

Fish has this without a config option too.

# Tests + Formatting

If tests are needed, I'll need help as I'm not well versed with the
codebase.
2023-10-20 11:21:58 +02:00
Hofer-Julian
d0dc6986dd
Use long options for string (#10777) 2023-10-19 22:08:09 +02:00
Hofer-Julian
11480c77be
Add long options for path (#10775) 2023-10-19 22:07:01 +02:00
Hofer-Julian
4fd2b702ee
Add long options for platform and random (#10776) 2023-10-19 22:04:33 +02:00
Antoine Stevan
030e55acbf
add unfold back with a deprecation warning (#10771)
related to
- https://github.com/nushell/nushell/pull/10770

# Description
because some people look into `unfold` already (myself included lol) and
there will be 4 weeks with that new command which has a decent section
in the release note, i fear that
https://github.com/nushell/nushell/pull/10770 is a bit too brutal,
removing `unfold` without any warning...

this PR brings `unfold` back to life.
the `unfold` command will have a deprecation warning and will be removed
in 0.88.

# User-Facing Changes
`unfold` is only deprecated, not removed.

# Tests + Formatting

# After Submitting
2023-10-19 19:23:06 +02:00
Antoine Stevan
c5e1b64b40
remove random integer in favor of random int (#10568)
related to
- https://github.com/nushell/nushell/pull/10520

# Description
this PR is a followup to https://github.com/nushell/nushell/pull/10520
and removes the `random integer` command completely, in favor of `random
int`.

# User-Facing Changes
`random integer` has been fully moved to `random int`
```nushell
> random integer 0..1
Error: nu::parser::extra_positional

  × Extra positional argument.
   ╭─[entry #1:1:1]
 1 │ random integer 0..1
   ·        ───┬───
   ·           ╰── extra positional argument
   ╰────
  help: Usage: random
```

# Tests + Formatting
tests have been moved from
`crates/nu-command/tests/commands/random/integer.rs` to
`crates/nu-command/tests/commands/random/int.rs`

# After Submitting
mention in 0.87.0 release notes
2023-10-19 18:42:07 +02:00
Hofer-Julian
999f7b229f
Remove to xml --pretty (#10668)
followup to
- https://github.com/nushell/nushell/pull/10660
2023-10-19 18:41:54 +02:00