Commit Graph

1086 Commits

Author SHA1 Message Date
JT
3db0aed9f7
Add rest and ignore-rest patterns (#8681)
# Description

Adds two more patterns when working with lists:

```
[1, ..$remainder]
```
and
```
[1, ..]
```
The first one collects the remaining items and assigns them into the
variable. The second one ignores any remaining values.

# User-Facing Changes

Adds more capability to list pattern matching.

# 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-03-31 11:08:53 +13:00
JT
7ec5f2f2eb
Add or-patterns, fix var binding scope (#8633)
# Description

Adds `|` patterns to `match`, allowing you to try multiple patterns for
the same case.

Example:

```
match {b: 1} { {a: $b} | {b: $b} => { print $b } }
```

Variables that don't bind are set to `$nothing` so that they can be
later checked.

This PR also:
fixes #8631 

Creates a set of integration tests for pattern matching also

# User-Facing Changes

Adds `|` to `match`. Fixes variable binding scope. 
# 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-03-27 11:31:57 +13:00
JT
5b03bca138
Remove autoprinting of loop block values (#8618)
# Description

This removes autoprinting the final value of a loop, much in the same
spirit as not autoprinting values at the end of statements. As we fix
these corner cases, it becomes more consistent that to print to the
screen in a script, you use the `print` command.

This gives a noticeable performance improvement as a bonus.

Before:
```
C:\Source\nushell〉 for x in 1..10 { $x }
1
2
3
4
5
6
7
8
9
10
```
Now:
```
C:\Source\nushell〉 for x in 1..10 { $x }
C:\Source\nushell〉
```

# User-Facing Changes

**BREAKING CHANGE**

Loops like `for`, `loop`, and `while` will no longer automatically print
loop values to the screen.

# 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-03-26 13:23:54 +13:00
Reilly Wood
d409171ba8
Change comparison operators to allow nulls (#8617)
Prior to this PR, the less/greater than operators (`<`, `>`, `<=`, `>=`)
would throw an error if either side was null. After this PR, these
operators return null if either side (or both) is null.

### Examples
```bash 
1 < 3       # true
1 < null    # null
null < 3    # null
null < null # null
```

### Motivation

JT [asked the C#
folks](https://discord.com/channels/601130461678272522/615329862395101194/1086137515053957140)
and this is apparently the approach they would choose for comparison
operators if they could start from scratch.

This PR makes `where` more convenient to use on jagged/missing data. For
example, we can now filter on columns that may not be present in every
row:
```
> [{foo: 123} {}] | where foo? > 10
╭───┬─────╮
│ # │ foo │
├───┼─────┤
│ 0 │ 123 │
╰───┴─────╯
```
2023-03-26 12:10:09 +13:00
JT
6872d2ac2a
Speed up tight loop benchmarks (#8609)
# Description

This does a few speedups for tight loops:
* Caches the DeclId for `table` so we don't look it up. This means users
can't easily replace the default one, we might want to talk about this
tradeoff. The lookup for finding `table` in a tight loop is currently
pretty heavy. Might be another way to speed this up.
* `table` no longer pre-calculates the width. Instead, it only
calculates the width when printing a table or record.
* Use more efficient way of collecting the block of each loop
* When printing output, only get the config when needed

Combined, this drops the runtime from a million loop tight iteration
from 1sec 8ms to 236ms.

# 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.
2023-03-26 06:12:57 +13:00
Reilly Wood
d8478ca690
Clean up unnecessary macro use (#8607)
Some minor code cleanup.

We've accumulated a few macros over the years that arguably don't need
to be macros. This PR removes 4 macros by either:
1. Inlining the macro
2. Replacing the macro with a local function
3. Replacing the macro with a closure
2023-03-25 20:17:20 +13:00
JT
aab31833a2
Add more pattern types to matcher (#8605)
# Description

Add float, string, and date patterns to matcher.

This could probably use some tests 😅 

# 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.
2023-03-25 17:30:35 +13:00
JT
c0648a83be
Move variables to var stack (#8604)
# 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.
2023-03-25 12:56:45 +13:00
Reilly Wood
b4b68afa17
Make HTTP requests cancellable when trying to connect (#8591)
Closes #8585.

Prior to this change, the `http` commands could get stuck for 30s while
attempting to make a connection to a remote server. After this change,
`ctrl+c` works as expected:


![image](https://user-images.githubusercontent.com/26268125/227395505-c2d5b19d-6228-4eac-836f-c0c3426b0c19.png)

To make this work, we perform blocking `ureq` calls in a background
thread and poll the channel while checking `ctrl+c`.
2023-03-24 12:45:55 -07:00
dependabot[bot]
4a1d12462f
Bump miette from 5.5.0 to 5.6.0 (#8531)
Bumps [miette](https://github.com/zkat/miette) from 5.5.0 to 5.6.0.
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/zkat/miette/blob/main/CHANGELOG.md">miette's
changelog</a>.</em></p>
<blockquote>
<h2>5.6.0 (2023-03-14)</h2>
<h3>Bug Fixes</h3>
<ul>
<li><strong>ci:</strong> configure clippy-specific MSRV (<a
href="b658fc020b">b658fc02</a>)</li>
<li><strong>graphical:</strong> Fix wrong severity of related errors (<a
href="https://redirect.github.com/zkat/miette/issues/234">#234</a>) (<a
href="3497508aa9">3497508a</a>)</li>
<li><strong>atty:</strong> Switch out <code>atty</code> for
<code>is-terminal</code> (<a
href="https://redirect.github.com/zkat/miette/issues/229">#229</a>) (<a
href="443d240f49">443d240f</a>)</li>
</ul>
<h3>Features</h3>
<ul>
<li><strong>protocol:</strong> implement <code>Ord</code> for
<code>Severity</code> (<a
href="https://redirect.github.com/zkat/miette/issues/240">#240</a>) (<a
href="ed486c959d">ed486c95</a>)</li>
</ul>
<p><!-- raw HTML omitted --><!-- raw HTML omitted --></p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="78fe18e699"><code>78fe18e</code></a>
chore: Release</li>
<li><a
href="2335b25ee7"><code>2335b25</code></a>
docs: update changelog</li>
<li><a
href="443d240f49"><code>443d240</code></a>
fix(atty): Switch out <code>atty</code> for <code>is-terminal</code> (<a
href="https://redirect.github.com/zkat/miette/issues/229">#229</a>)</li>
<li><a
href="ed486c959d"><code>ed486c9</code></a>
feat(protocol): implement <code>Ord</code> for <code>Severity</code> (<a
href="https://redirect.github.com/zkat/miette/issues/240">#240</a>)</li>
<li><a
href="3497508aa9"><code>3497508</code></a>
fix(graphical): Fix wrong severity of related errors (<a
href="https://redirect.github.com/zkat/miette/issues/234">#234</a>)</li>
<li><a
href="b658fc020b"><code>b658fc0</code></a>
fix(ci): configure clippy-specific MSRV</li>
<li><a
href="ebc61b5cf8"><code>ebc61b5</code></a>
docs: Mention miette::miette! macro under &quot;... in application
code&quot; (<a
href="https://redirect.github.com/zkat/miette/issues/233">#233</a>)</li>
<li><a
href="14f952dc91"><code>14f952d</code></a>
(cargo-release) start next development iteration 5.5.1-alpha.0</li>
<li><a
href="128c0a1fae"><code>128c0a1</code></a>
(cargo-release) start next development iteration 5.5.1-alpha.0</li>
<li>See full diff in <a
href="https://github.com/zkat/miette/compare/miette-derive-v5.5.0...miette-derive-v5.6.0">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=miette&package-manager=cargo&previous-version=5.5.0&new-version=5.6.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-03-24 22:55:25 +13:00
JT
2c3aade057
Add pattern matching (#8590)
# 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.
2023-03-24 14:52:01 +13:00
Reilly Wood
6a274b860a
Cell paths: make optional path members short-circuit (#8554)
This is a follow-up to https://github.com/nushell/nushell/pull/8379 and
https://github.com/nushell/nushell/discussions/8502.

This PR makes it so that the new `?` syntax for marking a path member as
optional short-circuits, as voted on in the
[8502](https://github.com/nushell/nushell/discussions/8502) poll.
Previously, `{ foo: 123 }.bar?.baz` would raise an error:

```
> { foo: 123 }.bar?.baz
  × Data cannot be accessed with a cell path
   ╭─[entry #15:1:1]
 1 │ { foo: 123 }.bar?.baz
   ·                   ─┬─
   ·                    ╰── nothing doesn't support cell paths
   ╰────
   ```

Here's what was happening:

1. The `bar?` path member access returns `nothing` because there is no field named `bar` on the record
2. The `baz` path member access fails when trying to access a `baz` field on that `nothing` value

After this change, `{ foo: 123 }.bar?.baz` returns `nothing`; the failed `bar?` access immediately returns `nothing` and the `baz` access never runs.
2023-03-23 09:54:19 +13:00
Sygmei
a1840e9d20
fix: fixed typo and improved Value TypeMismatch exceptions (#8324)
# Description

This PR aims to improve `TypeMismatch` exception that occurs when
comparing two values with `<`, `>`, `<=` or `>=` operators.

*Before*

![image](https://user-images.githubusercontent.com/3835355/222980803-8cb0f945-5a82-4512-9989-5df0ec4e4969.png)

*After*

![image](https://user-images.githubusercontent.com/3835355/226754903-68e56344-065d-42ee-b184-ab968e91c6de.png)

This PR also bundles a small refactor for histogram forbidden column
names exception, previous implementation forgot a column name in the
message, to avoid this, I'm re-using the same array for checking and
error display

# User-Facing Changes

Not much changes except a better and more readable exception for the
user

# Tests + Formatting

Does not break any tests, formatting passes as well :)
2023-03-22 09:47:40 +01:00
Steven Xu
1d3f6105f5
feat: add a command_not_found hook (#8314)
# Description
Add a `command_not_found` function to `$env.config.hooks`. If this
function outputs a string, then it's included in the `help`.

An example hook on *Arch Linux*, to find packages that contain the
binary, looks like:

```nushell
let-env config = {
  # ...
  hooks: {
    command_not_found: {
      |cmd_name| (
        try {
          let pkgs = (pkgfile --binaries --verbose $cmd_name)
          (
            $"(ansi $env.config.color_config.shape_external)($cmd_name)(ansi reset) " +
            $"may be found in the following packages:\n($pkgs)"
          )
        } catch {
          null
        }
      )
    }
    # ...
```

# User-Facing Changes
- Add a `command_not_found` function to `$env.config.hooks`.

# 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.
2023-03-20 17:05:22 +13:00
Michael Angerman
64f50a179e
remove unused imports: Deserialize, Serialize compiler warning for nu-protocol/src/example.rs (#8514)
when running the tests inside nu-protocol we were getting a compiler
warning...
this PR removes the compiler warning from nu-protocol.
by adding
```rust
#[allow(unused_imports)]
```
2023-03-18 11:45:12 -07:00
Artemiy
491a9c019c
Revert "Hide 7925" (#8500)
Revert nushell/nushell#8359
Turn `[empty list]` on by default again
2023-03-18 08:58:13 +13:00
Darren Schroeder
ef7fbf4bf9
Revert "Allow NU_LIBS_DIR and friends to be const" (#8501)
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.
2023-03-17 09:33:24 -05:00
StevenDoesStuffs
400a9d3b1e
Allow NU_LIBS_DIR and friends to be const (#8310)
# 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.
2023-03-17 07:23:29 -05:00
JT
2d41613039
bump to 0.77.2 (#8496)
# 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

> **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-03-17 21:29:15 +13:00
Artemiy
19beafa865
Disable pipeline echo (#8292)
# Description

Change behavior of block evaluation to not print result of intermediate
commands.
Previously result of every but last pipeline in a block was printed to
stdout, and last one was returned

![image](https://user-images.githubusercontent.com/17511668/222550110-3f62fbed-432c-4b46-b9b1-4cb45a1f893e.png)
With this change results of intermediate pipelines are discarded after
they finish and the last one is returned as before:

![image](https://user-images.githubusercontent.com/17511668/222550346-f1e74f80-f6b6-4aa3-98d6-888ea4cb4915.png)
Now one should use `print` explicitly to print something to stdout

![image](https://user-images.githubusercontent.com/17511668/222923955-fda0d77b-41b4-4f91-a80f-12b0a1880c05.png)

**Note, that this behavior is not limited to functions!** The scope of
this change are all blocks. All of the below are executed as blocks and
thus exibited this behavior in the same way:

![image](https://user-images.githubusercontent.com/17511668/222924062-342c15de-4273-4bf5-8b39-fe6e3aa96076.png)

With this change outputs for all types of blocks are cleaned:

![image](https://user-images.githubusercontent.com/17511668/222924118-7d51c27e-04bb-43e5-8efe-38b484683bfe.png)


# User-Facing Changes

All types of blocks (function bodies, closures, `if` branches, `for` and
`loop` bodies e.t.c.) no longer print result of intermediate pipelines.

# 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.
2023-03-17 11:53:46 +13:00
Matthew Deville
8543b0789d
Additional flags for commands from csv and from tsv (#8398)
# Description

Resolves issue #8370

Adds the following flags to commands `from csv` and `from tsv`:
- `--flexible`: allow the number of fields in records to be variable
- `-c --comment`: a comment character to ignore lines starting with it
- `-q --quote`: a quote character to ignore separators in strings,
defaults to '\"'
- `-e --escape`: an escape character for strings containing the quote
character

Internally, the `Value` struct has an additional helper function
`as_char` which converts it to a single `char`

# User-Facing Changes

The single quoted string `'\t'` can no longer be used as a parameter for
the flag `--separator '\t'` as it is interpreted as a two-character
string. One needs to use from now on the flag with a double quoted
string like so: `-s "\t"` which correctly interprets the string as a
single `char`.
2023-03-16 17:49:46 -05:00
Steven Xu
b2a557d4ed
fix: fix commandline when called with no arguments (#8207)
# Description

This fixes the `commandline` command when it's run with no arguments, so
it outputs the command being run. New line characters are included.

This allows for:

- [A way to get current command inside pre_execution hook · Issue #6264
· nushell/nushell](https://github.com/nushell/nushell/issues/6264)
- The possibility of *Atuin* to work work *Nushell*. *Atuin* hooks need
to know the current repl input before it is run.

# 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

# 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-03-16 17:45:35 -05:00
WindSoilder
31d9c0889c
Revert "Throw out error if external command in subexpression is failed to run (#8204)" (#8475)
This reverts commit dec0a2517f.

It breaks programs like `fzf`

# Description

Fixes: #8472 
Fixes:  #8313
Reopen: #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.
2023-03-17 07:07:32 +13:00
Reilly Wood
21b84a6d65
Optional members in cell paths: Attempt 2 (#8379)
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.
2023-03-15 20:50:58 -07:00
dependabot[bot]
aa876ce24f
Bump lru from 0.9.0 to 0.10.0 (#8425) 2023-03-15 18:47:40 +00:00
Thomas Coratger
0bd4d27e8d
Modify reject algorithm for identical elements (#8446)
# Description

The correction made here concerns the issue #8431. Indeed, the algorithm
initially proposed to remove elements of a `vector` performed a loop
with `remove` and an incident therefore appeared when several values
were equal because the deletion was done outside the length of the
vector:
```rust
let mut found = false;
for (i, col) in cols.clone().iter().enumerate() {
    if col == col_name {
        cols.remove(i);
        vals.remove(i);
        found = true;
    }
}

```

Then, `[[a, a]; [1, 2]] | reject a: ` gave `thread 'main' panicked at
'removal index (is 1) should be < len (is 1)',
crates/nu-protocol/src/value/mod.rs:1213:54`.

The proposed correction is therefore the implementation of the
`retain_mut` utility dedicated to this functionality.

```rust
let mut found = false;
let mut index = 0;
cols.retain_mut(|col| {
    if col == col_name {
        found = true;
        vals.remove(index);
        false
    } else {
        index += 1;
        true
    }
});
```
2023-03-14 23:26:48 +01:00
Stefan Holderbach
1701303279
Bump to 0.77.1 development version (#8453)
# Description

Either to be used in an emergency point release or to indicate
development builds in the `version` command
2023-03-14 23:26:08 +01:00
Stefan Holderbach
fd09609b44
Bump version to 0.77.0 (#8410) 2023-03-14 20:46:42 +02:00
Stefan Holderbach
79d0735864
Remove unused nu-json from nu-protocol (#8417)
This dependency apears unnecessary and should remove a link in the crate
graph that could favor parallel compilation
2023-03-12 20:26:35 +01:00
Stefan Holderbach
a52386e837
Box ShellError in Value::Error (#8375)
# 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
2023-03-12 09:57:27 +01:00
JT
e435196956
Hack around bad binary viewing logic (#8399)
# Description

This works around a bug introduced by #8058 

We should revisit the original fix, as it makes some assumptions about
how stdout redirection is used by `table`. We use the stdout by default
for table regularly during a repl session, so we should instead
special-case case for handling externals.

# User-Facing Changes

Restores the original default `table` behaviour for binary data

# 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.
2023-03-11 14:13:37 +13:00
Antoine Stevan
4e78f3649b
FEATURE: add the startup time to $nu (#8353)
# 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
```
2023-03-09 14:18:58 -06:00
StevenDoesStuffs
7e949595bd
Add is-interactive and is-login to NuVariable and allow running scripts with -i (#8306)
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.
2023-03-08 20:59:33 -06:00
Artemiy
d31a51e3bc
Hide 7925 (#8359)
# Description

Hides https://github.com/nushell/nushell/pull/7925 from config and
disables by default. Option is still present in config, just hidden.

# User-Facing Changes

Users can no longer find `table.show_empty` in config and it is set to
false by default.

# 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.
2023-03-09 10:26:59 +13:00
Bob Hyman
2ad0fcb377
Fix 8244 -- store timestamps with nanosecond resolution (consistently) (#8337)
# Description

Fix for data ambiguity noted in #8244.

Basic change is to use nanosecond resolution for unix timestamps (stored
in type Int). Previously, a timestamp might have seconds, milliseconds
or nanoseconds, but it turned out there were overlaps in data ranges
between different resolutions, so there wasn't always a unique mapping
back to date/time.

Due to higher precision, the *range* of dates that timestamps can map to
is restricted. Unix timestamps with seconds resolution and 64 bit
storage can cover all dates from the Big Bang to eternity. Timestamps
with seconds resolution and 32 bit storage can only represent dates from
1901-12-13 through 2038-01-19. The nanoseconds resolution and 64 bit
storage used with this fix can represent dates from 1677-09-21T00:12:44
to 2262-04-11T23:47:16, something of a compromise.

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

## `<datetime> | into int`
Converts to nanosecond resolution
```rust
〉date now | into int
1678084730502126846
```
This is the number of non-leap nanoseconds after the unix epoch date:
1970-01-01T00:00:00+00:00.

Conversion fails for dates outside the supported range:
```rust
〉1492-10-12 | into int
Error: nu:🐚:incorrect_value

  × Incorrect value.
   ╭─[entry #51:1:1]
 1 │ 1492-10-12 | into int
   ·              ────┬───
   ·                  ╰── DateTime out of timestamp range 1677-09-21T00:12:43 and 2262-04-11T23:47:16
   ╰────


```

## `<int> | into datetime`
Can no longer fail or produce incorrect results for any 64-bit input:
```rust
〉0 | into datetime 
Thu, 01 Jan 1970 00:00:00 +0000 (53 years ago)
〉"7fffffffffffffff" | into int -r 16 | into datetime
Fri, 11 Apr 2262 23:47:16 +0000 (in 239 years)
〉("7fffffffffffffff" | into int -r 16) * -1 | into datetime
Tue, 21 Sep 1677 00:12:43 +0000 (345 years ago)
```

## `<date> | date to-record` and `<date> | date to-table`
Now both have a `nanosecond` field.  
```rust
〉"7fffffffffffffff" | into int -r 16 | into datetime | date to-record
╭────────────┬───────────╮
│ year       │ 2262      │
│ month      │ 4         │
│ day        │ 11        │
│ hour       │ 23        │
│ minute     │ 47        │
│ second     │ 16        │
│ nanosecond │ 854775807 │
│ timezone   │ +00:00    │
╰────────────┴───────────╯
〉"7fffffffffffffff" | into int -r 16 | into datetime | date to-table
╭───┬──────┬───────┬─────┬──────┬────────┬────────┬────────────┬──────────╮
│ # │ year │ month │ day │ hour │ minute │ second │ nanosecond │ timezone │
├───┼──────┼───────┼─────┼──────┼────────┼────────┼────────────┼──────────┤
│ 0 │ 2262 │     4 │  11 │   23 │     47 │     16 │  854775807 │ +00:00   │
╰───┴──────┴───────┴─────┴──────┴────────┴────────┴────────────┴──────────╯
```

This change was not mandated by the OP problem, but it is nice to be
able to see the nanosecond bits that were present in Nushell `date` type
all along.
# 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.
2023-03-07 17:02:15 -06:00
Reilly Wood
e445c41454
Fix to json for SQLite databases (#8343)
Fixes #8341. 

The `CustomValue::to_json()` function is an odd duck; it defaults to
returning `null`, and no `CustomValue` implementations override it to do
anything useful. I forgot to implement `to_json()` for `SQLiteDatabase`,
so `open foo.db | to json` was returning `null`.

To fix this, I've removed `CustomValue::to_json()` and now `to json`
will collect a `CustomValue` into a regular `Value` before doing a JSON
conversion.
2023-03-06 14:36:26 -08:00
Stefan Holderbach
62575c9a4f
Document and critically review ShellError variants - Ep. 3 (#8340)
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`
2023-03-06 18:33:09 +01:00
Stefan Holderbach
f7b8f97873
Document and critically review ShellError variants - Ep. 2 (#8326)
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)
2023-03-06 11:31:07 +01:00
Stefan Holderbach
438062d7fc
Document and critically review ShellError variants - Ep. 1 (#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.

Feel free to add review comments if you spot inconsistent use of
`ShellError` variants.

- Name fields on `ShellError::OperatorOverflow`
- Name fields on `ShellError::PipelineMismatch`
- Add doc to `ShellError::OnlySupportsThisInputType`
- Name `ShellError::OnlySupportsThisInputType`
- Name field on `ShellError::PipelineEmpty`
- Comment about issues with `TypeMismatch*`
- Fix a few `exp_input_type`s
- Name fields on `ShellError::InvalidRange`

# User-Facing Changes

(None now, end goal more explicit and consistent error messages)

# Tests + Formatting

(No additional tests needed so far)
2023-03-01 20:34:48 +01:00
WindSoilder
dec0a2517f
Throw out error if external command in subexpression is failed to run (#8204) 2023-03-01 13:50:38 +02:00
Victor Wong
592e677caf
Type mismatch span fix #7288 (#8271)
# Description

This change fixes the bug associated with an incorrect span in
`type_mismatch` error message as described in #7288

The `span` argument in the method `into_value` was not being used to
convert a `PipelineData::Value` type so when called in
[eval_expression](https://github.com/nushell/nushell/blob/main/crates/nu-engine/src/eval.rs#L514-L515),
the original expression's span was not being used to overwrite the
result of `eval_subexpression`.

# User-Facing Changes

Using the example described in the issue, the whole bracketed
subexpression is correctly underlined.

Behavior before change:

```
let val = 10
($val | into string) + $val
Error: nu:🐚:type_mismatch

  × Type mismatch during operation.
   ╭─[entry #2:1:1]
 1 │ ($val | into string) + $val
   ·         ─────┬─────  ┬ ──┬─
   ·              │       │   ╰── int
   ·              │       ╰── type mismatch for operator
   ·              ╰── string
   ╰────
```

Behavior after change:
```
let val = 10
($val | into string) + $val
Error: nu:🐚:type_mismatch

  × Type mismatch during operation.
   ╭─[entry #2:1:1]
 1 │ ($val | into string) + $val
   · ──────────┬───────── ┬ ──┬─
   ·           │          │   ╰── int
   ·           │          ╰── type mismatch for operator
   ·           ╰── string
   ╰────
```


# 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.
2023-02-28 21:12:53 -08:00
Jakub Žádník
a3f817d71b
Re-implement aliases (#8123)
# Description

This PR adds an alternative alias implementation. Old aliases still work
but you need to use `old-alias` instead of `alias`.

Instead of replacing spans in the original code and re-parsing, which
proved to be extremely error-prone and a constant source of panics, the
new implementation creates a new command that references the old
command. Consider the new alias defined as `alias ll = ls -l`. The
parser creates a new command called `ll` and remembers that it is
actually a `ls` command called with the `-l` flag. Then, when the parser
sees the `ll` command, it will translate it to `ls -l` and passes to it
any parameters that were passed to the call to `ll`. It works quite
similar to how known externals defined with `extern` are implemented.

The new alias implementation should work the same way as the old
aliases, including exporting from modules, referencing both known and
unknown externals. It seems to preserve custom completions and pipeline
metadata. It is quite robust in most cases but there are some rough
edges (see later).

Fixes https://github.com/nushell/nushell/issues/7648,
https://github.com/nushell/nushell/issues/8026,
https://github.com/nushell/nushell/issues/7512,
https://github.com/nushell/nushell/issues/5780,
https://github.com/nushell/nushell/issues/7754

No effect: https://github.com/nushell/nushell/issues/8122 (we might
revisit the completions code after this PR)

Should use custom command instead:
https://github.com/nushell/nushell/issues/6048

# User-Facing Changes

Since aliases are now basically commands, it has some new implications:

1. `alias spam = "spam"` (requires command call)
	* **workaround**: use `alias spam = echo "spam"`
2. `def foo [] { 'foo' }; alias foo = ls -l` (foo defined more than
once)
* **workaround**: use different name (commands also have this
limitation)
4. `alias ls = (ls | sort-by type name -i)`
* **workaround**: Use custom command. _The common issue with this is
that it is currently not easy to pass flags through custom commands and
command referencing itself will lead to stack overflow. Both of these
issues are meant to be addressed._
5. TODO: Help messages, `which` command, `$nu.scope.aliases`, etc.
* Should we treat the aliases as commands or should they be separated
from regular commands?
6. Needs better error message and syntax highlight for recursed alias
(`alias f = f`)
7. Can't create alias with the same name as existing command (`alias ls
= ls -a`)
	* Might be possible to add support for it (not 100% sure)
8. Standalone `alias` doesn't list aliases anymore
9. Can't alias parser keywords (e.g., stuff like `alias ou = overlay
use` won't work)
	* TODO: Needs a better error message when attempting to do so

# 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.
2023-02-27 20:44:05 +13:00
alesito85
7c285750c7
Fixes autocomplete when using sudo (#8094)
# Description

This PR addresses issue #2047 in order to enable autocomplete
functionality when using sudo for executing commands. I'e done a couple
of auxiliary checks such as ignoring whitespace and the last pipe in
order to determine the last command.

# User-Facing Changes

The only user facing change should be the autocomplete working.

# Tests + Formatting

All tests and formatting pass.

# Screenshots

<img width="454" alt="image"
src="https://user-images.githubusercontent.com/4399118/219404037-6cce4358-68a9-42bb-a09b-2986b10fa6cc.png">

# Suggestions welcome

I still don't know the in's and out's if nushell very well, any
suggestions for improvements are welcome.
2023-02-24 15:05:36 -08:00
David Matos
42f0b55de0
allow Range to expand to array-like when converting to json (#8047)
# Description
Fixes #8002, which expands ranges `1..3` to expand to array-like when
saving and converting to json. Now,

```
> 1..3 | save foo.json
# foo.json
[
    1,
    2,
    3
]


> 1..3 | to json
[
    1,
    2,
    3
]
```
# 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:

- [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

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-02-24 15:31:33 -06:00
Ryan Devenney
b572b4ecbd
remove links to ShellError and ParseError docs - #8167 (#8193)
# Description

issue #8167

Remove the `(link)` to the docs for `ShellError` and `ParseError`. As
per discussion on the issue, the nu-parser version didn't update on the
docs causing deadlinks for those errors, which brought the usefullness
of these links into question and it was decided to remove all of them
that `derive(diagnostic)`.

# User-Facing Changes
Before:
```
/home/rdevenney/projects/open_source/nushell〉ls | get name}
Error: nu::parser::unbalanced_delimiter (link)

  × Unbalanced delimiter.
   ╭─[entry #1:1:1]
 1 │ ls | get name}
   ·              ▲
   ·              ╰── unbalanced { and }
   ╰────
```

After:
```
/home/rdevenney/projects/open_source/nushell〉ls | get name}
Error: nu::parser::unbalanced_delimiter

  × Unbalanced delimiter.
   ╭─[entry #1:1:1]
 1 │ ls | get name}
   ·              ▲
   ·              ╰── unbalanced { and }
   ╰────
```

# 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.
2023-02-24 09:26:31 -08:00
Artemiy
e389e51b2b
Display empty records and lists (#7925)
# Description

Fix some issues related to #7444 
1. Empty lists and records are now displayed as a small notice in a box:

![image](https://user-images.githubusercontent.com/17511668/215832023-3f8d743a-2899-416f-9109-7876ad2bbedf.png)

![image](https://user-images.githubusercontent.com/17511668/215832273-c737b8a4-af33-4c16-8dd3-bd4f0fd19b5a.png)
2. Empty records are now correctly displayed if inside of another record
list or table:

![image](https://user-images.githubusercontent.com/17511668/215832597-00f0cebc-a3b6-4ce8-8373-a9340d4c7020.png)

![image](https://user-images.githubusercontent.com/17511668/215832540-ab0e2a14-b8f6-4f47-976c-42003b622ef6.png)
3. Fixed inconsistent coloring of empty list placeholder inside of
lists/tables:

![image](https://user-images.githubusercontent.com/17511668/215832924-813ffe17-e04e-4301-97c3-1bdbccf1825c.png)

![image](https://user-images.githubusercontent.com/17511668/215832963-4765c4cf-3036-4bcc-81e1-ced941fa47cb.png)


# User-Facing Changes

`table` command now displays empty records and lists like a table with
text and correctly displays empty records inside tables and lists.

New behavior of displaying empty lists and records can be disabled using
`table.show_empty` config option.

# 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.
2023-02-22 16:18:33 +00:00
Darren Schroeder
58829e3560
fixes a def parsing bug with a default list (#8096)
# Description

This PR fixes a bug where a default list in a custom command parameter
wasn't being accepted. The reason was because it was comparing specific
types of list like `list<any>` != `list<string>`. So, this PR attempts
to fix that.

### Before

```
> def f [param: list = [one]] { echo $param }
Error: nu::parser::assignment_mismatch (link)

  × Default value wrong type
   ╭─[entry #1:1:1]
 1 │ def f [param: list = [one]] { echo $param }
   ·                      ──┬──
   ·                        ╰── default value not list<any>
   ╰────
```

### After

```
> def f [param: list = [one]] {echo $param}
> f
╭───┬─────╮
│ 0 │ one │
╰───┴─────╯
```

closes #8092 

# 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

# 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-02-22 12:53:11 +00:00
Stefan Holderbach
95ec2fcce7
Update to 0.76.1 version for development (#8161)
# Description

For tracking in `version` for bug reports during development. Might be
used for an urgent hotfix if necessary.
2023-02-21 23:21:39 +00:00
Stefan Holderbach
bc38a6a795
Bump version for 0.76.0 release (#8121)
Before landing:

- [x] `reedline 0.16.0` is out and pinned.
- [x] all fixes and features necessary are landed.

In the meantime:

- [ ] feed the release notes with relevant features and breaking changes
2023-02-21 20:46:29 +00:00
Darren Schroeder
664d8d3573
allow date grouping in group-by (#8084)
# Description

This small change allows tables to be grouped by date. It was previously
failing because nushell didn't know how to represent the date as a
string. This change allows the date to be formatted in rfc3339 format
with subseconds represented as dot milliseconds. This formatted datetime
representation is already understood by nushell.

Now you can do things like 

### Grouping by the exact time
```
> ls | group-by modified | table
╭───────────────────────────────┬────────────────╮
│ 2022-01-07T07:53:44.658-06:00 │ [table 1 row]  │
│ 2022-11-29T08:08:09.411-06:00 │ [table 2 rows] │
│ 2023-02-15T08:23:16.044-06:00 │ [table 5 rows] │
│ 2023-01-04T14:45:08.940-06:00 │ [table 2 rows] │
│ 2022-04-08T08:12:50.295-05:00 │ [table 1 row]  │
│ 2022-09-15T10:11:21.177-05:00 │ [table 1 row]  │
│ 2022-06-22T14:26:56.409-05:00 │ [table 1 row]  │
│ 2023-02-08T09:24:32.774-06:00 │ [table 1 row]  │
│ 2022-05-25T11:57:00.866-05:00 │ [table 2 rows] │
│ 2023-02-15T08:23:16.054-06:00 │ [table 4 rows] │
│ 2023-01-04T14:45:08.970-06:00 │ [table 3 rows] │
│ 2022-08-05T07:14:06.265-05:00 │ [table 1 row]  │
│ 2022-01-07T07:53:44.728-06:00 │ [table 1 row]  │
│ 2023-01-27T09:39:34.351-06:00 │ [table 1 row]  │
│ 2023-02-08T09:24:32.794-06:00 │ [table 1 row]  │
│ 2023-02-15T08:36:26.524-06:00 │ [table 1 row]  │
│ 2023-01-19T12:53:22.033-06:00 │ [table 1 row]  │
╰───────────────────────────────┴────────────────╯
```
### Grouping by only the date (truncating the time componenet to 0)
```
> ls | default "" date | update date {|r| $r.modified | date format '%Y-%m-%d' | into datetime} | group-by date | table
╭───────────────────────────────┬─────────────────╮
│ 2022-01-07T00:00:00.000-06:00 │ [table 2 rows]  │
│ 2022-11-29T00:00:00.000-06:00 │ [table 2 rows]  │
│ 2023-02-15T00:00:00.000-06:00 │ [table 10 rows] │
│ 2023-01-04T00:00:00.000-06:00 │ [table 5 rows]  │
│ 2022-04-08T00:00:00.000-06:00 │ [table 1 row]   │
│ 2022-09-15T00:00:00.000-06:00 │ [table 1 row]   │
│ 2022-06-22T00:00:00.000-06:00 │ [table 1 row]   │
│ 2023-02-08T00:00:00.000-06:00 │ [table 2 rows]  │
│ 2022-05-25T00:00:00.000-06:00 │ [table 2 rows]  │
│ 2022-08-05T00:00:00.000-06:00 │ [table 1 row]   │
│ 2023-01-27T00:00:00.000-06:00 │ [table 1 row]   │
│ 2023-01-19T00:00:00.000-06:00 │ [table 1 row]   │
╰───────────────────────────────┴─────────────────╯
```
### Grouping and Displaying only the date (you could do this before this
PR too)
```
> ls | default "" date | update date {|r| $r.modified | date format '%Y-%m-%d'} | group-by date | table
╭────────────┬─────────────────╮
│ 2022-01-07 │ [table 2 rows]  │
│ 2022-11-29 │ [table 2 rows]  │
│ 2023-02-15 │ [table 10 rows] │
│ 2023-01-04 │ [table 5 rows]  │
│ 2022-04-08 │ [table 1 row]   │
│ 2022-09-15 │ [table 1 row]   │
│ 2022-06-22 │ [table 1 row]   │
│ 2023-02-08 │ [table 2 rows]  │
│ 2022-05-25 │ [table 2 rows]  │
│ 2022-08-05 │ [table 1 row]   │
│ 2023-01-27 │ [table 1 row]   │
│ 2023-01-19 │ [table 1 row]   │
╰────────────┴─────────────────╯
```
### Shows that nushell understands the rfc3339 format
```
> 2022-01-07T07:53:44.658-06:00 | describe 
date
> 2022-01-07T07:53:44.658-06:00 | date format '%Y-%m-%d'
2022-01-07
```
# User-Facing Changes

Related to #8036

# 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.
2023-02-15 19:10:55 +00:00
WindSoilder
8136170431
support multiplication operation on string and list values (#8061)
# Description

As title, I found this feature is useful to me too :)

Closes: #8039

# User-Facing Changes

```
❯ 3 * "ab"
ababab

❯ 3 * [1 2 3]
╭───┬───╮
│ 0 │ 1 │
│ 1 │ 2 │
│ 2 │ 3 │
│ 3 │ 1 │
│ 4 │ 2 │
│ 5 │ 3 │
│ 6 │ 1 │
│ 7 │ 2 │
│ 8 │ 3 │
╰───┴───╯
```

# 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.
2023-02-13 16:35:53 +00:00
Stefan Holderbach
1cd70d7505
Disable auto-benchmark harness for crates (#8057)
# Description

This disables automatic detection of `#[bench]` and other benchmarks
within the crates. Our benchmarks should all live in `benches`

This fixes a problem with criterion flags and should also reduce the
build requirements for `cargo bench` a bit

Taken from https://github.com/nushell/nushell/pull/7952

See:
https://bheisler.github.io/criterion.rs/book/faq.html#cargo-bench-gives-unrecognized-option-errors-for-valid-command-line-options


# User-Facing Changes

None
2023-02-12 22:22:00 +00:00
Jakub Žádník
b0775b3f1e
Fix hidden env vars not being hidden in closures (#8055)
# Description

This one fixes env not being hidden inside closure, reported in the
conversation under https://github.com/nushell/nushell/issues/6593

https://github.com/nushell/nushell/issues/6593
https://github.com/nushell/nushell/issues/7937 still persist. These
seems a bit more involved and might need hidden env tracking also in the
engine state... I'm not yet sure what's causing it.

Also re-enables some env-related tests and removes unused Value clone.

# User-Facing Changes

Just a bugfix

# 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.
2023-02-12 17:48:51 +00:00
Bob Hyman
2894668b3e
Improve error when regex rejects pattern. Resolution of #8037 (#8050)
# Description

Improve error when `str replace <pattern>` detects a problem with
<pattern>.

# User-Facing Changes

New "Incorrect value" error:
```
〉 'C:\Users\kubouch' | str replace 'C:\Users' 'foo'
Error: nu:🐚:incorrect_value (link)

  × Incorrect value.
   ╭─[entry #1:1:1]
 1 │  'C:\Users\kubouch' | str replace 'C:\Users' 'foo'
   ·                                   ─────┬────
   ·                                        ╰── Regex error: Parsing error at position 4: Invalid hex escape
   ╰────
```

We could fruitfully replace some of the current uses of
`ShellError::UnsupportedInput` with this error. 'Incorrect value' is
different from 'wrong type'

# Tests + Formatting

Don't forget to add tests that cover your changes.
* none added / changed.

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

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-02-12 13:25:40 +00:00
Jakub Žádník
58529aa0b2
Benchmark each pipeline element (#7854)
# 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>
2023-02-11 21:35:48 +00:00
Reilly Wood
ddb7e4e179
Check ctrl+c when collecting a RawStream (#8020)
I noticed that `open some_big_file | into binary` cannot be cancelled
with `ctrl+c`.

This small PR fixes that by checking `ctrl+c` in
`RawStream::into_bytes()`, and does the same in
`RawStream::into_string()` for good measure.
2023-02-10 20:23:46 +13:00
Darren Schroeder
c31225fdcf
explain command (#7957)
# Description

The purpose of this PR is to introduce the `inspect` command. A command
that is used to inspect, but not run, a pipeline to ensure everything
looks right. This is meant as a debugging tool. This is some hackery, so
don't laugh. :)

![image](https://user-images.githubusercontent.com/343840/217896776-99c6bece-172c-4d3d-8cec-dda85d37cada.png)
2023-02-09 13:59:38 -06:00
Reilly Wood
16b99ed0ba
Make ++ operator work with strings and binary values (#8017)
This PR makes `++` (the append operator) work with strings and binary
values. Can now do things like:

```bash
〉"a" ++ "b"
ab
〉0x[01 02] ++ 0x[03]
Length: 3 (0x3) bytes | printable whitespace ascii_other non_ascii
00000000:   01 02 03                                             •••
```

Closes #8015.
2023-02-10 07:52:10 +13:00
Artemiy
99aea0c71c
Filesystem commands print --verbose to stderr (#8014)
# Description

Makes `mkdir`, `cp`, `mv` and `rm` return nothing and print info to
stderr:

![image](https://user-images.githubusercontent.com/17511668/217859228-feffa4bc-c22d-45d3-b330-1903f5a4d938.png)
See https://github.com/nushell/nushell/pull/7925#issuecomment-1420861638
and
[discord](https://discord.com/channels/601130461678272522/615329862395101194/1072523941865857055).

# User-Facing Changes

`mkdir`, `cp`, `mv` and `rm` will return nothing and print info to
stderr with `--verbose` flag.

# 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.
2023-02-09 10:29:34 -08:00
Darren Schroeder
023e244958
view span & view files commands (#7989)
# Description

This PR does the following:
1. Adds a new command called `view span` - which shows what is at the
location of the span parameters
2. Adds a new command called `view` - which just lists all the `view`
commands.
3. Renames `view-source` to `view source`.
4. Adds a new command called `view files` - which shows you what files
are loaded into nushell's EngineState memory.
5. Added a `Category::Debug` and put these commands (and others) into
it. (`inspect` needs to be added to it, but it's not landed yet)

Spans are important to nushell. One of their uses is to show where
errors are. For instance, in this example, the leader lines pointing to
parts of the command line are able to point to `10`, `/`, and `"bob"`
because each of those items have a span.
```
> 10 / "bob"
Error: nu::parser::unsupported_operation (link)

  × Types mismatched for operation.
   ╭─[entry #8:1:1]
 1 │ 10 / "bob"
   · ─┬ ┬ ──┬──
   ·  │ │   ╰── string
   ·  │ ╰── doesn't support these values.
   ·  ╰── int
   ╰────
  help: Change int or string to be the right types and try again.
```


# Examples

## view span
Example:
```
> $env.config | get keybindings | first | debug -r
... bunch of stuff
                    span: Span {
                        start: 68065,
                        end: 68090,
                    },
                },
            ],
            span: Span {
                start: 68050,
                end: 68101,
            },
        },
    ],
    span: Span {
        start: 67927,
        end: 68108,
    },
}
```
To view the last span:
```
> view span 67927 68108 
{
        name: clear_everything
        modifier: control
        keycode: char_l
        mode: emacs
        event: [
            { send: clearscrollback }
        ]
    }
```
> To view the 2nd to last span:
```
view span 68065 68090
{ send: clearscrollback }
```
> To view the 3rd to last span:
```
view span 68050 68101
[
            { send: clearscrollback }
        ]
```

## view files
```
> view files  
╭────┬───────────────────────────────────────────────────────┬────────┬────────┬───────╮
│  # │                       filename                        │ start  │  end   │ size  │
├────┼───────────────────────────────────────────────────────┼────────┼────────┼───────┤
│  0 │ source                                                │      0 │      2 │     2 │
│  1 │ Host Environment Variables                            │      2 │   6034 │  6032 │
│  2 │ C:\Users\a_username\AppData\Roaming\nushell\plugin.nu │   6034 │  31236 │ 25202 │
│  3 │ C:\Users\a_username\AppData\Roaming\nushell\env.nu    │  31236 │  44961 │ 13725 │
│  4 │ C:\Users\a_username\AppData\Roaming\nushell\config.nu │  44961 │  76134 │ 31173 │
│  5 │ defs.nu                                               │  76134 │  91944 │ 15810 │
│  6 │ prompt\oh-my.nu                                       │  91944 │ 111523 │ 19579 │
│  7 │ weather\get-weather.nu                                │ 111523 │ 125556 │ 14033 │
│  8 │ .zoxide.nu                                            │ 125556 │ 127504 │  1948 │
│  9 │ source                                                │ 127504 │ 127561 │    57 │
│ 10 │ entry #1                                              │ 127561 │ 127585 │    24 │
│ 11 │ entry #2                                              │ 127585 │ 127595 │    10 │
╰────┴───────────────────────────────────────────────────────┴────────┴────────┴───────╯
```
`entry #x` will be each command you type in the repl (i think). so, it
may be good to filter those out sometimes.
```
> view files | where filename !~ entry
╭───┬───────────────────────────────────────────────────────┬────────┬────────┬───────╮
│ # │                       filename                        │ start  │  end   │ size  │
├───┼───────────────────────────────────────────────────────┼────────┼────────┼───────┤
│ 0 │ source                                                │      0 │      2 │     2 │
│ 1 │ Host Environment Variables                            │      2 │   6034 │  6032 │
│ 2 │ C:\Users\a_username\AppData\Roaming\nushell\plugin.nu │   6034 │  31236 │ 25202 │
│ 3 │ C:\Users\a_username\AppData\Roaming\nushell\env.nu    │  31236 │  44961 │ 13725 │
│ 4 │ C:\Users\a_username\AppData\Roaming\nushell\config.nu │  44961 │  76134 │ 31173 │
│ 5 │ defs.nu                                               │  76134 │  91944 │ 15810 │
│ 6 │ prompt\oh-my.nu                                       │  91944 │ 111523 │ 19579 │
│ 7 │ weather\get-weather.nu                                │ 111523 │ 125556 │ 14033 │
│ 8 │ .zoxide.nu                                            │ 125556 │ 127504 │  1948 │
│ 9 │ source                                                │ 127504 │ 127561 │    57 │
╰───┴───────────────────────────────────────────────────────┴────────┴────────┴───────╯
```
# User-Facing Changes

I renamed `view-source` to `view source` just to make a group of
commands. No functionality has changed in `view source`.

# 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.
2023-02-09 11:35:23 -06:00
Darren Schroeder
f4bf7316fe
fix completions PATH vs Path (#8003)
# Description

This PR attempts to fix the completions issue where, on Windows,
completions wouldn't get generated from items in your path environment
variable. This seemed to be down to `PATH` vs `Path`. So, I tried to add
a new function that we can use anywhere to avoid this problem.

# 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.
2023-02-08 20:53:46 -06:00
WindSoilder
055edd886d
Make plugin commands support examples. (#7984)
# Description

As title, we can't provide examples for plugin commands, this pr would
make it possible


# User-Facing Changes

Take plugin `nu-example-1` as example:
```
❯ nu-example-1 -h
PluginSignature test 1 for plugin. Returns Value::Nothing

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

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

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

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

The examples session is newly added.

## Basic idea behind these changes
when nushell query plugin signatures, plugin just returns it's signature
without any examples, so nushell have no idea about the examples of
plugin commands.
To adding the feature, we just making plugin returns it's signature with
examples.

Before:
```
        1. get signature
         ----------------> 
Nushell ------------------  Plugin
        <-----------------
        2. returns Vec<Signature>
```

After:
```
        1. get signature
        ----------------> 
Nushell ------------------  Plugin
        <-----------------
        2. returns Vec<PluginSignature>
```
        
When writing plugin signature to $nu.plugin-path:
Serialize `<PluginSignature>` rather than `<Signature>`, which would
enable us to serialize examples to `$nu.plugin-path`

## Shortcoming
It's a breaking changes because `Plugin::signature` is changed, and it
requires plugin authors to change their code for new signatures.

Fortunally it should be easy to change, for rust based plugin, we just
need to make a global replace from word `Signature` to word
`PluginSignature` in their plugin project.

Our content of plugin-path is really large, if one plugin have many
examples, it'd results to larger body of $nu.plugin-path, which is not
really scale. A solution would be save register information in other
binary formats rather than `json`. But I think it'd be another story.

# 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.
2023-02-08 16:14:18 -06:00
Darren Schroeder
66e5e42fb1
report which datetime couldn't be converted (#7980)
# Description

This PR will help report a bad date that can't be converted where the
error message says `* Unable to parse datetime`. This is helpful when
you're converting a big table and it fails somewhere that you really
can't see. I put it in `[]` so that when it's null, you can see that
there should be something there.

Before:
```
> 'Tue 1 0' | into datetime 
Error: nu:🐚:datetime_parse_error (link)

  × Unable to parse datetime
   ╭─[entry #1:1:1]
 1 │ 'Tue 1 0' | into datetime
   · ────┬────
   ·     ╰── datetime parsing failed
   ╰────
  help: Examples of supported inputs:
         * "5 pm"
         * "2020/12/4"
         * "2020.12.04 22:10 +2"
         * "2020-04-12 22:10:57 +02:00"
         * "2020-04-12T22:10:57.213231+02:00"
         * "Tue, 1 Jul 2003 10:52:37 +0200"
```
After:
```
> 'Tue 1 0' | into datetime
Error: nu:🐚:datetime_parse_error (link)

  × Unable to parse datetime: [Tue 1 0].
   ╭─[entry #4:1:1]
 1 │ 'Tue 1 0' | into datetime
   · ────┬────
   ·     ╰── datetime parsing failed
   ╰────
  help: Examples of supported inputs:
         * "5 pm"
         * "2020/12/4"
         * "2020.12.04 22:10 +2"
         * "2020-04-12 22:10:57 +02:00"
         * "2020-04-12T22:10:57.213231+02:00"
         * "Tue, 1 Jul 2003 10:52:37 +0200"
```

# User-Facing Changes

New format for the error message.

# 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.
2023-02-06 14:17:07 -06:00
Leon
e89e734ca2
Only abbreviate to "[table x rows]" if every value is a record (#7922)
# Description

Closes #6768.

BEFORE:
```
〉{ foo: [{a:1, b:2},2,3,4,5] }
╭─────┬────────────────╮
│ foo │ [table 5 rows] │
╰─────┴────────────────╯
```
AFTER:
```
〉{ foo: [{a:1, b:2},2,3,4,5] }
╭─────┬────────────────╮
│ foo │ [list 5 items] │
╰─────┴────────────────╯
```

# 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.
2023-02-02 17:03:36 -06:00
Stefan Holderbach
5e957ecda6
Bump to 0.75.1 development version (#7930)
To demark development work or to be used with a point release in an
emergency
2023-01-31 23:55:29 +01:00
Stefan Holderbach
17a265b197
Version bump for 0.75 release (#7902)
- [x] Are we ready for the release
- [x] Upgrade to upcoming `reedline 0.15`
2023-01-31 21:00:59 +01:00
dependabot[bot]
c6eea5de6b
Bump typetag from 0.1.8 to 0.2.5 (#7908) 2023-01-30 02:46:31 +00:00
Stefan Holderbach
ab480856a5
Use variable names directly in the format strings (#7906)
# 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`)
2023-01-29 19:37:54 -06:00
Reilly Wood
f4d7d19370
Name threads (#7879)
I noticed that [it's pretty easy to name threads in
Rust](https://doc.rust-lang.org/std/thread/#naming-threads). We might as
well do this; it's a nice quality of life improvement when you're
profiling something and the developers took the time to give threads
names.

Also added/cleaned up some comments while I was in the area.
2023-01-28 21:40:52 +01:00
Jakub Žádník
2a39332d51
Fix panic when assigning value to $env (#7894) 2023-01-28 21:17:32 +02:00
Reilly Wood
9ae2e528c5
Remove 🆖 comments (#7877)
Noticed several instances of commented out code that should just be
deleted. Also a comment on `eval_external` that was incorrect. All gone
now.
2023-01-27 08:48:31 -05:00
Darren Schroeder
9d0e52b94d
with the release of rust 1.67, let's bump to 1.66.1 (#7866)
# Description

This PR bumps the required rust version to 1.66.1.

# 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

# 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-01-26 15:31:17 -06:00
pwygab
f9e99048c4
convert SyntaxShape::Table into the corresponding Type (#7781)
# Description

Small fix. Related: #7699.

# 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

# 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-01-25 16:17:41 -06:00
Darren Schroeder
e03c354e89
add decimal to SyntaxShape (#7852)
# Description

This adds the `SyntaxShape::Decimal` so you can create custom commands
with `decimal` types such as:
```shell
def cmd [x:decimal] { echo $x }
```

/cc @kurokirasama

Internally this is a little messy since we have `Type::Float` and
`SyntaxShape::Decimal`. I originally named it `float` and
`SyntaxShape::Float` but since we have `into decimal` and `1.1 |
describe` reports `decimal`, I decided to change the SyntaxShape.

# 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.
2023-01-25 06:43:22 -06:00
Hofer-Julian
41306aa7e0
Reduce again the number of match calls (#7815)
- Reduce the number of match calls (see commit messages)
- A few miscellaneous improvements
2023-01-24 12:23:42 +01:00
dependabot[bot]
bef397228f
Bump miette from 5.3.0 to 5.5.0 (#7838) 2023-01-23 01:56:28 +00:00
Jakub Žádník
ba12b0de0d
Fix command name lookup for known externals (#7830)
Fixes https://github.com/nushell/nushell/issues/7822
2023-01-22 21:40:18 +02:00
Jakub Žádník
3552d03f6c
Allow main command to define top-level module command (#7764) 2023-01-22 21:34:15 +02:00
Hofer-Julian
2d98d0fcc2
Extract manual PWD extraction with method current_work_dir (#7812) 2023-01-21 15:44:17 +02:00
Reilly Wood
3b5172a8fa
LazyRecord (#7619)
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)
2023-01-18 19:27:26 -08:00
Justin Ma
f823c7cb5d
fix some typos (#7773)
# Description

Nothing changed, just fix some typos

# 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: Stefan Holderbach <sholderbach@users.noreply.github.com>
2023-01-16 12:43:46 +01:00
Artemiy
a909c60f05
Ansi link (#7751) 2023-01-15 17:23:37 +02:00
Anton
7221eb7f39
Fix typos and use more idiomatic assertions (#7755)
I have changed `assert!(a == b)` calls to `assert_eq!(a, b)`, which give
better error messages. Similarly for `assert!(a != b)` and
`assert_ne!(a, b)`. Basically all instances were comparing primitives
(string slices or integers), so there is no loss of generality from
special-case macros,

I have also fixed a number of typos in comments, variable names, and a
few user-facing messages.
2023-01-15 15:03:32 +13:00
Darren Schroeder
b0b0482d71
Add cursor shape configuration for each edit mode (#7745)
# Description

This PR allows the configuration of cursor shapes in nushell for each
edit mode. This is the change that is in the default_config.nu file.
```
  cursor_shape: {
    emacs: line # block, underscore, line (line is the default)
    vi_insert: block # block, underscore, line (block is the default)
    vi_normal: underscore # block, underscore, line  (underscore is the default)
  }
```

# User-Facing Changes

See above. If you'd prefer a different default, please speak up and let
us know.

# 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.
2023-01-13 14:37:39 -06:00
WindSoilder
8aa2632661
Support redirect err and out to different streams (#7685)
# Description

Closes: #7364 

# User-Facing Changes

Given the following shell script:
```bash
x=$(printf '=%.0s' {1..100})
echo $x
echo $x 1>&2
```

It supports the following command:
```
bash test.sh out> out.txt err> err.txt
```

Then both `out.txt` and `err.txt` will contain `=`(100 times)

## About the change

The core idea is that when doing lite-parsing, introduce a new variant
`LiteElement::SeparateRedirection` if we meet two Redirection
token(which is generated by `lex` function),
During converting from lite block to block,
`LiteElement::SeparateRedirection` will be converted to
`PipelineElement::SeparateRedirection`.

Then in the block eval process, if we get
`PipelineElement::SeparateRedirection`, we invoke `save` command with
`--stderr` arguments to acthive our behavior.



## What happened internally?
Take the following command as example:
```
^ls out> out.txt err> err.txt
```

lex parsing result(`Tokens`) are not changed, but `LiteBlock` and
`Block` is changed after this pr.

### LiteBlock before
```rust
LiteBlock {
    block: [
        LitePipeline { commands: [
            Command(None, LiteCommand { comments: [], parts: [Span { start: 39041, end: 39044 }] }),
            // actually the span of first Redirection is wrong too..
            Redirection(Span { start: 39058, end: 39062 }, Stdout, LiteCommand { comments: [], parts: [Span { start: 39050, end: 39057 }] }),
            Redirection(Span { start: 39058, end: 39062 }, Stderr, LiteCommand { comments: [], parts: [Span { start: 39063, end: 39070 }] })
        ]
    }]
}
```
### LiteBlock after
```rust
LiteBlock {
    block: [
        LitePipeline { commands: [
            Command(
                None, 
                LiteCommand { comments: [], parts: [Span { start: 38525, end: 38528 }] }),
                // new one! two Redirection merged into one SeparateRedirection.
                SeparateRedirection { 
                    out: (Span { start: 38529, end: 38533 }, LiteCommand { comments: [], parts: [Span { start: 38534, end: 38541 }] }),
                    err: (Span { start: 38542, end: 38546 }, LiteCommand { comments: [], parts: [Span { start: 38547, end: 38554 }] })
                }
        ]
    }]
}
```

### Block before
```rust
Pipeline {
    elements: [
        Expression(None, Expression {
            expr: ExternalCall(Expression { expr: String("ls"), span: Span { start: 39042, end: 39044 }, ty: String, custom_completion: None }, [], false),
            span: Span { start: 39041, end: 39044 },
            ty: Any, custom_completion: None 
        }),
        Redirection(Span { start: 39058, end: 39062 }, Stdout, Expression { expr: String("out.txt"), span: Span { start: 39050, end: 39057 }, ty: String, custom_completion: None }),
        Redirection(Span { start: 39058, end: 39062 }, Stderr, Expression { expr: String("err.txt"), span: Span { start: 39063, end: 39070 }, ty: String, custom_completion: None })] }
```

### Block after
```rust
Pipeline {
    elements: [
        Expression(None, Expression {
            expr: ExternalCall(Expression { expr: String("ls"), span: Span { start: 38526, end: 38528 }, ty: String, custom_completion: None }, [], false),
            span: Span { start: 38525, end: 38528 },
            ty: Any,
            custom_completion: None 
        }),
        // new one! SeparateRedirection
        SeparateRedirection {
            out: (Span { start: 38529, end: 38533 }, Expression { expr: String("out.txt"), span: Span { start: 38534, end: 38541 }, ty: String, custom_completion: None }),
            err: (Span { start: 38542, end: 38546 }, Expression { expr: String("err.txt"), span: Span { start: 38547, end: 38554 }, ty: String, custom_completion: 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

# 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-01-12 10:22:30 +01:00
Stefan Holderbach
1ae9157985
Bump to 0.74.1 development version (#7721)
# Description

May be used for hotfix if needed
2023-01-11 22:30:41 +01:00
Xoffio
82ac590412
Progress bar Implementation (#7661)
# Description

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

I implemented the status bar we talk about yesterday. The idea was
inspired by the progress bar of `wget`.
I decided to go for the second suggestion by `@Reilly`
> 2. add an Option<usize> or whatever to RawStream (and ListStream?) for
situations where you do know the length ahead of time

For now only works with the command `save` but after the approve of this
PR we can see how we can implement it on commands like `cp` and `mv`

When using `fetch` nushell will check if there is any `content-length`
attribute in the request header. If so, then `fetch` will send it
through the new `Option` variable in the `RawStream` to the `save`.
If we know the total size we show the progress bar 

![nu_pb01](https://user-images.githubusercontent.com/38369407/210298647-07ee55ea-e751-41b1-a84d-f72ec1f6e9e5.jpg)
but if we don't then we just show the stats like: data already saved,
bytes per second, and time lapse.

![nu_pb02](https://user-images.githubusercontent.com/38369407/210298698-1ef65f51-40cc-4481-83de-309cbd1049cb.jpg)

![nu_pb03](https://user-images.githubusercontent.com/38369407/210298701-eef2ef13-9206-4a98-8202-e4fe5531d79d.jpg)

Please let me know If I need to make any changes and I will be happy to
do it.

# User-Facing Changes

A new flag (`--progress` `-p`) was added to the `save` command 
Examples:
```nu
fetch https://github.com/torvalds/linux/archive/refs/heads/master.zip | save --progress -f main.zip
fetch https://releases.ubuntu.com/22.04.1/ubuntu-22.04.1-desktop-amd64.iso | save --progress -f main.zip
open main.zip --raw | save --progress main.copy
```

# 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
-
I am getting some errors and its weird because the errors are showing up
in files i haven't touch. Is this normal?

# 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: Reilly Wood <reilly.wood@icloud.com>
2023-01-10 20:57:48 -05:00
Stefan Holderbach
8044fb2db0
Bump version to 0.74.0 (#7718)
Preparing the release
2023-01-10 20:58:13 +01:00
Stefan Holderbach
cef05d3553
Fix line-end trimming in subexpression (#7543)
# Description

Currently the implementation is different for Windows and Unix.

Thus certain operations will fail if the platform foreign line ending is
used:

example failing under windows

```
git show (git merge-base main HEAD)
```

Temporary cheat is to strip all `\r` and `\n` from the end. Proper
solution should trim them as correct patterns.

Also needed: test of behavior with both platform newline and
platform-foreign line endings

cc @WindSoilder 


# User-Facing Changes

Line endings should be trimmed no matter the source and no matter the
platform

# Tests + Formatting

Still missing
2023-01-08 22:51:51 +01:00
Michael Angerman
95cd9dd2b2
move BufferedReader out of nu-command (#7697)
src/main.rs has a dependency on BufferedReader
which is currently located in nu_command.

I am moving BufferedReader to a more relevant
location (crate) which will allow / eliminate main's dependency
on nu_command in a benchmark / testing environment...

now that @rgwood  has landed benches I want
to start experimenting with benchmarks related
to the parser.

For benchmark purposes when dealing with parsing
you need a very simple set of commands that show
how well the parser is doing, in other words
just the core commands... Not all of nu_command...

Having a smaller nu binary when running the benchmark CI
would enable building nushell quickly, yet still show us
how well the parser is performing...

Once this PR lands the only dependency main will have
on nu_command is create_default_context ---
meaning for benchmark purposes we can swap in a tiny
crate of commands instead of the gigantic nu_command
which has its "own" create_default_context...

It will also enable other crates going forward to
use BufferedReader.  Right now it is not accessible
to other lower level crates because it is located in a
"top of the stack crate".
2023-01-06 15:22:17 -08:00
Amirhossein Akhlaghpour
00469de93e
Limit recursion to avoid stack overflow (#7657)
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>
2023-01-04 18:38:50 -08:00
Leon
65d0b5b9d9
Make get hole errors and cell path hole errors identical (improvement on #7002) (#7647)
# 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.
2023-01-02 14:45:43 -08:00
Reilly Wood
27b06358ea
Tweak new input type error message (#7646)
A tiny follow-up from https://github.com/nushell/nushell/pull/7623,
changes "Only supports for specific input types" to "Input type not
supported"

Before:

```
〉"asdf" | append "foo"
Error: nu:🐚:only_supports_this_input_type (link)

  × Only supports for specific input types.
   ╭─[entry #2:1:1]
 1 │ "asdf" | append "foo"
   · ───┬──   ───┬──
   ·    │        ╰── only list, binary, raw data or range input data is supported
   ·    ╰── input type: string
   ╰────
```
   
After:
```
〉"asdf" | append "foo"
Error: nu:🐚:only_supports_this_input_type (link)

  × Input type not supported.
   ╭─[entry #2:1:1]
 1 │ "asdf" | append "foo"
   · ───┬──   ───┬──
   ·    │        ╰── only list, binary, raw data or range input data is supported
   ·    ╰── input type: string
   ╰────
```
2022-12-31 21:56:59 -08:00
WindSoilder
e9cc417fd5
last, skip, drop, take until, take while, skip until, skip while, where, reverse, shuffle, append, prepend and sort-by raise error when given non-lists (#7623)
Closes https://github.com/nushell/nushell/issues/6941
2022-12-31 13:35:12 +02:00
Jakub Žádník
8bfcea8054
Expand Nushell's help system (#7611) 2022-12-30 17:44:37 +02:00
Kian-Meng Ang
79000aa5e0
Fix typos by codespell (#7600)
# Description

Found via `codespell -S target -L
crate,ser,numer,falsy,ro,te,nd,bu,ndoes,statics,ons,fo,rouge,pard`

# User-Facing Changes

None.

# Tests + Formatting

None and done.

# After Submitting

None.
2022-12-26 02:31:26 -05:00
Stefan Holderbach
45fe3be83e
Further cleanup of Span::test_data usage + span fixes (#7595)
# 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
2022-12-24 07:41:57 -06:00
Leon
11bdab7e61
Change instances of Value::string("foo", Span::test_data()) to Value::test_string("foo") (#7592) 2022-12-24 10:25:38 +01:00
Reilly Wood
a43e66ef92
Add LRU regex cache (#7587)
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.
2022-12-23 14:30:04 -08:00
Leon
dd7b7311b3
Standardise the use of ShellError::UnsupportedInput and ShellError::TypeMismatch and add spans to every instance of the former (#7217)
# Description

* I was dismayed to discover recently that UnsupportedInput and
TypeMismatch are used *extremely* inconsistently across the codebase.
UnsupportedInput is sometimes used for input type-checks (as per the
name!!), but *also* used for argument type-checks. TypeMismatch is also
used for both.
I thus devised the following standard: input type-checking *only* uses
UnsupportedInput, and argument type-checking *only* uses TypeMismatch.
Moreover, to differentiate them, UnsupportedInput now has *two* error
arrows (spans), one pointing at the command and the other at the input
origin, while TypeMismatch only has the one (because the command should
always be nearby)
* In order to apply that standard, a very large number of
UnsupportedInput uses were changed so that the input's span could be
retrieved and delivered to it.
* Additionally, I noticed many places where **errors are not propagated
correctly**: there are lots of `match` sites which take a Value::Error,
then throw it away and replace it with a new Value::Error with
less/misleading information (such as reporting the error as an
"incorrect type"). I believe that the earliest errors are the most
important, and should always be propagated where possible.
* Also, to standardise one broad subset of UnsupportedInput error
messages, who all used slightly different wordings of "expected
`<type>`, got `<type>`", I created OnlySupportsThisInputType as a
variant of it.
* Finally, a bunch of error sites that had "repeated spans" - i.e. where
an error expected two spans, but `call.head` was given for both - were
fixed to use different spans.

# Example
BEFORE
```
〉20b | str starts-with 'a'
Error: nu:🐚:unsupported_input (link)

  × Unsupported input
   ╭─[entry #31:1:1]
 1 │ 20b | str starts-with 'a'
   ·   ┬
   ·   ╰── Input's type is filesize. This command only works with strings.
   ╰────

〉'a' | math cos
Error: nu:🐚:unsupported_input (link)

  × Unsupported input
   ╭─[entry #33:1:1]
 1 │ 'a' | math cos
   · ─┬─
   ·  ╰── Only numerical values are supported, input type: String
   ╰────

〉0x[12] | encode utf8
Error: nu:🐚:unsupported_input (link)

  × Unsupported input
   ╭─[entry #38:1:1]
 1 │ 0x[12] | encode utf8
   ·          ───┬──
   ·             ╰── non-string input
   ╰────
```
AFTER
```
〉20b | str starts-with 'a'
Error: nu:🐚:pipeline_mismatch (link)

  × Pipeline mismatch.
   ╭─[entry #1:1:1]
 1 │ 20b | str starts-with 'a'
   ·   ┬   ───────┬───────
   ·   │          ╰── only string input data is supported
   ·   ╰── input type: filesize
   ╰────

〉'a' | math cos
Error: nu:🐚:pipeline_mismatch (link)

  × Pipeline mismatch.
   ╭─[entry #2:1:1]
 1 │ 'a' | math cos
   · ─┬─   ────┬───
   ·  │        ╰── only numeric input data is supported
   ·  ╰── input type: string
   ╰────

〉0x[12] | encode utf8
Error: nu:🐚:pipeline_mismatch (link)

  × Pipeline mismatch.
   ╭─[entry #3:1:1]
 1 │ 0x[12] | encode utf8
   · ───┬──   ───┬──
   ·    │        ╰── only string input data is supported
   ·    ╰── input type: binary
   ╰────
```

# User-Facing Changes

Various error messages suddenly make more sense (i.e. have two arrows
instead of one).

# 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.
2022-12-23 01:48:53 -05:00