# Description
Follow-up of #8940. As @bobhy pointed out, it makes sense for the
behaviour of flags to match the one for positional arguments, where
default values are of type `Option<Value>` instead of
`Option<Expression>`.
# User-Facing Changes
The same ones from the original PR:
- Flag default values will now be parsed as constants.
- If the default value is not a constant, a parser error is displayed.
# Tests + Formatting
A [new
test](e34e2d35f4/src/tests/test_engine.rs (L338-L344))
has been added to verify the new restriction.
close? #8060
Quite a bit of refactoring took place.
I believe a few improvements to collapse/expand were made.
I've tried to track any performance regressions and seems like it is
fine.
I've noticed something different now with default configuration path or
something in this regard?
So I might missed something while testing because of this.
Requires some oversight.
---------
Signed-off-by: Maxim Zhiburt <zhiburt@gmail.com>
# Description
Fixes#8939.
# User-Facing Changes
- Parameter default values will now be parsed as constants.
- If the default value is not a constant, a parser error is displayed.
# Tests + Formatting
The [only affected
test](d42c2b2dbc/src/tests/test_engine.rs (L325-L328))
has been updated to reflect the new behavior.
# 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.
-->
# 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>
# Description
Prevents redefining fields in a record, for example `{a: 1, a: 2}` would
now error.
fixes https://github.com/nushell/nushell/issues/8699
# User-Facing Changes
Is technically a breaking change. If you relied on this behaviour to
give you the last value, your code will now error.
# 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.
# Description
I recently ran into an issue where one of the $nu paths was not expanded
and was causing issue because $env.PWD did not equal $nu.temp-path, even
though I was in $nu.temp-path. The reason it didn't match was because my
temp path was symlinked. This PR fixes that issue by expanding the paths
with canonicalize_with().
# 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
> **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.
# Description
This moves the representation of variables on the stack to a Vec, which
more closely resembles a stack. For small numbers of variables live at
any one point, this tends to be more efficient than a HashMap. Having a
stack-like vector also allows us to remember a stack position,
temporarily push variables on, then quickly drop the stack back to the
original size when we're done. We'll need this capability to allow
matching inside of conditions.
On this mac, a simple run of:
`timeit { mut x = 1; while $x < 1000000 { $x += 1 } }`
Went from 1 sec 86 ms, down to 1 sec 2 ms. Clearly, we have a lot more
ground we can make up in looping speed 😅 but it's nice that for fixing
this to make matching easier, we also get a win in terms of lookup speed
for small numbers of variables.
# User-Facing Changes
Likely users won't (hopefully) see any negative impact and may even see
a small positive impact.
# 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.
# Description
This adds `match` and basic pattern matching.
An example:
```
match $x {
1..10 => { print "Value is between 1 and 10" }
{ foo: $bar } => { print $"Value has a 'foo' field with value ($bar)" }
[$a, $b] => { print $"Value is a list with two items: ($a) and ($b)" }
_ => { print "Value is none of the above" }
}
```
Like the recent changes to `if` to allow it to be used as an expression,
`match` can also be used as an expression. This allows you to assign the
result to a variable, eg) `let xyz = match ...`
I've also included a short-hand pattern for matching records, as I think
it might help when doing a lot of record patterns: `{$foo}` which is
equivalent to `{foo: $foo}`.
There are still missing components, so consider this the first step in
full pattern matching support. Currently missing:
* Patterns for strings
* Or-patterns (like the `|` in Rust)
* Patterns for tables (unclear how we want to match a table, so it'll
need some design)
* Patterns for binary values
* And much more
# User-Facing Changes
[see above]
# 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.
# Description
This is an experiment to see what switching the `let/let-env` family to
math expressions for initialisers would be like.
# User-Facing Changes
This would require any commands you call from `let x = <command here>`
(and similar family) to call the command in parentheses. `let x = (foo)`
to call `foo`.
# 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.
# Description
Fixes#6706.
I took a look at this issue and it seems that the issue is because the
path is canonicalized and thus derives to the target. I've tested it
locally by checking if the path is a symlink and acting accordingly to
not canonicalize it and it seems fine.
In current release if the target is deleted but the symlink remains and
one `ls`'s it, it throws a `directory not found` error. But with the fix
it still shows the symlink (with red background, indicating missing
target).
The change I've applied only triggers when `ls` is done on a symlink, on
all other counts it should basically do the same as before.
# 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
## List existing symlink and target
Current
```
ls a_symlink ╭───┬────────┬──────┬──────┬──────────────╮
│ # │ name │ type │ size │ modified │
├───┼────────┼──────┼──────┼──────────────┤
│ 0 │ a_file │ file │ 0 B │ 20 hours ago │
╰───┴────────┴──────┴──────┴──────────────╯
```
With fix
```
ls a_symlink ╭───┬───────────┬─────────┬──────┬──────────────╮
│ # │ name │ type │ size │ modified │
├───┼───────────┼─────────┼──────┼──────────────┤
│ 0 │ a_symlink │ symlink │ 6 B │ 20 hours ago │
╰───┴───────────┴─────────┴──────┴──────────────╯
```
## List existing symlink with missing target
Current
```
ls symfile_x
Error: nu:🐚:directory_not_found (link)
× Directory not found
╭─[entry #13:1:1]
1 │ ls symfile_x
· ────┬────
· ╰── directory not found
╰────
```
With fix
```
ls symfile_x ╭───┬───────────┬─────────┬──────┬─────────────╮
│ # │ name │ type │ size │ modified │
├───┼───────────┼─────────┼──────┼─────────────┤
│ 0 │ symfile_x │ symlink │ 6 B │ 2 hours ago │
╰───┴───────────┴─────────┴──────┴─────────────╯
```
Reverts nushell/nushell#8310
In anticipation that we may want to revert this PR. I'm starting the
process because of this issue.
This stopped working
```
let-env NU_LIB_DIRS = [
($nu.config-path | path dirname | path join 'scripts')
'C:\Users\username\source\repos\forks\nu_scripts'
($nu.config-path | path dirname)
]
```
You have to do this now instead.
```
const NU_LIB_DIRS = [
'C:\Users\username\AppData\Roaming\nushell\scripts'
'C:\Users\username\source\repos\forks\nu_scripts'
'C:\Users\username\AppData\Roaming\nushell'
]
```
In talking with @kubouch, he was saying that the `let-env` version
should keep working. Hopefully it's a small change.
# Description
Allow NU_LIBS_DIR and friends to be const they can be updated within the
same parse pass. This will allow us to remove having multiple config
files eventually.
Small implementation detail: I've changed `call.parser_info` to a
hashmap with string keys, so the information can have names rather than
indices, and we don't have to worry too much about the order in which we
put things into it.
Closes https://github.com/nushell/nushell/issues/8422
# User-Facing Changes
In a single file, users can now do stuff like
```
const NU_LIBS_DIR = ['/some/path/here']
source script.nu
```
and the source statement will use the value of NU_LIBS_DIR declared the
line before.
Currently, if there is no `NU_LIBS_DIR` const, then we fallback to using
the value of the `NU_LIBS_DIR` env-var, so there are no breaking changes
(unless someone named a const NU_LIBS_DIR for some reason).
![2023-03-04-014103_hyprshot](https://user-images.githubusercontent.com/13265529/222885263-135cdd0d-7884-438b-b2ed-c3979fa44463.png)
# Tests + Formatting
~~TODO: write tests~~ Done
# After Submitting
~~TODO: update docs~~ Will do when we update default_env.nu/merge
default_env.nu into default_config.nu.
This reverts commit dec0a2517f.
It breaks programs like `fzf`
# Description
Fixes: #8472
Fixes: #8313Reopen: #7690
# 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
> **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.
This is a follow up from https://github.com/nushell/nushell/pull/7540.
Please provide feedback if you have the time!
## Summary
This PR lets you use `?` to indicate that a member in a cell path is
optional and Nushell should return `null` if that member cannot be
accessed.
Unlike the previous PR, `?` is now a _postfix_ modifier for cell path
members. A cell path of `.foo?.bar` means that `foo` is optional and
`bar` is not.
`?` does _not_ suppress all errors; it is intended to help in situations
where data has "holes", i.e. the data types are correct but something is
missing. Type mismatches (like trying to do a string path access on a
date) will still fail.
### Record Examples
```bash
{ foo: 123 }.foo # returns 123
{ foo: 123 }.bar # errors
{ foo: 123 }.bar? # returns null
{ foo: 123 } | get bar # errors
{ foo: 123 } | get bar? # returns null
{ foo: 123 }.bar.baz # errors
{ foo: 123 }.bar?.baz # errors because `baz` is not present on the result from `bar?`
{ foo: 123 }.bar.baz? # errors
{ foo: 123 }.bar?.baz? # returns null
```
### List Examples
```
〉[{foo: 1} {foo: 2} {}].foo
Error: nu:🐚:column_not_found
× Cannot find column
╭─[entry #30:1:1]
1 │ [{foo: 1} {foo: 2} {}].foo
· ─┬ ─┬─
· │ ╰── cannot find column 'foo'
· ╰── value originates here
╰────
〉[{foo: 1} {foo: 2} {}].foo?
╭───┬───╮
│ 0 │ 1 │
│ 1 │ 2 │
│ 2 │ │
╰───┴───╯
〉[{foo: 1} {foo: 2} {}].foo?.2 | describe
nothing
〉[a b c].4? | describe
nothing
〉[{foo: 1} {foo: 2} {}] | where foo? == 1
╭───┬─────╮
│ # │ foo │
├───┼─────┤
│ 0 │ 1 │
╰───┴─────╯
```
# Breaking changes
1. Column names with `?` in them now need to be quoted.
2. The `-i`/`--ignore-errors` flag has been removed from `get` and
`select`
1. After this PR, most `get` error handling can be done with `?` and/or
`try`/`catch`.
4. Cell path accesses like this no longer work without a `?`:
```bash
〉[{a:1 b:2} {a:3}].b.0
2
```
We had some clever code that was able to recognize that since we only
want row `0`, it's OK if other rows are missing column `b`. I removed
that because it's tricky to maintain, and now that query needs to be
written like:
```bash
〉[{a:1 b:2} {a:3}].b?.0
2
```
I think the regression is acceptable for now. I plan to do more work in
the future to enable streaming of cell path accesses, and when that
happens I'll be able to make `.b.0` work again.
# Description
`help externs` - command, which list external commands
Closes https://github.com/nushell/nushell/issues/8301
# User-Facing Changes
```nu
$ help externs
╭───┬──────────────┬─────────────┬───────────────────────────────────────────────────╮
│ # │ name │ module_name │ usage │
├───┼──────────────┼─────────────┼───────────────────────────────────────────────────┤
│ 0 │ git push │ completions │ Push changes │
│ │ │ │ │
│ 1 │ git fetch │ completions │ Download objects and refs from another repository │
│ │ │ │ │
│ 2 │ git checkout │ completions │ Check out git branches and files │
│ │ │ │ │
╰───┴──────────────┴─────────────┴───────────────────────────────────────────────────╯
```
# 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
# 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.
# Description
Our `ShellError` at the moment has a `std::mem::size_of<ShellError>` of
136 bytes (on AMD64). As a result `Value` directly storing the struct
also required 136 bytes (thanks to alignment requirements).
This change stores the `Value::Error` `ShellError` on the heap.
Pro:
- Value now needs just 80 bytes
- Should be 1 cacheline less (still at least 2 cachelines)
Con:
- More small heap allocations when dealing with `Value::Error`
- More heap fragmentation
- Potential for additional required memcopies
# Further code changes
Includes a small refactor of `try` due to a type mismatch in its large
match.
# User-Facing Changes
None for regular users.
Plugin authors may have to update their matches on `Value` if they use
`nu-protocol`
Needs benchmarking to see if there is a benefit in real world workloads.
**Update** small improvements in runtime for workloads with high volume
of values. Significant reduction in maximum resident set size, when many
values are held in memory.
# Tests + Formatting
# Description
in https://github.com/nushell/nushell/issues/8311 and the discord
server, the idea of moving the default banner from the `rust` source to
the `nushell` standar library has emerged 😋
however, in order to do this, one need to have access to all the
variables used in the default banner => all of them are accessible
because known constants, except for the startup time of the shell, which
is not anywhere in the shell...
#### this PR adds exactly this, i.e. the new `startup_time` to the `$nu`
variable, which is computed to have the exact same value as the value
shown in the banner.
## the changes
in order to achieve this, i had to
- add `startup_time` as an `i64` to the `EngineState` => this is, to the
best of my knowledge, the easiest way to pass such an information around
down to where the banner startup time is computed and where the `$nu`
variable is evaluated
- add `startup-time` to the `$nu` variable and use the `EngineState`
getter for `startup_time` to show it as a `Value::Duration`
- pass `engine_state` as a `&mut`able argument from `main.rs` down to
`repl.rs` to allow the setter to change the value of `startup_time` =>
without this, the value would not change and would show `-1ns` as the
default value...
- the value of the startup time is computed in `evaluate_repl` in
`repl.rs`, only once at the beginning, and the same value is used in the
default banner 👌
# User-Facing Changes
one can now access to the same time as shown in the default banner with
```bash
$nu.startup-time
```
# Tests + Formatting
- 🟢 `cargo fmt --all`
- 🟢 `cargo clippy --workspace -- -D warnings -D
clippy::unwrap_used -A clippy::needless_collect`
- 🟢 `cargo test --workspace`
# After Submitting
```
$nothing
```
Add two rows in `$nu`, `$nu.is-interactive` and `$nu.is-login`, which
are true when nu is run in interactive and login mode respectively.
The `-i` flag now behaves a bit more like that of bash's, where the any
provided command or file is run without REPL but in "interactive mode".
This should entail sourcing interactive-mode config files, but since we
are planning on overhauling the config system soon, I'm holding off on
that. For now, all `-i` does is set `$nu.is-interactive` to be true.
About testing, I can't seem to find where cli-args get tested, so I
haven't written any new tests for this. Also I don't think there are any
docs that need updating. However if I'm wrong please tell me.
Continuation of #8229 and #8326
# Description
The `ShellError` enum at the moment is kind of messy.
Many variants are basic tuple structs where you always have to reference
the implementation with its macro invocation to know which field serves
which purpose.
Furthermore we have both variants that are kind of redundant or either
overly broad to be useful for the user to match on or overly specific
with few uses.
So I set out to start fixing the lacking documentation and naming to
make it feasible to critically review the individual usages and fix
those.
Furthermore we can decide to join or split up variants that don't seem
to be fit for purpose.
# Call to action
**Everyone:** Feel free to add review comments if you spot inconsistent
use of `ShellError` variants.
# User-Facing Changes
(None now, end goal more explicit and consistent error messages)
# Tests + Formatting
(No additional tests needed so far)
# Commits (so far)
- Remove `ShellError::FeatureNotEnabled`
- Name fields on `SE::ExternalNotSupported`
- Name field on `SE::InvalidProbability`
- Name fields on `SE::NushellFailed` variants
- Remove unused `SE::NushellFailedSpannedHelp`
- Name field on `SE::VariableNotFoundAtRuntime`
- Name fields on `SE::EnvVarNotFoundAtRuntime`
- Name fields on `SE::ModuleNotFoundAtRuntime`
- Remove usused `ModuleOrOverlayNotFoundAtRuntime`
- Name fields on `SE::OverlayNotFoundAtRuntime`
- Name field on `SE::NotFound`
Continuation of #8229
# Description
The `ShellError` enum at the moment is kind of messy.
Many variants are basic tuple structs where you always have to reference
the implementation with its macro invocation to know which field serves
which purpose.
Furthermore we have both variants that are kind of redundant or either
overly broad to be useful for the user to match on or overly specific
with few uses.
So I set out to start fixing the lacking documentation and naming to
make it feasible to critically review the individual usages and fix
those.
Furthermore we can decide to join or split up variants that don't seem
to be fit for purpose.
**Everyone:** Feel free to add review comments if you spot inconsistent
use of `ShellError` variants.
- Name fields of `SE::IncorrectValue`
- Merge and name fields on `SE::TypeMismatch`
- Name fields on `SE::UnsupportedOperator`
- Name fields on `AssignmentRequires*` and fix doc
- Name fields on `SE::UnknownOperator`
- Name fields on `SE::MissingParameter`
- Name fields on `SE::DelimiterError`
- Name fields on `SE::IncompatibleParametersSingle`
# User-Facing Changes
(None now, end goal more explicit and consistent error messages)
# Tests + Formatting
(No additional tests needed so far)
Related to #8189.
Should close#8302.
Important to:
- have a complete `$nu` structure with all available information
- generate an accurate website, because the `make_docs.nu` script of
`nushell.github.io` uses `$nu.scope.command` to generate the pages of
https://nushell.sh/commands/
> **Note**
> i was looking for "scope" in the source of `nushell` to augment
`$nu.scope` and i found `crates/nu-engine/src/scope.rs` that defines
`nu_engine::scope::create_scope` which lead me to
`nu_engine::scope::ScopeData.collect_commands`.
> i hope this is the right file 😌
# Description
this PR slightly modifies
`nu_engine::scope::ScopeData.collect_commands`:
- add the "result" column to `$nu.scope.commands.examples`
- put the result of the example when a valid `Option(Value)`
- put a `Value::Nothing` when the result is set to `None` in the source
of the command
# User-Facing Changes
users can now access the results of all examples in
```bash
$nu.scope.commands | where name == <command> | get examples.0.result
```
## example...
### ...with a command that defines examples: `merge`
```bash
>_ $nu.scope.commands | where name == merge | get examples.0 | reject description | table --expand
╭───┬────────────────────────────────────────────────────────┬───────────────────────────╮
│ # │ example │ result │
├───┼────────────────────────────────────────────────────────┼───────────────────────────┤
│ 0 │ [a b c] | wrap name | merge ( [1 2 3] | wrap index ) │ ╭───┬──────╮ │
│ │ │ │ # │ name │ │
│ │ │ ├───┼──────┤ │
│ │ │ │ 1 │ a │ │
│ │ │ │ 2 │ b │ │
│ │ │ │ 3 │ c │ │
│ │ │ ╰───┴──────╯ │
│ 1 │ {a: 1, b: 2} | merge {c: 3} │ ╭───┬───╮ │
│ │ │ │ a │ 1 │ │
│ │ │ │ b │ 2 │ │
│ │ │ │ c │ 3 │ │
│ │ │ ╰───┴───╯ │
│ 2 │ [{columnA: A0 columnB: B0}] | merge [{columnA: 'A0*'}] │ ╭───┬─────────┬─────────╮ │
│ │ │ │ # │ columnA │ columnB │ │
│ │ │ ├───┼─────────┼─────────┤ │
│ │ │ │ 0 │ A0* │ B0 │ │
│ │ │ ╰───┴─────────┴─────────╯ │
╰───┴────────────────────────────────────────────────────────┴───────────────────────────╯
```
and we can check that these are "true" results and not just string, e.g.
```bash
>_ $nu.scope.commands | where name == merge | get examples.0.result.0 | describe
table<name: string, index: int>
```
### ...with a command without any example: `open`
```bash
>_ $nu.scope.commands | where name == open | get examples.0 | reject description | table --expand
╭───┬──────────────────────────────────────┬────────╮
│ # │ example │ result │
├───┼──────────────────────────────────────┼────────┤
│ 0 │ open myfile.json │ │
│ 1 │ open myfile.json --raw │ │
│ 2 │ 'myfile.txt' | open │ │
│ 3 │ open myfile.txt --raw | decode utf-8 │ │
╰───┴──────────────────────────────────────┴────────╯
```
and same thing, we can check that there is `$nothing` in this last
command
```bash
>_ $nu.scope.commands | where name == open | get examples.0.result.0 | describe
table<name: string, index: int>
```
# Tests + Formatting
- ✔️ `cargo fmt --all`
- ✔️ `cargo clippy --workspace -- -D warnings -D
clippy::unwrap_used -A clippy::needless_collect`
- ✔️ `cargo test --workspace` (~~currently running~~)
# After Submitting
the documentation would have to be regenerated!
Should close#8035.
> **Note**
> this is my first technical PR for `nushell`
> - i might very well miss things
> - i tried to be as complete as possible about the changes
> - please require further changes if i did something wrong, i'm open to
any remark 😌
# Description
this PR adds, when it is defined in the `examples` method of the
`Command` implementations, the output of the examples to the output of
the `help` command.
this PR
- only modifies `crates/nu-engine/src/documentation.rs` and the
`get_documentation` function
- defines a new `WD` constant to print a **W**hite **D**immed `...`
- a `match` statement at the end of the example loop to
- print a white dimmed `...` when the example is not set, i.e. set to
`None` in the `examples` method of the `Command` implementation of a
command
- pretty print the output of the associated example `Value` when it has
been defined
> **Warning**
> LIMITATIONS:
> - i use snippets from `crates/nu-protocol/src/pipeline_data.rs`
> - the table creation from `pub PipelineData::print`, i.e. the `let
decl_id = ...;` and `let table = ...;` in the change
> - the table item printing from `PipelineData::write_all_and_flush`,
i.e. the `for item in table { ... }`
>
> ADDRESSED:
> - ~~the formatting of the output is not perfect and has to be fully
left aligned with the first column for now~~ (fixed with
[`5abeefd558c34ba9bae15e2f183ff4625442921e`..`a62be1b5a2c730959da5dbc028bb91ffe5093f63`](5abeefd558c34ba9bae15e2f183ff4625442921e..a62be1b5a2c730959da5dbc028bb91ffe5093f63))
> - ~~i'm using `.unwrap()` on both the changes above, not sure how to
handle this for now~~ (fixed for now thanks to 49f1dc080)
> - ~~the tests and `clippy` checks do not pass for now, see below~~
(`clippy` now is happy with 49f1dc080 and the tests pass with
11666bc715)
# User-Facing Changes
the output of the `help <command>` command is now augmented with the
outputs of the examples, when they are defined.
- `with-env`
```bash
> help with-env
...
Examples:
Set the MYENV environment variable
> with-env [MYENV "my env value"] { $env.MYENV }
my env value
Set by primitive value list
> with-env [X Y W Z] { $env.X }
Y
Set by single row table
> with-env [[X W]; [Y Z]] { $env.W }
Z
Set by key-value record
> with-env {X: "Y", W: "Z"} { [$env.X $env.W] }
╭───┬───╮
│ 0 │ Y │
│ 1 │ Z │
╰───┴───╯
```
instead of the previous
```bash
> help with-env
...
Examples:
Set the MYENV environment variable
> with-env [MYENV "my env value"] { $env.MYENV }
Set by primitive value list
> with-env [X Y W Z] { $env.X }
Set by single row table
> with-env [[X W]; [Y Z]] { $env.W }
Set by key-value record
> with-env {X: "Y", W: "Z"} { [$env.X $env.W] }
```
- `merge`
```bash
> help merge
...
Examples:
Add an 'index' column to the input table
> [a b c] | wrap name | merge ( [1 2 3] | wrap index )
╭───┬──────╮
│ # │ name │
├───┼──────┤
│ 1 │ a │
│ 2 │ b │
│ 3 │ c │
╰───┴──────╯
Merge two records
> {a: 1, b: 2} | merge {c: 3}
╭───┬───╮
│ a │ 1 │
│ b │ 2 │
│ c │ 3 │
╰───┴───╯
Merge two tables, overwriting overlapping columns
> [{columnA: A0 columnB: B0}] | merge [{columnA: 'A0*'}]
╭───┬─────────┬─────────╮
│ # │ columnA │ columnB │
├───┼─────────┼─────────┤
│ 0 │ A0* │ B0 │
╰───┴─────────┴─────────╯
```
instead of the previous
```bash
> help merge
...
Examples:
Add an 'index' column to the input table
> [a b c] | wrap name | merge ( [1 2 3] | wrap index )
Merge two records
> {a: 1, b: 2} | merge {c: 3}
Merge two tables, overwriting overlapping columns
> [{columnA: A0 columnB: B0}] | merge [{columnA: 'A0*'}]
```
# Description
Adds a `profile` command that profiles each pipeline element of a block
and can also recursively step into child blocks.
# Limitations
* It is implemented using pipeline metadata which currently get lost in
some circumstances (e.g.,
https://github.com/nushell/nushell/issues/4501). This means that the
profiler will lose data coming from subexpressions. This issue will
hopefully be solved in the future.
* It also does not step into individual loop iteration which I'm not
sure why but maybe that's a good thing.
# User-Facing Changes
Shouldn't change any existing behavior.
# 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
# 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>
I noticed that `$nu.loginshell-path` was using backward *and* forward
slashes on Windows.
#### Before
`C:\Users\reill\AppData\Roaming\nushell/login.nu`
#### After
`C:\Users\reill\AppData\Roaming\nushell\login.nu`
Fixed up 2 other similar issues while I was at it.
# Description
Fixes: #7828
We delegate to `save` command to finish redirection, then if it runs to
success, the relative exit code is set to 0. To fix it, in redirection
context, we take exit_code stream before sending it to `save` command,
than manually returns `PipelineData::ExternalStream` to make nushell set
relative code properly.
# 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
# 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.
# Description
Lint: `clippy::uninlined_format_args`
More readable in most situations.
(May be slightly confusing for modifier format strings
https://doc.rust-lang.org/std/fmt/index.html#formatting-parameters)
Alternative to #7865
# User-Facing Changes
None intended
# Tests + Formatting
(Ran `cargo +stable clippy --fix --workspace -- -A clippy::all -D
clippy::uninlined_format_args` to achieve this. Depends on Rust `1.67`)
# Description
Relative:
`https://github.com/nushell/nushell/pull/7889#issuecomment-1407503567`
Make `search_terms` return empty string rather than nothing, so some
other command can handle it better
# 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
# 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.
# Description
BEFORE:
```
Subcommands:
str camel-case - Convert a string to camelCase
str capitalize - Capitalize first letter of text
str collect - 'str collect' is deprecated. Please use 'str join' instead.
str contains - Checks if string input contains a substring
str distance - Compare two strings and return the edit distance/Levenshtein distance
str downcase - Make text lowercase
str ends-with - Check if an input ends with a string
str find-replace - Deprecated command
str index-of - Returns start index of first occurrence of string in input, or -1 if no match
str join - Concatenate multiple strings into a single string, with an optional separator between each
str kebab-case - Convert a string to kebab-case
str length - Output the length of any strings in the pipeline
str lpad - Left-pad a string to a specific length
str pascal-case - Convert a string to PascalCase
str replace - Find and replace text
str reverse - Reverse every string in the pipeline
str rpad - Right-pad a string to a specific length
str screaming-snake-case - Convert a string to SCREAMING_SNAKE_CASE
str snake-case - Convert a string to snake_case
str starts-with - Check if an input starts with a string
str substring - Get part of a string. Note that the start is included but the end is excluded, and that the first character of a string is index 0.
str title-case - Convert a string to Title Case
str to-datetime - Deprecated command
str to-decimal - Deprecated command
str to-int - Deprecated command
str trim - Trim whitespace or specific character
str upcase - Make text uppercase
```
AFTER:
```
Subcommands:
str camel-case - Convert a string to camelCase
str capitalize - Capitalize first letter of text
str contains - Checks if string input contains a substring
str distance - Compare two strings and return the edit distance/Levenshtein distance
str downcase - Make text lowercase
str ends-with - Check if an input ends with a string
str index-of - Returns start index of first occurrence of string in input, or -1 if no match
str join - Concatenate multiple strings into a single string, with an optional separator between each
str kebab-case - Convert a string to kebab-case
str length - Output the length of any strings in the pipeline
str lpad - Left-pad a string to a specific length
str pascal-case - Convert a string to PascalCase
str replace - Find and replace text
str reverse - Reverse every string in the pipeline
str rpad - Right-pad a string to a specific length
str screaming-snake-case - Convert a string to SCREAMING_SNAKE_CASE
str snake-case - Convert a string to snake_case
str starts-with - Check if an input starts with a string
str substring - Get part of a string. Note that the start is included but the end is excluded, and that the first character of a string is index 0.
str title-case - Convert a string to Title Case
str trim - Trim whitespace or specific character
str upcase - Make text uppercase
```
The deprecated subcommands still exist, but are no longer listed in
`help` for the containing command.
# User-Facing Changes
See above.
# 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
# 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.
This is an attempt to implement a new `Value::LazyRecord` variant for
performance reasons.
`LazyRecord` is like a regular `Record`, but it's possible to access
individual columns without evaluating other columns. I've implemented
`LazyRecord` for the special `$nu` variable; accessing `$nu` is
relatively slow because of all the information in `scope`, and [`$nu`
accounts for about 2/3 of Nu's startup time on
Linux](https://github.com/nushell/nushell/issues/6677#issuecomment-1364618122).
### Benchmarks
I ran some benchmarks on my desktop (Linux, 12900K) and the results are
very pleasing.
Nu's time to start up and run a command (`cargo build --release;
hyperfine 'target/release/nu -c "echo \"Hello, world!\""' --shell=none
--warmup 10`) goes from **8.8ms to 3.2ms, about 2.8x faster**.
Tests are also much faster! Running `cargo nextest` (with our very slow
`proptest` tests disabled) goes from **7.2s to 4.4s (1.6x faster)**,
because most tests involve launching a new instance of Nu.
### Design (updated)
I've added a new `LazyRecord` trait and added a `Value` variant wrapping
those trait objects, much like `CustomValue`. `LazyRecord`
implementations must implement these 2 functions:
```rust
// All column names
fn column_names(&self) -> Vec<&'static str>;
// Get 1 specific column value
fn get_column_value(&self, column: &str) -> Result<Value, ShellError>;
```
### Serializability
`Value` variants must implement `Serializable` and `Deserializable`, which poses some problems because I want to use unserializable things like `EngineState` in `LazyRecord`s. To work around this, I basically lie to the type system:
1. Add `#[typetag::serde(tag = "type")]` to `LazyRecord` to make it serializable
2. Any unserializable fields in `LazyRecord` implementations get marked with `#[serde(skip)]`
3. At the point where a `LazyRecord` normally would get serialized and sent to a plugin, I instead collect it into a regular `Value::Record` (which can be serialized)
Add recursion limit to `def` and `block`.
Summary of this PR , it will detect if `def` call itself or not .
Then execute by using `stack` which I think best choice to use with this
design and core as it is available in all crates and mutable and
calculate the recursion limit on calling `def`.
Set 50 as recursion limit on `Config`.
Add some tests too .
Fixes#5899
Co-authored-by: Reilly Wood <reilly.wood@icloud.com>
# Description
This closes#7498, as well as fixes an issue reported in
https://github.com/nushell/nushell/pull/7002#issuecomment-1368340773
BEFORE:
```
〉[{foo: 'bar'} {}] | get foo
Error: nu:🐚:column_not_found (link)
× Cannot find column
╭─[entry #5:1:1]
1 │ [{foo: 'bar'} {}] | get foo
· ────────┬──────── ─┬─
· │ ╰── value originates here
· ╰── cannot find column 'Empty cell'
╰────
〉[{foo: 'bar'} {}].foo
╭───┬─────╮
│ 0 │ bar │
│ 1 │ │
╰───┴─────╯
```
AFTER:
```
〉[{foo: 'bar'} {}] | get foo
Error: nu:🐚:column_not_found (link)
× Cannot find column
╭─[entry #1:1:1]
1 │ [{foo: 'bar'} {}] | get foo
· ─┬ ─┬─
· │ ╰── cannot find column 'foo'
· ╰── value originates here
╰────
〉[{foo: 'bar'} {}].foo
Error: nu:🐚:column_not_found (link)
× Cannot find column
╭─[entry #3:1:1]
1 │ [{foo: 'bar'} {}].foo
· ─┬ ─┬─
· │ ╰── cannot find column 'foo'
· ╰── value originates here
╰────
```
EDIT: This also changes the semantics of `get`/`select` `-i` somewhat.
I've decided to leave it like this because it works more intuitively
with `default` and `compact`.
BEFORE:
```
〉[{a:1} {b:2} {a:3}] | select -i foo | to nuon
null
```
AFTER:
```
〉[{a:1} {b:2} {a:3}] | select -i foo | to nuon
[[foo]; [null], [null], [null]]
```
# User-Facing Changes
See above. EDIT: the issue with holes in cases like ` [{foo: 'bar'}
{}].foo.0` versus ` [{foo: 'bar'} {}].0.foo` has been resolved.
# 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
# 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.
# Description
Inspired by #7592
For brevity use `Value::test_{string,int,float,bool}`
Includes fixes to commands that were abusing `Span::test_data` in their
implementation. Now the call span is used where possible or the explicit
`Span::unknonw` is used.
## Command fixes
- Fix abuse of `Span::test_data()` in `query_xml`
- Fix abuse of `Span::test_data()` in `term size`
- Fix abuse of `Span::test_data()` in `seq date`
- Fix two abuses of `Span::test_data` in `nu-cli`
- Change `Span::test_data` to `Span::unknown` in `keybindings listen`
- Add proper call span to `registry query`
- Fix span use in `nu_plugin_query`
- Fix span assignment in `select`
- Use `Span::unknown` instead of `test_data` in more places
## Other
- Use `Value::test_int`/`test_float()` consistently
- More `test_string` and `test_bool`
- Fix unused imports
# User-Facing Changes
Some commands may now provide more helpful spans for downstream use in
errors
Closes#7572 by adding a cache for compiled regexes of type
`Arc<Mutex<LruCache<String, Regex>>>` to `EngineState` .
The cache is limited to 100 entries (limit chosen arbitrarily) and
evicts least-recently-used items first.
This PR makes a noticeable difference when using regexes for
`color_config`, e.g.:
```bash
#first set string formatting in config.nu like:
string: { if $in =~ '^#\w{6}$' { $in } else { 'white' } }`
# then try displaying and exploring a table with many strings
# this is instant after the PR, but takes hundreds of milliseconds before
['#ff0033', '#0025ee', '#0087aa', 'string', '#4101ff', '#ff0033', '#0025ee', '#0087aa', 'string', '#6103ff', '#ff0033', '#0025ee', '#0087aa', 'string', '#6103ff', '#ff0033', '#0025ee', '#0087aa', 'string', '#6103ff', '#ff0033', '#0025ee', '#0087aa', 'string', '#6103ff','#ff0033', '#0025ee', '#0087aa', 'string', '#6103ff','#ff0033', '#0025ee', '#0087aa', 'string', '#6103ff','#ff0033', '#0025ee', '#0087aa', 'string', '#6103ff','#ff0033', '#0025ee', '#0087aa', 'string', '#6103ff','#ff0033', '#0025ee', '#0087aa', 'string', '#6103ff']
```
## New dependency (`lru`)
This uses [the popular `lru` crate](https://lib.rs/crates/lru). The new
dependency adds 19.8KB to a Linux release build of Nushell. I think this
is OK, especially since the crate can be useful elsewhere in Nu.