Compare commits

...

119 Commits

Author SHA1 Message Date
a1b7261121 Bump version for 0.79.0 release (#8980) 2023-04-25 23:06:17 +03:00
5a4b6f0f7f Pin reedline to 0.19.0 release (#8996)
# Description
See release notes:

https://github.com/nushell/reedline/releases/tag/v0.19.0
2023-04-25 20:58:33 +02:00
78b227d1ef Pull the most recent reedline 2023-04-25 19:08:05 +02:00
07598c9620 Add npm installation instruction (#8982)
# Description

Add `npm` install instruction to README.md
2023-04-24 09:22:42 -05:00
7413ef2824 Tweak run-external signature so command must be a string (#8971)
Tiny fix: clarify in `run-external`'s signature that the external
command must be a string.

### Before
```
Signatures:
  <any> | run-external <any> -> <any>

Parameters:
  command <any>: external command to run
  ...args <any>: arguments for external command
```

### After
```
Signatures:
  <any> | run-external <string> -> <any>

Parameters:
  command <string>: external command to run
  ...args <any>: arguments for external command
```


### Notes

I was hoping to change more `any`s to more specific types, but alas I
think we can only change `command` right now. The input can be any type
and it gets rendered to a string before being passed to the external.
The args can be any value type and they get converted to strings. The
output can be either binary or a string.
2023-04-22 10:57:16 -07:00
0cc735a7b2 use record separator \x1e for include_path (#8961)
# Description

This changes how the include paths are joined together so that it uses a
character that will work across platforms. `;` didn't work on Mac/Linux.
`:` didn't work in Windows. So, the record separator should work, which
is \x1e.

This goes hand-in-hand with
https://github.com/nushell/vscode-nushell-lang/pull/113.

# 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 -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-std/tests/run.nu` 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-04-21 15:30:36 -05:00
JT
d00038eb4b Reuse the cached parse results of parsed files (#8949)
# Description

This does a lookup in the cache of parsed files to see if a span can be
found for a file that was previously loaded with the same contents, then
uses that span to find the parsed block for that file. The end result
should, in theory, be identical but doesn't require any reparsing or
creating new blocks/new definitions that aren't needed.

This drops the sg.nu benchmark from:
```
╭───┬───────────────────╮
│ 0 │ 280ms 606µs 208ns │
│ 1 │ 282ms 654µs 416ns │
│ 2 │ 252ms 640µs 541ns │
│ 3 │  250ms 940µs 41ns │
│ 4 │ 241ms 216µs 375ns │
│ 5 │ 257ms 310µs 583ns │
│ 6 │ 196ms 739µs 416ns │
╰───┴───────────────────╯
```

to:
```
╭───┬───────────────────╮
│ 0 │ 118ms 698µs 125ns │
│ 1 │       121ms 327µs │
│ 2 │ 121ms 873µs 500ns │
│ 3 │  124ms 94µs 708ns │
│ 4 │ 113ms 733µs 291ns │
│ 5 │ 108ms 663µs 125ns │
│ 6 │  63ms 482µs 625ns │
╰───┴───────────────────╯
```

I was hoping to also see some startup time improvements, but I didn't
notice much there.

# 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 -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-std/tests/run.nu` 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-04-22 07:00:33 +12:00
47af701380 Set override locale in toolkit (#8957)
# Description

Very simple change that sets the override locale that's used by
formatting tests

# User-Facing Changes

None

# Tests + Formatting

N/A

# After Submitting

N/A

Co-authored-by: Jelle Besseling <jelle@bigbridge.nl>
2023-04-21 11:58:19 -05:00
24b4ac692e std run-tests: Rename --command switch to --test; and likewise in --list output (#8895)
# 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.
-->
As described in #8893, switch `std run-tests --module` is ambiguous, but
`--command` is misleading. Fix that, and rename `--list` output column
to match.

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->
* `std run-tests --command test_foo_1` changes to `std run-tests --test
test_foo_1`, users may have to change existing scripts (or muscle
memory).
*
  ```
  〉std run-tests --list | columns
  ╭───┬────────╮
  │ 0 │ module │
  │ 1 │ name   │
  │ 2 │ file   │
  ╰───┴────────╯
  ```
  Changes to:
  
  ```
  〉std run-tests --list | columns
  ╭───┬────────╮
  │ 0 │ module │
  │ 1 │ test   │
  │ 2 │ file   │
  ╰───┴────────╯
  
  ```
# 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 -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-std/tests/run.nu` 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-04-20 19:41:33 -05:00
fb72da0e82 unify the *-BuiltinVar parser errors (#8944)
# Description

this pr condenses `MutBuiltinVar`, `LetBuiltinVar` and `ConstBuiltinVar`
into one error:
```nu
Error: nu::parser::name_is_builtin_var

  × `in` used as variable name.
   ╭─[entry #69:1:1]
 1 │ let in = 420
   ·     ─┬
   ·      ╰── already a builtin variable
   ╰────
  help: 'in' is the name of a builtin Nushell variable and cannot be used
        as a variable name
```

it also fixes this case which was previously not handled
```nu
let $nu = 420 # this variable would have been 'lost'
```
2023-04-20 19:44:31 +02:00
d339902dc6 stdlib: fix the clip command with integer values (#8898)
# Description
this PR fixes the `std clip` command which would not copy integer data
😮
and, as all the input data is now treated as raw `string` with the
`table | into string` conversion, i've removed the "stripped" print when
done clipping the data 👍

 from the `main` on which this PR is based (cbedc8403)
> **Note**
> from inside`cargo run` and with a `use std clip`
- ✔️ `'foo' | clip`
- ✔️ `ls | get 0 | clip`
-  `123 | clip`
 
# User-Facing Changes
✔️ from the tip of the PR branch
> **Note**
> from inside`cargo run` and with a `use std clip`
- ✔️ `'foo' | clip`
- ✔️ `ls | get 0 | clip`
- ✔️ `123 | clip`

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

# After Submitting
```
$nothing
```
2023-04-20 18:59:34 +02:00
393f424f1c allow find command to look in specified columns only (#8937)
# Description
This PR allows the `find` command to search in specific columns using
`--columns [col1 col2 col3]`. This is really meant to help with the
`help` command in the std.nu.

There are a few more things I want to look at so this is a draft for
now.
- [x] add example
- [x] look at regex part

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

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

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

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-std/tests/run.nu` 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-04-20 08:13:12 -05:00
c8f54476c9 Set env in exec command (#8917)
# Description

Previously variables with `let-env` were not available after doing an
`exec` command. This PR fixes that

# User-Facing Changes

Can now use environment variables set with nushell after `exec`

# Tests + Formatting

No tests made but formatting has been checked

# 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: Jelle Besseling <jelle@bigbridge.nl>
2023-04-20 22:10:46 +12:00
d42c2b2dbc refactor the CONTRIBUTING.md guidelines for nu-std (#8912)
## Description
just a little refactor of `CONTRIBUTING.md` of the standard library in
`nu-std`.
- see the new version
[here](https://github.com/amtoine/nushell/blob/stblib/refactor/CONTRIBUTING-guidelines/crates/nu-std/CONTRIBUTING.md).

> **Note**
> actually, that one might be best reviewed commit by commit 😋 
> i tried to be as explicit as possible 😌 

- i fixed the width to `80` columns
- cc/ @bobhy, if you want to jump in and find broken links / bad changes
2023-04-19 22:21:27 +02:00
ed64a44b82 add filter-map command to std iter (#8926)
# Description
as title says
2023-04-19 19:09:10 +02:00
1855dfb656 Fix into decimal command category (#8932)
Commands like this one belong to conversions category

Fixes #8931

Co-authored-by: Mate Farkas <Mate.Farkas@oneidentity.com>
2023-04-19 11:39:12 -05:00
91c01bf6b3 add iter module to standard library (#8899)
# Description
 
this pr introduces an `iter` module
to the standard library.

the module is aimed at extending the filter commands.
2023-04-18 16:01:36 -05:00
29256b161c fix reedline breaking changes due to PR562 (#8921)
# Description
This PR fixes the breaking changes to the reedline API due to
https://github.com/nushell/reedline/pull/562. It does not implement any
new features but just gets nushell back to compiling again.

# 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 -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-std/tests/run.nu` 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-04-18 08:35:10 -05:00
JT
32f098d91d Hopefully speedup startup (#8913)
# Description

Trying a few different things to hopefully speedup startup a bit. I'm
seeing some improvement on my box for the profiles I have, but the data
I'm seeing is noisy.

- Remove allocations in a few places where we created vec's but could
use iterators
- Pre-allocate space for blocks based on the lite block
- Removed a few extra clones

# 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 -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-std/tests/run.nu` 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-04-18 20:19:08 +12:00
06996d8c7f fix bug with include_path -I parameter (#8915)
# Description
This PR fixes a problem with the `-I` parameter. I probably broke it
when I added the `--ide-check <number>` parameter to limit the amount of
errors are shown.

# 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 -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-std/tests/run.nu` 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-04-17 19:07:54 -05:00
2306ef3063 Update issue templates (#8901)
Wanted to start to have a stdlib issue template. I know this is rough
but it's something to start with.
2023-04-17 19:14:28 +02:00
f82a1d8e4e Replace #8824: CONTRIBUTING.md for standard library (#8894)
# 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.
-->

Replaces #8824, which was languishing in review limbo and becoming
increasingly difficult to keep current with upstream changes.

In addition to all the edits, this PR includes updated documentation for
running unit tests via `std run-tests`.

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->
A CONTRIBUTING.md documenting guidelines and getting started info for
potential stdlib contributors.
# 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 -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-std/tests/run.nu` 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-04-17 19:13:50 +02:00
f0e0ab35fc allow custom commands to show up in $nu.scope.commands better (#8910)
# Description
This PR allows our custom commands to show up in `$nu.scope.commands`
better. It still needs work because this PR hard code the input and
output types as `Type::Any` but the reason they're being missed in the
first place is that they are not assigned an input and output type.

This allows things like this now. Note the `where is_custom == true` 

![image](https://user-images.githubusercontent.com/343840/232523925-97eeef78-9722-4184-b60f-9d06f994c8e3.png)

Another example.

![image](https://user-images.githubusercontent.com/343840/232525706-d4d088d8-6597-43ba-97c8-ab03c2c7408c.png)

![image](https://user-images.githubusercontent.com/343840/232525797-b7e9ded3-b299-489e-af33-7390f4291bfd.png)


# 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 -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-std/tests/run.nu` 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-04-17 11:19:37 -05:00
3b20d6890c remove debug print bug (#8909)
# Description
Oops. Someone just found a eprintln that I left in the code 3 weeks ago.
This removes that debug message.
2023-04-17 14:47:08 +02:00
6eb00f6c60 Fix strange error on unbalanced curly braces (#8906)
# Description

Fixes issue https://github.com/nushell/nushell/issues/8400 

# User-Facing Changes

Before

![image](https://user-images.githubusercontent.com/5063945/232443913-a8fe9f50-2014-4edd-95b0-516058566f64.png)

After

![image](https://user-images.githubusercontent.com/5063945/232444266-375d9438-0688-4f49-a884-b8650110f7fe.png)
2023-04-17 21:51:10 +12:00
4ecec59224 Upgrade open crate to fix WSL bug (#8905)
This PR upgrades the [`open`](https://github.com/Byron/open-rs) crate
(used in the `start` command) from 4.0.1 to 4.0.2. This fixes a bug
where `open` doesn't always work properly on WSL:
https://github.com/Byron/open-rs/pull/71
2023-04-16 22:05:40 -07:00
JT
bf3bb66c3e Allocate less when doing a capture discovery (#8903)
# Description

This should be a little more efficient when running the algorithm to
find the captured variables.

# 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 -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-std/tests/run.nu` 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-04-17 10:24:56 +12:00
6b3236715b rename toolkit's set-git-hooks to setup-git-hooks (#8897)
# Description
this pr renames toolkit's `set-git-hooks` to `setup-git-hooks` to match
[CONTRIBUTING.md](cbedc8403f/CONTRIBUTING.md (L112))
2023-04-15 20:39:52 -05:00
cbedc8403f update command: make $in(in closure body) takes cell path (#8610)
# Description

Make `$in` takes cell path in `update` command

The reason behind the change:
https://discord.com/channels/601130461678272522/615329862395101194/1088405671080370196
> when i use update on some cell path, it's almost always because i want
to start with its previous value and change it.

cc @amtoine 

# User-Facing Changes

## Before
```
open Cargo.toml | get package | update metadata.binstall.pkg-fmt {|| $in.metadata.binstall.pkg-fmt | str replace "g" "FOO"}
```

## After
```
open Cargo.toml | get package | update metadata.binstall.pkg-fmt {|| str replace "g" "FOO"}
```

If use want to access original raw, it can be accessed by parameters in
closure:
```
open Cargo.toml | get package | update metadata.binstall.pkg-fmt {|$it| $it.metadata.binstall.pkg-fmt | str replace "g" "FOO"}
```
For this reason, I don't think we need to add a flag like `--whole`

# 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 -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass

> **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-04-15 10:26:21 +02:00
1d68c48a92 Allow arguments for the last flag in short flag batch (#8808)
# Description
_Fixes #5923_

Currently `nushell` doesn't allow short flag batches to contain
arguments, despite this being a common pattern in commands like `git
commit -am 'My commit message'`. This PR relaxes this so that the last
flag in the batch can take an argument.

# User-Facing Changes
- `nu::parser::short_flag_arg_cant_take_arg` has been replaced by
`nu::parser::only_last_flag_in_batch_can_take_arg` and is displayed when
a flag other then the last in a short flag batch takes an argument.

# Tests + Formatting
- Both
[`test_parser.rs`](48af0ebc3c/crates/nu-parser/tests/test_parser.rs (L640-L704))
and
[`test_known_external.rs`](48af0ebc3c/src/tests/test_known_external.rs (L42-L61))
have been updated to test the new allowed and disallowed scenarios.

---------

Co-authored-by: sholderbach <sholderbach@users.noreply.github.com>
2023-04-15 10:24:51 +02:00
fff4de5c44 Apply continue to each (#8889)
# Description
Fixes #8878
Add continue command on each and added new tests too .
2023-04-15 17:11:02 +12:00
45d33e70db Change NU_LIB_DIRS not to depend on $nu.config-path (#8887) 2023-04-14 23:16:00 +03:00
9b35d59023 Update crossterm version to 0.26 (#8623)
# Description

This pr is a companion to https://github.com/nushell/reedline/pull/560

Fortunally, we don't need to change too much nushell code.

## Additional note about lscolor dependency
https://github.com/sharkdp/lscolors/pull/58~~
lscolor is using 0.26 for now
2023-04-14 22:14:57 +02:00
71611dec4f feat: added items command for Records (#8640)
# Description

This PR adds an `items` command which allows the user to iterate over
both `columns` and `values` of a `Record<>` type at the same time.


![image](https://user-images.githubusercontent.com/3835355/227976277-c9badbb2-2e31-4243-8d00-7e28f2289587.png)

# User-Facing Changes

No breaking changes, only a new `items` command.

# Formatting

- `cargo fmt --all -- --check` 👌 
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A
clippy::needless_collect` 👌
- `cargo test --workspace` 👌
2023-04-14 14:42:33 -05:00
a122e55129 use let-else syntax where possible (#8886)
# Description
this pr changes some `if-let`s to `let-else`s

# User-Facing Changes
none
2023-04-14 20:51:38 +02:00
6cedc05384 Fix span of multibyte short flags (#8866)
# Description

Follow up to #8849

Work for #8821
Should unblock work on #8808

Missing is a restriction to printables or identifiers according to
[UAX31](https://www.unicode.org/reports/tr31/)

# User-Facing Changes

Non ASCII characters should be allowed in shortflags.

# Tests + Formatting

Want to add some tests for the error reporting cases
2023-04-14 18:53:14 +02:00
8efbb48cb0 Pick up fix in dtparse for nanosec truncation noted at bottom of #8337 (#8805)
# Description

Pick up [enhancement in
`dtparse`](https://github.com/bspeice/dtparse/pull/41), to preserve
nanoseconds in string-to-date conversions.

# User-Facing Changes

An especially eagle-eyed user might notice that prior versions of
nushell were losing nanosecond precision when converting string format
date/time to datetime.

Before:
```nushell
〉'2023-03-02T01:02:03.987654321' | into datetime | date to-record
╭────────────┬───────────╮
│ year       │ 2023      │
│ month      │ 3         │
│ day        │ 2         │
│ hour       │ 1         │
│ minute     │ 2         │
│ second     │ 3         │
│ nanosecond │ 987654000 │
│ timezone   │ -04:00    │
╰────────────┴───────────╯
```
Now, it just works(tm)
```nushell
〉'2023-03-02T01:02:03.987654321' | into datetime | date to-record
╭────────────┬───────────╮
│ year       │ 2023      │
│ month      │ 3         │
│ day        │ 2         │
│ hour       │ 1         │
│ minute     │ 2         │
│ second     │ 3         │
│ nanosecond │ 987654321 │
│ timezone   │ -04:00    │
╰────────────┴───────────╯
```

# Tests + Formatting

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

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

- [x] `cargo fmt --all -- --check` to check standard code formatting
(`cargo fmt --all` applies these changes)
- [x] `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A
clippy::needless_collect` to check that you're using the standard code
style
- [x] `cargo test --workspace` to check that all tests pass  
Some (unrelated) tests did fail [^err]
- [x] `cargo run -- crates/nu-std/tests.nu` 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.

# (Unrelated) test failures noted
[^err]: Several tests are failing, unrelated to this PR

```
failures:

---- modules::module_import_env_1 stdout ----
=== stderr
Error: nu:🐚:file_not_found

  × File not found
   ╭─[source:1:1]
 1 │ source-env main.nu; use main.nu foo; foo
   ·            ───┬───
   ·               ╰── file not found
   ╰────


thread 'modules::module_import_env_1' panicked at 'assertion failed: `(left == right)`
  left: `""`,
 right: `"foo"`', tests/modules/mod.rs:316:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

---- modules::module_import_env_2 stdout ----
=== stderr
Error: nu:🐚:file_not_found

  × File not found
   ╭─[source:1:1]
 1 │ source-env main.nu; $env.FOO
   ·            ───┬───
   ·               ╰── file not found
   ╰────


thread 'modules::module_import_env_2' panicked at 'assertion failed: `(left == right)`
  left: `""`,
 right: `"foo"`', tests/modules/mod.rs:341:9

---- overlays::overlay_use_do_cd_file_relative stdout ----
=== stderr

thread 'overlays::overlay_use_do_cd_file_relative' panicked at 'assertion failed: `(left == right)`
  left: `"nushell"`,
 right: `"test1"`', tests/overlays/mod.rs:919:9

---- overlays::overlay_use_dont_cd_overlay stdout ----
=== stderr
Error: nu:🐚:file_not_found

  × File not found
   ╭─[source:1:1]
 1 │ source-env test1/test2/spam.nu; $env.PWD | path basename
   ·            ─────────┬─────────
   ·                     ╰── file not found
   ╰────


thread 'overlays::overlay_use_dont_cd_overlay' panicked at 'assertion failed: `(left == right)`
  left: `""`,
 right: `"overlay_use_dont_cd_overlay"`', tests/overlays/mod.rs:946:9

---- parsing::parse_file_relative_to_parsed_file_dont_use_cwd_1 stdout ----
=== stderr
Error: nu:🐚:file_not_found

  × File not found
   ╭─[source:1:1]
 1 │ source-env lol/lol.nu; $env.FOO
   ·            ─────┬────
   ·                 ╰── file not found
   ╰────


thread 'parsing::parse_file_relative_to_parsed_file_dont_use_cwd_1' panicked at 'assertion failed: `(left == right)`
  left: `""`,
 right: `"good"`', tests/parsing/mod.rs:177:9

---- parsing::parse_file_relative_to_parsed_file_simple stdout ----
=== stderr
Error: nu:🐚:file_not_found

  × File not found
   ╭─[source:1:1]
 1 │ source-env lol/lol/lol.nu; $env.LOL
   ·            ───────┬──────
   ·                   ╰── file not found
   ╰────


thread 'parsing::parse_file_relative_to_parsed_file_simple' panicked at 'assertion failed: `(left == right)`
  left: `""`,
 right: `"lol"`', tests/parsing/mod.rs:99:9

---- shell::const_nu_lib_dirs_relative stdout ----
=== stderr
Error: nu:🐚:file_not_found

  × File not found
   ╭─[main.nu:1:1]
 1 │ const NU_LIB_DIRS = [ 'scripts' ]
 2 │ source-env foo.nu
   ·            ───┬──

thread 'shell::const_nu_lib_dirs_relative' panicked at 'assertion failed: outcome.err.is_empty()', tests/shell/mod.rs:166:9

---- shell::pipeline::commands::external::it_evaluation::takes_rows_of_nu_value_lines stdout ----
=== stderr

thread 'shell::pipeline::commands::external::it_evaluation::takes_rows_of_nu_value_lines' panicked at 'assertion failed: `(left == right)`
  left: `""`,
 right: `"AndrásWithKitKat"`', tests/shell/pipeline/commands/external.rs:198:13

---- shell::pipeline::commands::external::it_evaluation::takes_rows_of_nu_value_strings stdout ----
=== stderr

thread 'shell::pipeline::commands::external::it_evaluation::takes_rows_of_nu_value_strings' panicked at 'assertion failed: `(left == right)`
  left: `""`,
 right: `"jt_likes_cake.txt"`', tests/shell/pipeline/commands/external.rs:173:13


failures:
    modules::module_import_env_1
    modules::module_import_env_2
    overlays::overlay_use_do_cd_file_relative
    overlays::overlay_use_dont_cd_overlay
    parsing::parse_file_relative_to_parsed_file_dont_use_cwd_1
    parsing::parse_file_relative_to_parsed_file_simple
    shell::const_nu_lib_dirs_relative
    shell::pipeline::commands::external::it_evaluation::takes_rows_of_nu_value_lines
    shell::pipeline::commands::external::it_evaluation::takes_rows_of_nu_value_strings

test result: FAILED. 386 passed; 9 failed; 20 ignored; 0 measured; 0 filtered out; finished in 98.06s

error: test failed, to rerun pass `-p nu --test main`

failures:

---- modules::module_import_env_1 stdout ----
=== stderr
Error: nu:🐚:file_not_found

  × File not found
   ╭─[source:1:1]
 1 │ source-env main.nu; use main.nu foo; foo
   ·            ───┬───
   ·               ╰── file not found
   ╰────


thread 'modules::module_import_env_1' panicked at 'assertion failed: `(left == right)`
  left: `""`,
 right: `"foo"`', tests/modules/mod.rs:316:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

---- modules::module_import_env_2 stdout ----
=== stderr
Error: nu:🐚:file_not_found

  × File not found
   ╭─[source:1:1]
 1 │ source-env main.nu; $env.FOO
   ·            ───┬───
   ·               ╰── file not found
   ╰────


thread 'modules::module_import_env_2' panicked at 'assertion failed: `(left == right)`
  left: `""`,
 right: `"foo"`', tests/modules/mod.rs:341:9

---- overlays::overlay_use_do_cd_file_relative stdout ----
=== stderr

thread 'overlays::overlay_use_do_cd_file_relative' panicked at 'assertion failed: `(left == right)`
  left: `"nushell"`,
 right: `"test1"`', tests/overlays/mod.rs:919:9

---- overlays::overlay_use_dont_cd_overlay stdout ----
=== stderr
Error: nu:🐚:file_not_found

  × File not found
   ╭─[source:1:1]
 1 │ source-env test1/test2/spam.nu; $env.PWD | path basename
   ·            ─────────┬─────────
   ·                     ╰── file not found
   ╰────


thread 'overlays::overlay_use_dont_cd_overlay' panicked at 'assertion failed: `(left == right)`
  left: `""`,
 right: `"overlay_use_dont_cd_overlay"`', tests/overlays/mod.rs:946:9

---- parsing::parse_file_relative_to_parsed_file_dont_use_cwd_1 stdout ----
=== stderr
Error: nu:🐚:file_not_found

  × File not found
   ╭─[source:1:1]
 1 │ source-env lol/lol.nu; $env.FOO
   ·            ─────┬────
   ·                 ╰── file not found
   ╰────


thread 'parsing::parse_file_relative_to_parsed_file_dont_use_cwd_1' panicked at 'assertion failed: `(left == right)`
  left: `""`,
 right: `"good"`', tests/parsing/mod.rs:177:9

---- parsing::parse_file_relative_to_parsed_file_simple stdout ----
=== stderr
Error: nu:🐚:file_not_found

  × File not found
   ╭─[source:1:1]
 1 │ source-env lol/lol/lol.nu; $env.LOL
   ·            ───────┬──────
   ·                   ╰── file not found
   ╰────


thread 'parsing::parse_file_relative_to_parsed_file_simple' panicked at 'assertion failed: `(left == right)`
  left: `""`,
 right: `"lol"`', tests/parsing/mod.rs:99:9

---- shell::const_nu_lib_dirs_relative stdout ----
=== stderr
Error: nu:🐚:file_not_found

  × File not found
   ╭─[main.nu:1:1]
 1 │ const NU_LIB_DIRS = [ 'scripts' ]
 2 │ source-env foo.nu
   ·            ───┬──

thread 'shell::const_nu_lib_dirs_relative' panicked at 'assertion failed: outcome.err.is_empty()', tests/shell/mod.rs:166:9

---- shell::pipeline::commands::external::it_evaluation::takes_rows_of_nu_value_lines stdout ----
=== stderr

thread 'shell::pipeline::commands::external::it_evaluation::takes_rows_of_nu_value_lines' panicked at 'assertion failed: `(left == right)`
  left: `""`,
 right: `"AndrásWithKitKat"`', tests/shell/pipeline/commands/external.rs:198:13

---- shell::pipeline::commands::external::it_evaluation::takes_rows_of_nu_value_strings stdout ----
=== stderr

thread 'shell::pipeline::commands::external::it_evaluation::takes_rows_of_nu_value_strings' panicked at 'assertion failed: `(left == right)`
  left: `""`,
 right: `"jt_likes_cake.txt"`', tests/shell/pipeline/commands/external.rs:173:13


failures:
    modules::module_import_env_1
    modules::module_import_env_2
    overlays::overlay_use_do_cd_file_relative
    overlays::overlay_use_dont_cd_overlay
    parsing::parse_file_relative_to_parsed_file_dont_use_cwd_1
    parsing::parse_file_relative_to_parsed_file_simple
    shell::const_nu_lib_dirs_relative
    shell::pipeline::commands::external::it_evaluation::takes_rows_of_nu_value_lines
    shell::pipeline::commands::external::it_evaluation::takes_rows_of_nu_value_strings

test result: FAILED. 386 passed; 9 failed; 20 ignored; 0 measured; 0 filtered out; finished in 98.06s

error: test failed, to rerun pass `-p nu --test main`
failures:

---- modules::module_import_env_1 stdout ----
=== stderr
Error: nu:🐚:file_not_found

  × File not found
   ╭─[source:1:1]
 1 │ source-env main.nu; use main.nu foo; foo
   ·            ───┬───
   ·               ╰── file not found
   ╰────


thread 'modules::module_import_env_1' panicked at 'assertion failed: `(left == right)`
  left: `""`,
 right: `"foo"`', tests/modules/mod.rs:316:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

---- modules::module_import_env_2 stdout ----
=== stderr
Error: nu:🐚:file_not_found

  × File not found
   ╭─[source:1:1]
 1 │ source-env main.nu; $env.FOO
   ·            ───┬───
   ·               ╰── file not found
   ╰────


thread 'modules::module_import_env_2' panicked at 'assertion failed: `(left == right)`
  left: `""`,
 right: `"foo"`', tests/modules/mod.rs:341:9

---- overlays::overlay_use_do_cd_file_relative stdout ----
=== stderr

thread 'overlays::overlay_use_do_cd_file_relative' panicked at 'assertion failed: `(left == right)`
  left: `"nushell"`,
 right: `"test1"`', tests/overlays/mod.rs:919:9

---- overlays::overlay_use_dont_cd_overlay stdout ----
=== stderr
Error: nu:🐚:file_not_found

  × File not found
   ╭─[source:1:1]
 1 │ source-env test1/test2/spam.nu; $env.PWD | path basename
   ·            ─────────┬─────────
   ·                     ╰── file not found
   ╰────


thread 'overlays::overlay_use_dont_cd_overlay' panicked at 'assertion failed: `(left == right)`
  left: `""`,
 right: `"overlay_use_dont_cd_overlay"`', tests/overlays/mod.rs:946:9

---- parsing::parse_file_relative_to_parsed_file_dont_use_cwd_1 stdout ----
=== stderr
Error: nu:🐚:file_not_found

  × File not found
   ╭─[source:1:1]
 1 │ source-env lol/lol.nu; $env.FOO
   ·            ─────┬────
   ·                 ╰── file not found
   ╰────


thread 'parsing::parse_file_relative_to_parsed_file_dont_use_cwd_1' panicked at 'assertion failed: `(left == right)`
  left: `""`,
 right: `"good"`', tests/parsing/mod.rs:177:9

---- parsing::parse_file_relative_to_parsed_file_simple stdout ----
=== stderr
Error: nu:🐚:file_not_found

  × File not found
   ╭─[source:1:1]
 1 │ source-env lol/lol/lol.nu; $env.LOL
   ·            ───────┬──────
   ·                   ╰── file not found
   ╰────


thread 'parsing::parse_file_relative_to_parsed_file_simple' panicked at 'assertion failed: `(left == right)`
  left: `""`,
 right: `"lol"`', tests/parsing/mod.rs:99:9

---- shell::const_nu_lib_dirs_relative stdout ----
=== stderr
Error: nu:🐚:file_not_found

  × File not found
   ╭─[main.nu:1:1]
 1 │ const NU_LIB_DIRS = [ 'scripts' ]
 2 │ source-env foo.nu
   ·            ───┬──

thread 'shell::const_nu_lib_dirs_relative' panicked at 'assertion failed: outcome.err.is_empty()', tests/shell/mod.rs:166:9

---- shell::pipeline::commands::external::it_evaluation::takes_rows_of_nu_value_lines stdout ----
=== stderr

thread 'shell::pipeline::commands::external::it_evaluation::takes_rows_of_nu_value_lines' panicked at 'assertion failed: `(left == right)`
  left: `""`,
 right: `"AndrásWithKitKat"`', tests/shell/pipeline/commands/external.rs:198:13

---- shell::pipeline::commands::external::it_evaluation::takes_rows_of_nu_value_strings stdout ----
=== stderr

thread 'shell::pipeline::commands::external::it_evaluation::takes_rows_of_nu_value_strings' panicked at 'assertion failed: `(left == right)`
  left: `""`,
 right: `"jt_likes_cake.txt"`', tests/shell/pipeline/commands/external.rs:173:13


failures:
    modules::module_import_env_1
    modules::module_import_env_2
    overlays::overlay_use_do_cd_file_relative
    overlays::overlay_use_dont_cd_overlay
    parsing::parse_file_relative_to_parsed_file_dont_use_cwd_1
    parsing::parse_file_relative_to_parsed_file_simple
    shell::const_nu_lib_dirs_relative
    shell::pipeline::commands::external::it_evaluation::takes_rows_of_nu_value_lines
    shell::pipeline::commands::external::it_evaluation::takes_rows_of_nu_value_strings

test result: FAILED. 386 passed; 9 failed; 20 ignored; 0 measured; 0 filtered out; finished in 98.06s

error: test failed, to rerun pass `-p nu --test main`
```
2023-04-14 07:24:46 -05:00
0bfa769b7d std: remove logging example (#8877)
The example is is going to be included in the documentation, so I think
we no longer need it here.
See: https://github.com/nushell/nushell.github.io/pull/870
2023-04-14 07:15:56 -05:00
5afc49250f Bump umask from 2.0.0 to 2.1.0 (#8835) 2023-04-14 12:15:22 +00:00
efb81a1277 Bump winreg from 0.11.0 to 0.50.0 (#8837) 2023-04-14 12:15:01 +00:00
JT
4a8124ad1e Improve hovers, including for custom commands (#8881)
# Description

Improves the info we give in hovers.


![image](https://user-images.githubusercontent.com/547158/231880027-78d8f3b1-a7cb-49aa-93d3-25cdbf2521d2.png)

Note: need to work on highlighting a bit before this is ready.

# 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 -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-std/tests/run.nu` 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-04-14 11:28:16 +12:00
8ddebcb932 Add $env.CURRENT_FILE variable (#8861)
Co-authored-by: Jelle Besseling <jelle@bigbridge.nl>
2023-04-13 23:33:29 +03:00
b2d7427d2d Move unit test runner to standard library (#8850)
Move test runner to standard library.
Originated from #8819 

# After Submitting

I'll update the documentation about testing:
http://www.nushell.sh/book/testing.html

---------

Co-authored-by: Mate Farkas <Mate.Farkas@oneidentity.com>
2023-04-13 21:46:37 +02:00
b4400c4896 Bump rstest from 0.16.0 to 0.17.0 (#8836) 2023-04-13 18:58:37 +00:00
5a8d4c628f Bump sys-locale from 0.2.4 to 0.3.0 (#8838) 2023-04-13 18:57:25 +00:00
ebdb7ac2d8 Run coverage immediately (#8876)
# Description
Don't wait for the tests to pass to try running the coverage job. In
theory that would save some wasted runs but waiting for it can also slow
down the review if you want to inspect that a certain branch is covered
by tests.

# Tests + Formatting
Coverage runs immediately and can also fail due to failing tests
2023-04-13 20:26:26 +02:00
a33a7960bb limit the ide-check error amount (#8875)
# Description

This PR limits the amount of errors returned with the --ide-check flag.

# 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 -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-std/tests/run.nu` 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-04-13 12:53:18 -05:00
3603610026 Correct error description for unknown external commands (#8868)
# Description
Fixes issue https://github.com/nushell/nushell/issues/8643 

# User-Facing Changes

Before
<img width="442" alt="image"
src="https://user-images.githubusercontent.com/5063945/231624884-49a1ce4e-598d-4d19-882d-c22d168e6a5a.png">

After
<img width="449" alt="image"
src="https://user-images.githubusercontent.com/5063945/231625076-5f1becd7-7477-4d2f-b765-3956210da7f2.png">
2023-04-13 19:33:05 +02:00
017151dff1 optimize hash md5 for binary input (#8860)
# Description

Fixes: #8260

# User-Facing Changes

`open bigfile | hash md5` no longer consumes too much memory

# 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 -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-std/tests/run.nu` 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-04-13 19:29:06 +02:00
e892aad3f6 change include dirs separator to colon (#8873)
# Description
This PR changes the include_path separator from a semicolon to a colon.
It seems that semicolon is not parsed well as an argument to nushell.

# 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 -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-std/tests/run.nu` 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-04-13 08:15:56 -05:00
ad90b6e5f3 rm: enable trash flag on android and ios platrofm (#8871)
# Description

As title, enable trash flag on all platforms make `rm` more portable
across different platforms, but `-t` will do nothing.

Fixes: #8104

# User-Facing Changes
Na

# Tests + Formatting
It's hard to add tests because we don't run tests for android and ios
platforms.

# 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-04-13 07:34:52 -05:00
4da7bbbb59 Add git hooks for formatting and running clippy (#8820)
# Description

As another life improvement (and to avoid those `run cargo fmt` commits
😉), this PR adds a command to the toolkit for formatting and running
`clippy` when committing and pushing.

Thanks to @amtoine for the idea!

---------

Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com>
2023-04-13 07:34:23 -05:00
b9808c8598 Reenable CI coverage (#8867)
# Description
Let's see if we don't run out of disk space as quickly again

This reverts commit 0e496f900d.
(#8677)



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

# Tests + Formatting

Same coverage setup as before
2023-04-13 15:27:02 +12:00
36036d9308 FEATURE: do not use theme-independant colors in the default configs (#8855)
# Description
i was playing with my theme a bit and i was thinking about the following
- the default themes should not use precise colors
- the default themes should let the terminal set the exact colors

for instance, the `filesize` field of the `$env.config.color_config`
looks good but not with terminal themes like dracula or tokyonight
😮

in this PR, i just use "built-in" colors, like `red` or `yellow_bold` or
`{fg: green attr: n}` to let the terminal theme set the colors 😋

# User-Facing Changes
i tried to stay as close as the previous default themes, so there should
be the least amount of differences 😌

# Tests + Formatting
```
$nothing
```

# After Submitting
```
$nothing
```
2023-04-12 17:09:44 -05:00
JT
99c0a2575f Make -I take in a ;-delimited list (#8864)
# Description
Changes `-I` to take in a semicolon-delimited list of paths. Eg) `-I
"/a/b;/foo/bar"`

# 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 -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-std/tests/run.nu` 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-04-13 06:21:02 +12:00
JT
487789b45b Adds multi-file support to IDE support (#8857)
# Description

This adds multi-file support to the in-progress IDE support. The main
new features are a `-I` flag that allows you to add a new source search
path when starting up the nu binary, and fixes for the current IDE
support to support spans in other files.

This needs accompanying fixes to the vscode/lsp implementation to pass
along the project directory via `-I`.

UPDATE: Marking this draft until we have a means to test this.

# User-Facing Changes

_(List of all changes that impact the user experience here. This helps
us keep track of breaking changes.)_

# Tests + Formatting

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

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

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-std/tests/run.nu` 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-04-13 05:36:29 +12:00
b3d6896977 DEV: make all "comments" real md comments in the PR template (#8708)
# Description
i sometimes see some sections of the PR template being left untouched by
contributors 🤔
this is not a big deal at all, but i thought we could hide them in the
final PR by making the italic hints real markdown comments with the
`<!-- ... -->` syntax.

this has the effect of 
- still showing the guidelines to the contributor in the PR creation
window
- not show these guidelines in the visible PR body

> **Warning**
> limitations
> - this won't remove the comments from the squashed commit when the PR
lands 🤔
> - we might need to use a more structured template for this, like in
the [feature
requests](https://github.com/nushell/nushell/issues/new?assignees=&labels=enhancement&template=feature_request.yml)
but i'm not sure this works with PR templates 😕

# User-Facing Changes
```
$nothing
```

# Tests + Formatting
```
$nothing
```

# After Submitting
```
$nothing
```
2023-04-12 12:30:12 -05:00
JT
8ee52b6ee1 Relax the closure syntax, highlight differently (#8846)
# Description

This relaxes the closure syntax so that `||` is no longer required. This
allows for `ls | each { $in.name }` for example.

I've gone ahead and changed the syntax highlighting so that blocks and
closures are distinct for now.

# User-Facing Changes

Removes `||` requirement for closures.

# 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 -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-std/tests/run.nu` 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-04-12 05:21:52 +12:00
JT
46dba8853a Revert numberlike parsing restriction (#8845)
# Description

This effectively reverts #8635. We shipped this change with 0.78 and
received many comments/issues related to this restriction feeling like a
step backward.

fixes: #8844 
(and probably other issues)

# User-Facing Changes

Returns numbers and number-like values to being allowed to be bare
words. Examples: `3*`, `1fb43`, `4,5`, and related.

# 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 -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-std/tests/run.nu` 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-04-12 05:21:31 +12:00
eb4d19fb9c Parser panic for signature with multibyte char for short flag #8821 (#8849)
Hey I'm a developer and I'm still new to nushell and rust but I would
like to learn more about both. This is my first PR for this project.

The intent of my change is to allow to use multibyte utf-8 characters in
commands short flags.
2023-04-11 09:52:51 +12:00
c3678764b4 stdlib test runner: implement setup and teardown commands to unit tests (#8776)
# Description

As in other testing frameworks, the `setup` runs before every test case,
and the `teardown` after that. A context can be created in `setup`,
which will be in the `$in` variable in the test cases, and in the
`teardown`. The `teardown` is called regardless of the test is passed,
skipped, or failed.

For example:

```nushell
use std.nu *

export def setup [] {
    log debug "Setup is running"
    {msg: "This is the context"}
}

export def teardown [] {
    log debug $"Teardown is running. Context: ($in)"
}

export def test_assert_pass [] {
    log debug $"Assert is running. Context: ($in)"
}

export def test_assert_skip [] {
    log debug $"Assert is running. Context: ($in)"
    assert skip
}

export def test_assert_fail_skipped_by_default [] {
    log debug $"Assert is running. Context: ($in)"
    assert false
}
```


![image](https://user-images.githubusercontent.com/282320/230466359-9908cc72-edbd-4150-9aff-d15fe42c0cc7.png)

# After Submitting

I'll update the documentation.

---------

Co-authored-by: Mate Farkas <Mate.Farkas@oneidentity.com>
2023-04-10 22:42:11 +02:00
9bb2c8faf5 Upgrade to nu v0.78 for binaries release workflow (#8840)
# Description

Upgrade to nu v0.78 for binary packages release workflow

Test Release: https://github.com/hustcer/nu-release/releases/tag/v0.78.2
Release workflow running output:
https://github.com/hustcer/nu-release/actions/runs/4656319252/jobs/8239828202

# 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 -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-std/tests/run.nu` 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-04-10 22:10:41 +02:00
74dcac3b0d Fix process_range on 32-bit platforms (#8842)
# Description

This PR fixes
`commands::str_::substrings_the_input_and_treats_end_index_as_length_if_blank_end_index_given`
testcase on 32-bit platform.

```
failures:
---- commands::str_::substrings_the_input_and_treats_end_index_as_length_if_blank_end_index_given stdout ----
=== stderr
thread 'commands::str_::substrings_the_input_and_treats_end_index_as_length_if_blank_end_index_given' panicked at 'assertion failed: `(left == right)`
  left: `"arepa"`,
 right: `"arepas"`', crates/nu-command/tests/commands/str_/mod.rs:363:9
failures:
    commands::str_::substrings_the_input_and_treats_end_index_as_length_if_blank_end_index_given
test result: FAILED. 1072 passed; 1 failed; 23 ignored; 0 measured; 0 filtered out; finished in 2.98s
error: test failed, to rerun pass `-p nu-command --test main`
```

https://gitlab.alpinelinux.org/nibon7/aports/-/jobs/1005935#L3864
https://gitlab.alpinelinux.org/nibon7/aports/-/jobs/1005931#L3867

# User-Facing 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 -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-std/tests/run.nu` 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-04-11 06:52:42 +12:00
6d51e34d0a stdlib: make helper modules available in std (#8841)
> **Note**
> waiting for the following to land
> - https://github.com/nushell/nushell/pull/8824 to avoid conflicts,
i'll add this to `CONTRIBUTING.md` once it's ready 👍

should close #8839 

# Description
this PR moves the `log` submodule of `std` to the top of the call stack,
making it available in the rest of the library as `log`.
i've added some comments around the `submodules` list in
`load_standard_library` to make it clear how it should work.
 
# User-Facing Changes
`log` and `assert` are now available in the rest of `std`.

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

# After Submitting
```
$nothing
```
2023-04-10 13:32:33 -05:00
de76c7a57d Remove autoprinting of for loop (#8843)
# Description

It's an addition to https://github.com/nushell/nushell/pull/8618
And I think it's good to keep the same behavior when we use for loop for
list.

# User-Facing 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 -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-std/tests/run.nu` 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-04-11 05:23:22 +12:00
0e23400510 Follow up #8758 with a style fix (#8822)
# Description

The old comment around the question mark operator doesn't make sense
 to me based on the closure signature.
The `match` expressions were thus superfluous.


# User-Facing Changes

None

# Tests + Formatting

No change
2023-04-09 18:42:43 -07:00
d0a83fec69 stdlib: add completion to help commands (#8799)
> **Note**
> waiting for
> - https://github.com/nushell/nushell/pull/8770
> - #8815

# Description
this PR adds a very basic completion support to the `help`
implementations of the `std`.

# User-Facing Changes
completion on all the `std help ...` commands, based on the names in
`$nu.scope.`

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

# After Submitting
```
$nothing
```
2023-04-10 10:59:57 +12:00
57510f2fd2 Move CLI related commands to nu-cli (#8832)
# Description

Part of the larger cratification effort.

Moves all `reedline` or shell line editor specific commands to `nu-cli`.

## From `nu-cmd-lang`:
- `commandline`
- This shouldn't have moved there. Doesn't directly depend on reedline
but assumes parts in the engine state that are specific to the use of
reedline or a REPL

## From `nu-command`:
- `keybindings` and subcommands
  - `keybindings default`
  - `keybindings list`
  - `keybindings listen`
    - very `reedline` specific
- `history`
  - needs `reedline`
- `history session`

## internal use
Instead of having a separate `create_default_context()` that calls
`nu-command`'s `create_default_context()`, I added a `add_cli_context()`
that updates an `EngineState`


# User-Facing Changes

None

## Build time comparison

`cargo build --timings` from a `cargo clean --profile dev`

### total
main: 64 secs
this: 59 secs

### `nu-command` build time

branch | total| codegen | fraction  
---|---|---|---
main | 14.0s | 6.2s | (44%)
this | 12.5s | 5.5s | (44%)

`nu-cli` depends on `nu-command` at the moment.
Thus it is built during the code-gen phase of `nu-command` (on 16
virtual cores)

# Tests + Formatting

I removed the `test_example()` facilities for now as we had not run any
of the commands in an `Example` test and importing the right context for
those tests seemed more of a hassle than the duplicated
`test_examples()` implementations in `nu-cmd-lang` and `nu-command`
2023-04-10 10:56:47 +12:00
JT
58b96fdede Add option to not load std-lib. Default tests to not use std-lib (#8833)
this adds a `--no-std-lib` flag. Moves `nu!` to use the `--no-std-lib`.
Adds a new `nu_with_std!` macro for future tests that need the std-lib.

# 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 -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-std/tests/run.nu` 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-04-10 10:55:29 +12:00
JT
9e3d6c3bfd Only add the std lib files once (#8830)
# Description

We were seeing duplicate entries for the std lib files, and this PR
addresses that. Each file should now only be added once.

Note: they are still parsed twice because it's hard to recover the
module from the output of `parse` but a bit of clever hacking in a
future PR might be able to do that.

# User-Facing Changes

_(List of all changes that impact the user experience here. This helps
us keep track of breaking changes.)_

# Tests + Formatting

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

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

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-std/tests/run.nu` 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-04-10 08:55:47 +12:00
4a955d7e76 stdlib: refactor into a multi-module library (#8815) 2023-04-09 20:00:20 +03:00
637283ffad allow register to accept a const argument (#8758)
# Description

this pr allows `register` to be used with const variables
```nu
const math_plugin = "~/.config/nushell/plugins/nu_plugin_math"
register $math_plugin
```

should close #8208, previous work #8435
2023-04-08 15:04:57 -05:00
5afbfb5c2c Use pretty_assertions in the root crate (#8818)
# Description

This PR is just a minor development improvement. While working on
another feature, I noticed that the root crate lists the super useful
`pretty_assertions` in the root crate but doesn't use it in most tests.
With this change `pretty_assertions::assert_eq!` is used instead of
`core::assert_eq!` for better diffs when debugging the tests.

I thought of adding the dependency to other crates but I decided not to
since I didn't want a huge disruptive PR :)
2023-04-08 11:52:37 -07:00
d128c0e02b stdlib: use the loaded library in tests and update README (#8811)
Should close #8809.

# Description
this PR uses the automatically loaded library from the tests by
replacing `use std.nu ...` with `use std ...`.

the `README` has been updated by
- removing the very deprencated "concrete examples"
- fixing the `use std` and the "run the tests" sections

the `README` can be previewed
[here](https://github.com/amtoine/nushell/blob/refactor/stdlib/use-std-in-tests-and-update-readme/crates/nu-std/README.md)
👍

# User-Facing Changes
```
$nothing
```

# Tests + Formatting
- 🟢 `toolkit test stdlib`

# After Submitting
```
$nothing
```
2023-04-08 07:35:16 -05:00
60e6ea5abd remove nu_cli crate dependency from nu_std (#8807)
now nu_std only depends on nu_parser, nu_protocol and miette
and removes the nu_cli dependency

this enables developers moving forward to come along and implement their
own CLI's without having to pull in a redundant nu-cli which will not be
needed for them.

I did this by moving report_error into nu_protocol
which nu_std already has a dependency on anyway....



- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-std/tests.nu` 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
> ```
2023-04-08 13:53:43 +02:00
415607706f remove the "MODULE NOT FOUND" print from the parser (#8816)
related to #8765.
should close #8812.

# Description
this PR simply removes the `prinln("MODULE NOT FOUND")` from the parser.

# User-Facing Changes
no more `MODULE NOT FOUND` while typing a `use` command
2023-04-08 13:19:09 +02:00
JT
f2b977b9c5 improve operation mismatch errors (#8800)
# Description

This improves the operation mismatch error in a few ways:

* We now detect if the left-hand side of the operation is at fault, and
show a simpler error/error message if it is
* Removed the unhelpful hint
* Updated the error text to make it clear what types are causing the
issue


![image](https://user-images.githubusercontent.com/547158/230666329-537a8cae-6350-4ee7-878e-777e05c4f265.png)


![image](https://user-images.githubusercontent.com/547158/230666353-93529dc2-039a-4774-a84c-a6faac94d8e2.png)


# User-Facing Changes

Error texts and spans will change

# 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 -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-utils/standard_library/tests.nu` 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-04-08 09:32:44 +12:00
35e8420780 fix(nu-command/tests): further remove unnecessary pipeline() and cwd() (#8793)
# Description

This PR further fixes tests as part of #8670 

# User-Facing Changes

None

# Tests + Formatting

None

# After Submitting

None

---------

Signed-off-by: Harshal Chaudhari <harshal.chaudhary@gmail.com>
Co-authored-by: Reilly Wood <reilly.wood@icloud.com>
2023-04-07 14:09:55 -07:00
1c5846e1fb make inlays show type instead of shape (#8801)
# Description

This tiny change fixes how inlays are shown.

![image](https://user-images.githubusercontent.com/343840/230671454-8adc7e69-4f4e-421f-b0e5-c9563a501c4b.png)


# User-Facing 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 -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-utils/standard_library/tests.nu` 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-04-07 15:40:59 -05:00
5ec6edb9c5 add LICENSE to nu-std (#8803)
# 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 -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-std/tests.nu` 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-04-07 13:39:21 -07:00
5d8bedfbe4 stdlib: make the library a standalone crate (#8770)
# Description
as we now have a prelude thanks to #8627, i'd like to work on the
structure of the library 😋

and i think the first step is to make it a true standalone crate 😏

this PR
- moves all the library from `crates/nu-utils/standard_library/` to
`crates/nu-std/`
- moves the `rust` loading code from `src/run.rs` to
`crates/nu-std/src/lib.rs`
2023-04-07 22:12:27 +02:00
JT
0477493734 Fix parser recovery after error (#8798)
# Description

This fixes the parser recovery after the first error (at least the main
culprit), where `parse_value` was not able to properly parse `any`
values after the first error.

fixes #8796 

# User-Facing Changes

None

# 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 -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-utils/standard_library/tests.nu` 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-04-08 07:01:12 +12:00
e6b196c141 Add $nu.current-exe variable (#8789)
# Description

Part solving #8752

Adds an extra variable to the `nu` table `current-exe` which is the path
to the running shell executable.

# User-Facing Changes

Adds a variable to the `nu` table.

# Tests + Formatting

Tests and formatting have been run. No new test added

# After Submitting

I could add documentation for this if wanted

Co-authored-by: Jelle Besseling <jelle@bigbridge.nl>
2023-04-07 13:51:09 -05:00
49960beb35 FEATURE: make the link in the ansi extra usage an ANSI link (#8795)
# Description
this addresses the comments of @fdncred from
https://github.com/nushell/nushell/issues/8713#issuecomment-1498206087

the exact ANSI link has been generated with
```bash
"https://en.wikipedia.org/wiki/ANSI_escape_code" | ansi link --text "ANSI escape code" | debug -r
```

# User-Facing Changes
there is now an ANSI link in the `ansi` help page instead of a markdown
link.

# Tests + Formatting
```
$nothing
```

# After Submitting
```
$nothing
```
2023-04-07 13:39:51 -05:00
1b677f167e Remove old alias implementation (#8797) 2023-04-07 21:09:38 +03:00
d881481758 add the standard help to the prelude as std help ... (#8794)
Related to #8505.

# Description
as #8505 has been landed, this PR fixes the prelude TODO and uses the
`help` commands from the standard library in the prelude.

# User-Facing Changes
can now access `std help ...` to use the `help` implementations from the
standard library

# Tests + Formatting
```
$nothing
```

# After Submitting
```
$nothing
```
2023-04-07 20:04:51 +02:00
a3ea0c304a Fix config {nu,env} to open $nu.{config,env}-file (#8792)
# Description

fixed #8755
Now, command `config {nu,env}` opens default file
`.config/nushell/{config,env}.nu`.
This behavior is inappropriate when `nu` is launched with option
`--config` or `--env-config`.
This PR changes the file that the command opens to
`$nu.{config,env}-file`.

# User-Facing Changes

`config {nu,env}` opens `$nu.{config,env}-file`.
2023-04-07 18:37:54 +02:00
WMR
4fda6d7eaa Add regex separators for split row/list/column (#8707)
# Description

Verified on discord with maintainer

Change adds regex separators in split rows/column/list. The primary
motivating reason was to make it easier to split on separators with
unbounded whitespace without requiring a lot of trim jiggery. But,
secondary motivation is the same as the set of all motivations for
adding split regex features to most languages.

# User-Facing Changes

Adds -r option to split rows/column/list.

# Tests + Formatting

Ran tests, however tests.nu fails with unrelated errors:

```
~/src/nushell> cargo run -- crates/nu-utils/standard_library/tests.nu                                                                                                                                                          04/02/2023 02:07:25 AM
    Finished dev [unoptimized + debuginfo] target(s) in 0.24s
     Running `target/debug/nu crates/nu-utils/standard_library/tests.nu`
INF|2023-04-02T02:07:27.060|Running tests in test_asserts
INF|2023-04-02T02:07:27.141|Running tests in test_dirs
Error:
  × list is just pwd after initialization

INF|2023-04-02T02:07:27.167|Running tests in test_logger
INF|2023-04-02T02:07:27.286|Running tests in test_std
Error:
  × some tests did not pass (see complete errors above):
  │
  │       test_asserts test_assert
  │       test_asserts test_assert_equal
  │       test_asserts test_assert_error
  │       test_asserts test_assert_greater
  │       test_asserts test_assert_greater_or_equal
  │       test_asserts test_assert_length
  │       test_asserts test_assert_less
  │       test_asserts test_assert_less_or_equal
  │       test_asserts test_assert_not_equal
  │     ⨯ test_dirs test_dirs_command
  │       test_logger test_critical
  │       test_logger test_debug
  │       test_logger test_error
  │       test_logger test_info
  │       test_logger test_warning
  │       test_std test_path_add
  │
```

Upon investigating seeing this difference:

```
╭───┬─────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ 0 │ /var/folders/1f/ltbr1m8s5s1811k6n1rhpc0r0000gn/T/test_dirs_c1ed89d6-19f7-47c7-9e1f-74c39f3623b5         │
│ 1 │ /private/var/folders/1f/ltbr1m8s5s1811k6n1rhpc0r0000gn/T/test_dirs_c1ed89d6-19f7-47c7-9e1f-74c39f3623b5 │
╰───┴─────────────────────────────────────────────────────────────────────────────────────────────────────────╯
```

This seems unrelated to my changes, but can investigate further if
desired.

# 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: Robert Waugh <robert@waugh.io>
2023-04-07 06:46:11 -05:00
771e24913d range operator accepts bot..=top as well as bot..top (#8382)
# Description

A compromise fix for #8162. Nushell range operator now accepts `..=` to
mean the range includes the top value, so you can use your Rust habits.
But the unadorned `..` range operator also includes the value, so you
can also use your Nushell habits.

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

```nushell
〉1..5
╭───┬───╮
│ 0 │ 1 │
│ 1 │ 2 │
│ 2 │ 3 │
│ 3 │ 4 │
│ 4 │ 5 │
╰───┴───╯
-------------------------------------------- /home/bobhy/src/rust/nushell --------------------------------------------
〉1..=5
╭───┬───╮
│ 0 │ 1 │
│ 1 │ 2 │
│ 2 │ 3 │
│ 3 │ 4 │
│ 4 │ 5 │
╰───┴───╯
-------------------------------------------- /home/bobhy/src/rust/nushell --------------------------------------------
〉1..<5
╭───┬───╮
│ 0 │ 1 │
│ 1 │ 2 │
│ 2 │ 3 │
│ 3 │ 4 │
╰───┴───╯
```
# User-Facing Changes

Existing scripts with range operator will continue to operate as
heretofore.

_(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:

- [x] `cargo fmt --all -- --check` to check standard code formatting
(`cargo fmt --all` applies these changes)
- [x] `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A
clippy::needless_collect` to check that you're using the standard code
style
- [x] `cargo test --workspace` to check that all tests pass

# After Submitting

Will update the book to include new syntax.
2023-04-07 06:40:05 -05:00
JT
aded2c1937 Refactor to support multiple parse errors (#8765)
# Description

This is a pretty heavy refactor of the parser to support multiple parser
errors. It has a few issues we should address before landing:

- [x] In some cases, error quality has gotten worse `1 / "bob"` for
example
- [x] if/else isn't currently parsing correctly
- probably others

# User-Facing Changes

This may have error quality degradation as we adjust to the new error
reporting mechanism.

# 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 -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-utils/standard_library/tests.nu` 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-04-07 12:35:45 +12:00
e54b867e8e Remove parser keywords label from commands that do not need it (#8780) 2023-04-07 01:12:21 +03:00
c12b4b4af7 Aliasing math expression shows error earlier (#8779) 2023-04-07 00:40:53 +03:00
87ddba0193 Allow multi-word aliases (#8777) 2023-04-07 00:05:09 +03:00
a29b61bd4f Bump miette from 5.6.0 to 5.7.0 (#8720) 2023-04-06 20:39:54 +00:00
7c6ea81dd4 Bump tempfile from 3.4.0 to 3.5.0 (#8719)
Bumps [tempfile](https://github.com/Stebalien/tempfile) from 3.4.0 to
3.5.0.
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/Stebalien/tempfile/blob/master/NEWS">tempfile's
changelog</a>.</em></p>
<blockquote>
<h1>3.5.0</h1>
<ul>
<li>Update rustix from 0.36 to 0.37.1. This makes wasi work on rust
stable</li>
<li>Update <code>windows-sys</code>, <code>redox_syscall</code></li>
<li>BREAKING: Remove the implementation of <code>Write for
&amp;NamedTempFile&lt;F&gt; where &amp;F: Write</code>. Unfortunately,
this can cause compile issues in unrelated code (<a
href="https://redirect.github.com/Stebalien/tempfile/issues/224">Stebalien/tempfile#224</a>).</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li>See full diff in <a
href="https://github.com/Stebalien/tempfile/commits">compare
view</a></li>
</ul>
</details>
<br />


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

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

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

---

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

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


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-04-06 15:39:31 -05:00
d06ebb1686 standard library: implement help commands with $nu (#8505) 2023-04-06 22:13:22 +03:00
d93953a56f FIX: load the library before anything else (#8774) 2023-04-06 13:21:33 -05:00
74283c3ebc stdlib: add assert skip command to skip test case (#8748) 2023-04-06 13:03:10 -05:00
8a030f3bfc Add ppid example for ps (#8768)
# Description

Add an extra example for the `ps` command

# User-Facing Changes

Only adds this example:


![image](https://user-images.githubusercontent.com/1576660/230374829-dc957b89-0a76-451d-baba-5e4463b150c3.png)

# Tests + Formatting

N/A

# After Submitting

This is related to https://github.com/nushell/nushell.github.io/pull/864

Co-authored-by: Jelle Besseling <jelle@bigbridge.nl>
2023-04-06 07:32:12 -05:00
5518ffd248 Stdlib: use default color for info log level (#8766)
To make it work with a light theme, as well. The dark theme is not
affected, since the default color is white there.

## Before


![image](https://user-images.githubusercontent.com/282320/230329663-6fae7b7d-7062-459c-ad80-8da3a243d606.png)

## After


![image](https://user-images.githubusercontent.com/282320/230329784-c40bf93e-0740-4b87-ae19-84fd7983898a.png)

Also, I added back the example command to the test script which is very
useful in these cases...

Co-authored-by: Mate Farkas <Mate.Farkas@oneidentity.com>
2023-04-06 06:45:45 -05:00
bcdb9bf5b4 Update some help examples (#8759)
# 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.)_
-->

Recently a few things changed, which now create issues:
- `1.0.0`, `+500`, and `0x000000` used to get parsed as string, but now
just errors
- `each { print $in }` -> `each {|| print $in }`

I looked through all the help pages and fixed every highlighted (red
background) error: `help commands | each {|i| help $i.name} | table |
less`

# User-Facing Changes

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

The examples work again and no longer contain error syntax-highlighting

# 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 -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-utils/standard_library/tests.nu` 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-04-05 18:36:00 -05:00
3509bde1a9 Bump windows from 0.46.0 to 0.48.0 (#8721)
Bumps [windows](https://github.com/microsoft/windows-rs) from 0.46.0 to
0.48.0.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/microsoft/windows-rs/releases">windows's
releases</a>.</em></p>
<blockquote>
<h2>0.48.0</h2>
<p>This release includes an update to all crates to address a target
version reliability issue. This issue is detailed here: <a
href="https://redirect.github.com/microsoft/windows-rs/issues/2410#issuecomment-1490802715">microsoft/windows-rs#2410</a></p>
<h2>What's Changed</h2>
<ul>
<li>Improve target version reliability by <a
href="https://github.com/kennykerr"><code>@​kennykerr</code></a> in <a
href="https://redirect.github.com/microsoft/windows-rs/pull/2412">microsoft/windows-rs#2412</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/microsoft/windows-rs/compare/0.47.0...0.48.0">https://github.com/microsoft/windows-rs/compare/0.47.0...0.48.0</a></p>
<h2>0.47.0</h2>
<p>As a reminder, updates are only published by request (<a
href="https://redirect.github.com/microsoft/windows-rs/issues/2397">#2397</a>;
<a
href="https://redirect.github.com/microsoft/win32metadata/issues/1507">microsoft/win32metadata#1507</a>).
This release provides an update to the <code>windows</code> crate. It
does not include an update to the <code>windows-sys</code> crate.</p>
<p>This update adds support for standalone code generation (<a
href="https://redirect.github.com/microsoft/windows-rs/issues/2396">#2396</a>)
as well as requested fixes to the Win32 metadata that prevented some
APIs from being used.</p>
<h2>What's Changed</h2>
<ul>
<li>Workaround for <code>rustdoc</code> regression by <a
href="https://github.com/kennykerr"><code>@​kennykerr</code></a> in <a
href="https://redirect.github.com/microsoft/windows-rs/pull/2381">microsoft/windows-rs#2381</a></li>
<li>Token privilege samples by <a
href="https://github.com/kennykerr"><code>@​kennykerr</code></a> in <a
href="https://redirect.github.com/microsoft/windows-rs/pull/2382">microsoft/windows-rs#2382</a></li>
<li>Apply <code>const</code> parameter metadata by <a
href="https://github.com/kennykerr"><code>@​kennykerr</code></a> in <a
href="https://redirect.github.com/microsoft/windows-rs/pull/2384">microsoft/windows-rs#2384</a></li>
<li>Advanced metadata filtering by <a
href="https://github.com/kennykerr"><code>@​kennykerr</code></a> in <a
href="https://redirect.github.com/microsoft/windows-rs/pull/2385">microsoft/windows-rs#2385</a></li>
<li>Update Win32 metadata v46 by <a
href="https://github.com/kennykerr"><code>@​kennykerr</code></a> in <a
href="https://redirect.github.com/microsoft/windows-rs/pull/2387">microsoft/windows-rs#2387</a></li>
<li>Support standalone code generation by <a
href="https://github.com/kennykerr"><code>@​kennykerr</code></a> in <a
href="https://redirect.github.com/microsoft/windows-rs/pull/2396">microsoft/windows-rs#2396</a></li>
<li>Update readme to include <code>windows-targets</code> and
<code>windows-bindgen</code> by <a
href="https://github.com/kennykerr"><code>@​kennykerr</code></a> in <a
href="https://redirect.github.com/microsoft/windows-rs/pull/2399">microsoft/windows-rs#2399</a></li>
<li>Update Win32 metadata v47 by <a
href="https://github.com/kennykerr"><code>@​kennykerr</code></a> in <a
href="https://redirect.github.com/microsoft/windows-rs/pull/2400">microsoft/windows-rs#2400</a></li>
<li>Version 0.47.0 by <a
href="https://github.com/kennykerr"><code>@​kennykerr</code></a> in <a
href="https://redirect.github.com/microsoft/windows-rs/pull/2401">microsoft/windows-rs#2401</a></li>
<li>Add CLR test for lib validation by <a
href="https://github.com/kennykerr"><code>@​kennykerr</code></a> in <a
href="https://redirect.github.com/microsoft/windows-rs/pull/2403">microsoft/windows-rs#2403</a></li>
<li>Restore reproducible libs by <a
href="https://github.com/riverar"><code>@​riverar</code></a> in <a
href="https://redirect.github.com/microsoft/windows-rs/pull/2402">microsoft/windows-rs#2402</a></li>
<li>Check diff for all targets by <a
href="https://github.com/kennykerr"><code>@​kennykerr</code></a> in <a
href="https://redirect.github.com/microsoft/windows-rs/pull/2404">microsoft/windows-rs#2404</a></li>
</ul>
<p><strong>Full Changelog</strong>: <a
href="https://github.com/microsoft/windows-rs/compare/0.46.0...0.47.0">https://github.com/microsoft/windows-rs/compare/0.46.0...0.47.0</a></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="406944152e"><code>4069441</code></a>
Improve target version reliability (<a
href="https://redirect.github.com/microsoft/windows-rs/issues/2412">#2412</a>)</li>
<li><a
href="ec95c1e6ac"><code>ec95c1e</code></a>
Check diff for all targets (<a
href="https://redirect.github.com/microsoft/windows-rs/issues/2404">#2404</a>)</li>
<li><a
href="91e0a5c079"><code>91e0a5c</code></a>
Restore reproducible libs (<a
href="https://redirect.github.com/microsoft/windows-rs/issues/2402">#2402</a>)</li>
<li><a
href="36ea325a8d"><code>36ea325</code></a>
Add CLR test for lib validation (<a
href="https://redirect.github.com/microsoft/windows-rs/issues/2403">#2403</a>)</li>
<li><a
href="e03d14e2d0"><code>e03d14e</code></a>
Version 0.47.0 (<a
href="https://redirect.github.com/microsoft/windows-rs/issues/2401">#2401</a>)</li>
<li><a
href="f86349d691"><code>f86349d</code></a>
Update Win32 metadata v47 (<a
href="https://redirect.github.com/microsoft/windows-rs/issues/2400">#2400</a>)</li>
<li><a
href="3e3c87b5ed"><code>3e3c87b</code></a>
Update readme to include <code>windows-targets</code> and
<code>windows-bindgen</code> (<a
href="https://redirect.github.com/microsoft/windows-rs/issues/2399">#2399</a>)</li>
<li><a
href="6672c6d28a"><code>6672c6d</code></a>
Support standalone code generation (<a
href="https://redirect.github.com/microsoft/windows-rs/issues/2396">#2396</a>)</li>
<li><a
href="f3ef2cdfa7"><code>f3ef2cd</code></a>
Update Win32 metadata v46 (<a
href="https://redirect.github.com/microsoft/windows-rs/issues/2387">#2387</a>)</li>
<li><a
href="3507dcd3b1"><code>3507dcd</code></a>
Advanced metadata filtering (<a
href="https://redirect.github.com/microsoft/windows-rs/issues/2385">#2385</a>)</li>
<li>Additional commits viewable in <a
href="https://github.com/microsoft/windows-rs/compare/0.46.0...0.48.0">compare
view</a></li>
</ul>
</details>
<br />


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

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

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

---

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

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


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-04-05 16:54:26 -05:00
add20873d0 make str index-of -r use ranges (#8724)
# Description

final follow up to #8660 

# User-Facing Changes

**BREAKING CHANGE**
any scripts using the previous string or list syntax will **BREAK**
2023-04-05 23:22:40 +02:00
427db0d101 FEATURE: better ansi -e error (#8709)
Should close #8704.

# Description
this PR
- makes the error thrown by things like `ansi -e {invalid: "invalid"}`
more explicit
- makes the `ansi -e` example more explicit about valid / invalid keys

# User-Facing Changes
the error
```bash
> ansi -e {invalid: "invalid"}
Error: nu:🐚:incompatible_parameters

  × Incompatible parameters.
   ╭─[entry #1:1:1]
 1 │ ansi -e {invalid: "invalid"}
   ·         ──────────┬─────────
   ·                   ╰── unknown ANSI format key: expected one of ['fg', 'bg', 'attr'], found 'invalid'
   ╰────
```

the new `ansi -e` example
```bash
  Use structured escape codes
  > let bold_blue_on_red = {  # `fg`, `bg`, `attr` are the acceptable keys, all other keys are considered invalid and will throw errors.
        fg: '#0000ff'
        bg: '#ff0000'
        attr: b
    }
    $"(ansi -e $bold_blue_on_red)Hello Nu World(ansi reset)"
  Hello Nu World
```

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

# After Submitting
```
$nothing
```
2023-04-05 23:14:39 +02:00
7bac0b417f stdlib: add an automatic loading of "prelude" commands (#8627) 2023-04-05 23:44:59 +03:00
JT
56efbd7de9 Add IDE support (#8745)
# Description

This adds a set of new flags on the `nu` binary intended for use in
IDEs. Here is the set of supported functionality so far:

* goto-def - go to the definition of a variable or custom command
* type hints - see the inferred type of variables
* check - see the errors in the document (currently only one error is
supported)
* hover - get information about the variable or custom command
* complete - get a completion list at the current position

# User-Facing Changes

No changes to the REPL experience. This only impacts the IDE scenario.

# 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 -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-utils/standard_library/tests.nu` 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-04-06 07:34:47 +12:00
91282d4404 Bump git2 from 0.16.1 to 0.17.0 (#8722) 2023-04-05 19:20:58 +00:00
398976e43e Bump spin from 0.9.5 to 0.9.8 (#8730)
Bumps [spin](https://github.com/mvdnes/spin-rs) from 0.9.5 to 0.9.8.
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/mvdnes/spin-rs/blob/master/CHANGELOG.md">spin's
changelog</a>.</em></p>
<blockquote>
<h1>[0.9.8] - 2023-04-03</h1>
<h3>Fixed</h3>
<ul>
<li>Unsoundness in <code>Once::try_call_once</code> caused by an
<code>Err(_)</code> result</li>
</ul>
<h1>[0.9.7] - 2023-03-27</h1>
<h3>Fixed</h3>
<ul>
<li>Relaxed accidentally restricted <code>Send</code>/<code>Sync</code>
bounds for <code>Mutex</code> guards</li>
</ul>
<h1>[0.9.6] - 2023-03-13</h1>
<h3>Fixed</h3>
<ul>
<li>Relaxed accidentally restricted <code>Send</code>/<code>Sync</code>
bounds for <code>RwLock</code> guards</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li>See full diff in <a
href="https://github.com/mvdnes/spin-rs/commits">compare view</a></li>
</ul>
</details>
<br />


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

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

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

---

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

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after
your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge
and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating
it. You can achieve the same result by closing it manually
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/nushell/nushell/network/alerts).

</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-04-05 13:58:32 -05:00
f723bc6989 Std xml utils (#8437)
# Description

Add `xaccess`,`xupdate` and `xinsert` scripts to standard library. They
allow accessing and manipulating data in new xml format
https://github.com/nushell/nushell/pull/7947 with relative ease.

Access some data in nushell xml structure:

![image](https://user-images.githubusercontent.com/17511668/224785447-317359e2-1430-4dfc-9307-73f1d5e50098.png)

Update attributes of xml tags matching a path:

![image](https://user-images.githubusercontent.com/17511668/224785506-85e9aa30-b36b-43db-af1d-2f4460563124.png)


# User-Facing Changes

New commands `std xaccess`, `std xupdate` and `std xinsert`

# 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 -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass

> **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-04-05 13:54:08 -05:00
22142bd4ae add a cross platform clip command to the standard library (#8695)
Should close the associated poin in #8311

# Description
this PR adds a `clip` command to `std` which
- has error support in case the clipboard system command is not
installed
- removes any ANSI escape sequences from the input to have a clean
copied text
- can throw desktop notifications on linux in case of a long pipeline
which needs to be copied (can be disabled with `--no-notify`)
- echoes the copied data to the output of the terminal (can be disabled
with --silent)
- has examples and dependencies listed
- has "charpage" 65001 (a.k.a. utf-8) support for windows

## new additions from 9cd3c951f to
ad3e8de25b
- better OS context error support
- use of the `match` statement for scalability
- `match` the value of the `$nu.os-info.name`
- add `macOS` with `pbcopy` to the list of supported systems
- throw an error when the OS is not supported
- ~~add simple tests to make sure `clip` works on all main OSes with the
CI~~ had to be removed in 6028b98483 (see
[the failing
test](https://github.com/nushell/nushell/actions/runs/4610091544/jobs/8148126550?pr=8695#step:6:35))

# User-Facing Changes
users can now access a `clip` to copy the output of any pipeline to the
system clipboard, on any system

# Tests + Formatting
```
$nothing
```

# After Submitting
```
$nothing
```
2023-04-05 13:19:42 -05:00
caf1432dc7 refactor the ansi help page (#8713)
# Description
i've always found the `ansi --help` extra usage hard to read and
understand...
i decided to give it a shot today, so here is what i came up 😋 

- make the extra usage structured with `nushell` tables
- make the examples clearer with variables and comments

one change that might appear strange is the following last two commits
```diff
diff --git a/crates/nu-command/src/platform/ansi/ansi_.rs b/crates/nu-command/src/platform/ansi/ansi_.rs
index 4746d27fa..ba3e597c4 100644
--- a/crates/nu-command/src/platform/ansi/ansi_.rs
+++ b/crates/nu-command/src/platform/ansi/ansi_.rs
@@ -507,10 +507,7 @@ impl Command for AnsiCommand {
 
     fn signature(&self) -> Signature {
         Signature::build("ansi")
-            .input_output_types(vec![
-                (Type::Nothing, Type::String),
-                (Type::List(Box::new(Type::String)), Type::String),
-            ])
+            .input_output_types(vec![(Type::Nothing, Type::String)])
             .optional(
                 "code",
                 SyntaxShape::Any,
```
`ansi` is never used on `list` inputs, as can be seen in the `Ansi.run`
function: `_input: PipelineData` is never used.
this broke the tests (see [this
action](https://github.com/nushell/nushell/actions/runs/4589552235/jobs/8104520078#step:4:1392))
for no real reason...

# User-Facing Changes
hopefully an easier to read `help ansi` page.

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

# After Submitting

If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
2023-04-05 13:16:36 -05:00
65c90d5b45 Add ppid to ps command (#8750)
# Description

Adds the `ppid` field that's available on all supported platforms to the
`ps` command. This would be useful in my scripts.

# User-Facing Changes

- ps output now contains an extra column

# Tests + Formatting

Not sure if I need to add a test for this

# After Submitting

Update https://www.nushell.sh/book/quick_tour.html#quick-tour to show
the new table
2023-04-05 13:12:01 -05:00
JT
50ca77437d Add atuin to official support (#8757)
# 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 -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-utils/standard_library/tests.nu` 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-04-05 13:08:32 -05:00
71b4949843 Change default config to display failed LAST_EXIT_CODE (#8735)
# Description

fixed #8655 
Change default nushell configuration file `default_env.nu` to display
LAST_EXIT_CODE in the prompt. For this change, users can quickly know
that a previous command failed.

# User-Facing Changes

This change affects only users who use the default configuration.
When a command fails, the exit code is displayed in the prompt like
these figures.
* before

![image](https://user-images.githubusercontent.com/37319612/229782830-45bc6b0d-75e4-459f-ae1d-46877f740239.png)
* after

![image](https://user-images.githubusercontent.com/37319612/229784089-e68b5d14-499b-4448-b764-e6b30ca64714.png)


# Tests + Formatting

When I ran tests, `test.nu` failed with the following error.
The error also occurs in the master branch, so it's probably unrelated
to these changes.
Do I need to address it?

* `cargo fmt --all -- --check`: passed
* `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A
clippy::needless_collect`: passed
* `cargo test --workspace`: passed
* `cargo run -- crates/nu-utils/standard_library/tests.nu`: ~failed~
passed
```
~/oss_dev/nushell> cargo run -- crates/nu-utils/standard_library/tests.nu
    Finished dev [unoptimized + debuginfo] target(s) in 0.15s
     Running `target/debug/nu crates/nu-utils/standard_library/tests.nu`
Error: nu:🐚:external_command

  × External command failed
    ╭─[/home/hiroki/oss_dev/nushell/crates/nu-utils/standard_library/tests.nu:73:1]
 73 │         | upsert test {|module|
 74 │             nu -c $'use ($module.file) *; $nu.scope.commands | select name module_name | to nuon'
    ·             ─┬
    ·              ╰── did you mean 'du'?
 75 │             | from nuon
    ╰────
  help: No such file or directory (os error 2)
  ```

# After Submitting

nothing
2023-04-05 13:06:24 -05:00
54a18991ab Loops return external stream when external command failed. (#8646) 2023-04-05 20:38:04 +03:00
1fcb98289a Add section on removing ANSI sequences with find command (#8519)
Co-authored-by: Phreno <phreno@pop-os.localdomain>
2023-04-05 20:26:20 +03:00
01e5ba01f6 Correction bug multiple dots mkdir and touch (#8486) 2023-04-05 20:22:56 +03:00
1134c2f16c Allow NU_LIBS_DIR and friends to be const (#8538) 2023-04-05 19:56:48 +03:00
d18cf19a3f Bump to 0.78.1 development version (#8741)
# Description

either just development or hotfix
2023-04-05 13:36:10 +12:00
255 changed files with 9593 additions and 7732 deletions

5
.githooks/pre-commit Executable file
View File

@ -0,0 +1,5 @@
#!/usr/bin/env nu
use ../toolkit.nu fmt
fmt --check --verbose

6
.githooks/pre-push Executable file
View File

@ -0,0 +1,6 @@
#!/usr/bin/env nu
use ../toolkit.nu [fmt, clippy]
fmt --check --verbose
clippy --verbose

View File

@ -0,0 +1,11 @@
---
name: standard library bug or feature report
about: Used to submit issues related to the nu standard library
title: ''
labels: std-library
assignees: ''
---
**Describe the bug or feature**
A clear and concise description of what the bug is.

View File

@ -1,16 +1,16 @@
# Description
<!--
Thank you for improving Nushell. Please, check our [contributing guide](../CONTRIBUTING.md) and talk to the core team before making major changes.
_(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.)_
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.)_
<!-- 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:
@ -18,7 +18,7 @@ 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 -A clippy::needless_collect` to check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-utils/standard_library/tests.nu` to run the tests for the standard library
- `cargo run -- crates/nu-std/tests/run.nu` to run the tests for the standard library
> **Note**
> from `nushell` you can also use the `toolkit` as follows
@ -26,7 +26,7 @@ Make sure you've run and fixed any issues with these commands:
> 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.
<!-- 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. -->

View File

@ -116,7 +116,7 @@ jobs:
run: cargo install --path . --locked --no-default-features
- name: Standard library tests
run: nu crates/nu-utils/standard_library/tests.nu
run: nu -c 'use std; std run-tests --path crates/nu-std'
- name: Setup Python
uses: actions/setup-python@v4
@ -169,40 +169,39 @@ jobs:
run: cargo test --profile ci --package nu_plugin_*
# nu-coverage:
# needs: nu-tests
# env:
# NUSHELL_CARGO_TARGET: ci
nu-coverage:
env:
NUSHELL_CARGO_TARGET: ci
# strategy:
# fail-fast: true
# matrix:
# # disabled mac due to problems with merging coverage and similarity to linux
# # disabled windows due to running out of disk space when having too many crates or tests
# platform: [ubuntu-20.04] # windows-latest
# rust:
# - stable
strategy:
fail-fast: true
matrix:
# disabled mac due to problems with merging coverage and similarity to linux
# disabled windows due to running out of disk space when having too many crates or tests
platform: [ubuntu-20.04] # windows-latest
rust:
- stable
# runs-on: ${{ matrix.platform }}
runs-on: ${{ matrix.platform }}
# steps:
# - uses: actions/checkout@v3
steps:
- uses: actions/checkout@v3
# - name: Setup Rust toolchain and cache
# uses: actions-rust-lang/setup-rust-toolchain@v1.4.4
# - name: Install cargo-llvm-cov
# uses: taiki-e/install-action@cargo-llvm-cov
- name: Setup Rust toolchain and cache
uses: actions-rust-lang/setup-rust-toolchain@v1.4.4
- name: Install cargo-llvm-cov
uses: taiki-e/install-action@cargo-llvm-cov
# - name: Tests
# shell: bash
# run: |
# source <(cargo llvm-cov show-env --export-prefix) # Set the environment variables needed to get coverage.
# cargo llvm-cov clean --workspace # Remove artifacts that may affect the coverage results.
# cargo build --workspace --profile ci
# cargo test --workspace --profile ci
# cargo llvm-cov report --profile ci --lcov --output-path lcov.info
- name: Tests
shell: bash
run: |
source <(cargo llvm-cov show-env --export-prefix) # Set the environment variables needed to get coverage.
cargo llvm-cov clean --workspace # Remove artifacts that may affect the coverage results.
cargo build --workspace --profile ci
cargo test --workspace --profile ci
cargo llvm-cov report --profile ci --lcov --output-path lcov.info
# - name: Upload coverage reports to Codecov with GitHub Action
# uses: codecov/codecov-action@v3
# with:
# files: lcov.info
- name: Upload coverage reports to Codecov with GitHub Action
uses: codecov/codecov-action@v3
with:
files: lcov.info

View File

@ -50,17 +50,17 @@ let flags = $env.TARGET_RUSTFLAGS
let dist = $'($env.GITHUB_WORKSPACE)/output'
let version = (open Cargo.toml | get package.version)
$'Debugging info:'
print $'Debugging info:'
print { version: $version, bin: $bin, os: $os, target: $target, src: $src, flags: $flags, dist: $dist }; hr-line -b
# $env
let USE_UBUNTU = 'ubuntu-20.04'
$'(char nl)Packaging ($bin) v($version) for ($target) in ($src)...'; hr-line -b
print $'(char nl)Packaging ($bin) v($version) for ($target) in ($src)...'; hr-line -b
if not ('Cargo.lock' | path exists) { cargo generate-lockfile }
$'Start building ($bin)...'; hr-line
print $'Start building ($bin)...'; hr-line
# ----------------------------------------------------------------------------
# Build for Ubuntu and macOS
@ -70,23 +70,28 @@ if $os in [$USE_UBUNTU, 'macos-latest'] {
sudo apt update
sudo apt-get install libxcb-composite0-dev -y
}
if $target == 'aarch64-unknown-linux-gnu' {
sudo apt-get install gcc-aarch64-linux-gnu -y
let-env CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER = 'aarch64-linux-gnu-gcc'
cargo-build-nu $flags
} else if $target == 'armv7-unknown-linux-gnueabihf' {
sudo apt-get install pkg-config gcc-arm-linux-gnueabihf -y
let-env CARGO_TARGET_ARMV7_UNKNOWN_LINUX_GNUEABIHF_LINKER = 'arm-linux-gnueabihf-gcc'
cargo-build-nu $flags
} else if $target == 'riscv64gc-unknown-linux-gnu' {
sudo apt-get install gcc-riscv64-linux-gnu -y
let-env CARGO_TARGET_RISCV64GC_UNKNOWN_LINUX_GNU_LINKER = 'riscv64-linux-gnu-gcc'
cargo-build-nu $flags
} else {
# musl-tools to fix 'Failed to find tool. Is `musl-gcc` installed?'
# Actually just for x86_64-unknown-linux-musl target
if $os == $USE_UBUNTU { sudo apt install musl-tools -y }
cargo-build-nu $flags
match $target {
'aarch64-unknown-linux-gnu' => {
sudo apt-get install gcc-aarch64-linux-gnu -y
let-env CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER = 'aarch64-linux-gnu-gcc'
cargo-build-nu $flags
}
'riscv64gc-unknown-linux-gnu' => {
sudo apt-get install gcc-riscv64-linux-gnu -y
let-env CARGO_TARGET_RISCV64GC_UNKNOWN_LINUX_GNU_LINKER = 'riscv64-linux-gnu-gcc'
cargo-build-nu $flags
}
'armv7-unknown-linux-gnueabihf' => {
sudo apt-get install pkg-config gcc-arm-linux-gnueabihf -y
let-env CARGO_TARGET_ARMV7_UNKNOWN_LINUX_GNUEABIHF_LINKER = 'arm-linux-gnueabihf-gcc'
cargo-build-nu $flags
}
_ => {
# musl-tools to fix 'Failed to find tool. Is `musl-gcc` installed?'
# Actually just for x86_64-unknown-linux-musl target
if $os == $USE_UBUNTU { sudo apt install musl-tools -y }
cargo-build-nu $flags
}
}
}
@ -107,31 +112,34 @@ if $os in ['windows-latest'] {
let suffix = if $os == 'windows-latest' { '.exe' }
# nu, nu_plugin_* were all included
let executable = $'target/($target)/release/($bin)*($suffix)'
$'Current executable file: ($executable)'
print $'Current executable file: ($executable)'
cd $src; mkdir $dist;
rm -rf $'target/($target)/release/*.d' $'target/($target)/release/nu_pretty_hex*'
$'(char nl)All executable files:'; hr-line
ls -f $executable
print $'(char nl)All executable files:'; hr-line
# We have to use `print` here to make sure the command output is displayed
print (ls -f $executable); sleep 1sec
$'(char nl)Copying release files...'; hr-line
print $'(char nl)Copying release files...'; hr-line
cp -v README.release.txt $'($dist)/README.txt'
[LICENSE $executable] | each {|it| cp -rv $it $dist } | flatten
# Sleep a few seconds to make sure the cp process finished successfully
sleep 3sec
$'(char nl)Check binary release version detail:'; hr-line
print $'(char nl)Check binary release version detail:'; hr-line
let ver = if $os == 'windows-latest' {
(do -i { ./output/nu.exe -c 'version' }) | str join
} else {
(do -i { ./output/nu -c 'version' }) | str join
}
if ($ver | str trim | is-empty) {
$'(ansi r)Incompatible nu binary...(ansi reset)'
} else { $ver }
print $'(ansi r)Incompatible nu binary...(ansi reset)'
} else { print $ver }
# ----------------------------------------------------------------------------
# Create a release archive and send it to output for the following steps
# ----------------------------------------------------------------------------
cd $dist; $'(char nl)Creating release archive...'; hr-line
cd $dist; print $'(char nl)Creating release archive...'; hr-line
if $os in [$USE_UBUNTU, 'macos-latest'] {
let files = (ls | get name)
@ -141,7 +149,7 @@ if $os in [$USE_UBUNTU, 'macos-latest'] {
mkdir $dest
$files | each {|it| mv $it $dest } | ignore
$'(char nl)(ansi g)Archive contents:(ansi reset)'; hr-line; ls $dest
print $'(char nl)(ansi g)Archive contents:(ansi reset)'; hr-line; ls $dest
tar -czf $archive $dest
print $'archive: ---> ($archive)'; ls $archive
@ -152,7 +160,7 @@ if $os in [$USE_UBUNTU, 'macos-latest'] {
let releaseStem = $'($bin)-($version)-($target)'
$'(char nl)Download less related stuffs...'; hr-line
print $'(char nl)Download less related stuffs...'; hr-line
aria2c https://github.com/jftuga/less-Windows/releases/download/less-v608/less.exe -o less.exe
aria2c https://raw.githubusercontent.com/jftuga/less-Windows/master/LICENSE -o LICENSE-for-less.txt
@ -160,7 +168,7 @@ if $os in [$USE_UBUNTU, 'macos-latest'] {
if (get-env _EXTRA_) == 'msi' {
let wixRelease = $'($src)/target/wix/($releaseStem).msi'
$'(char nl)Start creating Windows msi package...'
print $'(char nl)Start creating Windows msi package...'
cd $src; hr-line
# Wix need the binaries be stored in target/release/
cp -r $'($dist)/*' target/release/
@ -171,7 +179,7 @@ if $os in [$USE_UBUNTU, 'macos-latest'] {
} else {
$'(char nl)(ansi g)Archive contents:(ansi reset)'; hr-line; ls
print $'(char nl)(ansi g)Archive contents:(ansi reset)'; hr-line; ls
let archive = $'($dist)/($releaseStem).zip'
7z a $archive *
print $'archive: ---> ($archive)';

View File

@ -75,7 +75,7 @@ jobs:
- name: Setup Nushell
uses: hustcer/setup-nu@v3
with:
version: 0.72.1
version: 0.78.0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@ -61,12 +61,22 @@ The most comprehensive test suite we have is the `nu-test-support` crate. For te
```shell
cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A clippy::needless_collect
```
or via the `toolkit.nu` command:
```shell
use toolkit.nu clippy
clippy
```
- Run all tests:
```shell
cargo test --workspace
```
or via the `toolkit.nu` command:
```shell
use toolkit.nu test
test
```
- Run all tests for a specific command
@ -79,12 +89,30 @@ The most comprehensive test suite we have is the `nu-test-support` crate. For te
```shell
cargo fmt --all -- --check
```
or via the `toolkit.nu` command:
```shell
use toolkit.nu fmt
fmt --check
```
- Format the code in the project
```shell
cargo fmt --all
```
or via the `toolkit.nu` command:
```shell
use toolkit.nu fmt
fmt
```
- Set up `git` hooks to check formatting and run `clippy` before committing and pushing:
```shell
use toolkit.nu setup-git-hooks
setup-git-hooks
```
_Unfortunately, this hook isn't available on Windows._
### Debugging Tips

874
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -10,7 +10,7 @@ license = "MIT"
name = "nu"
repository = "https://github.com/nushell/nushell"
rust-version = "1.60"
version = "0.78.0"
version = "0.79.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@ -37,38 +37,41 @@ members = [
"crates/nu_plugin_query",
"crates/nu_plugin_custom_values",
"crates/nu_plugin_formats",
"crates/nu-std",
"crates/nu-utils",
]
[dependencies]
chrono = { version = "0.4.23", features = ["serde"] }
crossterm = "0.24.0"
crossterm = "0.26"
ctrlc = "3.2.1"
log = "0.4"
miette = { version = "5.6.0", features = ["fancy-no-backtrace"] }
nu-cli = { path = "./crates/nu-cli", version = "0.78.0" }
nu-color-config = { path = "./crates/nu-color-config", version = "0.78.0" }
nu-cmd-lang = { path = "./crates/nu-cmd-lang", version = "0.78.0" }
nu-command = { path = "./crates/nu-command", version = "0.78.0" }
nu-engine = { path = "./crates/nu-engine", version = "0.78.0" }
nu-json = { path = "./crates/nu-json", version = "0.78.0" }
nu-parser = { path = "./crates/nu-parser", version = "0.78.0" }
nu-path = { path = "./crates/nu-path", version = "0.78.0" }
nu-plugin = { path = "./crates/nu-plugin", optional = true, version = "0.78.0" }
nu-pretty-hex = { path = "./crates/nu-pretty-hex", version = "0.78.0" }
nu-protocol = { path = "./crates/nu-protocol", version = "0.78.0" }
nu-system = { path = "./crates/nu-system", version = "0.78.0" }
nu-table = { path = "./crates/nu-table", version = "0.78.0" }
nu-term-grid = { path = "./crates/nu-term-grid", version = "0.78.0" }
nu-utils = { path = "./crates/nu-utils", version = "0.78.0" }
miette = { version = "5.7.0", features = ["fancy-no-backtrace"] }
nu-cli = { path = "./crates/nu-cli", version = "0.79.0" }
nu-color-config = { path = "./crates/nu-color-config", version = "0.79.0" }
nu-cmd-lang = { path = "./crates/nu-cmd-lang", version = "0.79.0" }
nu-command = { path = "./crates/nu-command", version = "0.79.0" }
nu-engine = { path = "./crates/nu-engine", version = "0.79.0" }
nu-json = { path = "./crates/nu-json", version = "0.79.0" }
nu-parser = { path = "./crates/nu-parser", version = "0.79.0" }
nu-path = { path = "./crates/nu-path", version = "0.79.0" }
nu-plugin = { path = "./crates/nu-plugin", optional = true, version = "0.79.0" }
nu-pretty-hex = { path = "./crates/nu-pretty-hex", version = "0.79.0" }
nu-protocol = { path = "./crates/nu-protocol", version = "0.79.0" }
nu-system = { path = "./crates/nu-system", version = "0.79.0" }
nu-table = { path = "./crates/nu-table", version = "0.79.0" }
nu-term-grid = { path = "./crates/nu-term-grid", version = "0.79.0" }
nu-std = { path = "./crates/nu-std", version = "0.79.0" }
nu-utils = { path = "./crates/nu-utils", version = "0.79.0" }
nu-ansi-term = "0.47.0"
reedline = { version = "0.18.0", features = ["bashisms", "sqlite"] }
reedline = { version = "0.19.0", features = ["bashisms", "sqlite"]}
rayon = "1.7.0"
is_executable = "1.0.1"
simplelog = "0.12.0"
time = "0.3.12"
serde_json = "1.0"
[target.'cfg(not(target_os = "windows"))'.dependencies]
# Our dependencies don't use OpenSSL on Windows
@ -89,8 +92,8 @@ nix = { version = "0.26", default-features = false, features = [
atty = "0.2"
[dev-dependencies]
nu-test-support = { path = "./crates/nu-test-support", version = "0.78.0" }
tempfile = "3.4.0"
nu-test-support = { path = "./crates/nu-test-support", version = "0.79.0" }
tempfile = "3.5.0"
assert_cmd = "2.0.2"
criterion = "0.4"
pretty_assertions = "1.0.0"
@ -157,7 +160,7 @@ bench = false
# To use a development version of a dependency please use a global override here
# changing versions in each sub-crate of the workspace is tedious
[patch.crates-io]
# reedline = { git = "https://github.com/nushell/reedline.git", branch = "main" }
# reedline = { git = "https://github.com/nushell/reedline.git", branch = "main"}
# nu-ansi-term = {git = "https://github.com/nushell/nu-ansi-term.git", branch = "main"}
# Criterion benchmarking setup

View File

@ -6,7 +6,7 @@
[![@nu_shell](https://img.shields.io/badge/twitter-@nu_shell-1DA1F3?style=flat-square)](https://twitter.com/nu_shell)
[![GitHub commit activity](https://img.shields.io/github/commit-activity/m/nushell/nushell)](https://github.com/nushell/nushell/graphs/commit-activity)
[![GitHub contributors](https://img.shields.io/github/contributors/nushell/nushell)](https://github.com/nushell/nushell/graphs/contributors)
<!-- [![codecov](https://codecov.io/gh/nushell/nushell/branch/main/graph/badge.svg?token=JheS8qu2II)](https://codecov.io/gh/nushell/nushell) -->
[![codecov](https://codecov.io/gh/nushell/nushell/branch/main/graph/badge.svg?token=JheS8qu2II)](https://codecov.io/gh/nushell/nushell)
A new type of shell.
@ -46,6 +46,8 @@ To quickly install Nu:
brew install nushell
# Windows
winget install nushell
# Cross Platform installation if you have node and npm installed, Note that nu plugins were not included
npm install -g nushell
```
To use `Nu` in GitHub Action, check [setup-nu](https://github.com/marketplace/actions/setup-nu) for more detail.
@ -222,6 +224,7 @@ Please submit an issue or PR to be added to this list.
- [oh-my-posh](https://ohmyposh.dev)
- [Couchbase Shell](https://couchbase.sh)
- [virtualenv](https://github.com/pypa/virtualenv)
- [atuin](https://github.com/ellie/atuin)
## Contributing

View File

@ -22,7 +22,7 @@ fn parser_benchmarks(c: &mut Criterion) {
c.bench_function("parse_default_env_file", |b| {
b.iter_batched(
|| nu_protocol::engine::StateWorkingSet::new(&engine_state),
|mut working_set| parse(&mut working_set, None, default_env, false, &[]),
|mut working_set| parse(&mut working_set, None, default_env, false),
BatchSize::SmallInput,
)
});
@ -31,7 +31,7 @@ fn parser_benchmarks(c: &mut Criterion) {
c.bench_function("parse_default_config_file", |b| {
b.iter_batched(
|| nu_protocol::engine::StateWorkingSet::new(&engine_state),
|mut working_set| parse(&mut working_set, None, default_config, false, &[]),
|mut working_set| parse(&mut working_set, None, default_config, false),
BatchSize::SmallInput,
)
});

View File

@ -5,39 +5,40 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu-cli"
edition = "2021"
license = "MIT"
name = "nu-cli"
version = "0.78.0"
version = "0.79.0"
[lib]
bench = false
[dev-dependencies]
nu-test-support = { path = "../nu-test-support", version = "0.78.0" }
nu-test-support = { path = "../nu-test-support", version = "0.79.0" }
rstest = { version = "0.17.0", default-features = false }
[dependencies]
nu-command = { path = "../nu-command", version = "0.78.0" }
nu-engine = { path = "../nu-engine", version = "0.78.0" }
nu-path = { path = "../nu-path", version = "0.78.0" }
nu-parser = { path = "../nu-parser", version = "0.78.0" }
nu-protocol = { path = "../nu-protocol", version = "0.78.0" }
nu-utils = { path = "../nu-utils", version = "0.78.0" }
nu-color-config = { path = "../nu-color-config", version = "0.78.0" }
nu-command = { path = "../nu-command", version = "0.79.0" }
nu-engine = { path = "../nu-engine", version = "0.79.0" }
nu-path = { path = "../nu-path", version = "0.79.0" }
nu-parser = { path = "../nu-parser", version = "0.79.0" }
nu-protocol = { path = "../nu-protocol", version = "0.79.0" }
nu-utils = { path = "../nu-utils", version = "0.79.0" }
nu-color-config = { path = "../nu-color-config", version = "0.79.0" }
nu-ansi-term = "0.47.0"
reedline = { version = "0.18.0", features = ["bashisms", "sqlite"] }
reedline = { version = "0.19.0", features = ["bashisms", "sqlite"]}
atty = "0.2.14"
chrono = { default-features = false, features = ["std"], version = "0.4.23" }
crossterm = "0.24.0"
crossterm = "0.26"
fancy-regex = "0.11.0"
fuzzy-matcher = "0.3.7"
is_executable = "1.0.1"
once_cell = "1.17.0"
log = "0.4"
miette = { version = "5.6.0", features = ["fancy-no-backtrace"] }
miette = { version = "5.7.0", features = ["fancy-no-backtrace"] }
percent-encoding = "2"
sysinfo = "0.28.2"
thiserror = "1.0.31"
unicode-segmentation = "1.10.0"
[features]
plugin = []

View File

@ -0,0 +1,33 @@
use nu_protocol::engine::{EngineState, StateWorkingSet};
use crate::commands::*;
pub fn add_cli_context(mut engine_state: EngineState) -> EngineState {
let delta = {
let mut working_set = StateWorkingSet::new(&engine_state);
macro_rules! bind_command {
( $( $command:expr ),* $(,)? ) => {
$( working_set.add_decl(Box::new($command)); )*
};
}
bind_command! {
Commandline,
History,
HistorySession,
Keybindings,
KeybindingsDefault,
KeybindingsList,
KeybindingsListen,
};
working_set.render()
};
if let Err(err) = engine_state.merge_delta(delta) {
eprintln!("Error creating default context: {err:?}");
}
engine_state
}

View File

@ -91,7 +91,7 @@ impl Command for History {
match engine_state.config.history_file_format {
HistoryFileFormat::PlainText => Ok(history_reader
.and_then(|h| {
h.search(SearchQuery::everything(SearchDirection::Forward))
h.search(SearchQuery::everything(SearchDirection::Forward, None))
.ok()
})
.map(move |entries| {
@ -114,7 +114,7 @@ impl Command for History {
.into_pipeline_data(ctrlc)),
HistoryFileFormat::Sqlite => Ok(history_reader
.and_then(|h| {
h.search(SearchQuery::everything(SearchDirection::Forward))
h.search(SearchQuery::everything(SearchDirection::Forward, None))
.ok()
})
.map(move |entries| {

View File

@ -102,7 +102,13 @@ pub fn print_events(engine_state: &EngineState) -> Result<Value, ShellError> {
// are printed, it's a good chance your terminal is eating
// those events.
fn print_events_helper(event: Event) -> Result<Value, ShellError> {
if let Event::Key(KeyEvent { code, modifiers }) = event {
if let Event::Key(KeyEvent {
code,
modifiers,
kind,
state,
}) = event
{
match code {
KeyCode::Char(c) => {
let record = Value::Record {
@ -111,12 +117,16 @@ fn print_events_helper(event: Event) -> Result<Value, ShellError> {
"code".into(),
"modifier".into(),
"flags".into(),
"kind".into(),
"state".into(),
],
vals: vec![
Value::string(format!("{c}"), Span::unknown()),
Value::string(format!("{:#08x}", u32::from(c)), Span::unknown()),
Value::string(format!("{modifiers:?}"), Span::unknown()),
Value::string(format!("{modifiers:#08b}"), Span::unknown()),
Value::string(format!("{kind:?}"), Span::unknown()),
Value::string(format!("{state:?}"), Span::unknown()),
],
span: Span::unknown(),
};
@ -144,14 +154,3 @@ fn print_events_helper(event: Event) -> Result<Value, ShellError> {
Ok(record)
}
}
#[cfg(test)]
mod tests {
use crate::KeybindingsListen;
#[test]
fn examples_work_as_expected() {
use crate::test_examples;
test_examples(KeybindingsListen {})
}
}

View File

@ -1,9 +1,18 @@
mod commandline;
mod default_context;
mod history;
mod history_session;
mod keybindings;
mod keybindings_default;
mod keybindings_list;
mod keybindings_listen;
pub use commandline::Commandline;
pub use history::History;
pub use history_session::HistorySession;
pub use keybindings::Keybindings;
pub use keybindings_default::KeybindingsDefault;
pub use keybindings_list::KeybindingsList;
pub use keybindings_listen::KeybindingsListen;
pub use default_context::add_cli_context;

View File

@ -88,7 +88,7 @@ impl CommandCompletion {
let filter_predicate = |command: &[u8]| match_algorithm.matches_u8(command, partial);
let results = working_set
let mut results = working_set
.find_commands_by_predicate(filter_predicate)
.into_iter()
.map(move |x| Suggestion {
@ -97,20 +97,8 @@ impl CommandCompletion {
extra: None,
span: reedline::Span::new(span.start - offset, span.end - offset),
append_whitespace: true,
});
let results_aliases = working_set
.find_aliases_by_predicate(filter_predicate)
.into_iter()
.map(move |x| Suggestion {
value: String::from_utf8_lossy(&x).to_string(),
description: None,
extra: None,
span: reedline::Span::new(span.start - offset, span.end - offset),
append_whitespace: true,
});
let mut results = results.chain(results_aliases).collect::<Vec<_>>();
})
.collect::<Vec<_>>();
let partial = working_set.get_span_contents(span);
let partial = String::from_utf8_lossy(partial).to_string();
@ -169,7 +157,7 @@ impl Completer for CommandCompletion {
.take_while(|x| {
matches!(
x.1,
FlatShape::InternalCall
FlatShape::InternalCall(_)
| FlatShape::External
| FlatShape::ExternalArg
| FlatShape::Literal
@ -197,7 +185,7 @@ impl Completer for CommandCompletion {
let config = working_set.get_config();
let commands = if matches!(self.flat_shape, nu_parser::FlatShape::External)
|| matches!(self.flat_shape, nu_parser::FlatShape::InternalCall)
|| matches!(self.flat_shape, nu_parser::FlatShape::InternalCall(_))
|| ((span.end - span.start) == 0)
|| is_passthrough_command(working_set.delta.get_file_contents())
{
@ -311,7 +299,7 @@ mod command_completions_tests {
let delta = {
let mut working_set = StateWorkingSet::new(&engine_state);
working_set.add_file("child.nu".into(), input);
let _ = working_set.add_file("child.nu".into(), input);
working_set.render()
};

View File

@ -113,14 +113,13 @@ impl NuCompleter {
fn completion_helper(&mut self, line: &str, pos: usize) -> Vec<Suggestion> {
let mut working_set = StateWorkingSet::new(&self.engine_state);
let offset = working_set.next_span_start();
let (mut new_line, alias_offset) = try_find_alias(line.as_bytes(), &working_set);
let initial_line = line.to_string();
let alias_total_offset: usize = alias_offset.iter().sum();
new_line.insert(alias_total_offset + pos, b'a');
let mut line = line.to_string();
line.insert(pos, 'a');
let pos = offset + pos;
let config = self.engine_state.get_config();
let (output, _err) = parse(&mut working_set, Some("completer"), &new_line, false, &[]);
let output = parse(&mut working_set, Some("completer"), line.as_bytes(), false);
for pipeline in output.pipelines.into_iter() {
for pipeline_element in pipeline.elements {
@ -131,7 +130,6 @@ impl NuCompleter {
| PipelineElement::Or(_, expr)
| PipelineElement::SeparateRedirection { out: (_, expr), .. } => {
let flattened: Vec<_> = flatten_expression(&working_set, &expr);
let span_offset: usize = alias_offset.iter().sum();
let mut spans: Vec<String> = vec![];
for (flat_idx, flat) in flattened.iter().enumerate() {
@ -154,24 +152,17 @@ impl NuCompleter {
}
// Complete based on the last span
if pos + span_offset >= flat.0.start && pos + span_offset < flat.0.end {
if pos >= flat.0.start && pos < flat.0.end {
// Context variables
let most_left_var =
most_left_variable(flat_idx, &working_set, flattened.clone());
// Create a new span
let new_span = if flat_idx == 0 {
Span::new(flat.0.start, flat.0.end - 1 - span_offset)
} else {
Span::new(
flat.0.start - span_offset,
flat.0.end - 1 - span_offset,
)
};
let new_span = Span::new(flat.0.start, flat.0.end - 1);
// Parses the prefix. Completion should look up to the cursor position, not after.
let mut prefix = working_set.get_span_contents(flat.0).to_vec();
let index = pos - (flat.0.start - span_offset);
let index = pos - flat.0.start;
prefix.drain(index..);
// Variables completion
@ -391,85 +382,6 @@ impl ReedlineCompleter for NuCompleter {
}
}
type MatchedAlias = Vec<(Vec<u8>, Vec<u8>)>;
// Handler the completion when giving lines contains at least one alias. (e.g: `g checkout`)
// that `g` is an alias of `git`
fn try_find_alias(line: &[u8], working_set: &StateWorkingSet) -> (Vec<u8>, Vec<usize>) {
// An vector represents the offsets of alias
// e.g: the offset is 2 for the alias `g` of `git`
let mut alias_offset = vec![];
let mut output = vec![];
if let Some(matched_alias) = search_alias(line, working_set) {
let mut lens = matched_alias.len();
for (input_vec, line_vec) in matched_alias {
alias_offset.push(line_vec.len() - input_vec.len());
output.extend(line_vec);
if lens > 1 {
output.push(b' ');
lens -= 1;
}
}
if !line.is_empty() {
let last = line.last().expect("input is empty");
if last == &b' ' {
output.push(b' ');
}
}
} else {
output = line.to_vec();
}
(output, alias_offset)
}
fn search_alias(input: &[u8], working_set: &StateWorkingSet) -> Option<MatchedAlias> {
let mut vec_names = vec![];
let mut vec_alias = vec![];
let mut pos = 0;
let mut is_alias = false;
for (index, character) in input.iter().enumerate() {
if *character == b' ' {
let range = &input[pos..index];
vec_names.push(range.to_owned());
pos = index + 1;
}
}
// Push the rest to names vector.
if pos < input.len() {
vec_names.push(input[pos..].to_owned());
}
for name in &vec_names {
if let Some(alias_id) = working_set.find_alias(&name[..]) {
let alias_span = working_set.get_alias(alias_id);
let mut span_vec = vec![];
is_alias = true;
for alias in alias_span {
let name = working_set.get_span_contents(*alias);
if !name.is_empty() {
span_vec.push(name);
}
}
// Join span of vector together for complex alias, e.g: `f` is an alias for `git remote -v`
let full_aliases = span_vec.join(&[b' '][..]);
vec_alias.push(full_aliases);
} else {
vec_alias.push(name.to_owned());
}
}
if is_alias {
// Zip names and alias vectors, the original inputs and its aliases mapping.
// e.g:(['g'], ['g','i','t'])
let output = vec_names.into_iter().zip(vec_alias).collect();
Some(output)
} else {
None
}
}
// reads the most left variable returning it's name (e.g: $myvar)
// and the depth (a.b.c)
fn most_left_variable(
@ -490,7 +402,7 @@ fn most_left_variable(
let result = working_set.get_span_contents(item.0).to_vec();
match item.1 {
FlatShape::Variable => {
FlatShape::Variable(_) => {
variables_found.push(result);
found_var = true;

View File

@ -6,7 +6,7 @@ use nu_protocol::{
PipelineData, Span, Type, Value,
};
use reedline::Suggestion;
use std::sync::Arc;
use std::{collections::HashMap, sync::Arc};
use super::completer::map_value_completions;
@ -66,7 +66,7 @@ impl Completer for CustomCompletion {
],
redirect_stdout: true,
redirect_stderr: true,
parser_info: vec![],
parser_info: HashMap::new(),
},
PipelineData::empty(),
);

View File

@ -179,11 +179,7 @@ impl Completer for VariableCompletion {
let mut removed_overlays = vec![];
// Working set scope vars
for scope_frame in working_set.delta.scope.iter().rev() {
for overlay_frame in scope_frame
.active_overlays(&mut removed_overlays)
.iter()
.rev()
{
for overlay_frame in scope_frame.active_overlays(&mut removed_overlays).rev() {
for v in &overlay_frame.vars {
if options.match_algorithm.matches_u8_insensitive(
options.case_sensitive,
@ -204,12 +200,7 @@ impl Completer for VariableCompletion {
// Permanent state vars
// for scope in &self.engine_state.scope {
for overlay_frame in self
.engine_state
.active_overlays(&removed_overlays)
.iter()
.rev()
{
for overlay_frame in self.engine_state.active_overlays(&removed_overlays).rev() {
for v in &overlay_frame.vars {
if options.match_algorithm.matches_u8_insensitive(
options.case_sensitive,

View File

@ -1,14 +1,12 @@
use crate::util::eval_source;
use nu_command::util::report_error;
#[cfg(feature = "plugin")]
use nu_parser::ParseError;
#[cfg(feature = "plugin")]
use nu_path::canonicalize_with;
use nu_protocol::engine::{EngineState, Stack, StateWorkingSet};
#[cfg(feature = "plugin")]
use nu_protocol::Spanned;
use nu_protocol::report_error;
use nu_protocol::{HistoryFileFormat, PipelineData};
#[cfg(feature = "plugin")]
use nu_protocol::{ParseError, Spanned};
#[cfg(feature = "plugin")]
use nu_utils::utils::perf;
use std::path::PathBuf;

View File

@ -1,9 +1,9 @@
use log::info;
use miette::Result;
use nu_command::util::report_error;
use nu_engine::{convert_env_values, eval_block};
use nu_parser::parse;
use nu_protocol::engine::Stack;
use nu_protocol::report_error;
use nu_protocol::{
engine::{EngineState, StateWorkingSet},
PipelineData, Spanned, Value,
@ -34,9 +34,9 @@ pub fn evaluate_commands(
let mut working_set = StateWorkingSet::new(engine_state);
let (output, err) = parse(&mut working_set, None, commands.item.as_bytes(), false, &[]);
if let Some(err) = err {
report_error(&working_set, &err);
let output = parse(&mut working_set, None, commands.item.as_bytes(), false);
if let Some(err) = working_set.parse_errors.first() {
report_error(&working_set, err);
std::process::exit(1);
}

View File

@ -2,10 +2,10 @@ use crate::util::eval_source;
use log::info;
use log::trace;
use miette::{IntoDiagnostic, Result};
use nu_command::util::report_error;
use nu_engine::{convert_env_values, current_dir};
use nu_parser::parse;
use nu_path::canonicalize_with;
use nu_protocol::report_error;
use nu_protocol::{
ast::Call,
engine::{EngineState, Stack, StateWorkingSet},
@ -93,10 +93,14 @@ pub fn evaluate_file(
"FILE_PWD".to_string(),
Value::string(parent.to_string_lossy(), Span::unknown()),
);
stack.add_env_var(
"CURRENT_FILE".to_string(),
Value::string(file_path.to_string_lossy(), Span::unknown()),
);
let mut working_set = StateWorkingSet::new(engine_state);
trace!("parsing file: {}", file_path_str);
let _ = parse(&mut working_set, Some(file_path_str), &file, false, &[]);
let _ = parse(&mut working_set, Some(file_path_str), &file, false);
if working_set.find_decl(b"main", &Type::Any).is_some() {
let args = format!("main {}", args.join(" "));

View File

@ -1,6 +1,7 @@
mod commands;
mod completions;
mod config_files;
mod eval_cmds;
mod eval_file;
mod menus;
mod nu_highlight;
@ -13,12 +14,13 @@ mod syntax_highlight;
mod util;
mod validation;
pub use commands::evaluate_commands;
pub use commands::add_cli_context;
pub use completions::{FileCompletion, NuCompleter};
pub use config_files::eval_config_contents;
pub use eval_cmds::evaluate_commands;
pub use eval_file::evaluate_file;
pub use menus::{DescriptionMenu, NuHelpCompleter};
pub use nu_command::util::{get_init_cwd, report_error, report_error_new};
pub use nu_command::util::get_init_cwd;
pub use nu_highlight::NuHighlight;
pub use print::Print;
pub use prompt::NushellPrompt;

View File

@ -1,7 +1,7 @@
use crate::NushellPrompt;
use log::trace;
use nu_command::util::report_error;
use nu_engine::eval_subexpression;
use nu_protocol::report_error;
use nu_protocol::{
engine::{EngineState, Stack, StateWorkingSet},
Config, PipelineData, Value,

View File

@ -97,12 +97,11 @@ pub(crate) fn add_menus(
{
let (block, _) = {
let mut working_set = StateWorkingSet::new(&engine_state);
let (output, _) = parse(
let output = parse(
&mut working_set,
Some(name), // format!("entry #{}", entry_num)
definition.as_bytes(),
true,
&[],
);
(output, working_set.render())

View File

@ -5,18 +5,19 @@ use crate::{
util::eval_source,
NuHighlighter, NuValidator, NushellPrompt,
};
use crossterm::cursor::CursorShape;
use crossterm::cursor::SetCursorStyle;
use log::{trace, warn};
use miette::{IntoDiagnostic, Result};
use nu_color_config::StyleComputer;
use nu_command::hook::eval_hook;
use nu_command::util::{get_guaranteed_cwd, report_error, report_error_new};
use nu_command::util::get_guaranteed_cwd;
use nu_engine::{convert_env_values, eval_block};
use nu_parser::{lex, parse, trim_quotes_str};
use nu_protocol::{
config::NuCursorShape,
engine::{EngineState, Stack, StateWorkingSet},
format_duration, HistoryFileFormat, PipelineData, ShellError, Span, Spanned, Value,
format_duration, report_error, report_error_new, HistoryFileFormat, PipelineData, ShellError,
Span, Spanned, Value,
};
use nu_utils::utils::perf;
use reedline::{CursorConfig, DefaultHinter, EditCommand, Emacs, SqliteBackedHistory, Vi};
@ -706,11 +707,11 @@ pub fn evaluate_repl(
Ok(())
}
fn map_nucursorshape_to_cursorshape(shape: NuCursorShape) -> CursorShape {
fn map_nucursorshape_to_cursorshape(shape: NuCursorShape) -> SetCursorStyle {
match shape {
NuCursorShape::Block => CursorShape::Block,
NuCursorShape::UnderScore => CursorShape::UnderScore,
NuCursorShape::Line => CursorShape::Line,
NuCursorShape::Block => SetCursorStyle::SteadyBlock,
NuCursorShape::UnderScore => SetCursorStyle::DefaultUserShape,
NuCursorShape::Line => SetCursorStyle::BlinkingBar,
}
}
@ -789,7 +790,7 @@ pub fn eval_string_with_input(
) -> Result<Value, ShellError> {
let (block, delta) = {
let mut working_set = StateWorkingSet::new(engine_state);
let (output, _) = parse(&mut working_set, None, source.as_bytes(), false, &[]);
let output = parse(&mut working_set, None, source.as_bytes(), false);
(output, working_set.render())
};

View File

@ -18,10 +18,7 @@ impl Highlighter for NuHighlighter {
trace!("highlighting: {}", line);
let mut working_set = StateWorkingSet::new(&self.engine_state);
let block = {
let (block, _) = parse(&mut working_set, None, line.as_bytes(), false, &[]);
block
};
let block = parse(&mut working_set, None, line.as_bytes(), false);
let (shapes, global_span_offset) = {
let shapes = flatten_block(&working_set, &block);
(shapes, self.engine_state.next_span_start())
@ -91,9 +88,10 @@ impl Highlighter for NuHighlighter {
FlatShape::Int => add_colored_token(&shape.1, next_token),
FlatShape::Float => add_colored_token(&shape.1, next_token),
FlatShape::Range => add_colored_token(&shape.1, next_token),
FlatShape::InternalCall => add_colored_token(&shape.1, next_token),
FlatShape::InternalCall(_) => add_colored_token(&shape.1, next_token),
FlatShape::External => add_colored_token(&shape.1, next_token),
FlatShape::ExternalArg => add_colored_token(&shape.1, next_token),
FlatShape::Keyword => add_colored_token(&shape.1, next_token),
FlatShape::Literal => add_colored_token(&shape.1, next_token),
FlatShape::Operator => add_colored_token(&shape.1, next_token),
FlatShape::Signature => add_colored_token(&shape.1, next_token),
@ -113,11 +111,16 @@ impl Highlighter for NuHighlighter {
FlatShape::Block => {
add_colored_token_with_bracket_highlight!(shape.1, shape.0, next_token)
}
FlatShape::Closure => {
add_colored_token_with_bracket_highlight!(shape.1, shape.0, next_token)
}
FlatShape::Filepath => add_colored_token(&shape.1, next_token),
FlatShape::Directory => add_colored_token(&shape.1, next_token),
FlatShape::GlobPattern => add_colored_token(&shape.1, next_token),
FlatShape::Variable => add_colored_token(&shape.1, next_token),
FlatShape::Variable(_) | FlatShape::VarDecl(_) => {
add_colored_token(&shape.1, next_token)
}
FlatShape::Flag => add_colored_token(&shape.1, next_token),
FlatShape::Pipe => add_colored_token(&shape.1, next_token),
FlatShape::And => add_colored_token(&shape.1, next_token),

View File

@ -1,5 +1,4 @@
use nu_command::hook::eval_hook;
use nu_command::util::{report_error, report_error_new};
use nu_engine::{eval_block, eval_block_with_early_return};
use nu_parser::{escape_quote_string, lex, parse, unescape_unquote_string, Token, TokenContents};
use nu_protocol::engine::StateWorkingSet;
@ -7,6 +6,7 @@ use nu_protocol::{
engine::{EngineState, Stack},
print_if_stream, PipelineData, ShellError, Span, Value,
};
use nu_protocol::{report_error, report_error_new};
#[cfg(windows)]
use nu_utils::enable_vt_processing;
use nu_utils::utils::perf;
@ -113,7 +113,8 @@ fn gather_env_vars(
span,
}) = parts.get(0)
{
let bytes = engine_state.get_span_contents(span);
let mut working_set = StateWorkingSet::new(engine_state);
let bytes = working_set.get_span_contents(*span);
if bytes.len() < 2 {
report_capture_error(
@ -125,9 +126,12 @@ fn gather_env_vars(
continue;
}
let (bytes, parse_error) = unescape_unquote_string(bytes, *span);
let (bytes, err) = unescape_unquote_string(bytes, *span);
if let Some(err) = err {
working_set.error(err);
}
if parse_error.is_some() {
if working_set.parse_errors.first().is_some() {
report_capture_error(
engine_state,
&String::from_utf8_lossy(contents),
@ -153,7 +157,8 @@ fn gather_env_vars(
span,
}) = parts.get(2)
{
let bytes = engine_state.get_span_contents(span);
let mut working_set = StateWorkingSet::new(engine_state);
let bytes = working_set.get_span_contents(*span);
if bytes.len() < 2 {
report_capture_error(
@ -165,9 +170,12 @@ fn gather_env_vars(
continue;
}
let (bytes, parse_error) = unescape_unquote_string(bytes, *span);
let (bytes, err) = unescape_unquote_string(bytes, *span);
if let Some(err) = err {
working_set.error(err);
}
if parse_error.is_some() {
if working_set.parse_errors.first().is_some() {
report_capture_error(
engine_state,
&String::from_utf8_lossy(contents),
@ -209,16 +217,15 @@ pub fn eval_source(
let (block, delta) = {
let mut working_set = StateWorkingSet::new(engine_state);
let (output, err) = parse(
let output = parse(
&mut working_set,
Some(fname), // format!("entry #{}", entry_num)
source,
false,
&[],
);
if let Some(err) = err {
if let Some(err) = working_set.parse_errors.first() {
set_last_exit_code(stack, 1);
report_error(&working_set, &err);
report_error(&working_set, err);
return false;
}

View File

@ -1,5 +1,8 @@
use nu_parser::{parse, ParseError};
use nu_protocol::engine::{EngineState, StateWorkingSet};
use nu_parser::parse;
use nu_protocol::{
engine::{EngineState, StateWorkingSet},
ParseError,
};
use reedline::{ValidationResult, Validator};
use std::sync::Arc;
@ -10,9 +13,12 @@ pub struct NuValidator {
impl Validator for NuValidator {
fn validate(&self, line: &str) -> ValidationResult {
let mut working_set = StateWorkingSet::new(&self.engine_state);
let (_, err) = parse(&mut working_set, None, line.as_bytes(), false, &[]);
parse(&mut working_set, None, line.as_bytes(), false);
if matches!(err, Some(ParseError::UnexpectedEof(..))) {
if matches!(
working_set.parse_errors.first(),
Some(ParseError::UnexpectedEof(..))
) {
ValidationResult::Incomplete
} else {
ValidationResult::Complete

View File

@ -524,10 +524,12 @@ fn variables_completions() {
// Test completions for $nu
let suggestions = completer.complete("$nu.", 4);
assert_eq!(12, suggestions.len());
assert_eq!(14, suggestions.len());
let expected: Vec<String> = vec![
"config-path".into(),
"current-exe".into(),
"default-config-dir".into(),
"env-path".into(),
"history-path".into(),
"home-path".into(),
@ -663,8 +665,8 @@ fn run_external_completion(block: &str, input: &str) -> Vec<Suggestion> {
let (dir, _, mut engine_state, mut stack) = new_engine();
let (_, delta) = {
let mut working_set = StateWorkingSet::new(&engine_state);
let (block, err) = parse(&mut working_set, None, block.as_bytes(), false, &[]);
assert!(err.is_none());
let block = parse(&mut working_set, None, block.as_bytes(), false);
assert!(working_set.parse_errors.is_empty());
(block, working_set.render())
};

View File

@ -146,9 +146,9 @@ pub fn merge_input(
let (block, delta) = {
let mut working_set = StateWorkingSet::new(engine_state);
let (block, err) = parse(&mut working_set, None, input, false, &[]);
let block = parse(&mut working_set, None, input, false);
assert!(err.is_none());
assert!(working_set.parse_errors.is_empty());
(block, working_set.render())
};

View File

@ -6,17 +6,17 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu-cmd-lang"
edition = "2021"
license = "MIT"
name = "nu-cmd-lang"
version = "0.78.0"
version = "0.79.0"
[lib]
bench = false
[dependencies]
nu-color-config = { path = "../nu-color-config", version = "0.78.0" }
nu-engine = { path = "../nu-engine", version = "0.78.0" }
nu-parser = { path = "../nu-parser", version = "0.78.0" }
nu-protocol = { path = "../nu-protocol", version = "0.78.0" }
nu-utils = { path = "../nu-utils", version = "0.78.0" }
nu-color-config = { path = "../nu-color-config", version = "0.79.0" }
nu-engine = { path = "../nu-engine", version = "0.79.0" }
nu-parser = { path = "../nu-parser", version = "0.79.0" }
nu-protocol = { path = "../nu-protocol", version = "0.79.0" }
nu-utils = { path = "../nu-utils", version = "0.79.0" }
nu-ansi-term = "0.47.0"
@ -24,10 +24,9 @@ fancy-regex = "0.11.0"
itertools = "0.10.0"
log = "0.4.14"
shadow-rs = { version = "0.21.0", default-features = false }
unicode-segmentation = "1.10.0"
[build-dependencies]
shadow-rs = { version = "0.21.0", default-features = false }
[dev-dependencies]
nu-test-support = { path="../nu-test-support", version = "0.78.0" }
nu-test-support = { path="../nu-test-support", version = "0.79.0" }

View File

@ -20,15 +20,6 @@ impl Command for Break {
.category(Category::Core)
}
fn extra_usage(&self) -> &str {
r#"This command is a parser keyword. For details, check:
https://www.nushell.sh/book/thinking_in_nu.html"#
}
fn is_parser_keyword(&self) -> bool {
true
}
fn run(
&self,
_engine_state: &EngineState,

View File

@ -20,15 +20,6 @@ impl Command for Continue {
.category(Category::Core)
}
fn extra_usage(&self) -> &str {
r#"This command is a parser keyword. For details, check:
https://www.nushell.sh/book/thinking_in_nu.html"#
}
fn is_parser_keyword(&self) -> bool {
true
}
fn run(
&self,
_engine_state: &EngineState,

View File

@ -120,9 +120,11 @@ impl Command for For {
return Err(err);
}
Ok(pipeline) => {
let exit_code = pipeline.print(&engine_state, stack, false, false)?;
let exit_code = pipeline.drain_with_exit_code()?;
if exit_code != 0 {
break;
return Ok(PipelineData::new_external_stream_with_only_exit_code(
exit_code,
));
}
}
}
@ -164,7 +166,9 @@ impl Command for For {
Ok(pipeline) => {
let exit_code = pipeline.drain_with_exit_code()?;
if exit_code != 0 {
break;
return Ok(PipelineData::new_external_stream_with_only_exit_code(
exit_code,
));
}
}
}

View File

@ -7,7 +7,6 @@ use nu_protocol::{
span, Category, Example, IntoInterruptiblePipelineData, IntoPipelineData, PipelineData,
ShellError, Signature, Span, Spanned, SyntaxShape, Type, Value,
};
use std::borrow::Cow;
#[derive(Clone)]
pub struct HelpAliases;
@ -112,22 +111,22 @@ pub fn help_aliases(
name.push_str(&r.item);
}
let alias_id = if let Some(id) = engine_state.find_alias(name.as_bytes(), &[]) {
id
} else {
let Some(alias) = engine_state.find_decl(name.as_bytes(), &[]) else {
return Err(ShellError::AliasNotFound(span(
&rest.iter().map(|r| r.span).collect::<Vec<Span>>(),
)));
};
let alias_expansion = engine_state
.get_alias(alias_id)
.iter()
.map(|span| String::from_utf8_lossy(engine_state.get_span_contents(span)))
.collect::<Vec<Cow<str>>>()
.join(" ");
let Some(alias) = engine_state.get_decl(alias).as_alias() else {
return Err(ShellError::AliasNotFound(span(
&rest.iter().map(|r| r.span).collect::<Vec<Span>>(),
)));
};
let alias_usage = engine_state.build_alias_usage(alias_id);
let alias_expansion =
String::from_utf8_lossy(engine_state.get_span_contents(&alias.wrapped_call.span));
let usage = alias.usage();
let extra_usage = alias.extra_usage();
// TODO: merge this into documentation.rs at some point
const G: &str = "\x1b[32m"; // green
@ -136,14 +135,12 @@ pub fn help_aliases(
let mut long_desc = String::new();
if let Some((usage, extra_usage)) = alias_usage {
long_desc.push_str(&usage);
long_desc.push_str("\n\n");
long_desc.push_str(usage);
long_desc.push_str("\n\n");
if !extra_usage.is_empty() {
long_desc.push_str(&extra_usage);
long_desc.push_str("\n\n");
}
if !extra_usage.is_empty() {
long_desc.push_str(extra_usage);
long_desc.push_str("\n\n");
}
long_desc.push_str(&format!("{G}Alias{RESET}: {C}{name}{RESET}"));
@ -165,7 +162,7 @@ pub fn help_aliases(
fn build_help_aliases(engine_state: &EngineState, stack: &Stack, span: Span) -> Vec<Value> {
let mut scope_data = ScopeData::new(engine_state, stack);
scope_data.populate_aliases();
scope_data.populate_all();
scope_data.collect_aliases(span)
}

View File

@ -4,8 +4,8 @@ use nu_engine::{scope::ScopeData, CallExt};
use nu_protocol::{
ast::Call,
engine::{Command, EngineState, Stack},
span, AliasId, Category, DeclId, Example, IntoInterruptiblePipelineData, IntoPipelineData,
PipelineData, ShellError, Signature, Span, Spanned, SyntaxShape, Type, Value,
span, Category, DeclId, Example, IntoInterruptiblePipelineData, IntoPipelineData, PipelineData,
ShellError, Signature, Span, Spanned, SyntaxShape, Type, Value,
};
#[derive(Clone)]
@ -117,9 +117,7 @@ pub fn help_modules(
name.push_str(&r.item);
}
let module_id = if let Some(id) = engine_state.find_module(name.as_bytes(), &[]) {
id
} else {
let Some(module_id) = engine_state.find_module(name.as_bytes(), &[]) else {
return Err(ShellError::ModuleNotFoundAtRuntime {
mod_name: name,
span: span(&rest.iter().map(|r| r.span).collect::<Vec<Span>>()),
@ -152,9 +150,16 @@ pub fn help_modules(
long_desc.push_str("\n\n");
if !module.decls.is_empty() || module.main.is_some() {
let commands: Vec<(Vec<u8>, DeclId)> = engine_state.get_decls_sorted(false).collect();
let commands: Vec<(Vec<u8>, DeclId)> = engine_state
.get_decls_sorted(false)
.filter(|(_, id)| !engine_state.get_decl(*id).is_alias())
.collect();
let mut module_commands = module.decls();
let mut module_commands: Vec<(Vec<u8>, DeclId)> = module
.decls()
.into_iter()
.filter(|(_, id)| !engine_state.get_decl(*id).is_alias())
.collect();
module_commands.sort_by(|a, b| a.0.cmp(&b.0));
let commands_str = module_commands
@ -181,15 +186,18 @@ pub fn help_modules(
long_desc.push_str("\n\n");
}
if !module.aliases.is_empty() {
let aliases: Vec<(Vec<u8>, AliasId)> = engine_state.get_aliases_sorted(false).collect();
let mut module_aliases: Vec<(&[u8], AliasId)> = module
.aliases
.iter()
.map(|(name, id)| (name.as_ref(), *id))
if !module.decls.is_empty() {
let aliases: Vec<(Vec<u8>, DeclId)> = engine_state
.get_decls_sorted(false)
.filter(|(_, id)| engine_state.get_decl(*id).is_alias())
.collect();
module_aliases.sort_by(|a, b| a.0.cmp(b.0));
let mut module_aliases: Vec<(Vec<u8>, DeclId)> = module
.decls()
.into_iter()
.filter(|(_, id)| engine_state.get_decl(*id).is_alias())
.collect();
module_aliases.sort_by(|a, b| a.0.cmp(&b.0));
let aliases_str = module_aliases
.iter()
@ -198,7 +206,7 @@ pub fn help_modules(
if let Some((used_name_bytes, _)) =
aliases.iter().find(|(_, alias_id)| id == alias_id)
{
if engine_state.find_alias(name.as_bytes(), &[]).is_some() {
if engine_state.find_decl(name.as_bytes(), &[]).is_some() {
format!("{CB}{name}{RESET}")
} else {
let alias_name = String::from_utf8_lossy(used_name_bytes);

View File

@ -40,15 +40,6 @@ impl Command for If {
.category(Category::Core)
}
fn extra_usage(&self) -> &str {
r#"This command is a parser keyword. For details, check:
https://www.nushell.sh/book/thinking_in_nu.html"#
}
fn is_parser_keyword(&self) -> bool {
true
}
fn run(
&self,
engine_state: &EngineState,

View File

@ -25,15 +25,6 @@ impl Command for Loop {
.category(Category::Core)
}
fn extra_usage(&self) -> &str {
r#"This command is a parser keyword. For details, check:
https://www.nushell.sh/book/thinking_in_nu.html"#
}
fn is_parser_keyword(&self) -> bool {
true
}
fn run(
&self,
engine_state: &EngineState,
@ -69,7 +60,9 @@ impl Command for Loop {
Ok(pipeline) => {
let exit_code = pipeline.drain_with_exit_code()?;
if exit_code != 0 {
break;
return Ok(PipelineData::new_external_stream_with_only_exit_code(
exit_code,
));
}
}
}

View File

@ -29,15 +29,6 @@ impl Command for Match {
.category(Category::Core)
}
fn extra_usage(&self) -> &str {
r#"This command is a parser keyword. For details, check:
https://www.nushell.sh/book/thinking_in_nu.html"#
}
fn is_parser_keyword(&self) -> bool {
true
}
fn run(
&self,
engine_state: &EngineState,

View File

@ -1,7 +1,6 @@
mod alias;
mod break_;
mod collect;
mod commandline;
mod const_;
mod continue_;
mod def;
@ -43,7 +42,6 @@ mod while_;
pub use alias::Alias;
pub use break_::Break;
pub use collect::Collect;
pub use commandline::Commandline;
pub use const_::Const;
pub use continue_::Continue;
pub use def::Def;

View File

@ -1,4 +1,4 @@
use nu_engine::{eval_block, find_in_dirs_env, redirect_env, CallExt};
use nu_engine::{eval_block, find_in_dirs_env, get_dirs_var_from_call, redirect_env, CallExt};
use nu_parser::trim_quotes_str;
use nu_protocol::ast::{Call, Expr};
use nu_protocol::engine::{Command, EngineState, Stack};
@ -66,23 +66,24 @@ impl Command for OverlayUse {
let mut name_arg: Spanned<String> = call.req(engine_state, caller_stack, 0)?;
name_arg.item = trim_quotes_str(&name_arg.item).to_string();
let maybe_origin_module_id = if let Some(overlay_expr) = call.parser_info_nth(0) {
if let Expr::Overlay(module_id) = overlay_expr.expr {
module_id
let maybe_origin_module_id =
if let Some(overlay_expr) = call.get_parser_info("overlay_expr") {
if let Expr::Overlay(module_id) = overlay_expr.expr {
module_id
} else {
return Err(ShellError::NushellFailedSpanned {
msg: "Not an overlay".to_string(),
label: "requires an overlay (path or a string)".to_string(),
span: overlay_expr.span,
});
}
} else {
return Err(ShellError::NushellFailedSpanned {
msg: "Not an overlay".to_string(),
label: "requires an overlay (path or a string)".to_string(),
span: overlay_expr.span,
msg: "Missing positional".to_string(),
label: "missing required overlay".to_string(),
span: call.head,
});
}
} else {
return Err(ShellError::NushellFailedSpanned {
msg: "Missing positional".to_string(),
label: "missing required overlay".to_string(),
span: call.head,
});
};
};
let overlay_name = if let Some(name) = call.opt(engine_state, caller_stack, 1)? {
name
@ -113,7 +114,12 @@ impl Command for OverlayUse {
// Evaluate the export-env block (if any) and keep its environment
if let Some(block_id) = module.env_block {
let maybe_path = find_in_dirs_env(&name_arg.item, engine_state, caller_stack)?;
let maybe_path = find_in_dirs_env(
&name_arg.item,
engine_state,
caller_stack,
get_dirs_var_from_call(call),
)?;
let block = engine_state.get_block(block_id);
let mut callee_stack = caller_stack.gather_captures(&block.captures);
@ -128,6 +134,11 @@ impl Command for OverlayUse {
callee_stack.add_env_var("FILE_PWD".to_string(), file_pwd);
}
if let Some(file_path) = &maybe_path {
let file_path = Value::string(file_path.to_string_lossy(), call.head);
callee_stack.add_env_var("CURRENT_FILE".to_string(), file_path);
}
let _ = eval_block(
engine_state,
&mut callee_stack,

View File

@ -36,15 +36,6 @@ impl Command for Try {
.category(Category::Core)
}
fn extra_usage(&self) -> &str {
r#"This command is a parser keyword. For details, check:
https://www.nushell.sh/book/thinking_in_nu.html"#
}
fn is_parser_keyword(&self) -> bool {
true
}
fn run(
&self,
engine_state: &EngineState,

View File

@ -1,4 +1,4 @@
use nu_engine::{eval_block, find_in_dirs_env, redirect_env};
use nu_engine::{eval_block, find_in_dirs_env, get_dirs_var_from_call, redirect_env};
use nu_protocol::ast::{Call, Expr, Expression};
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
@ -45,13 +45,10 @@ impl Command for Use {
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let import_pattern = if let Some(Expression {
expr: Expr::ImportPattern(pat),
let Some(Expression {
expr: Expr::ImportPattern(import_pattern),
..
}) = call.parser_info_nth(0)
{
pat
} else {
}) = call.get_parser_info("import_pattern") else {
return Err(ShellError::GenericError(
"Unexpected import".into(),
"import pattern not supported".into(),
@ -72,13 +69,16 @@ impl Command for Use {
let module_arg_str = String::from_utf8_lossy(
engine_state.get_span_contents(&import_pattern.head.span),
);
let maybe_parent = if let Some(path) =
find_in_dirs_env(&module_arg_str, engine_state, caller_stack)?
{
path.parent().map(|p| p.to_path_buf()).or(None)
} else {
None
};
let maybe_file_path = find_in_dirs_env(
&module_arg_str,
engine_state,
caller_stack,
get_dirs_var_from_call(call),
)?;
let maybe_parent = maybe_file_path
.as_ref()
.and_then(|path| path.parent().map(|p| p.to_path_buf()));
let mut callee_stack = caller_stack.gather_captures(&block.captures);
@ -88,6 +88,11 @@ impl Command for Use {
callee_stack.add_env_var("FILE_PWD".to_string(), file_pwd);
}
if let Some(file_path) = maybe_file_path {
let file_path = Value::string(file_path.to_string_lossy(), call.head);
callee_stack.add_env_var("CURRENT_FILE".to_string(), file_path);
}
// Run the block (discard the result)
let _ = eval_block(
engine_state,

View File

@ -30,15 +30,6 @@ impl Command for While {
.category(Category::Core)
}
fn extra_usage(&self) -> &str {
r#"This command is a parser keyword. For details, check:
https://www.nushell.sh/book/thinking_in_nu.html"#
}
fn is_parser_keyword(&self) -> bool {
true
}
fn run(
&self,
engine_state: &EngineState,
@ -79,7 +70,11 @@ impl Command for While {
Ok(pipeline) => {
let exit_code = pipeline.drain_with_exit_code()?;
if exit_code != 0 {
break;
return Ok(
PipelineData::new_external_stream_with_only_exit_code(
exit_code,
),
);
}
}
}

View File

@ -19,7 +19,6 @@ pub fn create_default_context() -> EngineState {
Alias,
Break,
Collect,
Commandline,
Const,
Continue,
Def,

View File

@ -126,9 +126,9 @@ fn eval_pipeline_without_terminal_expression(
pub fn parse(contents: &str, engine_state: &EngineState) -> (Block, StateDelta) {
let mut working_set = StateWorkingSet::new(engine_state);
let (output, err) = nu_parser::parse(&mut working_set, None, contents.as_bytes(), false, &[]);
let output = nu_parser::parse(&mut working_set, None, contents.as_bytes(), false);
if let Some(err) = err {
if let Some(err) = working_set.parse_errors.first() {
panic!("test parse error in `{contents}`: {err:?}")
}

View File

@ -5,7 +5,7 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu-color-confi
edition = "2021"
license = "MIT"
name = "nu-color-config"
version = "0.78.0"
version = "0.79.0"
[lib]
bench = false
@ -15,11 +15,11 @@ serde = { version="1.0.123", features=["derive"] }
# used only for text_style Alignments
tabled = { version = "0.10.0", features = ["color"], default-features = false }
nu-protocol = { path = "../nu-protocol", version = "0.78.0" }
nu-protocol = { path = "../nu-protocol", version = "0.79.0" }
nu-ansi-term = "0.47.0"
nu-utils = { path = "../nu-utils", version = "0.78.0" }
nu-engine = { path = "../nu-engine", version = "0.78.0" }
nu-json = { path="../nu-json", version = "0.78.0" }
nu-utils = { path = "../nu-utils", version = "0.79.0" }
nu-engine = { path = "../nu-engine", version = "0.79.0" }
nu-json = { path="../nu-json", version = "0.79.0" }
[dev-dependencies]
nu-test-support = { path="../nu-test-support", version = "0.78.0" }
nu-test-support = { path="../nu-test-support", version = "0.79.0" }

View File

@ -9,6 +9,7 @@ pub fn default_shape_color(shape: String) -> Style {
"shape_binary" => Style::new().fg(Color::Purple).bold(),
"shape_block" => Style::new().fg(Color::Blue).bold(),
"shape_bool" => Style::new().fg(Color::LightCyan),
"shape_closure" => Style::new().fg(Color::Green).bold(),
"shape_custom" => Style::new().fg(Color::Green),
"shape_datetime" => Style::new().fg(Color::Cyan).bold(),
"shape_directory" => Style::new().fg(Color::Cyan),
@ -21,6 +22,7 @@ pub fn default_shape_color(shape: String) -> Style {
"shape_globpattern" => Style::new().fg(Color::Cyan).bold(),
"shape_int" => Style::new().fg(Color::Purple).bold(),
"shape_internalcall" => Style::new().fg(Color::Cyan).bold(),
"shape_keyword" => Style::new().fg(Color::Cyan).bold(),
"shape_list" => Style::new().fg(Color::Cyan).bold(),
"shape_literal" => Style::new().fg(Color::Blue),
"shape_match_pattern" => Style::new().fg(Color::Green),
@ -36,6 +38,7 @@ pub fn default_shape_color(shape: String) -> Style {
"shape_string_interpolation" => Style::new().fg(Color::Cyan).bold(),
"shape_table" => Style::new().fg(Color::Blue).bold(),
"shape_variable" => Style::new().fg(Color::Purple),
"shape_vardecl" => Style::new().fg(Color::Purple),
_ => Style::default(),
}
}

View File

@ -5,7 +5,7 @@ edition = "2021"
license = "MIT"
name = "nu-command"
repository = "https://github.com/nushell/nushell/tree/main/crates/nu-command"
version = "0.78.0"
version = "0.79.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@ -13,20 +13,20 @@ version = "0.78.0"
bench = false
[dependencies]
nu-cmd-lang = { path = "../nu-cmd-lang", version = "0.78.0" }
nu-color-config = { path = "../nu-color-config", version = "0.78.0" }
nu-engine = { path = "../nu-engine", version = "0.78.0" }
nu-explore = { path = "../nu-explore", version = "0.78.0" }
nu-glob = { path = "../nu-glob", version = "0.78.0" }
nu-json = { path = "../nu-json", version = "0.78.0" }
nu-parser = { path = "../nu-parser", version = "0.78.0" }
nu-path = { path = "../nu-path", version = "0.78.0" }
nu-pretty-hex = { path = "../nu-pretty-hex", version = "0.78.0" }
nu-protocol = { path = "../nu-protocol", version = "0.78.0" }
nu-system = { path = "../nu-system", version = "0.78.0" }
nu-table = { path = "../nu-table", version = "0.78.0" }
nu-term-grid = { path = "../nu-term-grid", version = "0.78.0" }
nu-utils = { path = "../nu-utils", version = "0.78.0" }
nu-cmd-lang = { path = "../nu-cmd-lang", version = "0.79.0" }
nu-color-config = { path = "../nu-color-config", version = "0.79.0" }
nu-engine = { path = "../nu-engine", version = "0.79.0" }
nu-explore = { path = "../nu-explore", version = "0.79.0" }
nu-glob = { path = "../nu-glob", version = "0.79.0" }
nu-json = { path = "../nu-json", version = "0.79.0" }
nu-parser = { path = "../nu-parser", version = "0.79.0" }
nu-path = { path = "../nu-path", version = "0.79.0" }
nu-pretty-hex = { path = "../nu-pretty-hex", version = "0.79.0" }
nu-protocol = { path = "../nu-protocol", version = "0.79.0" }
nu-system = { path = "../nu-system", version = "0.79.0" }
nu-table = { path = "../nu-table", version = "0.79.0" }
nu-term-grid = { path = "../nu-term-grid", version = "0.79.0" }
nu-utils = { path = "../nu-utils", version = "0.79.0" }
num-format = { version = "0.4.3" }
nu-ansi-term = "0.47.0"
@ -42,11 +42,11 @@ calamine = "0.19.1"
chrono = { version = "0.4.23", features = ["std", "unstable-locales"], default-features = false }
chrono-humanize = "0.2.1"
chrono-tz = "0.8.1"
crossterm = "0.24.0"
crossterm = "0.26"
csv = "1.2.0"
dialoguer = { default-features = false, version = "0.10.3" }
digest = { default-features = false, version = "0.10.0" }
dtparse = "1.2.0"
dtparse = "1.4.0"
encoding_rs = "0.8.30"
fancy-regex = "0.11.0"
filesize = "0.2.0"
@ -58,16 +58,16 @@ indicatif = "0.17.2"
is-root = "0.1.2"
itertools = "0.10.0"
log = "0.4.14"
lscolors = { version = "0.12.0", features = ["crossterm"], default-features = false }
lscolors = { version = "0.14", default-features = false, features = ["nu-ansi-term"] }
md5 = { package = "md-5", version = "0.10.0" }
miette = { version = "5.6.0", features = ["fancy-no-backtrace"] }
miette = { version = "5.7.0", features = ["fancy-no-backtrace"] }
mime = "0.3.16"
mime_guess = "2.0.4"
notify = "4.0.17"
num = { version = "0.4.0", optional = true }
num-traits = "0.2.14"
once_cell = "1.17"
open = "4.0.0"
open = "4.0.2"
pathdiff = "0.2.1"
powierza-coefficient = "1.0.2"
quick-xml = "0.28"
@ -85,7 +85,6 @@ serde_yaml = "0.9.4"
sha2 = "0.10.0"
# Disable default features b/c the default features build Git (very slow to compile)
percent-encoding = "2.2.0"
reedline = { version = "0.18.0", features = ["bashisms", "sqlite"] }
rusqlite = { version = "0.28.0", features = ["bundled"], optional = true }
sqlparser = { version = "0.32.0", features = ["serde"], optional = true }
sysinfo = "0.28.2"
@ -103,11 +102,11 @@ which = { version = "4.4.0", optional = true }
print-positions = "0.6.1"
[target.'cfg(windows)'.dependencies]
winreg = "0.11.0"
winreg = "0.50.0"
[target.'cfg(unix)'.dependencies]
libc = "0.2"
umask = "2.0.0"
umask = "2.1.0"
users = "0.11.0"
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies.trash]
@ -147,7 +146,7 @@ version = "0.27.2"
[target.'cfg(windows)'.dependencies.windows]
features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_SystemServices"]
version = "0.46.0"
version = "0.48.0"
[features]
dataframe = ["num", "polars", "sqlparser"]
@ -157,7 +156,7 @@ trash-support = ["trash"]
which-support = ["which"]
[dev-dependencies]
nu-test-support = { path = "../nu-test-support", version = "0.78.0" }
nu-test-support = { path = "../nu-test-support", version = "0.79.0" }
mockito = "1.0.0"
dirs-next = "2.0.0"

View File

@ -3,7 +3,7 @@ use nu_engine::CallExt;
use nu_protocol::{
ast::{Call, CellPath},
engine::{Command, EngineState, Stack},
Example, PipelineData, ShellError, Signature, Span, SyntaxShape, Type, Value,
Category, Example, PipelineData, ShellError, Signature, Span, SyntaxShape, Type, Value,
};
#[derive(Clone)]
@ -25,6 +25,7 @@ impl Command for SubCommand {
SyntaxShape::CellPath,
"for a data structure input, convert data at the given cell paths",
)
.category(Category::Conversions)
}
fn usage(&self) -> &str {

View File

@ -50,15 +50,9 @@ pub fn test_dataframe(cmds: Vec<Box<dyn Command + 'static>>) {
let (block, delta) = {
let mut working_set = StateWorkingSet::new(&engine_state);
let (output, err) = parse(
&mut working_set,
None,
example.example.as_bytes(),
false,
&[],
);
let output = parse(&mut working_set, None, example.example.as_bytes(), false);
if let Some(err) = err {
if let Some(err) = working_set.parse_errors.first() {
panic!("test parse error in `{}`: {:?}", example.example, err)
}

View File

@ -81,7 +81,7 @@ impl Command for SubCommand {
vec![
Example {
description: "Get the current date in UTC+05:00",
example: "date now | date to-timezone +0500",
example: "date now | date to-timezone '+0500'",
result: None,
},
Example {

View File

@ -41,8 +41,10 @@ impl Command for Ast {
let pipeline: Spanned<String> = call.req(engine_state, stack, 0)?;
let mut working_set = StateWorkingSet::new(engine_state);
let (block_output, error_output) =
parse(&mut working_set, None, pipeline.item.as_bytes(), false, &[]);
let block_output = parse(&mut working_set, None, pipeline.item.as_bytes(), false);
let error_output = working_set.parse_errors.first();
let block_value = Value::String {
val: format!("{block_output:#?}"),
span: pipeline.span,

View File

@ -51,7 +51,7 @@ impl Command for Explain {
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Explain a command within a closure",
example: "explain { ls | sort-by name type -i | get name } | table -e",
example: "explain {|| ls | sort-by name type -i | get name } | table -e",
result: None,
}]
}

View File

@ -106,7 +106,7 @@ Current known limitations are:
vec![Example {
description:
"Profile some code, stepping into the `spam` command and collecting source.",
example: r#"def spam [] { "spam" }; profile { spam | str length } -d 2 --source"#,
example: r#"def spam [] { "spam" }; profile {|| spam | str length } -d 2 --source"#,
result: None,
}]
}

View File

@ -1,4 +1,3 @@
use itertools::Itertools;
use nu_engine::CallExt;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
@ -133,15 +132,6 @@ impl Command for ViewSource {
Vec::new(),
))
}
} else if let Some(alias_id) = engine_state.find_alias(val.as_bytes(), &[]) {
let contents = &mut engine_state.get_alias(alias_id).iter().map(|span| {
String::from_utf8_lossy(engine_state.get_span_contents(span)).to_string()
});
Ok(Value::String {
val: contents.join(" "),
span: call.head,
}
.into_pipeline_data())
} else {
Err(ShellError::GenericError(
"Cannot view value".to_string(),
@ -166,7 +156,7 @@ impl Command for ViewSource {
vec![
Example {
description: "View the source of a code block",
example: r#"let abc = { echo 'hi' }; view source $abc"#,
example: r#"let abc = {|| echo 'hi' }; view source $abc"#,
result: Some(Value::test_string("{ echo 'hi' }")),
},
Example {

View File

@ -56,6 +56,7 @@ pub fn create_default_context() -> EngineState {
GroupBy,
Headers,
Insert,
Items,
Join,
SplitBy,
Take,
@ -102,9 +103,7 @@ pub fn create_default_context() -> EngineState {
// Misc
bind_command! {
History,
Tutor,
HistorySession,
};
// Path
@ -256,12 +255,8 @@ pub fn create_default_context() -> EngineState {
AnsiLink,
Clear,
Du,
KeybindingsDefault,
Input,
KeybindingsListen,
Keybindings,
Kill,
KeybindingsList,
Sleep,
TermSize,
};

View File

@ -45,7 +45,7 @@ impl Command for Source {
) -> Result<PipelineData, ShellError> {
// Note: this hidden positional is the block_id that corresponded to the 0th position
// it is put here by the parser
let block_id: i64 = call.req_parser_info(engine_state, stack, 0)?;
let block_id: i64 = call.req_parser_info(engine_state, stack, "block_id")?;
let block = engine_state.get_block(block_id as usize).clone();
eval_block_with_early_return(

View File

@ -42,21 +42,18 @@ impl Command for ConfigEnv {
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let env_vars_str = env_to_strings(engine_state, stack)?;
let mut config_path = match nu_path::config_dir() {
Some(path) => path,
let nu_config = match engine_state.get_config_path("env-path") {
Some(path) => path.clone(),
None => {
return Err(ShellError::GenericError(
"Could not find nu env path".to_string(),
"Could not find nu env path".to_string(),
"Could not find $nu.env-path".to_string(),
"Could not find $nu.env-path".to_string(),
None,
None,
Vec::new(),
));
}
};
config_path.push("nushell");
let mut nu_config = config_path.clone();
nu_config.push("env.nu");
let (item, config_args) = get_editor(engine_state, stack, call.head)?;

View File

@ -42,21 +42,18 @@ impl Command for ConfigNu {
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let env_vars_str = env_to_strings(engine_state, stack)?;
let mut config_path = match nu_path::config_dir() {
Some(path) => path,
let nu_config = match engine_state.get_config_path("config-path") {
Some(path) => path.clone(),
None => {
return Err(ShellError::GenericError(
"Could not find nu config path".to_string(),
"Could not find nu config path".to_string(),
"Could not find $nu.config-path".to_string(),
"Could not find $nu.config-path".to_string(),
None,
None,
Vec::new(),
));
}
};
config_path.push("nushell");
let mut nu_config = config_path.clone();
nu_config.push("config.nu");
let (item, config_args) = get_editor(engine_state, stack, call.head)?;

View File

@ -51,7 +51,7 @@ impl Command for LetEnv {
.0
.into_value(call.head);
if env_var.item == "FILE_PWD" || env_var.item == "PWD" {
if env_var.item == "FILE_PWD" || env_var.item == "CURRENT_FILE" || env_var.item == "PWD" {
return Err(ShellError::AutomaticEnvVarSetManually {
envvar_name: env_var.item,
span: env_var.span,

View File

@ -42,28 +42,22 @@ impl Command for LoadEnv {
match arg {
Some((cols, vals)) => {
for (env_var, rhs) in cols.into_iter().zip(vals) {
if env_var == "FILE_PWD" {
let env_var_ = env_var.as_str();
if ["FILE_PWD", "CURRENT_FILE", "PWD"].contains(&env_var_) {
return Err(ShellError::AutomaticEnvVarSetManually {
envvar_name: env_var,
span: call.head,
});
}
if env_var == "PWD" {
return Err(ShellError::AutomaticEnvVarSetManually {
envvar_name: env_var,
span: call.head,
});
} else {
stack.add_env_var(env_var, rhs);
}
stack.add_env_var(env_var, rhs);
}
Ok(PipelineData::empty())
}
None => match input {
PipelineData::Value(Value::Record { cols, vals, .. }, ..) => {
for (env_var, rhs) in cols.into_iter().zip(vals) {
if env_var == "FILE_PWD" {
let env_var_ = env_var.as_str();
if ["FILE_PWD", "CURRENT_FILE"].contains(&env_var_) {
return Err(ShellError::AutomaticEnvVarSetManually {
envvar_name: env_var,
span: call.head,

View File

@ -1,6 +1,8 @@
use std::path::PathBuf;
use nu_engine::{eval_block_with_early_return, find_in_dirs_env, redirect_env, CallExt};
use nu_engine::{
eval_block_with_early_return, find_in_dirs_env, get_dirs_var_from_call, redirect_env, CallExt,
};
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
@ -42,21 +44,30 @@ impl Command for SourceEnv {
// Note: this hidden positional is the block_id that corresponded to the 0th position
// it is put here by the parser
let block_id: i64 = call.req_parser_info(engine_state, caller_stack, 0)?;
let block_id: i64 = call.req_parser_info(engine_state, caller_stack, "block_id")?;
// Set the currently evaluated directory (file-relative PWD)
let mut parent = if let Some(path) =
find_in_dirs_env(&source_filename.item, engine_state, caller_stack)?
{
let file_path = if let Some(path) = find_in_dirs_env(
&source_filename.item,
engine_state,
caller_stack,
get_dirs_var_from_call(call),
)? {
PathBuf::from(&path)
} else {
return Err(ShellError::FileNotFound(source_filename.span));
};
parent.pop();
let file_pwd = Value::string(parent.to_string_lossy(), call.head);
if let Some(parent) = file_path.parent() {
let file_pwd = Value::string(parent.to_string_lossy(), call.head);
caller_stack.add_env_var("FILE_PWD".to_string(), file_pwd);
caller_stack.add_env_var("FILE_PWD".to_string(), file_pwd);
}
caller_stack.add_env_var(
"CURRENT_FILE".to_string(),
Value::string(file_path.to_string_lossy(), call.head),
);
// Evaluate the block
let block = engine_state.get_block(block_id as usize).clone();
@ -76,6 +87,7 @@ impl Command for SourceEnv {
// Remove the file-relative PWD
caller_stack.remove_env_var(engine_state, "FILE_PWD");
caller_stack.remove_env_var(engine_state, "CURRENT_FILE");
result
}

View File

@ -315,7 +315,7 @@ impl Command for Ls {
},
Example {
description: "List given paths and show directories themselves",
example: "['/path/to/directory' '/path/to/file'] | each { ls -D $in } | flatten",
example: "['/path/to/directory' '/path/to/file'] | each {|| ls -D $in } | flatten",
result: None,
},
]

View File

@ -50,21 +50,15 @@ impl Command for Rm {
"filename",
SyntaxShape::Filepath,
"the path of the file you want to remove",
);
#[cfg(all(
feature = "trash-support",
not(target_os = "android"),
not(target_os = "ios")
))]
let sig = sig
)
.switch(
"trash",
"move to the platform's trash instead of permanently deleting",
"move to the platform's trash instead of permanently deleting. not used on android and ios",
Some('t'),
)
.switch(
"permanent",
"delete permanently, ignoring the 'always_trash' config option",
"delete permanently, ignoring the 'always_trash' config option. always enabled on android and ios",
Some('p'),
);
sig.switch("recursive", "delete subdirectories recursively", Some('r'))
@ -169,18 +163,13 @@ fn rm(
let rm_always_trash = config.rm_always_trash;
#[cfg(any(
not(feature = "trash-support"),
target_os = "android",
target_os = "ios"
))]
#[cfg(not(feature = "trash-support"))]
{
if rm_always_trash {
return Err(ShellError::GenericError(
"Cannot execute `rm`; the current configuration specifies \
`always_trash = true`, but the current nu executable was not \
built with feature `trash_support` or trash is not supported on \
your platform."
built with feature `trash_support`."
.into(),
"trash required to be true but not supported".into(),
Some(span),
@ -189,8 +178,7 @@ fn rm(
));
} else if trash {
return Err(ShellError::GenericError(
"Cannot execute `rm` with option `--trash`; feature `trash-support` not \
enabled or trash is not supported on your platform"
"Cannot execute `rm` with option `--trash`; feature `trash-support` not enabled"
.into(),
"this option is only available if nu is built with the `trash-support` feature"
.into(),

View File

@ -269,7 +269,7 @@ impl Command for Watch {
vec![
Example {
description: "Run `cargo test` whenever a Rust file changes",
example: r#"watch . --glob=**/*.rs { cargo test }"#,
example: r#"watch . --glob=**/*.rs {|| cargo test }"#,
result: None,
},
Example {

View File

@ -164,6 +164,7 @@ with 'transpose' first."#
redirect_stderr,
) {
Ok(v) => Some(v.into_value(span)),
Err(ShellError::Continue(v)) => Some(Value::nothing(v)),
Err(ShellError::Break(_)) => None,
Err(error) => {
let error = chain_error_with_input(error, input_span);
@ -188,6 +189,7 @@ with 'transpose' first."#
let x = match x {
Ok(x) => x,
Err(ShellError::Continue(v)) => return Some(Value::nothing(v)),
Err(ShellError::Break(_)) => return None,
Err(err) => {
return Some(Value::Error {
@ -212,6 +214,7 @@ with 'transpose' first."#
redirect_stderr,
) {
Ok(v) => Some(v.into_value(span)),
Err(ShellError::Continue(v)) => Some(Value::nothing(v)),
Err(ShellError::Break(_)) => None,
Err(error) => {
let error = Box::new(chain_error_with_input(error, input_span));

View File

@ -58,6 +58,12 @@ impl Command for Find {
"dotall regex mode: allow a dot . to match newlines \\n; equivalent to (?s)",
Some('s'),
)
.named(
"columns",
SyntaxShape::List(Box::new(SyntaxShape::String)),
"column names to be searched (with rest parameter, not regex yet)",
Some('c'),
)
.switch("invert", "invert the match", Some('v'))
.rest("rest", SyntaxShape::Any, "terms to search")
.category(Category::Filters)
@ -131,6 +137,36 @@ impl Command for Find {
span: Span::test_data(),
}),
},
Example {
description: "Remove ANSI sequences from result",
example: "[[foo bar]; [abc 123] [def 456]] | find 123 | get bar | ansi strip",
result: None, // This is None because ansi strip is not available in tests
},
Example {
description: "Find and highlight text in specific columns",
example: "[[col1 col2 col3]; [moe larry curly] [larry curly moe]] | find moe -c [col1 col3]",
result: Some(Value::List {
vals: vec![
Value::test_record(
vec!["col1".to_string(), "col2".to_string(), "col3".to_string()],
vec![
Value::test_string("\u{1b}[37m\u{1b}[0m\u{1b}[41;37mmoe\u{1b}[0m\u{1b}[37m\u{1b}[0m".to_string()),
Value::test_string("larry".to_string()),
Value::test_string("curly".to_string()),
]
),
Value::test_record(
vec!["col1".to_string(), "col2".to_string(), "col3".to_string()],
vec![
Value::test_string("larry".to_string()),
Value::test_string("curly".to_string()),
Value::test_string("\u{1b}[37m\u{1b}[0m\u{1b}[41;37mmoe\u{1b}[0m\u{1b}[37m\u{1b}[0m".to_string()),
]
),
],
span: Span::test_data(),
}),
}
]
}
@ -174,13 +210,13 @@ fn find_with_regex(
let flags = match (insensitive, multiline, dotall) {
(false, false, false) => "",
(true, false, false) => "(?i)",
(false, true, false) => "(?m)",
(false, false, true) => "(?s)",
(true, true, false) => "(?im)",
(true, false, true) => "(?is)",
(false, true, true) => "(?ms)",
(true, true, true) => "(?ims)",
(true, false, false) => "(?i)", // case insensitive
(false, true, false) => "(?m)", // multi-line mode
(false, false, true) => "(?s)", // allow . to match \n
(true, true, false) => "(?im)", // case insensitive and multi-line mode
(true, false, true) => "(?is)", // case insensitive and allow . to match \n
(false, true, true) => "(?ms)", // multi-line mode and allow . to match \n
(true, true, true) => "(?ims)", // case insensitive, multi-line mode and allow . to match \n
};
let regex = flags.to_string() + regex.as_str();
@ -221,7 +257,9 @@ fn find_with_regex(
)
}
fn highlight_terms_in_record(
#[allow(clippy::too_many_arguments)]
fn highlight_terms_in_record_with_search_columns(
search_cols: &Vec<String>,
cols: &mut [String],
vals: &mut Vec<Value>,
span: &mut Span,
@ -230,23 +268,32 @@ fn highlight_terms_in_record(
string_style: Style,
ls_colors: &LsColors,
) -> Value {
let cols_to_search = if search_cols.is_empty() {
cols.to_vec()
} else {
search_cols.to_vec()
};
let mut output = vec![];
for val in vals {
let mut potential_output = vec![];
let mut found_a_hit = false;
for (cur_col, val) in cols.iter().zip(vals) {
let val_str = val.into_string("", config);
let lower_val = val.into_string("", config).to_lowercase();
let mut term_added_to_output = false;
for term in terms {
let term_str = term.into_string("", config);
let lower_term = term.into_string("", config).to_lowercase();
if lower_val.contains(&lower_term) {
if lower_val.contains(&lower_term) && cols_to_search.contains(cur_col) {
found_a_hit = true;
term_added_to_output = true;
if config.use_ls_colors {
// Get the original LS_COLORS color
let style = ls_colors.style_for_path(val_str.clone());
let ansi_style = style
.map(LsColors_Style::to_crossterm_style)
.map(LsColors_Style::to_nu_ansi_term_style)
.unwrap_or_default();
let ls_colored_val = ansi_style.apply(&val_str).to_string();
let ls_colored_val = ansi_style.paint(&val_str).to_string();
let ansi_term_style = style
.map(to_nu_ansi_term_style)
@ -258,11 +305,10 @@ fn highlight_terms_in_record(
Ok(hi) => hi,
Err(_) => string_style.paint(term_str.to_string()).to_string(),
};
output.push(Value::String {
potential_output.push(Value::String {
val: hi,
span: *span,
});
term_added_to_output = true;
} else {
// No LS_COLORS support, so just use the original value
let hi = match highlight_search_string(&val_str, &term_str, &string_style) {
@ -277,9 +323,14 @@ fn highlight_terms_in_record(
}
}
if !term_added_to_output {
output.push(val.clone());
potential_output.push(val.clone());
}
}
if found_a_hit {
output.append(&mut potential_output);
}
Value::Record {
cols: cols.to_vec(),
vals: output,
@ -310,6 +361,7 @@ fn find_with_rest_and_highlight(
}
})
.collect::<Vec<Value>>();
let columns_to_search: Option<Vec<String>> = call.get_flag(&engine_state, stack, "columns")?;
let style_computer = StyleComputer::from_config(&engine_state, stack);
// Currently, search results all use the same style.
@ -323,20 +375,28 @@ fn find_with_rest_and_highlight(
};
let ls_colors = get_ls_colors(ls_colors_env_str);
let cols_to_search = match columns_to_search {
Some(cols) => cols,
None => vec![],
};
match input {
PipelineData::Empty => Ok(PipelineData::Empty),
PipelineData::Value(_, _) => input
.map(
move |mut x| match &mut x {
Value::Record { cols, vals, span } => highlight_terms_in_record(
cols,
vals,
span,
&config,
&terms,
string_style,
&ls_colors,
),
Value::Record { cols, vals, span } => {
highlight_terms_in_record_with_search_columns(
&cols_to_search,
cols,
vals,
span,
&config,
&terms,
string_style,
&ls_colors,
)
}
_ => x,
},
ctrlc.clone(),
@ -412,15 +472,18 @@ fn find_with_rest_and_highlight(
PipelineData::ListStream(stream, meta) => Ok(ListStream::from_stream(
stream
.map(move |mut x| match &mut x {
Value::Record { cols, vals, span } => highlight_terms_in_record(
cols,
vals,
span,
&config,
&terms,
string_style,
&ls_colors,
),
Value::Record { cols, vals, span } => {
highlight_terms_in_record_with_search_columns(
&cols_to_search,
cols,
vals,
span,
&config,
&terms,
string_style,
&ls_colors,
)
}
_ => x,
})
.filter(move |value| {

View File

@ -0,0 +1,155 @@
use super::utils::chain_error_with_input;
use nu_engine::{eval_block_with_early_return, CallExt};
use nu_protocol::ast::Call;
use nu_protocol::engine::{Closure, Command, EngineState, Stack};
use nu_protocol::{
Category, Example, IntoInterruptiblePipelineData, PipelineData, ShellError, Signature, Span,
SyntaxShape, Type, Value,
};
#[derive(Clone)]
pub struct Items;
impl Command for Items {
fn name(&self) -> &str {
"items"
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.input_output_types(vec![(
Type::Record(vec![]),
Type::List(Box::new(Type::String)),
)])
.required(
"closure",
SyntaxShape::Closure(Some(vec![SyntaxShape::Any, SyntaxShape::Any])),
"the closure to run",
)
.category(Category::Filters)
}
fn usage(&self) -> &str {
"Given a record, iterate on each pair of column name and associated value."
}
fn extra_usage(&self) -> &str {
"This is a the fusion of `columns`, `values` and `each`."
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let capture_block: Closure = call.req(engine_state, stack, 0)?;
let metadata = input.metadata();
let ctrlc = engine_state.ctrlc.clone();
let engine_state = engine_state.clone();
let block = engine_state.get_block(capture_block.block_id).clone();
let mut stack = stack.captures_to_stack(&capture_block.captures);
let orig_env_vars = stack.env_vars.clone();
let orig_env_hidden = stack.env_hidden.clone();
let span = call.head;
let redirect_stdout = call.redirect_stdout;
let redirect_stderr = call.redirect_stderr;
let input_span = input.span().unwrap_or(call.head);
let run_for_each_item = move |keyval: (String, Value)| -> Option<Value> {
// with_env() is used here to ensure that each iteration uses
// a different set of environment variables.
// Hence, a 'cd' in the first loop won't affect the next loop.
stack.with_env(&orig_env_vars, &orig_env_hidden);
if let Some(var) = block.signature.get_positional(0) {
if let Some(var_id) = &var.var_id {
stack.add_var(*var_id, Value::string(keyval.0.clone(), span));
}
}
if let Some(var) = block.signature.get_positional(1) {
if let Some(var_id) = &var.var_id {
stack.add_var(*var_id, keyval.1);
}
}
match eval_block_with_early_return(
&engine_state,
&mut stack,
&block,
PipelineData::empty(),
redirect_stdout,
redirect_stderr,
) {
Ok(v) => Some(v.into_value(span)),
Err(ShellError::Break(_)) => None,
Err(error) => {
let error = chain_error_with_input(error, Ok(input_span));
Some(Value::Error {
error: Box::new(error),
})
}
}
};
match input {
PipelineData::Empty => Ok(PipelineData::Empty),
PipelineData::Value(Value::Record { cols, vals, .. }, ..) => Ok(cols
.into_iter()
.zip(vals.into_iter())
.into_iter()
.map_while(run_for_each_item)
.into_pipeline_data(ctrlc)),
// Errors
PipelineData::ListStream(..) => Err(ShellError::OnlySupportsThisInputType {
exp_input_type: "record".into(),
wrong_type: "stream".into(),
dst_span: call.head,
src_span: input_span,
}),
PipelineData::Value(Value::Error { error }, ..) => Err(*error),
PipelineData::Value(other, ..) => Err(ShellError::OnlySupportsThisInputType {
exp_input_type: "record".into(),
wrong_type: other.get_type().to_string(),
dst_span: call.head,
src_span: other.expect_span(),
}),
PipelineData::ExternalStream { .. } => Err(ShellError::OnlySupportsThisInputType {
exp_input_type: "record".into(),
wrong_type: "raw data".into(),
dst_span: call.head,
src_span: input_span,
}),
}
.map(|x| x.set_metadata(metadata))
}
fn examples(&self) -> Vec<Example> {
vec![Example {
example:
"{ new: york, san: francisco } | items {|key, value| echo $'($key) ($value)' }",
description: "Iterate over each key-value pair of a record",
result: Some(Value::List {
vals: vec![
Value::test_string("new york"),
Value::test_string("san francisco"),
],
span: Span::test_data(),
}),
}]
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(Items {})
}
}

View File

@ -19,6 +19,7 @@ mod group;
mod group_by;
mod headers;
mod insert;
mod items;
mod join;
mod last;
mod length;
@ -75,6 +76,7 @@ pub use group::Group;
pub use group_by::GroupBy;
pub use headers::Headers;
pub use insert::Insert;
pub use items::Items;
pub use join::Join;
pub use last::Last;
pub use length::Length;

View File

@ -47,7 +47,7 @@ impl Command for ParEach {
fn examples(&self) -> Vec<Example> {
vec![
Example {
example: "[1 2 3] | par-each { 2 * $in }",
example: "[1 2 3] | par-each {|| 2 * $in }",
description:
"Multiplies each number. Note that the list will become arbitrarily disordered.",
result: None,
@ -279,7 +279,6 @@ impl Command for ParEach {
// This match allows non-iterables to be accepted,
// which is currently considered undesirable (Nov 2022).
PipelineData::Value(x, ..) => {
eprint!("value");
let block = engine_state.get_block(block_id);
if let Some(var) = block.signature.get_positional(0) {

View File

@ -46,7 +46,7 @@ impl Command for Shuffle {
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Shuffle rows randomly (execute it several times and see the difference)",
example: r#"[[version patch]; [1.0.0 false] [3.0.1 true] [2.0.0 false]] | shuffle"#,
example: r#"[[version patch]; ['1.0.0' false] ['3.0.1' true] ['2.0.0' false]] | shuffle"#,
result: None,
}]
}

View File

@ -75,6 +75,11 @@ impl Command for Update {
example: "[[project, authors]; ['nu', ['Andrés', 'JT', 'Yehuda']]] | update authors {|row| $row.authors | str join ','}",
result: Some(Value::List { vals: vec![Value::Record { cols: vec!["project".into(), "authors".into()], vals: vec![Value::test_string("nu"), Value::test_string("Andrés,JT,Yehuda")], span: Span::test_data()}], span: Span::test_data()}),
},
Example {
description: "You can also use a simple command to update 'authors' to a single string",
example: "[[project, authors]; ['nu', ['Andrés', 'JT', 'Yehuda']]] | update authors {|| str join ','}",
result: Some(Value::List { vals: vec![Value::Record { cols: vec!["project".into(), "authors".into()], vals: vec![Value::test_string("nu"), Value::test_string("Andrés,JT,Yehuda")], span: Span::test_data()}], span: Span::test_data()}),
}
]
}
}
@ -118,11 +123,16 @@ fn update(
}
}
let input_at_path = match input.clone().follow_cell_path(&cell_path.members, false)
{
Err(e) => return Value::Error { error: Box::new(e) },
Ok(v) => v,
};
let output = eval_block(
&engine_state,
&mut stack,
&block,
input.clone().into_pipeline_data(),
input_at_path.into_pipeline_data(),
redirect_stdout,
redirect_stderr,
);

View File

@ -150,7 +150,7 @@ not supported."#
},
Example {
description: "Find files whose filenames don't begin with the correct sequential number",
example: "ls | where type == file | sort-by name -n | enumerate | where {|e| $e.item.name !~ $'^($e.index + 1)' } | each { get item }",
example: "ls | where type == file | sort-by name -n | enumerate | where {|e| $e.item.name !~ $'^($e.index + 1)' } | each {|| get item }",
result: None,
},
]

View File

@ -77,7 +77,7 @@ impl Command for Zip {
}),
},
Example {
example: "glob *.ogg | zip ['bang.ogg', 'fanfare.ogg', 'laser.ogg'] | each { mv $in.0 $in.1 }",
example: "glob *.ogg | zip ['bang.ogg', 'fanfare.ogg', 'laser.ogg'] | each {|| mv $in.0 $in.1 }",
description: "Rename .ogg files to match an existing list of filenames",
result: None,
},

View File

@ -64,10 +64,8 @@ impl Command for FromNuon {
let engine_state = engine_state.clone();
let mut working_set = StateWorkingSet::new(&engine_state);
let mut error = None;
let (mut block, err) =
nu_parser::parse(&mut working_set, None, string_input.as_bytes(), false, &[]);
error = error.or(err);
let mut block = nu_parser::parse(&mut working_set, None, string_input.as_bytes(), false);
if let Some(pipeline) = block.pipelines.get(1) {
if let Some(element) = pipeline.elements.get(0) {
@ -146,7 +144,7 @@ impl Command for FromNuon {
}
};
if let Some(err) = error {
if let Some(err) = working_set.parse_errors.first() {
return Err(ShellError::GenericError(
"error when parsing nuon text".into(),
"could not parse nuon text".into(),

View File

@ -2,10 +2,10 @@ use crate::input_handler::{operate, CmdArgument};
use nu_engine::CallExt;
use nu_protocol::ast::{Call, CellPath};
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::Span;
use nu_protocol::{
Category, Example, PipelineData, ShellError, Signature, SyntaxShape, Type, Value,
};
use nu_protocol::{IntoPipelineData, Span};
use std::marker::PhantomData;
pub trait HashDigest: digest::Digest + Clone {
@ -88,13 +88,58 @@ where
let cell_paths: Vec<CellPath> = call.rest(engine_state, stack, 0)?;
let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths);
let args = Arguments { binary, cell_paths };
operate(
action::<D>,
args,
input,
call.head,
engine_state.ctrlc.clone(),
)
let mut hasher = D::new();
match input {
PipelineData::ExternalStream {
stdout: Some(stream),
span,
..
} => {
for item in stream {
match item {
// String and binary data are valid byte patterns
Ok(Value::String { val, .. }) => hasher.update(val.as_bytes()),
Ok(Value::Binary { val, .. }) => hasher.update(val),
// If any Error value is output, echo it back
Ok(v @ Value::Error { .. }) => return Ok(v.into_pipeline_data()),
// Unsupported data
Ok(other) => {
return Ok(Value::Error {
error: Box::new(ShellError::OnlySupportsThisInputType {
exp_input_type: "string and binary".into(),
wrong_type: other.get_type().to_string(),
dst_span: span,
src_span: other.expect_span(),
}),
}
.into_pipeline_data());
}
Err(err) => return Err(err),
};
}
let digest = hasher.finalize();
if args.binary {
Ok(Value::Binary {
val: digest.to_vec(),
span,
}
.into_pipeline_data())
} else {
Ok(Value::String {
val: format!("{digest:x}"),
span,
}
.into_pipeline_data())
}
}
_ => operate(
action::<D>,
args,
input,
call.head,
engine_state.ctrlc.clone(),
),
}
}
}

View File

@ -1,8 +1,9 @@
use crate::util::{get_guaranteed_cwd, report_error, report_error_new};
use crate::util::get_guaranteed_cwd;
use miette::Result;
use nu_engine::{eval_block, eval_block_with_early_return};
use nu_parser::parse;
use nu_protocol::ast::PathMember;
use nu_protocol::cli_error::{report_error, report_error_new};
use nu_protocol::engine::{EngineState, Stack, StateWorkingSet};
use nu_protocol::{BlockId, PipelineData, PositionalArg, ShellError, Span, Type, Value, VarId};
@ -166,10 +167,10 @@ pub fn eval_hook(
vars.push((var_id, val));
}
let (output, err) =
parse(&mut working_set, Some("hook"), val.as_bytes(), false, &[]);
if let Some(err) = err {
report_error(&working_set, &err);
let output =
parse(&mut working_set, Some("hook"), val.as_bytes(), false);
if let Some(err) = working_set.parse_errors.first() {
report_error(&working_set, err);
return Err(ShellError::UnsupportedConfigValue(
"valid source code".into(),

View File

@ -1,7 +1,3 @@
mod history;
mod history_session;
mod tutor;
pub use history::History;
pub use history_session::HistorySession;
pub use tutor::Tutor;

View File

@ -507,10 +507,7 @@ impl Command for AnsiCommand {
fn signature(&self) -> Signature {
Signature::build("ansi")
.input_output_types(vec![
(Type::Nothing, Type::String),
(Type::List(Box::new(Type::String)), Type::String),
])
.input_output_types(vec![(Type::Nothing, Type::String)])
.optional(
"code",
SyntaxShape::Any,
@ -518,12 +515,12 @@ impl Command for AnsiCommand {
)
.switch(
"escape", // \x1b[
"escape sequence without the escape character(s)",
r#"escape sequence without the escape character(s) ('\x1b[' is not required)"#,
Some('e'),
)
.switch(
"osc", // \x1b]
"operating system command (ocs) escape sequence without the escape character(s)",
r#"operating system command (osc) escape sequence without the escape character(s) ('\x1b]' is not required)"#,
Some('o'),
)
.switch("list", "list available ansi code names", Some('l'))
@ -531,58 +528,72 @@ impl Command for AnsiCommand {
}
fn usage(&self) -> &str {
"Output ANSI codes to change color."
"Output ANSI codes to change color and style of text."
}
fn extra_usage(&self) -> &str {
r#"For escape sequences:
Escape: '\x1b[' is not required for --escape parameter
Format: #(;#)m
Example: 1;31m for bold red or 2;37;41m for dimmed white fg with red bg
There can be multiple text formatting sequence numbers
separated by a ; and ending with an m where the # is of the
following values:
attribute_number, abbreviation, description
0 reset / normal display
1 b bold or increased intensity
2 d faint or decreased intensity
3 i italic on (non-mono font)
4 u underline on
5 l slow blink on
6 fast blink on
7 r reverse video on
8 h nondisplayed (invisible) on
9 s strike-through on
"An introduction to what ANSI escape sequences are can be found in the
\u{1b}]8;;https://en.wikipedia.org/wiki/ANSI_escape_code\u{1b}\\ANSI escape code\u{1b}]8;;\u{1b}\\ Wikipedia page.
foreground/bright colors background/bright colors
30/90 black 40/100 black
31/91 red 41/101 red
32/92 green 42/102 green
33/93 yellow 43/103 yellow
34/94 blue 44/104 blue
35/95 magenta 45/105 magenta
36/96 cyan 46/106 cyan
37/97 white 47/107 white
39 default 49 default
https://en.wikipedia.org/wiki/ANSI_escape_code
Escape sequences usual values:
╭────┬────────────┬────────┬────────┬─────────╮
# │ type │ normal │ bright │ name │
├────┼────────────┼────────┼────────┼─────────┤
0 │ foreground │ 30 │ 90 │ black │
1 │ foreground │ 31 │ 91 │ red │
2 │ foreground │ 32 │ 92 │ green │
3 │ foreground │ 33 │ 93 │ yellow │
│ 4 │ foreground │ 34 │ 94 │ blue │
5 │ foreground │ 35 │ 95 │ magenta │
6 │ foreground │ 36 │ 96 │ cyan │
│ 7 │ foreground │ 37 │ 97 │ white │
│ 8 │ foreground │ 39 │ │ default │
│ 9 │ background │ 40 │ 100 │ black │
│ 10 │ background │ 41 │ 101 │ red │
│ 11 │ background │ 42 │ 102 │ green │
│ 12 │ background │ 43 │ 103 │ yellow │
│ 13 │ background │ 44 │ 104 │ blue │
│ 14 │ background │ 45 │ 105 │ magenta │
│ 15 │ background │ 46 │ 106 │ cyan │
│ 16 │ background │ 47 │ 107 │ white │
│ 17 │ background │ 49 │ │ default │
╰────┴────────────┴────────┴────────┴─────────╯
OSC: '\x1b]' is not required for --osc parameter
Example: echo [(ansi -o '0') 'some title' (char bel)] | str join
Format: #
0 Set window title and icon name
1 Set icon name
2 Set window title
4 Set/read color palette
9 iTerm2 Grown notifications
10 Set foreground color (x11 color spec)
11 Set background color (x11 color spec)
... others"#
Escape sequences attributes:
╭───┬────┬──────────────┬──────────────────────────────╮
│ # │ id │ abbreviation │ description │
├───┼────┼──────────────┼──────────────────────────────┤
│ 0 │ 0 │ │ reset / normal display │
│ 1 │ 1 │ b │ bold or increased intensity │
│ 2 │ 2 │ d │ faint or decreased intensity │
│ 3 │ 3 │ i │ italic on (non-mono font) │
│ 4 │ 4 │ u │ underline on │
│ 5 │ 5 │ l │ slow blink on │
│ 6 │ 6 │ │ fast blink on │
│ 7 │ 7 │ r │ reverse video on │
│ 8 │ 8 │ h │ nondisplayed (invisible) on │
│ 9 │ 9 │ s │ strike-through on │
╰───┴────┴──────────────┴──────────────────────────────╯
Operating system commands:
╭───┬─────┬───────────────────────────────────────╮
│ # │ id │ description │
├───┼─────┼───────────────────────────────────────┤
│ 0 │ 0 │ Set window title and icon name │
│ 1 │ 1 │ Set icon name │
│ 2 │ 2 │ Set window title │
│ 3 │ 4 │ Set/read color palette │
│ 4 │ 9 │ iTerm2 Grown notifications │
│ 5 │ 10 │ Set foreground color (x11 color spec) │
│ 6 │ 11 │ Set background color (x11 color spec) │
│ 7 │ ... │ others │
╰───┴─────┴───────────────────────────────────────╯"
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Change color to green",
description: "Change color to green (see how the next example text will be green!)",
example: r#"ansi green"#,
result: Some(Value::test_string("\u{1b}[32m")),
},
@ -592,23 +603,32 @@ Format: #
result: Some(Value::test_string("\u{1b}[0m")),
},
Example {
description:
"Use ansi to color text (rb = red bold, gb = green bold, pb = purple bold)",
example: r#"$'(ansi rb)Hello (ansi gb)Nu (ansi pb)World(ansi reset)'"#,
description: "Use different colors and styles in the same text",
example: r#"$'(ansi red_bold)Hello(ansi reset) (ansi green_dimmed)Nu(ansi reset) (ansi purple_italic)World(ansi reset)'"#,
result: Some(Value::test_string(
"\u{1b}[1;31mHello \u{1b}[1;32mNu \u{1b}[1;35mWorld\u{1b}[0m",
"\u{1b}[1;31mHello\u{1b}[0m \u{1b}[2;32mNu\u{1b}[0m \u{1b}[3;35mWorld\u{1b}[0m",
)),
},
Example {
description: "Use ansi to color text (italic bright yellow on red 'Hello' with green bold 'Nu' and purple bold 'World')",
example: r#"[(ansi -e '3;93;41m') Hello (ansi reset) " " (ansi gb) Nu " " (ansi pb) World (ansi reset)] | str join"#,
description: "The same example as above with short names",
example: r#"$'(ansi rb)Hello(ansi reset) (ansi gd)Nu(ansi reset) (ansi pi)World(ansi reset)'"#,
result: Some(Value::test_string(
"\u{1b}[3;93;41mHello\u{1b}[0m \u{1b}[1;32mNu \u{1b}[1;35mWorld\u{1b}[0m",
"\u{1b}[1;31mHello\u{1b}[0m \u{1b}[2;32mNu\u{1b}[0m \u{1b}[3;35mWorld\u{1b}[0m",
)),
},
Example {
description: "Use ansi to color text with a style (blue on red in bold)",
example: r#"$"(ansi -e { fg: '#0000ff' bg: '#ff0000' attr: b })Hello Nu World(ansi reset)""#,
description: "Use escape codes, without the '\\x1b['",
example: r#"$"(ansi -e '3;93;41m')Hello(ansi reset)" # italic bright yellow on red background"#,
result: Some(Value::test_string("\u{1b}[3;93;41mHello\u{1b}[0m")),
},
Example {
description: "Use structured escape codes",
example: r#"let bold_blue_on_red = { # `fg`, `bg`, `attr` are the acceptable keys, all other keys are considered invalid and will throw errors.
fg: '#0000ff'
bg: '#ff0000'
attr: b
}
$"(ansi -e $bold_blue_on_red)Hello Nu World(ansi reset)""#,
result: Some(Value::test_string(
"\u{1b}[1;48;2;255;0;0;38;2;0;0;255mHello Nu World\u{1b}[0m",
)),
@ -745,7 +765,7 @@ Format: #
"attr" => nu_style.attr = Some(v.as_string()?),
_ => {
return Err(ShellError::IncompatibleParametersSingle {
msg: format!("problem with key: {k}"),
msg: format!("unknown ANSI format key: expected one of ['fg', 'bg', 'attr'], found '{k}'"),
span: code.expect_span(),
})
}

View File

@ -72,25 +72,25 @@ impl Command for SubCommand {
Example {
description: "draw text in a gradient with foreground start and end colors",
example:
"'Hello, Nushell! This is a gradient.' | ansi gradient --fgstart 0x40c9ff --fgend 0xe81cff",
"'Hello, Nushell! This is a gradient.' | ansi gradient --fgstart '0x40c9ff' --fgend '0xe81cff'",
result: None,
},
Example {
description: "draw text in a gradient with foreground start and end colors and background start and end colors",
example:
"'Hello, Nushell! This is a gradient.' | ansi gradient --fgstart 0x40c9ff --fgend 0xe81cff --bgstart 0xe81cff --bgend 0x40c9ff",
"'Hello, Nushell! This is a gradient.' | ansi gradient --fgstart '0x40c9ff' --fgend '0xe81cff' --bgstart '0xe81cff' --bgend '0x40c9ff'",
result: None,
},
Example {
description: "draw text in a gradient by specifying foreground start color - end color is assumed to be black",
example:
"'Hello, Nushell! This is a gradient.' | ansi gradient --fgstart 0x40c9ff",
"'Hello, Nushell! This is a gradient.' | ansi gradient --fgstart '0x40c9ff'",
result: None,
},
Example {
description: "draw text in a gradient by specifying foreground end color - start color is assumed to be black",
example:
"'Hello, Nushell! This is a gradient.' | ansi gradient --fgend 0xe81cff",
"'Hello, Nushell! This is a gradient.' | ansi gradient --fgend '0xe81cff'",
result: None,
},
]

View File

@ -4,7 +4,6 @@ mod dir_info;
mod du;
mod input;
mod kill;
mod reedline_commands;
mod sleep;
mod term_size;
@ -14,6 +13,5 @@ pub use dir_info::{DirBuilder, DirInfo, FileInfo};
pub use du::Du;
pub use input::Input;
pub use kill::Kill;
pub use reedline_commands::{Keybindings, KeybindingsDefault, KeybindingsList, KeybindingsListen};
pub use sleep::Sleep;
pub use term_size::TermSize;

View File

@ -197,7 +197,7 @@ impl Command for Char {
},
Example {
description: "Output Unicode character",
example: r#"char -u '1f378'"#,
example: r#"char -u 1f378"#,
result: Some(Value::test_string("\u{1f378}")),
},
Example {
@ -207,7 +207,7 @@ impl Command for Char {
},
Example {
description: "Output multi-byte Unicode character",
example: r#"char -u '1F468' '200D' '1F466' '200D' '1F466'"#,
example: r#"char -u 1F468 200D 1F466 200D 1F466"#,
result: Some(Value::test_string(
"\u{1F468}\u{200D}\u{1F466}\u{200D}\u{1F466}",
)),

View File

@ -290,8 +290,8 @@ fn format_record(
}
}
FormatOperation::ValueNeedEval(_col_name, span) => {
let (exp, may_parse_err) = parse_expression(working_set, &[*span], &[], false);
match may_parse_err {
let exp = parse_expression(working_set, &[*span], false);
match working_set.parse_errors.first() {
None => {
let parsed_result = eval_expression(engine_state, stack, &exp);
if let Ok(val) = parsed_result {

View File

@ -5,6 +5,7 @@ use nu_protocol::{
Category, Example, PipelineData, ShellError, Signature, Span, Spanned, SyntaxShape, Type,
Value,
};
use regex::Regex;
#[derive(Clone)]
pub struct SubCommand;
@ -30,6 +31,7 @@ impl Command for SubCommand {
"the character or string that denotes what separates columns",
)
.switch("collapse-empty", "remove empty columns", Some('c'))
.switch("regex", "separator is a regular expression", Some('r'))
.rest(
"rest",
SyntaxShape::String,
@ -117,6 +119,25 @@ impl Command for SubCommand {
span: Span::test_data(),
}),
},
Example {
description: "Split a list of strings into a table, ignoring padding",
example: r"['a - b' 'c - d'] | split column -r '\s*-\s*'",
result: Some(Value::List {
vals: vec![
Value::Record {
cols: vec!["column1".to_string(), "column2".to_string()],
vals: vec![Value::test_string("a"), Value::test_string("b")],
span: Span::test_data(),
},
Value::Record {
cols: vec!["column1".to_string(), "column2".to_string()],
vals: vec![Value::test_string("c"), Value::test_string("d")],
span: Span::test_data(),
},
],
span: Span::test_data(),
}),
},
]
}
}
@ -132,30 +153,43 @@ fn split_column(
let rest: Vec<Spanned<String>> = call.rest(engine_state, stack, 1)?;
let collapse_empty = call.has_flag("collapse-empty");
let regex = if call.has_flag("regex") {
Regex::new(&separator.item)
} else {
let escaped = regex::escape(&separator.item);
Regex::new(&escaped)
}
.map_err(|err| {
ShellError::GenericError(
"Error with regular expression".into(),
err.to_string(),
Some(separator.span),
None,
Vec::new(),
)
})?;
input.flat_map(
move |x| split_column_helper(&x, &separator, &rest, collapse_empty, name_span),
move |x| split_column_helper(&x, &regex, &rest, collapse_empty, name_span),
engine_state.ctrlc.clone(),
)
}
fn split_column_helper(
v: &Value,
separator: &Spanned<String>,
separator: &Regex,
rest: &[Spanned<String>],
collapse_empty: bool,
head: Span,
) -> Vec<Value> {
if let Ok(s) = v.as_string() {
let split_result: Vec<_> = if collapse_empty {
s.split(&separator.item).filter(|s| !s.is_empty()).collect()
} else {
s.split(&separator.item).collect()
};
let split_result: Vec<_> = separator
.split(&s)
.filter(|x| !(collapse_empty && x.is_empty()))
.collect();
let positional: Vec<_> = rest.iter().map(|f| f.item.clone()).collect();
// If they didn't provide column names, make up our own
let mut cols = vec![];
let mut vals = vec![];
if positional.is_empty() {

View File

@ -5,6 +5,7 @@ use nu_protocol::{
Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, Span, SyntaxShape,
Type, Value,
};
use regex::Regex;
#[derive(Clone)]
pub struct SubCommand;
@ -25,6 +26,10 @@ impl Command for SubCommand {
SyntaxShape::Any,
"the value that denotes what separates the list",
)
.switch(
"regex",
"separator is a regular expression, matching values that can be coerced into a string",
Some('r'))
.category(Category::Filters)
}
@ -121,10 +126,76 @@ impl Command for SubCommand {
span: Span::test_data(),
}),
},
Example {
description: "Split a list of chars into lists based on multiple characters",
example: r"[a, b, c, d, a, e, f, g] | split list -r '(b|e)'",
result: Some(Value::List {
vals: vec![
Value::List {
vals: vec![Value::test_string("a")],
span: Span::test_data(),
},
Value::List {
vals: vec![
Value::test_string("c"),
Value::test_string("d"),
Value::test_string("a"),
],
span: Span::test_data(),
},
Value::List {
vals: vec![Value::test_string("f"), Value::test_string("g")],
span: Span::test_data(),
},
],
span: Span::test_data(),
}),
},
]
}
}
enum Matcher {
Regex(Regex),
Direct(Value),
}
impl Matcher {
pub fn new(regex: bool, lhs: Value) -> Result<Self, ShellError> {
if regex {
Ok(Matcher::Regex(Regex::new(&lhs.as_string()?).map_err(
|err| {
ShellError::GenericError(
"Error with regular expression".into(),
err.to_string(),
match lhs {
Value::Error { error: _ } => None,
_ => Some(lhs.expect_span()),
},
None,
Vec::new(),
)
},
)?))
} else {
Ok(Matcher::Direct(lhs))
}
}
pub fn compare(&self, rhs: &Value) -> Result<bool, ShellError> {
Ok(match self {
Matcher::Regex(regex) => {
if let Ok(rhs_str) = rhs.as_string() {
regex.is_match(&rhs_str)
} else {
false
}
}
Matcher::Direct(lhs) => rhs == lhs,
})
}
}
fn split_list(
engine_state: &EngineState,
stack: &mut Stack,
@ -134,9 +205,11 @@ fn split_list(
let separator: Value = call.req(engine_state, stack, 0)?;
let mut temp_list = Vec::new();
let mut returned_list = Vec::new();
let iter = input.into_interruptible_iter(engine_state.ctrlc.clone());
let matcher = Matcher::new(call.has_flag("regex"), separator)?;
for val in iter {
if val == separator {
if matcher.compare(&val)? {
if !temp_list.is_empty() {
returned_list.push(Value::List {
vals: temp_list.clone(),

View File

@ -5,7 +5,7 @@ use nu_protocol::{
Category, Example, PipelineData, ShellError, Signature, Span, Spanned, SyntaxShape, Type,
Value,
};
use regex::Regex;
#[derive(Clone)]
pub struct SubCommand;
@ -21,7 +21,7 @@ impl Command for SubCommand {
.required(
"separator",
SyntaxShape::String,
"the character that denotes what separates rows",
"a character or regex that denotes what separates rows",
)
.named(
"number",
@ -29,6 +29,7 @@ impl Command for SubCommand {
"Split into maximum number of items",
Some('n'),
)
.switch("regex", "use regex syntax for separator", Some('r'))
.category(Category::Strings)
}
@ -92,6 +93,18 @@ impl Command for SubCommand {
span: Span::test_data(),
}),
},
Example {
description: "Split a string by regex",
example: r"'a b c' | split row -r '\s+'",
result: Some(Value::List {
vals: vec![
Value::test_string("a"),
Value::test_string("b"),
Value::test_string("c"),
],
span: Span::test_data(),
}),
},
]
}
}
@ -104,30 +117,40 @@ fn split_row(
) -> Result<PipelineData, ShellError> {
let name_span = call.head;
let separator: Spanned<String> = call.req(engine_state, stack, 0)?;
let regex = if call.has_flag("regex") {
Regex::new(&separator.item)
} else {
let escaped = regex::escape(&separator.item);
Regex::new(&escaped)
}
.map_err(|err| {
ShellError::GenericError(
"Error with regular expression".into(),
err.to_string(),
Some(separator.span),
None,
Vec::new(),
)
})?;
let max_split: Option<usize> = call.get_flag(engine_state, stack, "number")?;
input.flat_map(
move |x| split_row_helper(&x, &separator, max_split, name_span),
move |x| split_row_helper(&x, &regex, max_split, name_span),
engine_state.ctrlc.clone(),
)
}
fn split_row_helper(
v: &Value,
separator: &Spanned<String>,
max_split: Option<usize>,
name: Span,
) -> Vec<Value> {
fn split_row_helper(v: &Value, regex: &Regex, max_split: Option<usize>, name: Span) -> Vec<Value> {
match v.span() {
Ok(v_span) => {
if let Ok(s) = v.as_string() {
match max_split {
Some(max_split) => s
.splitn(max_split, &separator.item)
.map(|s| Value::string(s, v_span))
Some(max_split) => regex
.splitn(&s, max_split)
.map(|x: &str| Value::string(x, v_span))
.collect(),
None => s
.split(&separator.item)
.map(|s| Value::string(s, v_span))
None => regex
.split(&s)
.map(|x: &str| Value::string(x, v_span))
.collect(),
}
} else {

View File

@ -1,18 +1,18 @@
use crate::grapheme_flags;
use crate::input_handler::{operate, CmdArgument};
use crate::{grapheme_flags, util};
use nu_engine::CallExt;
use nu_protocol::ast::Call;
use nu_protocol::ast::CellPath;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::Category;
use nu_protocol::Spanned;
use nu_protocol::{Example, PipelineData, ShellError, Signature, Span, SyntaxShape, Type, Value};
use nu_protocol::{
ast::{Call, CellPath},
engine::{Command, EngineState, Stack},
Category, Example, PipelineData, Range, ShellError, Signature, Span, Spanned, SyntaxShape,
Type, Value,
};
use unicode_segmentation::UnicodeSegmentation;
struct Arguments {
end: bool,
substring: String,
range: Option<Value>,
range: Option<Range>,
cell_paths: Option<Vec<CellPath>>,
graphemes: bool,
}
@ -56,7 +56,7 @@ impl Command for SubCommand {
)
.named(
"range",
SyntaxShape::Any,
SyntaxShape::Range,
"optional start and/or end index",
Some('r'),
)
@ -105,23 +105,18 @@ impl Command for SubCommand {
result: Some(Value::test_int(4)),
},
Example {
description: "Returns index of string in input with start index",
example: " '.rb.rb' | str index-of '.rb' -r '1,'",
description: "Returns index of string in input within a`rhs open range`",
example: " '.rb.rb' | str index-of '.rb' -r 1..",
result: Some(Value::test_int(3)),
},
Example {
description: "Returns index of string in input with end index",
example: " '123456' | str index-of '6' -r ',4'",
description: "Returns index of string in input within a lhs open range",
example: " '123456' | str index-of '6' -r ..4",
result: Some(Value::test_int(-1)),
},
Example {
description: "Returns index of string in input with start and end index",
example: " '123456' | str index-of '3' -r '1,4'",
result: Some(Value::test_int(2)),
},
Example {
description: "Alternatively you can use this form",
example: " '123456' | str index-of '3' -r [1 4]",
description: "Returns index of string in input within a range",
example: " '123456' | str index-of '3' -r 1..4",
result: Some(Value::test_int(2)),
},
Example {
@ -144,18 +139,29 @@ fn action(
}: &Arguments,
head: Span,
) -> Value {
let range = match range {
Some(range) => range.clone(),
None => Value::string("", head),
};
let r = process_range(input, &range, head);
match input {
Value::String { val: s, .. } => {
let (start_index, end_index) = match r {
Ok(r) => (r.0 as usize, r.1 as usize),
Err(e) => return Value::Error { error: Box::new(e) },
let (start_index, end_index) = if let Some(range) = range {
match util::process_range(range) {
Ok(r) => {
// `process_range()` returns `isize::MAX` if the range is open-ended,
// which is not ideal for us
let end = if r.1 as usize > s.len() {
s.len()
} else {
r.1 as usize
};
(r.0 as usize, end)
}
Err(processing_error) => {
let err = processing_error("could not find `index-of`", head);
return Value::Error {
error: Box::new(err),
};
}
}
} else {
(0usize, s.len())
};
// When the -e flag is present, search using rfind instead of find.s
@ -196,73 +202,10 @@ fn action(
}
}
fn process_range(
input: &Value,
range: &Value,
head: Span,
) -> Result<IndexOfOptionalBounds, ShellError> {
let input_len = match input {
Value::String { val: s, .. } => s.len(),
_ => 0,
};
let min_index_str = String::from("0");
let max_index_str = input_len.to_string();
let r = match range {
Value::String { val: s, .. } => {
let indexes: Vec<&str> = s.split(',').collect();
let start_index = indexes.first().unwrap_or(&&min_index_str[..]).to_string();
let end_index = indexes.get(1).unwrap_or(&&max_index_str[..]).to_string();
Ok((start_index, end_index))
}
Value::List { vals, .. } => {
if vals.len() > 2 {
Err(ShellError::TypeMismatch {
err_message: String::from("there shouldn't be more than two indexes"),
span: head,
})
} else {
let idx: Vec<String> = vals
.iter()
.map(|v| v.as_string().unwrap_or_else(|_| String::from("")))
.collect();
let start_index = idx.get(0).unwrap_or(&min_index_str).to_string();
let end_index = idx.get(1).unwrap_or(&max_index_str).to_string();
Ok((start_index, end_index))
}
}
Value::Error { error } => Err(*error.clone()),
_ => Err(ShellError::OnlySupportsThisInputType {
exp_input_type: "string".into(),
wrong_type: input.get_type().to_string(),
dst_span: head,
src_span: input.expect_span(),
}),
}?;
let start_index = r.0.parse::<i32>().unwrap_or(0);
let end_index = r.1.parse::<i32>().unwrap_or(input_len as i32);
if start_index < 0 || start_index > end_index {
return Err(ShellError::TypeMismatch {
err_message: String::from("start index can't be negative or greater than end index"),
span: head,
});
}
if end_index < 0 || end_index < start_index || end_index > input_len as i32 {
return Err(ShellError::TypeMismatch { err_message: String::from(
"end index can't be negative, smaller than start index or greater than input length"), span: head });
}
Ok(IndexOfOptionalBounds(start_index, end_index))
}
#[cfg(test)]
mod tests {
use nu_protocol::ast::RangeInclusion;
use super::*;
use super::{action, Arguments, SubCommand};
@ -279,11 +222,7 @@ mod tests {
let options = Arguments {
substring: String::from(".tomL"),
range: Some(Value::String {
val: String::from(""),
span: Span::test_data(),
}),
range: None,
cell_paths: None,
end: false,
graphemes: false,
@ -300,10 +239,7 @@ mod tests {
let options = Arguments {
substring: String::from("Lm"),
range: Some(Value::String {
val: String::from(""),
span: Span::test_data(),
}),
range: None,
cell_paths: None,
end: false,
graphemes: false,
@ -317,14 +253,25 @@ mod tests {
#[test]
fn returns_index_of_next_substring() {
let word = Value::test_string("Cargo.Cargo");
let range = Range {
from: Value::Int {
val: 1,
span: Span::test_data(),
},
incr: Value::Int {
val: 1,
span: Span::test_data(),
},
to: Value::Nothing {
span: Span::test_data(),
},
inclusion: RangeInclusion::Inclusive,
};
let options = Arguments {
substring: String::from("Cargo"),
range: Some(Value::String {
val: String::from("1"),
span: Span::test_data(),
}),
range: Some(range),
cell_paths: None,
end: false,
graphemes: false,
@ -337,14 +284,25 @@ mod tests {
#[test]
fn index_does_not_exist_due_to_end_index() {
let word = Value::test_string("Cargo.Banana");
let range = Range {
from: Value::Nothing {
span: Span::test_data(),
},
inclusion: RangeInclusion::Inclusive,
incr: Value::Int {
val: 1,
span: Span::test_data(),
},
to: Value::Int {
val: 5,
span: Span::test_data(),
},
};
let options = Arguments {
substring: String::from("Banana"),
range: Some(Value::String {
val: String::from(",5"),
span: Span::test_data(),
}),
range: Some(range),
cell_paths: None,
end: false,
graphemes: false,
@ -357,14 +315,26 @@ mod tests {
#[test]
fn returns_index_of_nums_in_middle_due_to_index_limit_from_both_ends() {
let word = Value::test_string("123123123");
let range = Range {
from: Value::Int {
val: 2,
span: Span::test_data(),
},
incr: Value::Int {
val: 1,
span: Span::test_data(),
},
to: Value::Int {
val: 6,
span: Span::test_data(),
},
inclusion: RangeInclusion::Inclusive,
};
let options = Arguments {
substring: String::from("123"),
range: Some(Value::String {
val: String::from("2,6"),
span: Span::test_data(),
}),
range: Some(range),
cell_paths: None,
end: false,
graphemes: false,
@ -377,14 +347,26 @@ mod tests {
#[test]
fn index_does_not_exists_due_to_strict_bounds() {
let word = Value::test_string("123456");
let range = Range {
from: Value::Int {
val: 2,
span: Span::test_data(),
},
incr: Value::Int {
val: 1,
span: Span::test_data(),
},
to: Value::Int {
val: 5,
span: Span::test_data(),
},
inclusion: RangeInclusion::RightExclusive,
};
let options = Arguments {
substring: String::from("1"),
range: Some(Value::String {
val: String::from("2,4"),
span: Span::test_data(),
}),
range: Some(range),
cell_paths: None,
end: false,
graphemes: false,

View File

@ -81,6 +81,7 @@ fn exec(
let cwd = current_dir(engine_state, stack)?;
let mut command = external_command.spawn_simple_command(&cwd.to_string_lossy())?;
command.current_dir(cwd);
command.envs(&external_command.env_vars);
let err = command.exec(); // this replaces our process, should not return

View File

@ -1,4 +1,4 @@
use nu_engine::{find_in_dirs_env, CallExt};
use nu_engine::{find_in_dirs_env, get_dirs_var_from_call, CallExt};
use nu_parser::{parse, parse_module_block, unescape_unquote_string};
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack, StateWorkingSet};
@ -106,7 +106,12 @@ impl Command for NuCheck {
_ => {
if let Some(path_str) = path {
// look up the path as relative to FILE_PWD or inside NU_LIB_DIRS (same process as source-env)
let path = match find_in_dirs_env(&path_str.item, engine_state, stack) {
let path = match find_in_dirs_env(
&path_str.item,
engine_state,
stack,
get_dirs_var_from_call(call),
) {
Ok(path) => {
if let Some(path) = path {
path
@ -255,9 +260,14 @@ fn heuristic_parse_file(
call: &Call,
is_debug: bool,
) -> Result<PipelineData, ShellError> {
let (filename, err) = unescape_unquote_string(path.as_bytes(), call.head);
if err.is_none() {
if let Ok(contents) = std::fs::read(&path) {
let starting_error_count = working_set.parse_errors.len();
let bytes = working_set.get_span_contents(call.head);
let (filename, err) = unescape_unquote_string(bytes, call.head);
if let Some(err) = err {
working_set.error(err);
}
if starting_error_count == working_set.parse_errors.len() {
if let Ok(contents) = std::fs::read(path) {
match parse_script(
working_set,
Some(filename.as_str()),
@ -304,18 +314,20 @@ fn parse_module(
) -> Result<PipelineData, ShellError> {
let filename = filename.unwrap_or_else(|| "empty".to_string());
let start = working_set.next_span_start();
working_set.add_file(filename.clone(), contents);
let end = working_set.next_span_start();
let file_id = working_set.add_file(filename.clone(), contents);
let new_span = working_set.get_span_for_file(file_id);
let new_span = Span::new(start, end);
let (_, _, _, err) = parse_module_block(working_set, new_span, filename.as_bytes(), &[]);
let starting_error_count = working_set.parse_errors.len();
parse_module_block(working_set, new_span, filename.as_bytes());
if err.is_some() {
if starting_error_count != working_set.parse_errors.len() {
if is_debug {
let msg = format!(
r#"Found : {}"#,
err.expect("Unable to parse content as module")
working_set
.parse_errors
.first()
.expect("Unable to parse content as module")
);
Err(ShellError::GenericError(
"Failed to parse content".to_string(),
@ -339,9 +351,16 @@ fn parse_script(
is_debug: bool,
span: Span,
) -> Result<PipelineData, ShellError> {
let (_, err) = parse(working_set, filename, contents, false, &[]);
if err.is_some() {
let msg = format!(r#"Found : {}"#, err.expect("Unable to parse content"));
let starting_error_count = working_set.parse_errors.len();
parse(working_set, filename, contents, false);
if starting_error_count != working_set.parse_errors.len() {
let msg = format!(
r#"Found : {}"#,
working_set
.parse_errors
.first()
.expect("Unable to parse content")
);
if is_debug {
Err(ShellError::GenericError(
"Failed to parse content".to_string(),
@ -364,9 +383,14 @@ fn parse_file_script(
call: &Call,
is_debug: bool,
) -> Result<PipelineData, ShellError> {
let (filename, err) = unescape_unquote_string(path.as_bytes(), call.head);
if err.is_none() {
if let Ok(contents) = std::fs::read(&path) {
let starting_error_count = working_set.parse_errors.len();
let bytes = working_set.get_span_contents(call.head);
let (filename, err) = unescape_unquote_string(bytes, call.head);
if let Some(err) = err {
working_set.error(err)
}
if starting_error_count == working_set.parse_errors.len() {
if let Ok(contents) = std::fs::read(path) {
parse_script(
working_set,
Some(filename.as_str()),
@ -388,8 +412,13 @@ fn parse_file_module(
call: &Call,
is_debug: bool,
) -> Result<PipelineData, ShellError> {
let (filename, err) = unescape_unquote_string(path.as_bytes(), call.head);
if err.is_none() {
let starting_error_count = working_set.parse_errors.len();
let bytes = working_set.get_span_contents(call.head);
let (filename, err) = unescape_unquote_string(bytes, call.head);
if let Some(err) = err {
working_set.error(err);
}
if starting_error_count == working_set.parse_errors.len() {
if let Ok(contents) = std::fs::read(path) {
parse_module(working_set, Some(filename), &contents, is_debug, call.head)
} else {

View File

@ -67,6 +67,11 @@ impl Command for Ps {
example: "ps | where name =~ 'nu'",
result: None,
},
Example {
description: "Get the parent process id of the current nu process",
example: "ps | where pid == $nu.pid | get ppid",
result: None,
},
]
}
}
@ -86,6 +91,12 @@ fn run_ps(engine_state: &EngineState, call: &Call) -> Result<PipelineData, Shell
span,
});
cols.push("ppid".to_string());
vals.push(Value::Int {
val: proc.ppid() as i64,
span,
});
cols.push("name".to_string());
vals.push(Value::String {
val: proc.name(),

View File

@ -42,7 +42,7 @@ impl Command for External {
.switch("redirect-stdout", "redirect stdout to the pipeline", None)
.switch("redirect-stderr", "redirect stderr to the pipeline", None)
.switch("trim-end-newline", "trimming end newlines", None)
.required("command", SyntaxShape::Any, "external command to run")
.required("command", SyntaxShape::String, "external command to run")
.rest("args", SyntaxShape::Any, "arguments for external command")
.category(Category::System)
}
@ -312,7 +312,12 @@ impl ExternalCommand {
format!("command '{cmd_name}' was not found but it exists in module '{module_name}'; try importing it with `use`")
}
} else {
format!("did you mean '{s}'?")
// If command and suggestion are the same, display not found
if cmd_name == &s {
format!("'{cmd_name}' was not found")
} else {
format!("did you mean '{s}'?")
}
}
}
}
@ -543,7 +548,7 @@ impl ExternalCommand {
}
}
fn create_process(
pub fn create_process(
&self,
input: &PipelineData,
use_cmd: bool,

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