Commit Graph

1224 Commits

Author SHA1 Message Date
Stefan Holderbach
cd75640a90
Add Record::truncate for trimming based on len (#11004)
# Description
Compatible with `Vec::truncate` and `indexmap::IndexMap::truncate`

Found useful in #10903 for `drop column`

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

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

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

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

# User-Facing Changes

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

# Tests + Formatting

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

---------

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

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

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

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

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

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

Found useful in #10903
2023-11-08 22:54:02 +01:00
Ian Manske
59ea28cf06
Use Record::get instead of Value functions (#10925)
# Description
Where appropriate, this PR replaces instances of
`Value::get_data_by_key` and `Value::follow_cell_path` with
`Record::get`. This avoids some unnecessary clones and simplifies the
code in some places.
2023-11-08 21:47:37 +01:00
Stefan Holderbach
86cd387439
Refactor and fix Config<->Value mechanism (#10896)
# Description
Our config exists both as a `Config` struct for internal consumption and
as a `Value`. The latter is exposed through `$env.config` and can be
both set and read.
Thus we have a complex bug-prone mechanism, that reads a `Value` and
then tries to plug anything where the value is unrepresentable in
`Config` with the correct state from `Config`.

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

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

# Parts:

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

Part of #10700

# User-Facing Changes

None

# Tests + Formatting

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

# After Submitting

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

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

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

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

Part of #10700

# User-Facing Changes

None

# Tests + Formatting

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

# After Submitting

N/A

---------

Co-authored-by: Stefan Holderbach <sholderbach@users.noreply.github.com>
2023-11-07 23:25:32 +01:00
dependabot[bot]
45b02ce2ab
Bump indexmap from 2.0.2 to 2.1.0 (#10969) 2023-11-07 15:36:34 +00:00
dzorya
77fbf3e2d2
better help message for MissingPositional error (#10949)
Added "Use `--help` for more information." to the help of
MissingPositional error
- this PR should close
[#10946](https://github.com/nushell/nushell/issues/10946)

**Before:**

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

**After:**

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



<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

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

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

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

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

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

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use std testing; testing run-tests --path
crates/nu-std"` to run the tests for the standard library

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

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

---------

Co-authored-by: Denis Zorya <denis.zorya@trafigura.com>
2023-11-04 12:24:21 -05:00
Andrej Kolchin
1a864ea6f4
Refactor error make (#10923)
- Replaced `start`/`end` with span.
- Fixed standard library.
- Add `help` option.
- Add a couple more errors for invalid record types.

Resolve #10914


# Description



# User-Facing Changes

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

  ```Nushell
  error make {
      msg: "Message"
      label: {
          text: "Label text"
          span: (metadata $var).span
      }
  }
  ```
- `error make` now has a `help` argument for custom error help.
2023-11-03 10:09:33 -05:00
Ian Manske
56e35fc3f9
Reduce element shifting in Record::retain_mut (#10915)
# Description
Replaces the `Vec::remove` in `Record::retain_mut` with some swaps which
should eliminate the `O(n^2)` complexity due to repeated shifting of
elements.
2023-11-02 20:01:46 +01:00
Stefan Holderbach
a46048f362
Use Record APIs in nu-protocol/nu-engine (#10917)
# Description
Consequences of #10841

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

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

# User-Facing Changes
None

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

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

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

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

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

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

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

```
Error: nu:🐚:column_defined_twice

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

this may under rare circumstances block code from evaluating.

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

# Tests + Formatting
Added tests for each of the different evaluation paths that materialize
tables.
2023-11-01 21:25:35 +01:00
Ian Manske
15c22db8f4
Make FromValue take owned Values (#10900)
# Description
Changes `FromValue` to take owned `Value`s instead of borrowed `Value`s.
This eliminates some unnecessary clones (e.g., in `call_ext.rs`).

# User-Facing Changes
Breaking API change for `nu_protocol`.
2023-10-31 19:47:00 +01:00
Ian Manske
72cb4b6032
Reuse Closure type in Value::Closure (#10894)
# Description
Reuses the existing `Closure` type in `Value::Closure`. This will help
with the span refactoring for `Value`. Additionally, this allows us to
more easily box or unbox the `Closure` case should we chose to do so in
the future.

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


# User-Facing Changes
None

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

This PR fixes that:

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

Continuation of #10841 

# User-Facing Changes
None yet.

# Tests + Formatting
Doctests for the `retain`ing fun
2023-10-30 19:51:28 +01:00
Stefan Holderbach
c87bac04c0
Add common map-like API to nu_protocol::Record (#10841)
# Description

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

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

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

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

## End goal

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

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

# User-Facing Changes
None directly

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

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

## State

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

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

# Bycatch

Where I noticed it I replaced usage of `Value` constructors with
`Span::test_data()` or `Span::unknown()` to the `Value::test_...`
constructors. This should make things more readable and also simplify
changes to the `Span` system in the future.
2023-10-28 14:52:31 +02:00
Hudson Clark
78b4472b32
Support pattern matching null literals (#10829)
# Description
Support pattern matching against the `null` literal.  Fixes #10799 

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

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

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->
Users can pattern match against a `null` literal.
2023-10-25 06:30:45 +08:00
Jakub Žádník
a35ecb4837
Finish removing profile command and related data (#10807) 2023-10-22 14:06:53 +03:00
Antoine Stevan
de1c7bb39f
remove the $nothing variable (#10567)
related to 
- https://github.com/nushell/nushell/pull/10478

# Description
this PR is the followup removal to
https://github.com/nushell/nushell/pull/10478.

# User-Facing Changes
`$nothing` is now an undefined variable, unless define by the user.
```nushell
> $nothing
Error: nu::parser::variable_not_found

  × Variable not found.
   ╭─[entry #1:1:1]
 1 │ $nothing
   · ────┬───
   ·     ╰── variable not found.
   ╰────
```

# Tests + Formatting

# After Submitting
mention that in release notes
2023-10-19 18:41:38 +02:00
Gaëtan
27e6271402
Implement modulo for duration (#10745)
# Description
This PR adds the ability to use modulo with durations:

```nu
(2min + 31sec) mod 20sec # 11sec
```

# User-Facing Changes

Allows to use `<duration> mod <duration>`
2023-10-19 12:27:00 +02:00
dependabot[bot]
93b4aa5fcf
Bump lru from 0.11.1 to 0.12.0 (#10732) 2023-10-18 21:00:11 +00:00
Bob Hyman
09b3dab35d
Allow filesystem commands to access files with glob metachars in name (#10694)
(squashed version of #10557, clean commit history and review thread)

Fixes #10571, also potentially: #10364, #10211, #9558, #9310,


# Description
Changes processing of arguments to filesystem commands that are source
paths or globs.
Applies to `cp, cp-old, mv, rm, du` but not `ls` (because it uses a
different globbing interface) or `glob` (because it uses a different
globbing library).

The core of the change is to lookup the argument first as a file and
only glob if it is not. That way,
a path containing glob metacharacters can be referenced without glob
quoting, though it will have to be single quoted to avoid nushell
parsing.

Before: A file path that looks like a glob is not matched by the glob
specified as a (source) argument and takes some thinking about to
access. You might say the glob pattern shadows a file with the same
spelling.
```
> ls a*
╭───┬────────┬──────┬──────┬────────────────╮
│ # │  name  │ type │ size │    modified    │
├───┼────────┼──────┼──────┼────────────────┤
│ 0 │ a[bc]d │ file │  0 B │ 34 seconds ago │
│ 1 │ abd    │ file │  0 B │ now            │
│ 2 │ acd    │ file │  0 B │ now            │
╰───┴────────┴──────┴──────┴────────────────╯

> cp --verbose 'a[bc]d' dest
copied /home/bobhy/src/rust/work/r4/abd to /home/bobhy/src/rust/work/r4/dest/abd
copied /home/bobhy/src/rust/work/r4/acd to /home/bobhy/src/rust/work/r4/dest/acd

> ## Note -- a[bc]d *not* copied, and seemingly hard to access.
> cp --verbose 'a\[bc\]d' dest
Error:   × No matches found
   ╭─[entry #33:1:1]
 1 │ cp --verbose 'a\[bc\]d' dest
   ·              ─────┬────
   ·                   ╰── no matches found
   ╰────

> #.. but is accessible with enough glob quoting.
> cp --verbose 'a[[]bc[]]d' dest
copied /home/bobhy/src/rust/work/r4/a[bc]d to /home/bobhy/src/rust/work/r4/dest/a[bc]d
```
Before_2: if file has glob metachars but isn't a valid pattern, user
gets a confusing error:

```
> touch 'a[b'
> cp 'a[b' dest
Error:   × Pattern syntax error near position 30: invalid range pattern
   ╭─[entry #13:1:1]
 1 │ cp 'a[b' dest
   ·    ──┬──
   ·      ╰── invalid pattern
   ╰────
```

After: Args to cp, mv, etc. are tried first as literal files, and only
as globs if not found to be files.

```
> cp --verbose 'a[bc]d' dest
copied /home/bobhy/src/rust/work/r4/a[bc]d to /home/bobhy/src/rust/work/r4/dest/a[bc]d
> cp --verbose '[a][bc]d' dest
copied /home/bobhy/src/rust/work/r4/abd to /home/bobhy/src/rust/work/r4/dest/abd
copied /home/bobhy/src/rust/work/r4/acd to /home/bobhy/src/rust/work/r4/dest/acd
```
After_2: file with glob metachars but invalid pattern just works.
(though Windows does not allow file name to contain `*`.).

```
> cp --verbose 'a[b' dest
copied /home/bobhy/src/rust/work/r4/a[b to /home/bobhy/src/rust/work/r4/dest/a[b
```

So, with this fix, a file shadows a glob pattern with the same spelling.
If you have such a file and really want to use the glob pattern, you
will have to glob quote some of the characters in the pattern. I think
that's less confusing to the user: if ls shows a file with a weird name,
s/he'll still be able to copy, rename or delete it.

# User-Facing Changes
Could break some existing scripts. If user happened to have a file with
a globbish name but was using a glob pattern with the same spelling, the
new version will process the file and not expand the glob.

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

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

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use std testing; testing run-tests --path
crates/nu-std"` to run the tests for the standard library

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

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

---------

Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com>
2023-10-18 13:31:15 -05:00
Stefan Holderbach
88a87158c2
Bump version to 0.86.1 (#10755)
To dev or to patch that is the question
2023-10-18 13:00:51 -05:00
Stefan Holderbach
5d8763ed1d
Bump version for 0.86.0 release (#10726)
## Release checklist:

- [x] `uu_cp` on crates.io #10725
- [x] new `reedline` released and used nushell/reedline#645
- [x] check of workspace dependency DAG
- [x] release notes ready:
https://github.com/nushell/nushell.github.io/pull/1071
2023-10-18 06:08:20 +13:00
Darren Schroeder
55044aa7d6
change Type::Float => SyntaxShape::Number to SyntaxShape::Float (#10689)
# Description

This PR changes `Type::Float` to point at `SyntaxShape::Float` instead
of `SyntaxShape::Number`.

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

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

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

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use std testing; testing run-tests --path
crates/nu-std"` to run the tests for the standard library

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

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
2023-10-11 12:27:09 -05:00
Antoine Stevan
f481879ed3
make "can't follow stream paths" error a bit better (#10569)
related to
- https://github.com/nushell/nushell/issues/9373
- https://github.com/nushell/nushell/issues/8639

might be able to close https://github.com/nushell/nushell/issues/8639? 

# Description
"can't follow stream paths" errors have always been a bit scary and
obnoxious because they give no information about what happens...

in this PR i try to slightly improve the error message by telling if the
stream was empty or not and give span information when available.

# User-Facing Changes
```nushell
> update value (get value)
Error: nu:🐚:incompatible_path_access

  × Data cannot be accessed with a cell path
   ╭─[entry #1:1:1]
 1 │ update value (get value)
   ·               ─┬─
   ·                ╰── empty pipeline doesn't support cell paths
   ╰────
```
```nushell
> ^echo "foo" | get 0
Error: nu:🐚:incompatible_path_access

  × Data cannot be accessed with a cell path
   ╭─[entry #2:1:1]
 1 │ ^echo "foo" | get 0
   ·  ──┬─
   ·    ╰── external stream doesn't support cell paths
   ╰────
```

# Tests + Formatting

# After Submitting
2023-10-03 18:57:26 +02:00
Stefan Holderbach
7c1487e18d
Use int type name consistently (#10579)
# Description
When referring to the type use `int` consistently. Only when referring
to the concept of integer numbers use `integer`.

- Fix `random integer` to `random int` tests
  - Forgot in #10520
- Use int instead of integer in error messages
- Use int type name in bits commands
- Fix messages in `for` examples
- Use int typename in `into` commands
- Use int typename in rest of commands
- Report errors in `nu-protocol` with int typename

Work for #10332 

# User-Facing Changes
User errorrs should now use `int` so you can easily find the necessary
commands or type annotations.

# Tests + Formatting
Only two tests found that needed updating
2023-10-03 18:24:32 +02:00
JT
844cb1213b
Remove cd w/ abbreviations (#10588)
# Description

This removes the old style "cd with abbreviations" that would attempt to
guess what directory you wanted to `cd` to. This would sometimes have
false positives, so we left it off by default in the config.

In the current main, we have much-improved path completions
(https://github.com/nushell/nushell/pull/10543) so you can now do `cd
a/b<tab>` and get a much better experience (because you can see the
directory you're about to cd to). This removes the need for the previous
abbreviation system.

# User-Facing Changes

This does remove the old abbreviation system. It will likely mean that
old config files that have settings for abbreviations will now get
errors.

update: here's an example of the error you'll see:


![image](https://github.com/nushell/nushell/assets/547158/6847a25d-895a-4b92-8251-278a57e8d29a)

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

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

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use std testing; testing run-tests --path
crates/nu-std"` to run the tests for the standard library

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

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
2023-10-03 10:51:46 +13:00
Jakub Žádník
eb6870cab5
Add --env and --wrapped flags to def (#10566) 2023-10-02 21:13:31 +03:00
Stefan Holderbach
9e445fd4c5
Rename SyntaxShape::Custom to CompleterWrapper (#10548)
# Description
The description `Custom` doesn't really reflect meaning in the set of
`SyntaxShape`. Makes it a bit more verbose but explicit


# User-Facing Changes
Only hypothetically breaking as plugins can not effectively use a
requirement on `SyntaxShape::Custom`.

# Tests + Formatting
(-)
2023-09-29 19:22:58 +02:00
Stefan Holderbach
80a183dde2
Fix editor config for reedline and config nu/env (#10535)
# Description
This merges @horasal 's changes from #10246 and #10269

Closes #10205
Closes #8714

Fixes the bug that editor paths with spaces are unusable

Closes #10210 
Closes #10269


# User-Facing Changes
You can now either pass a string with the name of the executable or a
list with the executable and any flags to
`$env.config.buffer_editor`/`$env.EDITOR`/`$env.VISUAL`

Both the external buffer editor of reedline (by default bound to
`Ctrl-o`) and the commands `config nu` and `config env` will respect
those variables in the following order:
1. `$env.config.buffer_editor`
2. `$env.EDITOR`
3. `$env.VISUAL`

Example:
```
$env.EDITOR = "nvim"                      # The system-wide EDITOR is neovim
$env.config.buffer_editor = ["vim" "-p2"] # Force vim to open two tabs (not particularly useful)
$env.config.buffer_editor = null          # Unset `buffer_editor` -> Uses `$env.EDITOR` ergo nvim
```
# Tests + Formatting
None

---------

Co-authored-by: Horasal <1991933+horasal@users.noreply.github.com>
2023-09-29 16:36:03 +02:00
Stefan Holderbach
f2af12af2c
Docstring some intricacies around SyntaxShape (#10544)
Inspired by @fdncred and @amtoine's questions
https://github.com/nushell/nushell/pull/10512#issuecomment-1739996967
2023-09-29 16:35:22 +02:00
Faïz Hernawan
7ad4c679b3
Add kitty protocol config to nushell (#10540)
# Description

Support keyboard enhancement protocol as implemented by Kitty console,
hence Kitty protocol.

This PR enables Nushell to use keybinding that is not available before,
such as Ctrl+i (that alias to Tab) or Ctrl+e (that alias to Esc, likely
I mistaken). After this PR merged and you set `use_kitty_protocol`
enabled, if your console app support Kitty protocol (WezTerm, Kitty,
etc.) you will be able to set more fine-grained keybinding.

For Colemak users, this feature is a blessing, because some Ctrl+[hjkl]
that previously unmap-able to Ctlr+[hnei] now it is.

# User-Facing Changes

This adds `use_kitty_protocol` config which defaults to false. When set
to `true`, it enables kitty protocol on the line editor when supported,
or else it warns.


---------

Co-authored-by: Stefan Holderbach <sholderbach@users.noreply.github.com>
2023-09-29 15:52:34 +02:00
Stefan Holderbach
d1dc610769
Remove unused SyntaxShape::Variable (#10511)
# Description
We don't use this shape during parsing and never reference it in command
signatures. Thus it should be removed.

# User-Facing Changes
None functional.
Plugin authors that used it would never be provided with data that
specifically matched `SyntaxShape::Variable`
Builds using it will now fail.

# Tests + Formatting
NA
2023-09-28 11:53:03 +02:00
Antoine Stevan
6c026242d4
remove the $nothing variable (#10478)
related to 
- https://github.com/nushell/nushell/pull/9973
- https://github.com/nushell/nushell/pull/9918

thanks to @jntrnr and their super useful tips on this PR, i learned
about the parser + evaluation, so 🙏

# Description
because we already have `null` as the value of the type `nothing` and as
a followup to the two other attempts of mine, i propose to remove the
redundant `$nothing` built-in variable 😋

this PR is the first step, deprecating `$nothing`.
a followup PR will remove it altogether and wait for 0.87 👍 

⚙️ **details**: a new `NOTHING_VARIABLE_ID = 3` has been added,
parsing `$nothing` will create it, finally a `Value::Nothing` will be
produced and a warning will be reported.

this PR already fixes the `toolkit.nu` module so that it does not throw
a bunch of warnings each time 👌

# User-Facing Changes
`$nothing` is now deprecated and will be removed in 0.87
```nushell
> $nothing
Error:   × Deprecated variable
   ╭─[entry #1:1:1]
 1 │ $nothing
   · ────┬───
   ·     ╰── `$nothing` is deprecated and will be removed in 0.87.
   ╰────
  help: Use `null` instead
```

# Tests + Formatting
tests have been updated, especially
- `nothing_fails_string`
- `nothing_fails_int`
which use a variable called `nil` now to make sure `nothing` does not
support cell paths 👍

# After Submitting
classic deprecation mention 👍
2023-09-26 18:49:28 +02:00
Antoine Stevan
feef612388
show the full directory / file path in "directory not found" error (#10430)
should close https://github.com/nushell/nushell/issues/10406

# Description
when writing a script, with variables you try to `ls` or `open`, you
will get a "directory not found" error but the variable won't be
expanded and you won't be able to see which one of the variable was the
issue...

this PR adds this information to the error.

# User-Facing Changes
let's define a variable
```nushell
let does_not_exist = "i_do_not_exist_in_the_current_directory"
```
### before
```nushell
> open $does_not_exist
Error: nu:🐚:directory_not_found

  × Directory not found
   ╭─[entry #7:1:1]
 1 │ open $does_not_exist
   ·      ───────┬───────
   ·             ╰── directory not found
   ╰────
```
```nushell
> ls $does_not_exist
Error: nu:🐚:directory_not_found

  × Directory not found
   ╭─[entry #8:1:1]
 1 │ ls $does_not_exist
   ·    ───────┬───────
   ·           ╰── directory not found
   ╰────
```

### after
```nushell
> open $does_not_exist
Error: nu:🐚:directory_not_found

  × Directory not found
   ╭─[entry #3:1:1]
 1 │ open $does_not_exist
   ·      ───────┬───────
   ·             ╰── directory not found
   ╰────
  help: /home/amtoine/documents/repos/github.com/amtoine/nushell/i_do_not_exist_in_the_current_directory does not exist
```
```nushell
> ls $does_not_exist
Error: nu:🐚:directory_not_found

  × Directory not found
   ╭─[entry #4:1:1]
 1 │ ls $does_not_exist
   ·    ───────┬───────
   ·           ╰── directory not found
   ╰────
  help: /home/amtoine/documents/repos/github.com/amtoine/nushell/i_do_not_exist_in_the_current_directory does not exist
```

# Tests + Formatting
shouldn't harm anything 🤞 

# After Submitting
2023-09-26 17:38:58 +08:00
Antoine Stevan
6a2fd91a01
show the whole path in "missing mod.nu" errors (#10416) 2023-09-23 16:30:03 +03:00
Stefan Holderbach
ef7ade59f3
Split up nu-protocol/src/engine/engine_state.rs (#10368)
Factor the big parts into separate files:
- `state_delta.rs`
- `state_working_set.rs`
- smaller `usage.rs`

This required adjusting the visibility of several parts.
Makes `StateDelta` transparent for the module.
Trying to reduce visibility in some other places
2023-09-21 22:53:36 +02:00
Maxim Zhiburt
7cfd4d2cfa
nu-table: Add table option --abbreviated (#10399)
- Added `--abbreviated`/`-a` option
- Adedd `abbreviate_if_longer_than` config opt for it.

```nu
ls | table -a 3
```

```
╭───┬────────────────────┬──────┬───────────┬──────────────╮
│ # │        name        │ type │   size    │   modified   │
├───┼────────────────────┼──────┼───────────┼──────────────┤
│ 0 │ CODE_OF_CONDUCT.md │ file │   3.4 KiB │ 4 days ago   │
│ 1 │ CONTRIBUTING.md    │ file │  18.3 KiB │ 2 weeks ago  │
│ 2 │ Cargo.lock         │ file │ 144.3 KiB │ 15 hours ago │
│ 3 │ ...                │ ...  │ ...       │ ...          │
│ 4 │ tests              │ dir  │   4.0 KiB │ 4 months ago │
│ 5 │ toolkit.nu         │ file │  14.6 KiB │ 5 days ago   │
│ 6 │ wix                │ dir  │   4.0 KiB │ 2 months ago │
╰───┴────────────────────┴──────┴───────────┴──────────────╯
```

```nu
$env | table -a 3
```

```
╭──────────────────┬──────────────────────────────────────────────────────────────────────────╮
│ BROWSER          │ firefox                                                                  │
│ CARGO            │ /home/maxim/.rustup/toolchains/1.70.0-x86_64-unknown-linux-gnu/bin/cargo │
│ CARGO_HOME       │ /home/maxim/.cargo                                                       │
│ ...              │ ...                                                                      │
│ XDG_SESSION_TYPE │ x11                                                                      │
│ XDG_VTNR         │ 7                                                                        │
│ _                │ /home/maxim/.cargo/bin/cargo                                             │
╰──────────────────┴──────────────────────────────────────────────────────────────────────────╯
```

close #10393

PS: Maybe as a separate issue (good candidate for `GOOD FIRST ISSUE`)
add a config option to change a default `...` truncation sign to a
custom? (which would be applicable not only for `--abbreviated` but all
kind of tables)

---------

Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com>
2023-09-20 12:59:08 -05:00
Stefan Holderbach
af15f794b4
Bump to 0.85.1 development version (#10431) 2023-09-20 18:38:42 +12:00
Stefan Holderbach
a6f62e05ae
Bump version for the 0.85 release (#10425) 2023-09-19 21:42:47 +03:00
Stefan Holderbach
bbf0b45c59
Update internal use of decimal to float (#10333)
# Description
We made the decision that our floating point type should be referred to
as `float` over `decimal`.
Commands were updated by #9979 and #10320

Now make the internal codebase consistent in referring to this data type
as `float`.

Work for #10332

# User-Facing Changes

`decimal` has been removed as a type name/symbol. 

Instead of 
```nushell
def foo [bar: decimal] decimal -> decimal {}
```
use 
```nushell
def foo [bar: float] float -> float {}
```

Potential effect of `SyntaxShape`'s `Display` implementation now also
referring to `float` instead of `decimal`

# Details
- Rename `SyntaxShape::Decimal` to `Float`
- Update `Display for SyntaxShape` to `float`
- Update error message + fn name in dataframe code
- Fix docs in command examples
- Rename tests that are float specific
- Update doccomment on `SyntaxShape`
- Update comment in script

# Tests + Formatting
Updates the names of some tests
2023-09-13 23:53:55 +02:00
Stefan Holderbach
7f39609d9a
Remove python-like string multiplication (#10293)
# Description
Currently we support "multiplication" of strings, resulting in a terse
way to repeat a particular string.
This can have unintended side effects when dealing with mixed data (e.g.
after parsing data that is not all numbers).
Furthermore as we frequently fall-back to strings while parsing source
code, this introduced a runaway edge case in const evaluation (#10212)

Work for #10233

## Details
- Remove python-like string multiplication.
- Workaround for indentation
  - This should probably be addressed with a purpose built command
- Remove special const-eval error test

# User-Facing Changes
**Major breaking change!**
`"string" * 42` will stop working. (This was used for example in the
stdlib)

We should bless a good alternative before landing this

---------

Co-authored-by: JT <547158+jntrnr@users.noreply.github.com>
2023-09-13 19:52:04 +12:00
Stefan Holderbach
a14e9e0a2e
Invert &Options to Option<&T> (#10315)
Elide the reference for `Copy` type (`usize`)
Use the canonical deref where possible.
* `&Box` -> `&`
* `&String` -> `&str`
* `&PathBuf` -> `&Path`

Skips the ctrl-C handler for now.
2023-09-13 07:00:58 +08:00