Commit Graph

845 Commits

Author SHA1 Message Date
mike
d9a888528a
fix unhelpful error message with '@' custom completion (#8620)
# Description

with such a line 
```nu
extern err [--flag: string@]
```
this pr changes the error message from
```nu
Error: nu::parser::unknown_command

  × Unknown command.
   ╭─[entry #69:1:1]
 1 │ extern err [--flag: string@]
   ·                            ▲
   ·                            ╰── unknown command
   ╰────
```
to
```nu
Error: nu::parser::parse_mismatch

  × Parse mismatch during operation.
   ╭─[entry #69:1:1]
 1 │ extern err [--flag: string@]
   ·                            ▲
   ·                            ╰── expected command name
   ╰────
```
2023-03-26 10:58:33 +02: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
mike
744a28b31d
type-check default values of list annotations (#8600)
# Description

@fdncred noticed an
[issue](https://github.com/nushell/nushell/pull/8529#issuecomment-1482770636)
with list annotations that while i was trying to find a fix found
another issue.

innitially, this was accepted by the parser
```nu
def err [list: list<int> = ['a' 'b' 'c']] {}
```

but now an error is raised
```nu
Error: nu::parser::assignment_mismatch

  × Default value wrong type
   ╭─[entry #1:1:1]
 1 │ def err [list: list<int> = ['a' 'b' 'c']] {}
   ·                            ──────┬────
   ·                                   ╰── expected default value to be `list<int>`
   ╰────
```

# User-Facing Changes

none

# Tests + Formatting

done
2023-03-25 08:57:18 +13:00
mike
8cf9bc9993
allow lists to have type annotations (#8529)
this pr refines #8270 and closes #8109

# description
examples:

the original syntax is okay
```nu
def okay [nums: list] {}         # the type of list will be list<any>
```

empty annotations are allowed in any variation
the last two may be caught by a future formatter, 
but do not affect `nu` code currently
```nu
def okay [nums: list<>] {}       # okay

def okay [nums: list<     >] {}  # weird but also okay

def okay [nums: list<
>] {}                            # also weird but okay
```

types are allowed (See [notes](#notes) below)
```nu
def okay [nums: list<int>] {}    # `test [a b c]` will throw an error 

def okay [nums: list< int > {}   # any amount of space within the angle brackets is okay

def err [nums: list <int>] {}    # this is not okay, `nums` and `<int>` will be parsed as
                                 # two separate params, 
```

nested annotations are allowed in many variations
```nu
def okay [items: list<list<int>>] {}

def okay [items: list<list>] {}
```

any unterminated annotation is caught
```nu
Error: nu::parser::unexpected_eof

  × Unexpected end of code.
   ╭─[source:1:1]
 1 │ def err [nums: list<int] {}
   ·                       ▲
   ·                       ╰── expected closing >
   ╰────
```

unknown types are flagged
```nu
Error: nu::parser::unknown_type

  × Unknown type.
   ╭─[source:1:1]
 1 │ def err [nums: list<str>] {}
   ·                     ─┬─
   ·                      ╰── unknown type
   ╰────

Error: nu::parser::unknown_type

  × Unknown type.
   ╭─[source:1:1]
 1 │ def err [nums: list<int, string>] {}
   ·                    ─────┬─────
   ·                          ╰── unknown type
   ╰────
```

# notes
the error message for mismatched types in not as intuitive
```nu
Error: nu::parser::parse_mismatch

  × Parse mismatch during operation.
   ╭─[source:1:1]
 1 │ def err [nums: list<int>] {}; err [a b c]
   ·                                    ┬
   ·                                    ╰── expected int
   ╰────
```
it should be something like this
```nu
Error: nu::parser::parse_mismatch

  × Parse mismatch during operation.
   ╭─[source:1:1]
 1 │ def err [nums: list<int>] {}; err [a b c]
   ·                                    ──┬──
   ·                                      ╰── expected list<int>
   ╰────
```
this is currently not implemented
2023-03-24 12:54:06 +01: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
8d5fbc6fcb
Fix closures that use matches. Move 'collect' to core. (#8596)
# Description

Fix patterns in pattern matching to properly declare their variables
when discovering which variables need to be closed over when creating a
closure.

Also, moves `collect` to core, so that the core language can use `$in`.

Fixes #8595 

# 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 22:50:23 +13:00
JT
546c753d1e
Move timeit to use blocks. Make match vars immutable (#8592)
# Description

This does a couple random changes/fixes:

* Moves `timeit` to use a block instead of a closure. This makes it a
bit more flexible.
* Moves var bindings in patterns to be immutable

# User-Facing Changes

`timeit` now takes a block and no arguments.

# 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 17:33:11 +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
Jakub Žádník
c48e9cdf5b
Disable alias recursion (for real) (#8557) 2023-03-22 23:16:06 +02:00
JT
2f8a52d256
Switch let/let-env family to init with math expressions (#8545)
# Description

This is an experiment to see what switching the `let/let-env` family to
math expressions for initialisers would be like.

# User-Facing Changes

This would require any commands you call from `let x = <command here>`
(and similar family) to call the command in parentheses. `let x = (foo)`
to call `foo`.

# Tests + Formatting

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

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

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

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

# After Submitting

If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
2023-03-23 09:14:10 +13:00
WindSoilder
cd6f86052d
better error message if plugin name doesn't starts with nu_plugin_ (#8562)
# Description

Fixes: #8548 

# User-Facing Changes
```
❯ register target/debug/formats
Error:
  × Register plugin failed
   ╭─[entry #1:1:1]
 1 │ register target/debug/formats
   ·          ──────────┬─────────
   ·                    ╰── plugin name must starts with nu_plugin_
   ╰────

```
# 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-22 07:02:28 -05:00
Dan Davison
77e9f8d7df
Short redirection syntax (#8503)
This one's pretty clear from the diff! It's more of a language design
discussion.
2023-03-18 08:57:37 +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
WindSoilder
eb2e2e6370
make else if generate helpful error when condition have an issue (#8274)
# Description

Fixes: #7575

# User-Facing Changes

Previously:
```
if❯ if false { "aaa" } else if $a { 'a' }
Error: nu::parser::parse_mismatch

  × Parse mismatch during operation.
   ╭─[entry #10:1:1]
 1 │ if false { "aaa" } else if $a { 'a' }
   ·                         ─┬
   ·                          ╰── expected block, closure or record
   ╰────

```

After:
```
❯ if false { "aaa" } else if $a { 'a' }
Error: nu::parser::variable_not_found

  × Variable not found.
   ╭─[entry #1:1:1]
 1 │ if false { "aaa" } else if $a { 'a' }
   ·                            ─┬
   ·                             ╰── variable not found
   ╰────

```


# 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 07:37:59 -05:00
WindSoilder
a8eef9af33
Restrict closure expression to be something like {|| ...} (#8290)
# Description

As title, closes: #7921 closes: #8273

# User-Facing Changes

when define a closure without pipe, nushell will raise error for now:
```
❯ let x = {ss ss}
Error: nu::parser::closure_missing_pipe

  × Missing || inside closure
   ╭─[entry #2:1:1]
 1 │ let x = {ss ss}
   ·         ───┬───
   ·            ╰── Parsing as a closure, but || is missing
   ╰────
  help: Try add || to the beginning of closure
```

`any`, `each`, `all`, `where` command accepts closure, it forces user
input closure like `{||`, or parse error will returned.
```
❯ {major:2, minor:1, patch:4} | values | each { into string }
Error: nu::parser::closure_missing_pipe

  × Missing || inside closure
   ╭─[entry #4:1:1]
 1 │ {major:2, minor:1, patch:4} | values | each { into string }
   ·                                             ───────┬───────
   ·                                                    ╰── Parsing as a closure, but || is missing
   ╰────
  help: Try add || to the beginning of closure
```

`with-env`, `do`, `def`, `try` are special, they still remain the same,
although it says that it accepts a closure, but they don't need to be
written like `{||`, it's more likely a block but can capture variable
outside of scope:
```
❯ def test [input] { echo [0 1 2] | do { do { echo $input } } }; test aaa
aaa
```

Just realize that It's a big breaking change, we need to update config
and scripts...

# 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 07:36:28 -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
JT
1552eb921a
parser: Add cell path literal syntax (#8493)
# Description

This adds a new cell path literal syntax for use in any value position,
not just in a context where we expect a cell path.

This can be used to assign to a variable and then later use that
variable as a cell path.

Example:
```
> let cell_path = $.a.b
> {a: {b: 3}} | get $cell_path
3
```
# User-Facing Changes

This adds the syntax `$.a.b` to universally mean the cell path `a.b`,
even in a context that doesn't expect a cell path.

# Tests + Formatting

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

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

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -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 15:19:41 +13:00
JT
0ac3f7a1c8
parser: Fix panic that happens when you type a single { (#8492)
# Description

Fix the recent parser panic with a single `{`

Introduced by https://github.com/nushell/nushell/pull/8470

# 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 15:19:23 +13:00
JT
0903a891e4
Fix parse of def with paren params (#8490)
# Description

This adds back support for parens around params, eg `def foo (x: int) {
... }`

# User-Facing Changes

returns to the original support before the recent parser refactor

# 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 09:08:41 +13:00
JT
222c0f11c3
Escape will now escape paths with '=' in them (#8485)
# Description

Fixes the issue where there is no way to escape `FOO=BAR` in a way that
treats it as a file path/executable name. Previously `^FOO=BAR` would be
handled as an environment shorthand. Now, environment shorthands are not
allowed to start with `^`. To create an environment shorthand value that
uses `^` as the first character of the environment variable name, use
quotes, eg `"^FOO"=BAR`

# User-Facing Changes

This should enable `=` being in paths and external command names in
command position.

# 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:05:08 +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
JT
b0ce602e4b
Start grouping parsing of values better (#8470)
# Description

This starts working on refactoring the parser to no longer use
SyntaxShape when making parsing decisions about values. This PR covers
grouping a few of the steps in `parse_value` to key off the first
character for what group of parsing steps it should use.

# User-Facing Changes

Hopefully 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

> **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-16 16:06:43 +13: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
Jakub Žádník
808e523adc
Disable alias recursion (#8397)
# Description

Prevents alias from aliasing itself. It allows a commonly requested
pattern similar to `alias ls = ls -l`.

One small issue is that the syntax highlighting is a bit off:

![alias_itself_no_color](https://user-images.githubusercontent.com/25571562/224545129-8a3ff535-347b-4a4e-b686-11493bb2a33b.png)

Fixes https://github.com/nushell/nushell/issues/8246

# User-Facing Changes

Shouldn't be a breaking change.

# Tests + Formatting

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

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

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

# 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-13 06:16:26 +13:00
Jakub Žádník
af1ab39851
Allow aliasing parser keywords (#8250) 2023-03-10 23:20:31 +02:00
JT
baddc86d9d
Fix quicktest-found parser crash (#8394)
# Description

Fixes the crash when handing `{}#.}`

# 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-03-11 09:26:14 +13: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
Jérémy Audiger
b9c78a05aa
Resolve Clippy warnings inside tests. (#8315)
# Description

Command: `cargo clippy --workspace --all-targets`

Resolve those warnings:

```
warning: this expression creates a reference which is immediately dereferenced by the compiler
  --> crates/nu-parser/tests/test_parser.rs:86:59
   |
86 |             compare_rhs_binaryOp(test_tag, &expected_val, &observed_val);
   |                                                           ^^^^^^^^^^^^^ help: change this to: `observed_val`
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_borrow
   = note: `#[warn(clippy::needless_borrow)]` on by default

warning: `assert!(false, ..)` should probably be replaced
   --> crates/nu-cli/src/completions/command_completions.rs:319:17
    |
319 |                 assert!(false, "Merge delta has failed: {}", err);
    |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |
    = help: use `panic!(..)` or `unreachable!(..)`
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#assertions_on_constants
    = note: `#[warn(clippy::assertions_on_constants)]` on by default

warning: 1 warning emitted

warning: `assert!(false, ..)` should probably be replaced
   --> crates/nu-cli/src/completions/completer.rs:600:13
    |
600 |             assert!(false, "Error merging delta: {:?}", err);
    |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |
    = help: use `panic!(..)` or `unreachable!(..)`
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#assertions_on_constants

warning: length comparison to zero
   --> crates/nu-cli/src/completions/completer.rs:620:24
    |
620 |             assert_eq!(result.len() > 0, has_result, "line: {}", line);
    |                        ^^^^^^^^^^^^^^^^ help: using `!is_empty` is clearer and more explicit: `!result.is_empty()`
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#len_zero
    = note: `#[warn(clippy::len_zero)]` on by default

warning: equality checks against true are unnecessary
   --> crates/nu-cli/src/completions/completer.rs:632:33
    |
632 |                     .filter(|x| *x == true)
    |                                 ^^^^^^^^^^ help: try simplifying it as shown: `*x`
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#bool_comparison
    = note: `#[warn(clippy::bool_comparison)]` on by default

    Checking nu v0.76.1 (/home/jaudiger/Development/git-repositories/jaudiger/nushell)
warning: 4 warnings emitted

warning: the borrowed expression implements the required traits
  --> crates/nu-command/tests/commands/cp.rs:26:40
   |
26 |         let first_hash = get_file_hash(&test_file.display());
   |                                        ^^^^^^^^^^^^^^^^^^^^ help: change this to: `test_file.display()`
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_borrow
   = note: `#[warn(clippy::needless_borrow)]` on by default

warning: the borrowed expression implements the required traits
   --> crates/nu-command/tests/commands/cp.rs:178:13
    |
178 |             &jonathans_expected_copied_dir
    |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: change this to: `jonathans_expected_copied_dir`
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_borrow

warning: the borrowed expression implements the required traits
   --> crates/nu-command/tests/commands/cp.rs:182:13
    |
182 |             &andres_expected_copied_dir
    |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: change this to: `andres_expected_copied_dir`
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_borrow

warning: the borrowed expression implements the required traits
   --> crates/nu-command/tests/commands/cp.rs:186:13
    |
186 |             &yehudas_expected_copied_dir
    |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: change this to: `yehudas_expected_copied_dir`
    |
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_borrow

warning: 4 warnings emitted
```

# User-Facing Changes

None.

# Tests + Formatting

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

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

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

# 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-04 14:58:20 +01:00
mike
e01eb42e74
fix NotAConstant error help message (#8293)
```
Error: nu::parser::not_a_constant (link)

  × Not a constant.
   ╭─[entry #23:1:1]
 1 │ let file = "/home/user/file"; source $file
   ·                                      ──┬──
   ·                                        ╰── Value is not a parse-time constant
   ╰────
  help: Only a subset of expressions are allowed
        constants during parsing. Try using the 'let'
        command or typing the value literally.
```
this pr changes the help message to 'Try using the `const` command ...'
2023-03-02 19:07:25 -06:00
Jérémy Audiger
a5c604c283
Uniformize usage() and extra_usage() message ending for commands helper. (#8268)
# Description

Working on uniformizing the ending messages regarding methods usage()
and extra_usage(). This is related to the issue
https://github.com/nushell/nushell/issues/5066 after discussing it with
@jntrnr

# User-Facing Changes

None.

# Tests + Formatting

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

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

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

# 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:33:02 -08:00
mike
0a2e711351
fix: allow subtraction of durations from dates (#8247)
`date` - `duration` is
[implemented](ba5258d716/crates/nu-protocol/src/value/mod.rs (L2145))
but the type checker rejects it

this pr fixes that
2023-02-27 21:17:58 +01: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
dependabot[bot]
ffc8e752a5
Bump bytesize from 1.1.0 to 1.2.0 (#8236)
Bumps [bytesize](https://github.com/hyunsik/bytesize) from 1.1.0 to
1.2.0.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/hyunsik/bytesize/releases">bytesize's
releases</a>.</em></p>
<blockquote>
<h2>Release 1.2.0</h2>
<h2>Changes</h2>
<ul>
<li>serde improvements <a
href="https://github-redirect.dependabot.com/hyunsik/bytesize/issues/29">#29</a>
(<a
href="https://github.com/joeroback"><code>@​joeroback</code></a>)</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="476dc867b2"><code>476dc86</code></a>
Remove -dev suffix for release</li>
<li><a
href="eaaf3bc097"><code>eaaf3bc</code></a>
Merge pull request <a
href="https://github-redirect.dependabot.com/hyunsik/bytesize/issues/29">#29</a>
from joeroback/serde_improvements</li>
<li><a
href="c7a785bd2c"><code>c7a785b</code></a>
resolves <a
href="https://github-redirect.dependabot.com/hyunsik/bytesize/issues/27">#27</a>,
fixes several clippy warnings with u16/u8 and is_digit/is_ascii...</li>
<li><a
href="db44636f05"><code>db44636</code></a>
Merge pull request <a
href="https://github-redirect.dependabot.com/hyunsik/bytesize/issues/28">#28</a>
from ileixe/master</li>
<li><a
href="58cf4a5024"><code>58cf4a5</code></a>
Change as_u64() to const</li>
<li><a
href="065c00b54f"><code>065c00b</code></a>
Change the crate version to 1.2.0-dev</li>
<li>See full diff in <a
href="https://github.com/hyunsik/bytesize/compare/v1.1.0...v1.2.0">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=bytesize&package-manager=cargo&previous-version=1.1.0&new-version=1.2.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-02-27 19:48:14 +13: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
Mango The Fourth
d0e0701a88
fix: fix lexing of comments, such that a#b becomes a coherent Item (#8151)
# Description

Previously `nix run nixpkgs#hello` was lexed as `Item, Item, Item,
Comment`, however, `#hello` is *not* supposed to be a comment here and
should be parsed as part of the third `Item`.

This change introduces this behavior by not interrupting the parse of
the current token upon seeing a `#`.

Thank you so much for considering this, I think many `nix` users will be
grateful for this change and I think this will lead to more adaptation
in the ecosystem.

- closes #8137 and #6335 

# User-Facing Changes

- code like `somecode# bla` and `somecode#bla` will not be parsed as
`somecode, comment` but as `somecode#bla`, hence this is a breaking
change for all users who didn't put a space before a comment introducing
token (`#`)

# Tests + Formatting

I've added tests that cover this behavior in `test_lex.rs`

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

I think this is expected behavior in most other shells, so the
documentation was lacking for not documenting the unexpected behavior
before and hence now is automatically more complete >D
2023-02-22 12:59:47 +00:00
Darren Schroeder
e761954cf0
allow different types of lists to be appended (#8157)
# Description

closes #8153

This PR allows different types of lists, like `list<string>` and
`list<any>` to be appended with the `++=` operator.

## Before

```
mut args = [ hello ("hello" | path join world)]
$args ++= [ foo bar ]
Error: nu::parser::type_mismatch (link)

  × Type mismatch during operation.
   ╭─[entry #2:1:1]
 1 │ $args ++= [ foo bar ]
   ·           ─────┬─────
   ·                ╰── expected list<any>, found list<string>
   ╰────
```

## After

```
mut args = [ hello ("hello" | path join world)]
$args ++= [ foo bar ]
$args
╭───┬─────────────╮
│ 0 │ hello       │
│ 1 │ hello\world │
│ 2 │ foo         │
│ 3 │ bar         │
╰───┴─────────────╯
```

# User-Facing Changes

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

# Tests + Formatting

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

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

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

# 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:36 +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
WindSoilder
62652cf8c1
simplify parse_expression function code. (#8149)
# Description

When reading parser code to see how it works, I found that
`parse_expression` function contains some duplicate code about function
call, we can match several values at once to simplify code

# User-Facing Changes

None

# Tests + Formatting

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

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

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

# 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:14:20 +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
JT
ade7bde813
Bare word improvements (#8066)
# Description

This does two fixes for bare words:

* It changes completions for paths to wrap a path with backticks if it
starts with a number. This helps bare words that start with numbers be
separate from unit values
* It allows bare words wrapped with backticks to be the name of a
command. Backtick values in command positions are no longer treated as
strings

# 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-16 02:30:56 +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
Bob Hyman
007916c2c1
Syntax errors for string and int (#7952)
# Description

Added a few syntax errors in ints and strings, changed parser to stop
and show that error rather than continue trying to parse those tokens as
some other shape. However, I don't see how to push this direction much
further, and most of the classic confusing errors can't be changed.

Flagged as WIP for the moment, but passes all checks and works better
than current release:
1. I have yet to figure out how to make these errors refer back to the
book, as I see some other errors do.
2. How to give syntax error when malformed int is first token in line?
Currently parsed as external command, user gets confusing error message.
3. Would like to be more strict with *decimal* int literals (lacking,
e.g, `0x' prefix). Need to tinker more with the order of parse shape
calls, currently, float is tried after int, so '1.4' has to be passed.

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

```bash

〉"\z"
Error: 
   ╭─[entry #3:1:1]
 1 │ "\z"
   ·  ─┬─
   ·   ╰── Syntax error in string, unrecognized character after escape '\'.
   ╰────
```
Canonic presentation of a syntax error.
```bash
〉"  \u{01ffbogus}"
Error: 
  × Invalid syntax
   ╭─[entry #2:1:1]
 1 │ "  \u{01ffbogus}"
   ·    ───────┬──────
   ·           ╰── Syntax error in string, expecting 1 to 6 hex digits in unicode escape '\u{X...}', max value 10FFFF.
   ╰────
```
Malformed unicode escape in string, flagged as error.  
String parse can be opinionated, it's the last shape tried.
```bash
〉0x22bogus
Error: nu:🐚:external_command (link)
  × External command failed
   ╭─[entry #4:1:1]
1 │ 0x22bogus
   · ────┬────
   ·     ╰── executable was not found
   ╰────
  help: No such file or directory (os error 2)
```
A *correct* number in first token would be evaluated, but an *incorrect*
one is treated as external command? Confusing to users.
```bash
〉0 + 0x22bogus
Error: 
  × Invalid syntax
   ╭─[entry #5:1:1]
1 │ 0 + 0x22bogus
   ·     ────┬────
   ·         ╰── Syntax error in int, invalid digits in radix 16 int.
   ╰────
```
Can give syntax error if token is unambiguously int literal. e.g has 0b
or 0x prefix, could not be a float.
```bash
〉0 + 098bogus
Error: nu::parser::unsupported_operation (link)

  × Types mismatched for operation.
   ╭─[entry #6:1:1]
 1 │ 0 + 098bogus
   · ┬ ┬ ────┬───
   · │ │     ╰── string
   · │ ╰── doesn't support these values.
   · ╰── int
   ╰────
  help: Change int or string to be the right types and try again.
```
But *decimal* literal (no prefix) can't be too strict. Parser is going
to try float later. So '1.4' must be passed.

# User-Facing Changes

First and foremost, more specific error messages for typos in string and
int literals. Probably improves interactive user experience.

But a script that was causing and then checking for specific error might
notice a different error message.

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

# Tests + Formatting

Added (positive and negative unit tests in `cargo test -p nu-parser`.
Didn't add integration tests.

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.

---------

Co-authored-by: Stefan Holderbach <sholderbach@users.noreply.github.com>
2023-02-13 16:09:50 +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
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
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
Jérémy Audiger
99076af18b
Use imported names in Command::run signatures (#7967)
# Description

_(Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.)_

I opened this PR to unify the run command method. It's mainly to improve
consistency across the tree.

# User-Facing Changes

None.

# Tests + Formatting

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

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

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

# 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-05 22:17:46 +01: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