Compare commits

...

388 Commits

Author SHA1 Message Date
JT
06cf3fa5ad Bump to 0.63 (#5627) 2022-05-25 11:33:28 +12:00
9a482ce284 Overlay keep (#5629)
* Allow env vars to be kept from removed overlay

* Rename --keep to --keep-custom; Add new test

* Rename some symbols

* (WIP) Start working on --keep for defs and aliases

* Fix decls/aliases not melting properly

* Use id instead of the whole cloned overlay

* Rewrite overlay remove for no reason

Doesn't fix the bug but at least looks better.

* Rename variable

* Fix adding overlay env vars

* Add more tests; Fmt + Clippy
2022-05-25 09:22:17 +12:00
8018ae3286 Pin reedline v0.6.0 for the nushell v0.63.0 release (#5620)
Release notes: https://github.com/nushell/reedline/releases/tag/v0.6.0

This release contains several bug fixes and improvements to the vi-emulation and documentation.

- Improvements to the vi-style keybindings (@sadmac7000):
  - `w` now correctly moves to the beginning of the word.
  - `e` to move to the end of the word.
- Bugfixes:
  - Support terminal emulators that erroneously report a size of 0x0 by assuming a default size to avoid panics and draw nevertheless (@DhruvDh)
  - Fix `ListMenu` layout calculations. Avoids scrolling bug when wrapping occurs due to the line numbering (@ahkrr)
  - Avoid allocating to the total history capacity which can cause the application to go out of memory (@sholderbach)
- Documentation improvements including addition of documentation intended for reedline developers (@petrisch, @sholderbach)
2022-05-24 00:39:55 +02:00
ef322a24c5 fix date format (#5619) 2022-05-23 09:59:34 -07:00
a8db4f0b0e load config when requried (#5618) 2022-05-23 15:47:08 +03:00
98a4280c41 Add octal binary literals (#5604)
Schema `0o[77]` with the same padding behavior as the other binary literals

- this updates #5551
- test for parsing binary from octal
- test for string parsing
2022-05-23 11:01:15 +02:00
0e1bfae13d Fallback for config.buffer_editor from EDITOR (#5614)
For the reedline `buffer_editor` use the `EDITOR` and `VISUAL`
environment variables as fallback.

Same resolution order as #5607

Closes #5430
2022-05-23 05:32:52 +12:00
6ff717c0ba Add meta command for the config subcommands (#5616)
When using `config` without the `config nu` or `config env` subcommands
introduced by #5607 display basic usage like `str`.
2022-05-23 05:31:57 +12:00
d534a89867 Make flatten works better and predictable (#5611)
* only want to flatten at most one column which contains a list

* make flatten works better

* more readable
2022-05-22 06:22:38 -05:00
5bc9246f0f Allow for test_iteration_errors to work when run as root (#5609)
* allow for test_iteration_errors to work when run as root

* Add comment to skip condition

Co-authored-by: Stefan Holderbach <sholderbach@users.noreply.github.com>
2022-05-22 11:47:03 +02:00
1e89cc3578 fix typo for version command (#5610) 2022-05-22 16:48:39 +08:00
06f5199570 Add config command (#5607)
* Add config command

* Format code

Co-authored-by: Frank Zhang <v-frankz@microsoft.com>
2022-05-22 15:13:58 +12:00
9e5e9819d6 adjust flatten default behavior (#5606) 2022-05-21 08:32:51 -05:00
1f8ccd8e5e Add search term to str substring command. (#5603) 2022-05-21 11:40:37 +03:00
e9d8b19d4d feat: add search terms to network (#5602)
Co-authored-by: Leyoh Li <leyohli@LeyohdeMacBook-Air.local>
2022-05-20 23:19:17 -04:00
7c63ce15d8 attempts to allow the test to work when run as root (#5601) 2022-05-20 21:48:36 -05:00
JT
a3a9571dac Add environment change hook (#5600)
* add environment change hook

* clippy
2022-05-21 09:49:42 +12:00
2cc5952c37 Fix cp bug (#5462)
* Cleanup - remove old commented code

* Force a / or \ to distinguish between folders and files for cp

* Force a / or \ to distinguish between folders and files for cp

* Remove unneeded code

* Add cp test for checking copy to non existing directory

* Fix warning in test
2022-05-21 09:49:29 +12:00
aa88449f29 Refer to the span of error make if not given (#5599)
* Refer to the span of `error make` if not given

Implements #5591

Currently the span of the "throwing" `error make`

Also allow to set `msg` and `label` without an additional span.

* Message plus "originates from here" label
2022-05-21 09:48:36 +12:00
06199d731b Use bleeding edge reedline, with fix for #5593 (#5598)
Fixes #5593 (OOM introduced with #5587 when no config was present and an attempt was
made to allocate all memory in advance)

Includes also other changes to reedline:

- Vi word definition fixed and `w` and `e` work as expected
2022-05-20 17:35:25 +02:00
0ba86d7eb8 Fix #5578, assume pipe file be zero-sized (#5594)
* Fix #5578, assume pipe file be zero-sized

* rust fmt
2022-05-20 09:27:21 -05:00
6efd1bcb3f Don't report error when cwd is not exists. (#5590)
* only set cwd for child process if cwd exists, and avoid showing error when pwd is not exists

* better comment text

Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com>
2022-05-20 07:03:03 -05:00
0d06b6259f Change miette theme based on ANSI config (#5588)
* Change miette theme based on ANSI config

Use the base ansi colors to simplify the use of the terminal emulator
theming.
Turn of most eye-candy (including unicode) when using
`$config.use_ansi_coloring: false`

Addresses #5582

* Fix error test affected by changed styling
2022-05-19 13:59:14 -05:00
8fdc272bcc Use effectively unlimited history size if not set (#5587)
Fixes #5586
2022-05-19 12:42:41 -05:00
0ea7a38c21 Move help menu to canonical F1 binding (#5510)
Currently the fully fledged help menu is bound to `Ctrl-Q`.
Help is widely associated with `F1`.

Before merging check that it is passed through on all platforms and
terminal emulators
2022-05-19 08:24:04 -05:00
1999e0dcf3 Fix flatten behavior (#5584)
* one step closer to flatten

* integration code is passing, but still need to do one more level flatten for table

* fix flatten

* using match instead of several if let

* make better comment

* fmt code

* better comment
2022-05-19 06:46:48 -05:00
ac30b3d108 Fix menu panic for empty examples. (#5581) 2022-05-19 10:04:56 +02:00
2b1e05aad0 add quantile column (#5583) 2022-05-18 20:47:26 -05:00
6c56829976 Allowing for flags with '=' in them to register as flags. (#5579)
* hacky fix for registering flags with '='

* fmt
2022-05-18 11:26:58 -05:00
2c58beec13 cp, mv, and rm commands need to support -i flag (#5523)
* restored interactive mode to rm command

* removed unnecessary whitespace in rm file

* removed unnecessary whitespace in rm file

* fixed python-vertualenv build issue

* moved interactive logic to utils file

* restored interactive mode to cp command

* interactive mode for mv wip

* finished mv implementation

* removed unnecessary whitespace

* changed unwrap to expect
2022-05-18 09:53:46 -05:00
9c779b071b feat: apply the --numbered option to acc in reduce command. (#5575)
* feat: apply the `-n` option to acc

* feat: update tests and examples
2022-05-18 09:49:34 -05:00
1e94793df5 Add str title-case (#5573)
Co-authored-by: kyle <kyle@archtop.local>
2022-05-18 08:57:20 -05:00
7d9a77f179 fix select tests (#5577) 2022-05-18 06:20:26 -05:00
bb079608dd fix move test (#5576)
* fix move test

* remove ignore
2022-05-18 06:18:21 -05:00
5fa42eeb8c Make format support nested column and use variable (#5570)
* fix format for nested structure

* make little revert

* add tests

* fix format

* better comment

* make better comment
2022-05-18 06:08:43 -05:00
3e09158afc Move capitalize, downcase, upcase to /cases; fix some example descriptions; clarify usage text (#5572)
Co-authored-by: kyle <kyle@archtop.local>
2022-05-18 00:55:43 -04:00
7a78171b34 move items to showcase (#5569) 2022-05-17 18:21:14 -05:00
633ebc7e43 Revert "Enable backtraces by default (#5562)" (#5568)
This reverts commit 8004e8e2a0.
2022-05-17 15:02:45 -07:00
f0cb2f38df refactor all write_alls to ensure flushing (#5567) 2022-05-17 13:28:18 -05:00
f26d3bf8d7 make print flush (#5566) 2022-05-17 09:27:12 -05:00
498672f5e5 feat(errors): more explicit module_or_overlay_not_found_error help message (#5564) 2022-05-17 06:22:31 -05:00
038391519b Upgrade trash crate for faster non-Windows builds (#5563) 2022-05-16 17:48:41 -07:00
8004e8e2a0 Enable backtraces by default (#5562) 2022-05-16 17:04:41 -07:00
JT
e192684612 Revert "Try to do less work during capture discovery (#5560)" (#5561)
This reverts commit 5d40fc2726.
2022-05-17 10:49:59 +12:00
JT
5d40fc2726 Try to do less work during capture discovery (#5560) 2022-05-17 09:05:26 +12:00
a22d70718f Add search terms to build-string command. (#5557) 2022-05-16 12:21:01 -07:00
24a49f1b0a Remove doctests action (#5556)
We're no longer using `cargo nextest` for our main test job. The separate action for doctests was only necessary because `cargo nextest` does not support doctests, it can be removed.

Hoping this will result in less data cached but we'll see.
2022-05-16 09:10:00 -07:00
04473a5593 Update pull request template for faster clippy+tests
Updating the Clippy and `cargo test` instructions to be more similar to what we do in CI. Will speed things up a bit for contributors.
2022-05-16 08:42:38 -07:00
d1e7884d19 table refactor for readability (#5555) 2022-05-16 10:35:57 -05:00
2b96c93b8d Sync resources version (#5554)
Fix line ending
2022-05-16 09:15:10 -05:00
fc41a0f96b use reverse iter on value search (#5553) 2022-05-16 06:29:40 -05:00
8bd68416e3 Lazy dataframes (#5546)
* lazyframe definition

* expressions and lazy frames

* new alias expression

* more expression commands

* updated to polars main

* more expressions and groupby

* more expressions, fetch and sort-by

* csv reader

* removed open csv

* unique function

* joining functions

* join lazy frames commands with eager commands

* corrected tests

* Update .gitignore

* Update .gitignore

Co-authored-by: JT <547158+jntrnr@users.noreply.github.com>
2022-05-16 08:27:43 +01:00
2062e33c37 CI: bust caches (#5550)
* bust test cache to see if that fixes issue

* bust all caches
2022-05-15 22:24:51 -07:00
JT
c6383874e9 Try removing debuginfo for ci builds (#5549)
* Try removing debuginfo for ci builds

* oops, wrong inherits

* extra flag

* nextest doesn't support --profile in the same way

* try to allow for a ci-specific target

* Oops, run more tests
2022-05-16 16:02:11 +12:00
d90b25c633 Look up git commit hash ourselves, drop libgit2 dependency (#5548) 2022-05-16 13:57:25 +12:00
44bcfb3403 fix zip test (#5536) 2022-05-15 16:44:32 -05:00
c047fd4778 nu-cli/completions: add custom completion test (#5543) 2022-05-14 15:09:41 -05:00
16bd7b6d0d Fix Value::Record compare logic, and pass uniq tests. (#5541)
* fix record compare logic

* add more comment
2022-05-14 06:04:09 -05:00
3cef94ba39 nu-glob: add fs::symlink_metadata to detect broken symlinks (#5537)
* nu-glob: add fs::symlink_metadata to detect broken symlinks

* fix join result
2022-05-13 17:56:26 -07:00
f818193b53 Change history menu keybinding from ctrl+x to ctrl+r (#5507)
* Change history menu keybinding to ctrl+r from ctrl+x

* Remove menupage actions from default config

* remove trailing whitespace

* re-add next+previous page keybindings

* Remove hardcoded menu keybindings

* Hardcode new keybindings
2022-05-13 09:26:14 -05:00
1aec4a343a Made a change to completion resolution order (#5440)
* Made a change to completion resolution order

* Potential fix for completion (remove file paths from command completer)

* Updating formatting

* Removed commented out code for readability

* Fixed compile error on merge
2022-05-13 08:15:24 -05:00
852de79212 Implement histogram command (#5518)
* finish histogram

* adjust comment

* add test for histogram

* add Date to test

* move hashable value back inside chart package
2022-05-13 06:48:47 -05:00
06f40405fe add rename (#5534) 2022-05-13 06:47:11 -05:00
65bac77e8a More CI work (#5527)
* Add cache+docs to plugin CI job

* CI perf: don't statically link OpenSSL

* Run Clippy in plugin job

* comment

* bust cache

* trigger build

* remove nextest, split plugins better

* trigger CI

* try disabling embed-resource

* try disabling libgit2 in shadow-rs

* use lld linker on Windows

* Skip embedding Windows resource (slow) during tests

* disable shadow-rs git integration during tests

* go back to simpler shadow-rs and embed-resources setup

* some renaming

* forgot nextest

* trigger ci

* Remove Clippy and unnecessary build

* trigger CI

* disable lld

* reenable lld

* cleanup

* revert embed_resource change
2022-05-13 06:40:46 -05:00
32d1939a95 nu-command/filesystem: fix rm .sock file (#5524) 2022-05-12 19:25:21 -05:00
53e35670ea add the ability to change table mode when running script (#5520) 2022-05-12 07:27:44 -05:00
a92567489f nu-cli/completions: verify case for matching dir, .nu, file and command (#5506)
* nu-cli/completions: verify case for matching dir, .nu, file and command

* avoid copy

* fix clippy
2022-05-11 16:16:52 -05:00
2145feff5d feat: add tutor list support, remove tutor engine-q, fix: #4950 (#5511)
* feat: add `tutor list` support, remove tutor `engine-q`, fix: #4950

* cs

* fmt
2022-05-11 16:16:01 -05:00
0b95465ea1 add --table_mode -m parameter (#5513)
* add `--table_mode` `-m` parameter

* underscores to dashes
2022-05-11 16:15:31 -05:00
ec804f4568 nu-command ls - bump umask crate to 2.0.0 (#5514) 2022-05-11 16:13:45 -05:00
4717ac70fd Add verbose (#5512)
Co-authored-by: Frank Zhang <v-frankz@microsoft.com>
2022-05-11 11:46:13 -05:00
9969fbfbb1 Add feedback to cp (#5482)
Co-authored-by: Frank Zhang <v-frankz@microsoft.com>
2022-05-11 20:06:30 +08:00
5f39267a80 Make $nothing | into string == "" (#5490)
* Make $nothing | into string == ""

* Fix up existing into string tests

* Add $nothing | into string test

* Formatting

* Windows line endings test fix
2022-05-11 12:26:43 +03:00
94a9380e8b adjust where prompt markers go (#5491)
* adjust where prompt markers go

* marks are working, yipee!
2022-05-10 16:33:18 -05:00
1d64863585 nu-cli/completions: add variable completions test + refactor tests (#5504)
* refactor tests

* removed old test file
2022-05-10 15:17:07 -05:00
8218f72eea nu-cli/completions: added tests for dotnu completions (#5460) 2022-05-10 13:18:18 -05:00
c0b99b7131 Enable converting dates to ints (#5489) 2022-05-10 13:15:28 -05:00
75c033e4d1 refactor for legibility (#5503)
* refactor for legibility

* clippy
2022-05-10 12:49:34 -05:00
d88d057bf6 keep metadata while format filesize (#5502) 2022-05-10 11:24:06 -05:00
b00098ccc6 opt: improve ls by call get_file_type only one time (#5500)
* opt: improve ls by call get_file_type only one time

* fmt

* cs
2022-05-10 08:01:06 -05:00
7e5e9c28dd Fix #3899, make mv and rm to be quiet by default (#5501) 2022-05-10 08:00:27 -05:00
8ffffe9bcc Improve #4975 of filtering ls output by size issue (#5494)
* Improve #4975 of filtering `ls` output by size issue

* cargo fmt
2022-05-10 06:39:37 -05:00
8030f7e9f0 add format filesize (#5498)
* add format filesize

* add comment

* add comment

* remove comment
2022-05-10 06:35:14 -05:00
e4959d2f9f Update comment in default_config.nu [skip ci] (#5496) 2022-05-10 06:21:01 -05:00
f311da9623 Adds fix for when multiple flags are in one line. (#5493) 2022-05-10 06:13:19 -05:00
14d80d54fe Parse timestamps as UTC by default (#5488)
* Parse timestamps as UTC by default

* Fix up flags and examples
2022-05-09 13:57:28 -05:00
23b467061b Display range values better (#5487) 2022-05-09 12:18:37 -05:00
8d8f25b210 Fixing the flag issue (#5447)
* Fixing the flag issue

* whoops, forgot the original point of the function

* Update deparse.rs

* Update deparse.rs

* Update deparse.rs

* maybe this might work

* fmt

* quotation marks works now due to a rigorous check for args.

* fmt and clippy

* kept the original escape_quote_string(), escaped " and \

* removed script.nu

* Added appropriate comments.
2022-05-09 07:01:58 -05:00
7ee22603ac Fix #5469, making $nothing or null convert to filesize of 0B (#5485) 2022-05-09 06:19:28 -05:00
4052a99ff5 Handle int input in into datetime (#5484) 2022-05-09 06:16:01 -05:00
ccfa35289b Fix to csv and to tsv for simple list, close: #4780 (#5483)
* Fix `to csv` and `to tsv` for simple list, close: #4780

* ci skip
2022-05-09 06:14:42 -05:00
JT
54fc164e1c Allow hooks to be lists of blocks (#5480) 2022-05-09 13:56:48 +12:00
JT
3a35bf7d4e Add hooks to cli/repl (#5479)
* Add hooks to cli/repl

* Clippy

* Clippy
2022-05-09 07:28:39 +12:00
a61d09222f document out positional argument type (#5461) 2022-05-08 08:11:28 -05:00
07ac3c3aab Add Nushell REPL simulator; Fix bug in overlay add (#5478)
* Add Nushell REPL simulator; Fix bug in overlay add

The `nu_repl` function takes an array of strings and processes them as
if they were REPL lines entered one by one. This helps to discover bugs
due to the state changes between the parse and eval stages.

* Fix REPL tests on Windows
2022-05-08 16:09:39 +03:00
061e9294b3 join and from derived tables (#5477) 2022-05-08 11:12:03 +01:00
JT
374757f286 Bump to the 0.62.1 dev version (#5473) 2022-05-08 08:38:12 +12:00
ca75cd7c0a nu-cli/completions: add tests for flag completions (#5468) 2022-05-07 15:19:48 -05:00
d08c072f19 feat: add disable field type inferencing for from csv and from tsv, fix: #3485 and #4217 (#5467) 2022-05-07 15:04:31 -05:00
9b99b2f6ac Overlays (#5375)
* WIP: Start laying overlays

* Rename Overlay->Module; Start adding overlay

* Revamp adding overlay

* Add overlay add tests; Disable debug print

* Fix overlay add; Add overlay remove

* Add overlay remove tests

* Add missing overlay remove file

* Add overlay list command

* (WIP?) Enable overlays for env vars

* Move OverlayFrames to ScopeFrames

* (WIP) Move everything to overlays only

ScopeFrame contains nothing but overlays now

* Fix predecls

* Fix wrong overlay id translation and aliases

* Fix broken env lookup logic

* Remove TODOs

* Add overlay add + remove for environment

* Add a few overlay tests; Fix overlay add name

* Some cleanup; Fix overlay add/remove names

* Clippy

* Fmt

* Remove walls of comments

* List overlays from stack; Add debugging flag

Currently, the engine state ordering is somehow broken.

* Fix (?) overlay list test

* Fix tests on Windows

* Fix activated overlay ordering

* Check for active overlays equality in overlay list

This removes the -p flag: Either both parser and engine will have the
same overlays, or the command will fail.

* Add merging on overlay remove

* Change help message and comment

* Add some remove-merge/discard tests

* (WIP) Track removed overlays properly

* Clippy; Fmt

* Fix getting last overlay; Fix predecls in overlays

* Remove merging; Fix re-add overwriting stuff

Also some error message tweaks.

* Fix overlay error in the engine

* Update variable_completions.rs

* Adds flags and optional arguments to view-source (#5446)

* added flags and optional arguments to view-source

* removed redundant code

* removed redundant code

* fmt

* fix bug in shell_integration (#5450)

* fix bug in shell_integration

* add some comments

* enable cd to work with directory abbreviations (#5452)

* enable cd to work with abbreviations

* add abbreviation example

* fix tests

* make it configurable

* make cd recornize symblic link (#5454)

* implement seq char command to generate single character sequence (#5453)

* add tmp code

* add seq char command

* Add split number flag in `split row` (#5434)

Signed-off-by: Yuheng Su <gipsyh.icu@gmail.com>

* Add two more overlay tests

* Add ModuleId to OverlayFrame

* Fix env conversion accidentally activating overlay

It activated overlay from permanent state prematurely which would
cause `overlay add` to misbehave.

* Remove unused parameter; Add overlay list test

* Remove added traces

* Add overlay commands examples

* Modify TODO

* Fix $nu.scope iteration

* Disallow removing default overlay

* Refactor some parser errors

* Remove last overlay if no argument

* Diversify overlay examples

* Make it possible to update overlay's module

In case the origin module updates, the overlay add loads the new module,
makes it overlay's origin and applies the changes. Before, it was
impossible to update the overlay if the module changed.

Co-authored-by: JT <547158+jntrnr@users.noreply.github.com>
Co-authored-by: pwygab <88221256+merelymyself@users.noreply.github.com>
Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com>
Co-authored-by: WindSoilder <WindSoilder@outlook.com>
Co-authored-by: Yuheng Su <gipsyh.icu@gmail.com>
2022-05-08 07:39:22 +12:00
1cb449b2d1 Database commands (#5466)
* change query to statement

* internal functions and over definitions

* cargo fmt
2022-05-07 13:33:33 +01:00
6cc66c8afd complete some commands tests (#5464)
* complete hash test

* unignore source relative tests
2022-05-07 06:23:49 -05:00
08e495ea67 Enable string interpolation for environment shorthand (#5463) 2022-05-07 06:21:29 -05:00
b0647f780d nu-cli/completions: send original line to custom completer (#5459) 2022-05-06 16:58:42 -05:00
2dfd975940 add -n flag to print to print without a newline (#5458)
* add -n flag to print to print without a newline

* clippy
2022-05-06 15:33:00 -05:00
fbdb125141 Add split number flag in split row (#5434)
Signed-off-by: Yuheng Su <gipsyh.icu@gmail.com>
2022-05-06 10:53:02 -05:00
c2ea993f7e implement seq char command to generate single character sequence (#5453)
* add tmp code

* add seq char command
2022-05-06 10:40:02 -05:00
e14e60dd2c make cd recornize symblic link (#5454) 2022-05-06 10:39:48 -05:00
768ff47d28 enable cd to work with directory abbreviations (#5452)
* enable cd to work with abbreviations

* add abbreviation example

* fix tests

* make it configurable
2022-05-06 07:58:32 -05:00
78a1879e36 fix bug in shell_integration (#5450)
* fix bug in shell_integration

* add some comments
2022-05-05 10:10:03 -05:00
0b9c0fea9d Adds flags and optional arguments to view-source (#5446)
* added flags and optional arguments to view-source

* removed redundant code

* removed redundant code

* fmt
2022-05-05 06:37:56 -05:00
Tom
02a3430ef0 Use correct ParseError (#5431) 2022-05-05 07:41:32 +12:00
6623ed9061 sometimes you want a text output (#5441) 2022-05-04 14:12:23 -05:00
48cf103439 Allowed for view-source to include entire custom command definition (#5435)
* allowed for view-source to include entire custom command definition

* fmt

* clippy
2022-05-04 06:35:09 -05:00
1bcb87c48d Update rust version (#5432) 2022-05-04 13:56:31 +12:00
JT
da104050e6 Update release.yml 2022-05-04 09:50:33 +12:00
JT
d306b834ca Bump to 0.62 (#5422) 2022-05-04 09:01:27 +12:00
d4371438d1 Pin reedline to v0.5.0 for the next release (#5427)
Release notes: https://github.com/nushell/reedline/releases/tag/v0.5.0

Co-authored-by: JT <547158+jntrnr@users.noreply.github.com>
2022-05-04 08:11:31 +12:00
6a972312d4 added open editor event in config parsing (#5426) 2022-05-04 07:52:53 +12:00
ac48f5a318 Fix coloring when string has spaces (#5425)
* Replace ansi-cut with ansi-str

There's no issues with it we just need to use it later.

Signed-off-by: Maxim Zhiburt <zhiburt@gmail.com>

* Fix color losing in string spliting into Sublines

Signed-off-by: Maxim Zhiburt <zhiburt@gmail.com>
2022-05-03 09:48:43 -05:00
JT
e36649f74b Update path completions to handle spaces (#5419) 2022-05-03 12:37:38 +12:00
1a52460695 Database commands (#5417)
* dabase access commands

* select expression

* select using expressions

* cargo fmt

* alias for database

* database where command

* expression operations

* and and or operators

* limit and sort by commands
2022-05-03 06:38:18 +12:00
ab98ecd55b Fix erroneous removal of "./" folder prefix (#5416) 2022-05-02 12:36:18 -05:00
9a8e939cbe remove ctrl-l from config.nu (#5415) 2022-05-02 08:31:52 -07:00
bb27b9f371 Don't resuggest accepted completions (#5369)
To avoid resuggesting the same completion, add a space after commands or flags that have been accepted via `Enter`. Don't do that for filepaths or external completions

* Add append_whitespace choice for suggestion

Signed-off-by: gipsyh <gipsyh.icu@gmail.com>

* Fixed `test <path>` appending space.

* Update reedline

Co-authored-by: sholderbach <sholderbach@users.noreply.github.com>
2022-05-02 11:35:37 +02:00
1ca3063ac3 Fix CI to run doctests again (#5410)
The faster `cargo nextest` currently doesn't support running the doctests.

Thus, add an additional step for them with cargo's default test runner.

- Fix doctests for the `nu-pretty-hex` crate
2022-05-02 11:32:57 +02:00
7c9a78d922 Fixed ctrl-c in recursion loop bug #5362 (#5409) 2022-05-02 20:18:25 +12:00
49cbc30974 Add ends-with operator and fix dataframe operator behavior (#5395)
* add ends-with operator

* escape needles in dataframe operator regex patterns
2022-05-02 20:02:38 +12:00
07a7bb14bf Fixed interrupting a for-loop over a list bug #5378 (#5408)
Signed-off-by: gipsyh <gipsyh.icu@gmail.com>
2022-05-02 19:56:37 +12:00
74f1c5b67b CI: Add plugins job (#5406) 2022-05-02 19:20:57 +12:00
3b0151aba6 event ClearScrollback is now working in reedline / update default config.nu (#5405) 2022-05-02 19:20:24 +12:00
JT
4a69819f9a Rename =^ to 'starts-with' (#5407) 2022-05-02 19:20:07 +12:00
1f7d3498cd Bump reedline (#5404)
- Fix to the `ClearScrollback` command
- Fix of vi mode `x` so it adds the character to the clipboard
- Vi mode shorthands `s` and `S`
2022-05-02 13:14:24 +12:00
f0b9dc9da1 CI: build virtualenv tests in dev profile for speed (#5396) 2022-05-02 10:01:36 +12:00
JT
96f8691c8d More escaping/unescaping fixes (#5403) 2022-05-02 09:49:31 +12:00
07255e576d Add Miette "fancy" feature to fix plugin builds (#5402) 2022-05-02 08:52:49 +12:00
260be40774 Update reedline to use partial completion changes (#5401) 2022-05-02 08:41:25 +12:00
JT
14c9bd44ef Adds error printing back in a couple places (#5400) 2022-05-02 08:40:46 +12:00
JT
92785ab92c Add unescaping to external command parsing (#5399) 2022-05-02 07:26:29 +12:00
JT
98ab31e15e Move uses of trim_quotes to unescape for filenames (#5398)
* Move uses of trim_quotes to unescape for filenames

* Fix Windows tests
2022-05-02 06:37:20 +12:00
80d57d70cd a little database cleanup (#5394) 2022-05-01 07:44:29 -05:00
8dc199d817 Fix PATH update example (#5393) 2022-05-01 14:53:59 +03:00
435693a8bb Line buffer keybinding (#5390)
* dabase access commands

* select expression

* select using expressions

* cargo fmt

* change keybinding
2022-05-01 08:59:49 +01:00
5077242892 Error printing changes for watch (#5389)
* Move CliError to nu-protocol

clean up comment

* Enable printing errors instead of just returning them

* Nicer Miette error printing in watch command
2022-05-01 19:33:41 +12:00
7a7aa310aa Remove 'empty' block support reminders, for now. (#5214) 2022-04-30 22:32:30 -05:00
07893e01c1 Remove "./" prefix for file path completions (#5387) 2022-04-30 16:54:04 -05:00
JT
f16401152b Make if else more lazy (#5386) 2022-05-01 09:13:21 +12:00
3df03e2e6d nu-cli/completions: complete external args as filepath (#5385) 2022-05-01 08:07:09 +12:00
7c6f976d65 nu-cli/completions: apply correctly nesting for env vars (#5382) 2022-04-30 14:14:04 -05:00
ae9c0fc138 Fix quoting for command line args (#5384)
* Fix quoting for command line args

* Replace custom quoting with escape_quote_string

* Use raw string for now
2022-04-30 13:23:05 -05:00
9da2e142b2 Line buffer editor (#5381)
* allow line editing

* cargo fmt
2022-04-30 15:40:41 +01:00
5999506f87 allows for nushell to have tables without the index column (#5380) 2022-04-30 09:07:46 -05:00
1fc7abcc38 Faster CI (#5374)
* More-parallel CI

* Split all+default caches

* Rename ci job to build-clippy

* cargo nextest

* Remove fmt from tests
2022-04-29 22:48:04 +03:00
2659ea3dbd Revert "nu-cli/completions: better fix for files with special characters (#5254)" (#5372)
This reverts commit 3cf3329e49.
2022-04-29 13:11:41 -05:00
fa27110651 Avoid using time conversion methods that may panic (#5365) 2022-04-29 06:03:39 -05:00
b4f8798a3a rust-cache fix (#5359)
* Enable CI on merges to main

* Re-enable rust-cache for virtualenv tests
2022-04-28 17:57:26 -05:00
7714956276 CI: remove rust-cache from virtualenv tests (#5358) 2022-04-28 15:27:18 -05:00
8e5cc655e9 cleanup version command and add in database feature (#5356)
* cleanup version command and add in database feature

* static-link-openssl
2022-04-28 15:25:04 -05:00
c78e28511d CI: make Clippy reuse build artifacts, other cleanup (#5357)
* CI: move clippy after build so it can reuse build artifacts

* CI: Remove unused rustfmt+clippy from venv
2022-04-28 14:39:21 -05:00
f189369fd7 Change description of sort (#5355) 2022-04-28 14:33:26 -05:00
2516305fa8 CI: enable rust-cache, remove minimal (#5354)
* Enable rust-cache

Add cache buster key

Add rust-cache to python venv

* Remove minimal CI
2022-04-28 13:18:27 -05:00
f2d7454330 Add watch command (#5331) 2022-04-28 09:26:34 -05:00
3cf3329e49 nu-cli/completions: better fix for files with special characters (#5254)
* nu-cli/completions: fix paths with special chars

* add backticks

* fix replace

* added single quotes to check list

* check escape using fold

* fix clippy errors

* fix comment line

* fix conflicts

* change to vec

* skip sort checking

* removed invalid windows path

* remove comment

* added tests for escape function

* fix fn import

* fix fn import error

* test windows issue fix

* fix windows backslash path in the tests

* show expected path on error

* skip test for windows
2022-04-28 08:36:32 -05:00
d2bc2dcbb2 Openssl feature (#5352)
* Move statically linked OpenSSL behind a feature

* Re-add README.txt for releases
2022-04-28 06:33:17 -05:00
4ec4649903 mute false import warning for nu-command test where_ (#5350) 2022-04-27 22:45:39 -07:00
55e5106695 Statically link OpenSSL (#5349) 2022-04-28 12:25:09 +12:00
5f35e4ad1e improve inc plugin docs (#5346)
This is a convenience for anyone using GitHub features to copy paste directly into your local shell
2022-04-27 18:56:32 -05:00
e7831d38ae fixes an issue with an empty selector panic (#5345)
* fixes an issue with an empty selector panic

* missed web_tables

* oops, missed a test
2022-04-27 07:38:36 -05:00
5c9fe85ec4 Database commands (#5343)
* dabase access commands

* select expression

* select using expressions

* cargo fmt
2022-04-27 11:52:31 +01:00
cd5199de31 db info tweaks (#5338)
* Rename db info to db schema

* Change db schema to take db as input
2022-04-26 18:16:46 -05:00
5319544481 db info command (#5335)
* db info WIP

* working now

* clippy
2022-04-26 14:20:59 -05:00
JT
be3f0edc97 Fix 'range' range exclusive (#5334) 2022-04-26 13:39:38 -05:00
fb8f7b114e Fix use of export/alias --help bug (#5332)
* fix alias --help bug

Signed-off-by: SuYuheng <yuheng.su@motiong.com>

* fix export --help bug

Signed-off-by: SuYuheng <yuheng.su@motiong.com>

Co-authored-by: SuYuheng <yuheng.su@motiong.com>
2022-04-26 11:51:49 -05:00
187f2454c8 Move print_pipeline_data to nu-protocol (#5328) 2022-04-26 11:44:57 +12:00
JT
3492d4015d Allow bare words to interpolate (#5327)
* Allow bare words to interpolate

* fix highlighting
2022-04-26 11:44:44 +12:00
190f379ff3 activates optional trim in 'from csv' and 'from tsv' (#5326) 2022-04-25 12:54:14 -05:00
5c2bc73d7b Allows cd (and other commands that depend on current working directory) to use path of type '~user' (#5323)
* Added search terms to math commands

* Attempts to add ~user.

From: // Extend this to work with "~user" style of home paths

* Clippy recommendation

* clippy suggestions, again.

* fixing non-compilation on windows and macos

* fmt apparently does not like my imports

* even more clippy issues.

* less expect(), single conversion, match. Should work for MacOS too.

* Attempted to add functionality for windows: all it does is take the home path of current user, and replace the username.

* silly mistake in Windows version of user_home_dir()

* Update tilde.rs

* user_home_dir now returns a path instead of a string - should be smoother with no conversions to string

* clippy warnings

* clippy warnings 2

* Changed user_home_dir to return PathBuf now.

* Changed user_home_dir to return PathBuf now.

* forgot to fmt

* fixed windows build errors from modifying pathbuf but not returning it

* fixed windows clippy errors from returning () instead of pathbuf

* forgot to fmt

* borrowed path did not live long enough.

* previously, path.push did not work because rest_of_path started with "/" - it was not relative. Removing the / makes it a relative path again.

* Issue fixed.

* Update tilde.rs

* fmt.

* There is now a zero chance of panic. All expect()s have been removed.

* Patched join_path_relative to accommodate ~user paths. Previously, /some/path/~user might have been passed on; now, ~user is taken as absolute.

* fmt

* clippy errors
2022-04-25 06:01:48 -05:00
aeed8670f1 add database feature to extra (#5322) 2022-04-24 18:26:56 -05:00
b38f90d4c7 Adding ~user tilde recognition in file paths (#5251)
* Added search terms to math commands

* Attempts to add ~user.

From: // Extend this to work with "~user" style of home paths

* Clippy recommendation

* clippy suggestions, again.

* fixing non-compilation on windows and macos

* fmt apparently does not like my imports

* even more clippy issues.

* less expect(), single conversion, match. Should work for MacOS too.

* Attempted to add functionality for windows: all it does is take the home path of current user, and replace the username.

* silly mistake in Windows version of user_home_dir()

* Update tilde.rs

* user_home_dir now returns a path instead of a string - should be smoother with no conversions to string

* clippy warnings

* clippy warnings 2

* Changed user_home_dir to return PathBuf now.

* Changed user_home_dir to return PathBuf now.

* forgot to fmt

* fixed windows build errors from modifying pathbuf but not returning it

* fixed windows clippy errors from returning () instead of pathbuf

* forgot to fmt

* borrowed path did not live long enough.

* previously, path.push did not work because rest_of_path started with "/" - it was not relative. Removing the / makes it a relative path again.

* Issue fixed.

* Update tilde.rs

* fmt.

* There is now a zero chance of panic. All expect()s have been removed.
2022-04-24 17:12:57 -05:00
9771270b38 Fuzzy completion matching (#5320)
* Implement fuzzy match algorithm for suggestions

* Use MatchingAlgorithm for custom completions
2022-04-24 16:43:18 -05:00
f6b99b2d8f update build status badge (#5321) 2022-04-24 16:28:54 -05:00
JT
ec611526ac Warn if we see let config = ../.. (#5318) 2022-04-25 08:40:55 +12:00
cd2df83ddc nu-command/filesystem: clean whitespaces from paths in cd and open (#5310) 2022-04-25 07:15:33 +12:00
3eb447030b update contrib to max=500 (#5317) 2022-04-24 13:03:20 -05:00
f2a45b3eac Update ci.yml 2022-04-24 08:03:21 -05:00
e94d13da1b Database commands (#5307)
* database commands

* db commands

* filesystem opens sqlite file

* clippy error

* corrected error in ci file

* removes matrix flag from ci

* flax matrix for clippy

* add conditional compile for tests

* add conditional compile for tests

* correct order of command

* correct error msg

* correct typo
2022-04-24 10:29:21 +01:00
c20ba95885 fix: remove println!() from exec builtin (#5311) 2022-04-24 15:24:44 +12:00
8eab311565 consolidate shell integration behind config setting (#5302)
* consolidate shell integration behind config setting

* write output differently
2022-04-24 12:53:12 +12:00
e2b510b65e update sys with new items, add kernel version to os-info (#5308)
* update sys with new items, add kernel version to os-info

* clippy
2022-04-23 16:33:27 -05:00
e6a70f9846 Add MatchAlgorithm for completion suggestions (#5244)
* Pass completion options to each fetch() call

* Add MatchAlgorithm to CompletionOptions

* Add unit test for MatchAlgorithm

* Pass completion options to directory completer
2022-04-23 10:01:19 -05:00
667eb27d1b feat: add search terms to date (#5306)
* add search terms

* add search terms

* add search terms

* add search terms

* add search terms

* add search terms

* add search terms

* add search terms

* add search patterns

* run cargo fmt --all
2022-04-23 08:54:03 -05:00
b9eb213f36 nu-cli/completions: added completion for $nu (#5303) 2022-04-23 11:49:17 +12:00
JT
cc78446ffd Fix cd - (#5301) 2022-04-23 11:48:10 +12:00
5ff2ae628b nu-cli: directory syntax shape + completions (#5299) 2022-04-22 15:18:51 -05:00
661283c4d2 nu-cli/completions: support record for custom completions (#5298) 2022-04-22 15:17:08 -05:00
JT
ee29a15119 Add 'and' and 'or' operators (#5297) 2022-04-23 07:14:31 +12:00
2a18206771 add virtualenv to integrations (#5280) 2022-04-21 06:50:32 -05:00
a26272b44b Clean up tests and unused documentation code (#5273)
* Delete unused documentation code+test

* Fix up test to account for new select behavior
2022-04-21 06:13:58 -05:00
7e730e28bb Delete obsolete+unused files (#5272) 2022-04-21 17:56:56 +12:00
JT
96253c69fb Use better quoting for commandline args (#5271) 2022-04-21 15:31:52 +12:00
JT
ded9d1cedb Some cleanups for clippy (#5266) 2022-04-21 12:08:12 +12:00
d1cc70fc4a update os-info os to name (#5265) 2022-04-21 10:36:39 +12:00
18c9b62b00 git completion: 'git fetch' for remotes (#5253) 2022-04-21 07:52:44 +12:00
1295495758 typo: seach -> search (#5264) 2022-04-21 07:38:24 +12:00
e97ba9b74c feat: add search terms for conversions (#5259) 2022-04-20 11:48:32 -05:00
09b972f1dc add newlines to end of the default configs (#5256) 2022-04-20 07:56:15 -07:00
0fb6f8f93c refactor html module (#5246)
* refactor around html module

* Update html.rs

fix clippy warning

* minify json
2022-04-20 08:50:14 -05:00
995d8db1fe Set to reedline main branch for development cycle (#5249)
Changes to reedline since `v0.4.0`:

- vi normal mode `I` for inserting at line beginning
- `InsertNewline` edit command that can be bound to `Alt-Enter` if
desired to have line breaks without relying on the `Validator`
- `ClearScreen` will directly clear the visible screen. `Signal::CtrlL` has been
removed.
- `ClearScrollback` will clear the screen and scrollback. Can be used to
mimic macOS `Cmd-K` screen clearing. Helps with #5089
2022-04-20 21:10:33 +12:00
7e97be1dd4 Handle custom values in describe command (#5248) 2022-04-20 16:59:53 +12:00
b501db673a SQLite overhaul: custom value, query db command (#5247)
Clean up query errors
2022-04-20 16:58:21 +12:00
c0ce1e9057 nu-cli/completions: fix file completions with quotes (#5242)
* nu-cli/completions: fix file completions with quotes

* wrap with backticks
2022-04-20 16:54:37 +12:00
4d7b86f278 nu-cli: added tests for file completions (#5232)
* nu-cli: added tests for file completions

* test adding extra sort

* Feature/refactor completion options (#5228)

* Copy completion filter to custom completions

* Remove filter function from completer

This function was a no-op for FileCompletion and CommandCompletion.
Flag- and VariableCompletion just filters with `starts_with` which
happens in both completers anyway and should therefore also be a no-op.
The remaining use case in CustomCompletion was moved into the
CustomCompletion source file.

Filtering should probably happen immediately while fetching completions
to avoid unnecessary memory allocations.

* Add get_sort_by() to Completer trait

* Remove CompletionOptions from Completer::fetch()

* Fix clippy lints

* Apply Completer changes to DotNuCompletion

* add os to $nu based on rust's understanding (#5243)

* add os to $nu based on rust's understanding

* add a few more constants

Co-authored-by: Richard <Tropid@users.noreply.github.com>
Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com>
2022-04-20 16:54:00 +12:00
f2d47f97da add os to $nu based on rust's understanding (#5243)
* add os to $nu based on rust's understanding

* add a few more constants
2022-04-19 14:11:58 -05:00
0de289f6b7 Feature/refactor completion options (#5228)
* Copy completion filter to custom completions

* Remove filter function from completer

This function was a no-op for FileCompletion and CommandCompletion.
Flag- and VariableCompletion just filters with `starts_with` which
happens in both completers anyway and should therefore also be a no-op.
The remaining use case in CustomCompletion was moved into the
CustomCompletion source file.

Filtering should probably happen immediately while fetching completions
to avoid unnecessary memory allocations.

* Add get_sort_by() to Completer trait

* Remove CompletionOptions from Completer::fetch()

* Fix clippy lints

* Apply Completer changes to DotNuCompletion
2022-04-19 13:59:10 -05:00
JT
ae674bfaec move config back to config.nu (#5237) 2022-04-19 20:54:25 +12:00
JT
76079d5183 Move config to be an env var (#5230)
* Move config to be an env var

* fix fmt and tests
2022-04-19 10:28:01 +12:00
409f1480f5 allow par-each to receive $in (#5229)
Co-authored-by: Yethal <nosuchemail@email.com>
2022-04-19 10:02:58 +12:00
e206555d9d add custom_completion field to .scope command (#5227) 2022-04-19 10:02:03 +12:00
88ec4186ec Added search terms to math commands (#5224) 2022-04-19 09:33:32 +12:00
dd1d9b7623 nu-cli/completions: completion for use and source (#5210)
* nu-cli/completions: completion for use and source

* handle subfolders for different base dirs

* fix clippy errors
2022-04-19 00:59:13 +12:00
1314a87cb0 update miette and switch to GenericErrors (#5222) 2022-04-19 00:34:10 +12:00
cf65f77b02 Simplify known external tests (#5219)
* Simplify known external tests

* Cargo fmt
2022-04-17 14:31:03 -05:00
c9f05f074a nth -> select command (#5217) 2022-04-17 09:54:24 -05:00
7710317224 Add known external tests (#5216)
* Add known external tests

* Add some documentation to the tests

* Document test_hello example

* Set PWD in run_test
2022-04-17 05:39:56 -05:00
0a990ed105 Simplify known external name recovery (#5213)
Prior to this change we would recover the names for known
externals by looking up the span in the engine state. This would fail
when using an alias for two reasons:

1. In cases where we don't have a subcommand, like this:

```
>>> extern bat [filename: string]
>>> alias b = bat
>>> bat some_file
'b' is not recognized as an internal or external command,
operable program or batch file.
```

The problem is that after alias expansion, we replace the span of the
expanded name with the original alias (this is done to alleviate
non-related issues). The span contents we look up therefore contain `b`,
the alias, instead of the expanded command name.

2. In cases where there's a subcommand:
```
>>> alias g = git
>>> g push
thread 'main' panicked at 'internal error: span missing in file contents cache', crates\nu-protocol\src\engine\engine_state.rs:474:9
note: run with `RUST_BACKTRACE=1` environment variable to display a
backtrace
```

In this case, the span in call starts where the expansion for the `g`
alias is defined and end after `push` on the last command entered. This
is not a proper span and causes a panic when we try to look it up. Note
that this is the case for all expanded aliases that involve a
subcommand, but we never actually try to retrieve the contents for that
span in other cases.

Anyway, the new way of looking up the name is arguably cleaner
regardless of the issues mentioned above. But it's nice that it fixes
them too.

Co-authored-by: Hristo Filaretov <h.filaretov@protonmail.com>
2022-04-16 22:07:38 -05:00
a35b975d84 Shell Integration (#5162)
This commit renders ANSI chars in order to provide shell integrations
such Kitty's opening feature that captures the output of the last
command in a pager such as less.

Fixes #5138
2022-04-16 22:03:02 -05:00
6e85b04923 [ls, path relative-to] Fix use of ls ~ | path relative-to ~ (#5212)
* [ls] implement 1b.

> `ls ~` does not return paths relative to the current directory.

We now return `/Users/blah` instead of `../../blah`

* expand lhs and rhs on `path relative-to`

/Users/nimazzuc/projects/nushell〉'~' | path relative-to '~'
/Users/nimazzuc/projects/nushell〉'~/foo' | path relative-to '~'
foo
/Users/nimazzuc/projects/nushell〉'/Users/nimazzuc/foo' | path relative-to '~'
foo
/Users/nimazzuc/projects/nushell〉'~/foo' | path relative-to '/Users/nimazzuc'
foo

* format
2022-04-16 15:05:42 -05:00
4d31139a44 add hex color parsing to ansi (#5209) 2022-04-16 10:44:04 -05:00
1bad40726d cleanup nu-command, remove redundant code (#5208) 2022-04-16 18:16:46 +12:00
cb3276fb3b nu-cli/completions: removed unnecessary bool (#5207) 2022-04-16 13:34:38 +12:00
c17129a92a Fix env capture (#5205)
* Fix env capture

* Add test for env capture
2022-04-16 10:38:27 +12:00
JT
5bf1c98a39 Move to dev version 0.61.1 (#5206) 2022-04-16 09:29:30 +12:00
13b371ab58 nu-cli/completions: add completion for record vars (#5204) 2022-04-16 08:24:41 +12:00
2a3991cfdb nu-cli/completions: add completion for $env. (#5199)
* nu-cli/completions: add completion for $env.

* use stack to avoid showing hidden env vars
2022-04-15 16:17:53 +03:00
583b7b1821 fix: reduce command have not redirected block's evaluation output (#5193)
fixes https://github.com/nushell/nushell/issues/5190
2022-04-15 07:03:16 -05:00
581afc9023 updated cargo.lock with cargo update (#5201) 2022-04-15 06:04:15 -05:00
8e2847431e Avoid duplicating post headers (#5200)
* Avoid duplicating post headers

This should fix #5194

* Update post.rs

Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com>
2022-04-15 06:02:22 -05:00
6a1378c1bb Update README.md 2022-04-15 05:27:42 -05:00
2fe14a7a5a fix timestamp parsing on 32-bit platforms (#5192)
Fixes #5191
2022-04-14 08:52:32 -05:00
7490392eb9 Add char -i for chars from integers (#5183)
* Revert "Allow integer to `char -u` (#5174)"

This reverts commit cfefb65d55.

* Add `char -i`

* Reword example
2022-04-14 08:34:02 -05:00
9844e6125b Fix completions for git push and git checkout close: #5021 and #4599 (#5188) 2022-04-14 08:17:58 -05:00
56af7e8d5f tweak badge (#5187)
added `?branch=main?event=push` to see if it makes any difference.
2022-04-14 06:48:17 -05:00
dc612e7ffb documented ShellError errors. (#5172)
* documented ShellError errors.

* just a few touch-ups

Co-authored-by: JT <547158+jntrnr@users.noreply.github.com>
2022-04-14 17:08:46 +12:00
1d1dbfd04c update crate chrono-tz to its latest version (#5184) 2022-04-13 21:16:08 -07:00
c150e11cb4 Initial SQLite functionality (#5182)
* Add SQLite functionality to open

* Add in-memory SQLite tests

* clippy fixes

* Fix up old SQLite-related tests
2022-04-13 20:15:02 -07:00
87c684c7da don't join paths to cwd ever in calls to external functions (#5180)
This is a follow-up to #5131, since I don't personally like the way it worked.
2022-04-13 21:42:57 +03:00
10792a29f7 allow default color shortcut names (#5177)
* allow default color shortcut names

* clippy
2022-04-13 07:02:15 -05:00
257290acc2 Add a dockerfile example based on debian bullseye-slim (#5176)
* feat: add nu dockerfile, based on debian bullseye

* use aria2 instead of wget for bad network

* some small fix
2022-04-13 14:48:54 +03:00
cfefb65d55 Allow integer to char -u (#5174) 2022-04-13 13:33:08 +03:00
3783c19d02 bump miette to 4.4.0 (#5167)
This fixes an issue where docsrs error links were not working.

Ref: https://github.com/zkat/miette/issues/147
2022-04-13 08:38:15 +12:00
1f6e0255c0 Fix typo in link (#5168)
skip-checks:true
2022-04-12 22:13:40 +02:00
JT
b61af9a26a Update README.md 2022-04-13 06:24:46 +12:00
JT
6e2f6c71fe Update README.md 2022-04-13 06:15:34 +12:00
JT
f51d5789a3 Update README.md 2022-04-13 06:15:09 +12:00
JT
933cee27ae Update README.md 2022-04-13 06:12:33 +12:00
JT
4566c904d0 Bump 0.61 (#5166) 2022-04-13 05:42:26 +12:00
9b020c056b Pin reedline version for 0.61 release (#5164) 2022-04-13 04:38:36 +12:00
JT
60b5863058 Remove the im crate dependency (#5161) 2022-04-12 07:01:05 +12:00
836f914163 Clean REPL code, hide Hints without ANSI coloring (#5157)
- With a change to reedline hints can now be hidden. This is useful when
no ANSI coloring is available as hints become indistinguishable from the
actual buffer
- remove commented out code
- order the logging calls according to the implementation
2022-04-12 06:19:42 +12:00
594006cfa0 Fix failing unit tests on Windows (#5142) (#5143)
* Fix failing unit tests on Windows (#5142)

Fix let_env_expressions failing on Windows:
The env expression uses PATH, but on windows Path is used.

Fix correctly_escape_external_arguments, execute_binary_in_string
failing on Windows:
Using cococo now to make sure testresults are platform independent

* Update macros.rs

Co-authored-by: JT <547158+jntrnr@users.noreply.github.com>
2022-04-12 06:18:46 +12:00
57761149f4 Update incorrect crate descriptions (#5159) 2022-04-12 06:17:06 +12:00
521e28dcdc fix #5131 (#5153)
I don't personally agree with this; I'd prefer less magic,
and not expanding _anything_ except `~` as an initial path element

Co-authored-by: nicole mazzuca <mazzucan@outlook.com>
2022-04-11 20:05:39 +12:00
a30930324d Support binary literals with binary format (#5149)
* 4924 Support binary literals with binary format

* 4924 Support automatic padding for binary literals
2022-04-11 19:58:57 +12:00
625e807a35 Support unbinding a particular key event (#5152)
To remove a default keybinding for a particular edit mode, set the `event: null`:

e.g. to disable screen clearing with Ctrl-L

```
let $config = {keybindings: [{
        modifier: control
        keycode: char_l
        mode: [emacs, vi_normal, vi_insert]
        event: null
      } ]}

```
2022-04-10 23:54:09 +02:00
d18f34daa4 Allow overriding of menu keybindings (#5148)
Keybindings that were attached to menus like `Ctrl-x` or `Ctrl-q` could not be replaced with custom bindings
2022-04-10 22:48:55 +02:00
JT
4fd73ef54a Allows aliases in use lists (#5150) 2022-04-11 07:37:22 +12:00
58f395989a Remove unused dependencies (#5145)
* Remove unused packages from base Cargo.toml

* Remove unused crossterm_winapi from nu-cli

* Remove unused dependencies from nu-system

* Remove unused dependencies from nu-test-support
2022-04-10 09:14:55 +12:00
791e8a0e59 enable ls to output datetime in local time vs utc (#5141)
* enable `ls` to output datetime in local time vs utc

* clippy
2022-04-09 11:39:41 -05:00
JT
14066ccc30 Fix known externals, fix operator spans (#5140) 2022-04-09 17:17:48 +12:00
683b912263 Track call arguments in a single list (#5125)
* Initial implementation of ordered call args

* Run cargo fmt

* Fix some clippy lints

* Add positional len and nth

* Cargo fmt

* Remove more old nth calls

* Good ole rustfmt

* Add named len

Co-authored-by: Hristo Filaretov <h.filaretov@protonmail.com>
2022-04-09 14:55:02 +12:00
3bac480ca0 rename menu/fix type-o (#5139) 2022-04-08 20:22:33 -05:00
JT
97eb8492a3 Improve $in handling (#5137)
* Simplify in logic

* Add tests

* more tests, and fixes
2022-04-09 09:41:05 +12:00
JT
0892a16a3d Let 'each' also send input to block (#5136) 2022-04-09 07:57:43 +12:00
JT
0b85938415 Soften the block arity checking (#5135) 2022-04-09 07:57:27 +12:00
aaec840b91 doc change from engine-q to nushell (#5134) 2022-04-08 10:29:21 -07:00
74d0f19291 added ability to opt in to normal string replacement in replace cmd (#5133)
* added ability to opt in to normal string replacement in `replace` cmd

* type-o
2022-04-08 12:23:16 -05:00
JT
7ce570e52c Update LICENSE
this isn't our crate originally, we adapted it
2022-04-08 21:53:29 +12:00
JT
3a0eded0b8 Delete LICENSE
this is dual-licensed, there can't be just one LICENSE file
2022-04-08 21:51:25 +12:00
JT
5afd45414e Revert "nu-cli/completions: cache layer for fetching (#5114)" (#5132)
This reverts commit e86c1b118e.
2022-04-08 21:48:27 +12:00
6ed033737d Include license text in all crates (#5094)
* Include license text in all crates

Three crates already have license texts, so I'm keeping them, but
symlinking the `LICENSE` from the top level to the rest of the crate
directories. This works as long as `cargo publish` is done on a Unix-y
system and not Windows.

Also bump the copyright year to end in 2022.

Signed-off-by: Michel Alexandre Salim <salimma@fedoraproject.org>

* Replace symlinks

Co-authored-by: sholderbach <sholderbach@users.noreply.github.com>
2022-04-08 10:47:13 +02:00
d38a3a8b4e Fix command descriptions+examples (#5129)
* Fix exit usage

* Move dfr as-date* format examples to extra_usage

* Update command usage and examples

* More docs on `str trim`

Co-authored-by: sholderbach <sholderbach@users.noreply.github.com>
2022-04-08 10:30:49 +02:00
6b4cb8b0e0 short descriptions (#5130) 2022-04-08 07:57:39 +01:00
48fa25fd42 nu-cli/completions: removed default filter for command (#5126) 2022-04-07 18:45:04 -05:00
bdfad6b1de add keep deprecated commands (#5124) 2022-04-08 10:10:46 +12:00
JT
4f974efeba Move 'keep' to 'take' (#5123) 2022-04-08 08:49:28 +12:00
e86c1b118e nu-cli/completions: cache layer for fetching (#5114) 2022-04-08 07:36:16 +12:00
5e177fe8e7 nu-cli/completions: fix file completions filtering (#5122) 2022-04-08 07:31:56 +12:00
4129f15eb9 update str find-replace to str replace (#5120) 2022-04-07 08:41:09 -05:00
690ec9abfa Implement rest of touch flags (#5119)
* Add timestamp flag to `touch` command

* Add modify flag to `touch` command

* Add date flag to `touch` command

* Remove unnecessary `touch` test and fix tests setups

* Change `touch` flags descriptions

* Update `touch` example

* Add reference flag to `touch` command

* Add access flag to `touch` command

* Add no-create flag to `touch` command

* Replace `unwrap` with `expect`
2022-04-07 06:44:05 -05:00
b2c52b51b7 Change string contains operators to regex (#5117) 2022-04-07 18:23:14 +12:00
JT
888369022f Add datetime to math-like (#5118)
* Add datetime to math-like

* add test
2022-04-07 18:02:28 +12:00
JT
4409185e1b Improve describe to be more accurate (#5116) 2022-04-07 16:34:09 +12:00
JT
ef1934a7ee Remove external name exceptions (#5115) 2022-04-07 14:01:31 +12:00
JT
591fb4bd36 Add unary not (#5111) 2022-04-07 07:10:25 +12:00
12d3e4e424 Add env.nu file for environment config (#5099)
* Add env.nu file for environment config

* Add missing flag

* Add $nu.env-path variable

Prints `env.nu` path

* Add example of adding entries to PATH
2022-04-07 05:11:51 +12:00
c3bed1352a nu-cli/completions: prioritize non hidden folders (#5108) 2022-04-06 16:56:43 +01:00
3ceb39c82c use arc to avoid cloning entire engine for menus (#5104)
* use arc to avoid cloning entire engine for menus

* remove complete import path

* remove stack clone

* reference in completer
2022-04-06 13:25:02 +01:00
13869e7d52 nu-cli: refactor completions (#5102) 2022-04-06 19:58:55 +12:00
JT
121a4f06fb Load plugins for scripts and commands, too (#5105) 2022-04-06 19:45:26 +12:00
d0e636ae7a Trim newline from input results (#5097) 2022-04-05 12:52:09 -05:00
6e7e2dbb97 enables find to search records with regex (#5100)
* enables find to search records with regex

* clippy
2022-04-05 12:26:11 -05:00
d64cf1687e Fix Format for non-basic data types (#5095) 2022-04-05 07:45:38 -05:00
657b631fdc Add search terms to many commands (#5096) 2022-04-05 07:01:21 -05:00
fa6ed7a40b allow record as text style (#5092) 2022-04-04 22:36:48 +01:00
80f21d37e0 Update reedline to mut Completer API 2022-04-04 23:35:31 +02:00
e2cf4cc7d6 new glob command (#5087) 2022-04-05 08:45:01 +12:00
JT
abe028f930 Add raw strings, use raw strings for env (#5090) 2022-04-05 08:42:26 +12:00
ef1cf7e634 feature: Add some context to completions (#5078)
* send current line and position

* copy current line

* fix error

* deleted test completion
2022-04-05 06:31:40 +12:00
1e4b33b9c6 Add quiet and feedback to mv command (#5073)
* Add quiet and feedback to mv command

* replaced filter and map with filter_map
2022-04-05 06:30:51 +12:00
4654f03d31 update shadow-rs, update git2, remove indexmap from version (#5086) 2022-04-04 09:59:59 -05:00
608b6f3634 Generic menus (#5085)
* updated to reedline generic menus

* help menu with examples

* generic menus in the engine

* description menu template

* list of menus in config

* default value for menu

* menu from block

* generic menus examples

* change to reedline git path

* cargo fmt

* menu name typo

* remove commas from default file

* added error message
2022-04-04 15:54:48 +01:00
a86e6ce89b Set LAST_EXIT_CODE on parse error (#5084) 2022-04-04 06:11:27 -05:00
c4cfbaec2d Fix Python plugin (missing search terms) (#5083)
* Add search_terms to Python plugin

* Clean up Python plugin comments
2022-04-03 20:00:53 -05:00
d40109f210 Tweak append+prepend help (#5080) 2022-04-03 17:50:22 -05:00
20be8a4987 Fix for search terms in help --find (#5081)
* Fix search terms in help --find

* Update help --find description
2022-04-03 17:37:22 -05:00
d6dd4078b1 Remove enqine-q from issue template (#5075)
The notice is not necessary anymore since engine-q is merged now
2022-04-03 06:52:42 -05:00
JT
6649da3f5d Add support for single value row conditions (#5072) 2022-04-03 10:41:36 +12:00
62901573d0 update the readme in the docs folder (#5065)
* update docs/Readme

* tweak readme
2022-04-01 13:48:09 -07:00
JT
80c9888f82 Add command descriptions to completions (#5063) 2022-04-02 08:18:11 +13:00
19c3570cf9 Allow open to work with 'from ...' block commands (#5049)
* Remove panic from BlockCommands run function

Instead of panicing, the run method now returns an error to prevent
nushell from unexpected termination.

* Add ability to open command to run with blocks

The open command tries to parse the content of the file
if there is a command called 'from (file ending)'.  This works
fine if the command was 'built in' because the run method doesn't
fail in this case.  It did fail on a BlockCommand, though.

This change will first probe if the command contains a block and
evaluate it, if this is the case.  If there is no block, it will run
the command the same way as before.

* Add test open files with BlockCommands

* Update open.rs

* Adjust file type on open with BlockCommand parser

Co-authored-by: JT <547158+jntrnr@users.noreply.github.com>
2022-04-02 07:52:32 +13:00
2cb815b7b4 Add starts with operator (#5061)
* add starts_with operator

* added a test
2022-04-01 13:35:46 -05:00
a088081695 update reedline (#5062) 2022-04-01 19:22:40 +01:00
JT
4bb95a880f let a simple last be a single value (#5060) 2022-04-01 23:12:31 +13:00
JT
9beecff736 Add 'date to-record' (#5058) 2022-04-01 21:09:30 +13:00
JT
fa0400c3f2 Fix sort signature (#5055) 2022-04-01 13:03:07 +13:00
JT
1d2d31580b Allow strings for prompt env vars (#5052) 2022-04-01 12:00:50 +13:00
JT
834f993547 Sort command (#5054) 2022-04-01 11:43:16 +13:00
2193910579 Update reedline to new constructor API (#5051) 2022-04-01 11:16:28 +13:00
f692da487e Fix load-env unsupported input error message (#5039) 2022-04-01 10:59:04 +13:00
0986c61a5d Lift line editor construction out of loop (#5041)
Enables the use of some features on reedline

- Keeping the line when clearing the screen with `Ctrl-L`
- Using the internal cut buffer between lines
- Submitting external commands via keybinding and keeping the line

Additional effect:

Keep the history around and do basic syncs (performance improvement
minimal as session changes have to be read and written)

Additional change:

Give the option to defer writing/rereading the history file to the
closing of the session ($config.sync_history_on_enter)
2022-03-31 23:25:48 +02:00
msp
6a6471b04b feat: add --suppress-output (-s) to input command (#5017)
* feat: add --suppress-output (-s) to input command

* Don't handle cursor position since existing impl doesn't

* Handle all raw mode outcomes
2022-03-31 14:20:31 -05:00
05f7d7d38b finish hooking up completion descriptions (#5047) 2022-03-31 11:13:16 -05:00
d89ad4fafd Add record, list, and table to signature types (#5040) 2022-03-31 11:11:03 +03:00
385bc40627 evaluate indicators as commands (#5026)
* evaluate indicators are commands

* default strings in config

* default multiline

* removed build string command
2022-03-31 06:22:55 +01:00
e2d24c5956 Fix which-support feature (#5038) 2022-03-30 13:37:31 -05:00
82633e2df7 update nu-glob README (#5037) 2022-03-30 10:44:23 -07:00
31a4fc41eb Fix env var shorthand when value contains = (#5022) 2022-03-30 09:56:55 +13:00
79182db587 Clean up which/which-support Cargo feature (#5019)
* Rename "which" feature to "which-support"

* Ignore currently broken environment tests
2022-03-29 06:10:43 -05:00
a2872b4ccc Strip '+ ' decoration in git branch list (#5016)
- '+' is the prefix for the current branch in some worktree

Closes #5014
2022-03-28 16:07:55 -05:00
JT
0afa18ac4a Use real stack during custom completion (#5010) 2022-03-29 06:49:41 +13:00
1aef3a730a fix: pass metadata to more filter commands for ls_colors (#5009)
* fix(filters): pass metadata for select

* fix(filters): pass metadata for group, window

* fix(filters): pass metadata for each, every

* fix(filters): pass metadata for collect, compact, flatten

* fix(filters): pass metadata for get

* fix: get rid of necessary `.clone()``

* style: rename closure call to be consistent w/ others

* fix(filters): pass metadata for par-each, prepend

* fix(filters): pass metadata for range

* fix(filters): pass metadata for reject

* fix(filters): pass metadata for more commands

* style: run cargo fmt
2022-03-28 06:43:09 -05:00
e934062542 corrects menu selection (#5004) 2022-03-28 20:43:27 +13:00
JT
2e3b74f1b2 Fix for loop ctrlc not terminating (#5003) 2022-03-28 19:13:43 +13:00
JT
a87f53072a See if levenshtein sorting feels goofor completions (#5001) 2022-03-28 13:31:31 +13:00
047081fa72 Add a README about changing capnp schema (#4998)
* Add a README about changing schema

* Add example PRs
2022-03-27 19:02:19 -05:00
5586d4a0a0 did_you_mean: case-insensitive edit distance, tests (#4999) 2022-03-27 17:11:56 -05:00
JT
911fba8a8a Help menu improvements (#4997)
* Help menu improvements

* default config
2022-03-27 15:21:40 -05:00
2873e943b3 Add search terms to Command and Signature (#4980)
* Add search terms to command

* Rename Signature desc to usage

To be named uniformly with extra_usage

* Throw in foldl search term for reduce

* Add missing usage to post

* Add search terms to signature

* Try to add capnp Signature serialization
2022-03-27 22:25:30 +03:00
0c9dd6a29a Update README.md for Rust 1.59 (#4995)
Since `Cargo.toml` now specifies `strip = ...`, and `strip` is only available in cargo >=1.59, specify that at least this version is required.
2022-03-28 07:28:04 +13:00
a4410fef40 Help menu (#4992)
* nu-completer with suggestions

* help menu with scrolling

* updates description rows based on space

* configuration for help menu

* update nu-ansi-term

* corrected test for update cells

* changed keybinding
2022-03-27 14:01:04 +01:00
0011f4df56 Check same-string-different-case in did_you_mean (#4991) 2022-03-27 19:21:39 +13:00
ee5064abed Nu ansi term update (#4988)
* WIP: Testing 0.45.1 nu-ansi-term with the new Default colors

* point reedline to git in cargo.toml
2022-03-27 16:57:31 +13:00
JT
82e3bb0f38 Bump nushell to 0.60.1 (#4987) 2022-03-27 16:18:47 +13:00
319930a1b9 Add streaming support to save for ExternalStream data (#4985)
* Add streaming support to save for ExternalStream data

Prior to this change, save would collect data from an ExternalStream (data
originating from externals) consuming memory for the full amount of data piped
to it,

This change adds streaming support for ExternalStream allowing saving of
arbitrarily large files and bounding memory usage.

* Remove broken save test

This test passes but not for the right reasons, since this test was
written filename has become a required parameter.  The parser outputs
an error but the test still passes as is checking the original un-mutated
file assuming save has re-written the contents.

This change removes the test.

```
running 1 test
=== stderr
Error: nu::parser::missing_positional (https://docs.rs/nu-parser/0.60.0/nu-parser/enum.ParseError.html#variant.MissingPositional)

  × Missing required positional argument.
   ╭─[source:1:1]
 1 │ open save_test_1/cargo_sample.toml | save
   ·                                          ▲
   ·                                          ╰── missing filename
   ╰────
  help: Usage: save {flags} <filename>

test commands::save::figures_out_intelligently_where_to_write_out_with_metadata ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 515 filtered out; finished in 0.10s
```
2022-03-27 15:39:27 +13:00
a64e0956cd Support binary data to stdin of run-external (#4984)
* Add test for passing binary data through externals

This change adds an ignored test to confirm that binary data is passed
correctly between externals to be enabled in a later commit along with
the fix.

To assist in platform agnostic testing of binary data a couple of
additional testbins were added to allow testing on `Value::Binary` inside
`ExternalStream`.

* Support binary data to stdin of run-external

Prior to this change, any pipeline producing binary data (not detected
as string) then feed into an external would be ignored due to
run-external only supporting `Value::String` on stdin.

This change adds binary stdin support for externals allowing something
like this for example:

  〉^cat /dev/urandom | ^head -c 1MiB | ^pv -b | ignore
  1.00MiB

This would previously output `0.00 B [0.00 B/s]` due to the data not
being pushed to stdin at each stage.
2022-03-27 15:35:59 +13:00
91e17d2f9f Limit mem usage + back-pressure via bounded channels (#4986)
Prior to this change, a pipeline of externals would result in high memory
usage if any of the producers in the chain, produced data faster than
the consumers.

For example a pipeline:

  > fast-producer | slow-consumer

Would cause a build up of `Value::{String,Binary}`'s in the mpsc channels
between each command as values are added to the channels faster than they
are consumed, eventually OOM'ing depnding on system resources, the volume
of data and speed diff. between fast v's slow.

This change replaces the unbounded channels with bounded channels
to limit the number of values that can build up and providing
back-pressure to limit ram usage.
2022-03-27 15:34:34 +13:00
56a546e73d fix ls when file is a socket on mac (#4983) 2022-03-26 21:26:39 -05:00
JT
cf88c8eef3 Improve escaping in string interpolation (#4982) 2022-03-27 12:52:09 +13:00
3484e0defd Add parser keyword note to help and $nu.scope (#4978) 2022-03-26 21:22:45 +02:00
79e4d35f01 Remove is_private from $nu.scope.commands (#4979) 2022-03-26 21:22:35 +02:00
71dd857926 Termux/Android target support for v0.60.0 (#4956)
* Add android as target os for procfs-based ps

* Turn off code for dealing with trash on platforms which are known to not support a standard trash protocol

* Update lib.rs

* Update lib.rs

Co-authored-by: JT <547158+jntrnr@users.noreply.github.com>
2022-03-27 07:21:19 +13:00
7a789d68a2 Don't include trailing separator when expanding tilde (#4974)
* Fix path when expanding tilde

Expanding tilde with no other relative paths would result in:
`$HOME/` instead of `$HOME`. This occurs when users run `cd` with
no extra arguments. In that case, the user's PWD would include the
trailing separator. This does not happen when explicitly passing
a value, such as `cd ~`, because in that case, the path would be
canonicalized.

This happens because std::path::PathBuf::push always adds a separator,
even if adding an empty path, which is what happens when `cd` is
invoked.

* Add test

* Fix test on Windows

Co-authored-by: Hristo Filaretov <h.filaretov@protonmail.com>
2022-03-27 06:28:31 +13:00
8a9cc33aac Fix alias import (#4968)
* Fix alias import

Alias importing was registering the alias id as a decl instead of alias.
This caused issues when hiding and then reimporting the alias.

* Clippy format

Co-authored-by: Hristo Filaretov <h.filaretov@protonmail.com>
2022-03-25 17:56:40 -05:00
JT
66087b01e6 Improve the 'use' and 'source' errors (#4966)
* Improve the 'use' and 'source' errors

* Add register
2022-03-26 10:43:46 +13:00
JT
19fa41b114 Fix single quote environment values (#4960)
* Fix single quote external values

* Try to fix windows

* fix test

* fix test
2022-03-26 09:14:48 +13:00
JT
91cd1717e9 Add escapes to 'to nuon' (#4964) 2022-03-26 08:35:37 +13:00
JT
12b85beecc Fix path join on streams (#4959) 2022-03-26 07:46:48 +13:00
2252833917 bump cargo crate sys-locale to the latest version (#4957) 2022-03-25 10:00:35 -07:00
JT
4e9c1067fb Fix 4946 (#4951)
* Fix reject

* test

* clippy
2022-03-25 20:48:01 +13:00
e505e57a7a align all of the serde_json crates to the same version (#4949) 2022-03-25 18:54:49 +13:00
JT
d122827a30 Fix operator precedence parser (#4947) 2022-03-25 16:23:08 +13:00
b007290a4e Fix #4942, and add a table sorting example for sort-by command (#4948)
* Fix #4942, and add a table sorting example for `sort-by` command

* ci skip
2022-03-25 16:22:57 +13:00
7c92791eed add .mailmap to .gitignore 2022-03-24 20:36:52 -05:00
80769b7197 Set the minimum Rust version to 1.59 (#4940)
nushell uses the strip option in two of its profiles in Cargo.toml.
This option is new in Rust 1.59[0], so this commit adjusts Cargo.toml to
mark 1.59 as the minimum supported Rust version[1].

[0] https://blog.rust-lang.org/2022/02/24/Rust-1.59.0.html
[1] https://doc.rust-lang.org/cargo/reference/manifest.html#the-rust-version-field

Signed-off-by: Randy Barlow <randy@electronsweatshop.com>
2022-03-25 08:08:34 +13:00
9b5dff828d bump csv crate to the latest 1.1.6 (#4939) 2022-03-24 12:59:27 -05:00
90013295aa Fix parse_string_strict() to detect unbalanced quotes properly (#4928) 2022-03-25 05:57:03 +13:00
ea7c8c237e CantConvert improvements (#4926)
* CantConvert improvements

* cargo fmt
2022-03-24 07:04:31 -05:00
JT
5d5b02d8dc Don't assume external ls (#4925) 2022-03-24 16:42:41 +13:00
00b67d338d added missing metadata for drop and uniq #4763 (#4908)
* added missing metadata for drop and uniq #4763

* added missing metadata for keep #4763

* added missing metadata for append #4763

* added missing metadata for shuffle #4763
2022-03-24 07:27:01 +13:00
d32e878868 rename export def to export alias (#4912)
copy-n-paste error
2022-03-23 07:53:10 -05:00
41af2e4b30 update link (#4915) 2022-03-23 07:52:49 -05:00
e9f9aab79f chore: Update default register examples (#4904) 2022-03-23 20:41:58 +13:00
e826540037 Pass /D flag to cmd.exe to disable AutoRun (#4903)
* Pass `/D` flag to `cmd.exe` to disable AutoRun

* Pass `/D` flag before `/c`

This avoids running the command '/D <&self.name.item>' in cmd
2022-03-23 19:05:06 +13:00
a435a9924c add ability to execute on demand (#4896) 2022-03-22 21:09:58 -05:00
JT
02ed15b932 Update Cargo.toml 2022-03-23 09:44:24 +13:00
JT
81e269c483 Update Cargo.toml 2022-03-23 09:44:03 +13:00
JT
eceae26b0a Update Cargo.toml 2022-03-23 09:39:03 +13:00
JT
ec5fd62f9f Add licenses (#4893)
* Add licenses

* Add licenses
2022-03-23 09:25:38 +13:00
658 changed files with 29254 additions and 8624 deletions

View File

@ -5,7 +5,7 @@ body:
id: description
attributes:
label: Describe the bug
description: Thank you for your bug report. We are working diligently with our community to integrate our latest code base that we call [engine-q](https://github.com/nushell/engine-q). We would like your help with this by checking to see if this bug report is still needed in engine-q. Thank you for your patience while we ready the next version of nushell.
description: Thank you for your bug report.
validations:
required: true
- type: textarea

View File

@ -5,7 +5,7 @@ body:
id: problem
attributes:
label: Related problem
description: Thank you for your feature request. We are working diligently with our community to integrate our latest code base that we call [engine-q](https://github.com/nushell/engine-q). We would like your help with this by checking to see if this feature request is still needed in engine-q. Thank you for your patience while we ready the next version of nushell.
description: Thank you for your feature request.
placeholder: |
A clear and concise description of what the problem is.
Example: I am trying to do [...] but [...]

View File

@ -7,5 +7,5 @@
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 --all --all-features -- -D warnings -D clippy::unwrap_used -A clippy::needless_collect` to check that you're using the standard code style
- [ ] `cargo build; cargo test --all --all-features` to check that all the tests pass
- [ ] `cargo clippy --workspace --features=extra -- -D warnings -D clippy::unwrap_used -A clippy::needless_collect` to check that you're using the standard code style
- [ ] `cargo test --workspace --features=extra` to check that all the tests pass

View File

@ -1,34 +1,23 @@
on: [pull_request]
on:
pull_request:
push: # Run CI on the main branch after every merge. This is important to fill the GitHub Actions cache in a way that pull requests can see it
branches:
- main
name: Continuous integration
name: continuous-integration
jobs:
ci:
nu-fmt-clippy:
strategy:
fail-fast: false
fail-fast: true
matrix:
platform: [windows-latest, macos-latest, ubuntu-latest]
style: [all, default, minimal]
rust:
- stable
include:
- style: all
flags: '--all-features'
- style: default
flags: ''
- style: minimal
flags: '--no-default-features'
exclude:
- platform: windows-latest
style: default
- platform: windows-latest
style: minimal
- platform: macos-latest
style: default
- platform: macos-latest
style: minimal
runs-on: ${{ matrix.platform }}
env:
NUSHELL_CARGO_TARGET: ci
steps:
- uses: actions/checkout@v2
@ -41,6 +30,10 @@ jobs:
override: true
components: rustfmt, clippy
- uses: Swatinem/rust-cache@v1
with:
key: "v2" # increment this to bust the cache if needed
- name: Rustfmt
uses: actions-rs/cargo@v1
with:
@ -51,24 +44,58 @@ jobs:
uses: actions-rs/cargo@v1
with:
command: clippy
args: --all ${{ matrix.flags }} -- -D warnings -D clippy::unwrap_used -A clippy::needless_collect
args: --features=extra --workspace --exclude nu_plugin_* -- -D warnings -D clippy::unwrap_used -A clippy::needless_collect
- name: Build Nushell
uses: actions-rs/cargo@v1
nu-tests:
env:
NUSHELL_CARGO_TARGET: ci
strategy:
fail-fast: true
matrix:
platform: [windows-latest, macos-latest, ubuntu-latest]
style: [extra, default]
rust:
- stable
include:
- style: extra
flags: "--features=extra"
- style: default
flags: ""
exclude:
- platform: windows-latest
style: default
- platform: macos-latest
style: default
runs-on: ${{ matrix.platform }}
steps:
- uses: actions/checkout@v2
- name: Setup Rust toolchain
uses: actions-rs/toolchain@v1
with:
command: build
args: ${{ matrix.flags }}
profile: minimal
toolchain: ${{ matrix.rust }}
override: true
- uses: Swatinem/rust-cache@v1
with:
key: ${{ matrix.style }}v3 # increment this to bust the cache if needed
- name: Tests
uses: actions-rs/cargo@v1
with:
command: test
args: --all ${{ matrix.flags }}
args: --workspace --profile ci --exclude nu_plugin_* ${{ matrix.flags }}
python-virtualenv:
env:
NUSHELL_CARGO_TARGET: ci
strategy:
fail-fast: false
fail-fast: true
matrix:
platform: [ubuntu-latest, macos-latest, windows-latest]
rust:
@ -87,13 +114,16 @@ jobs:
profile: minimal
toolchain: ${{ matrix.rust }}
override: true
components: rustfmt, clippy
- uses: Swatinem/rust-cache@v1
with:
key: "2" # increment this to bust the cache if needed
- name: Install Nushell
uses: actions-rs/cargo@v1
with:
command: install
args: --path=. --no-default-features
args: --path=. --profile ci --no-default-features
- name: Setup Python
uses: actions/setup-python@v2
@ -112,3 +142,40 @@ jobs:
- name: Test Nushell in virtualenv
run: cd virtualenv && tox -e ${{ matrix.py }} -- -k nushell
shell: bash
# Build+test plugins on their own, without the rest of Nu. This helps with CI parallelization and
# also helps test that the plugins build without any feature unification shenanigans
plugins:
env:
NUSHELL_CARGO_TARGET: ci
strategy:
fail-fast: true
matrix:
platform: [windows-latest, macos-latest, ubuntu-latest]
rust:
- stable
runs-on: ${{ matrix.platform }}
steps:
- uses: actions/checkout@v2
- name: Setup Rust toolchain
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: ${{ matrix.rust }}
override: true
- name: Clippy
uses: actions-rs/cargo@v1
with:
command: clippy
args: --package nu_plugin_* ${{ matrix.flags }} -- -D warnings -D clippy::unwrap_used -A clippy::needless_collect
- name: Tests
uses: actions-rs/cargo@v1
with:
command: test
args: --profile ci --package nu_plugin_*

View File

@ -27,7 +27,7 @@ jobs:
uses: actions-rs/cargo@v1
with:
command: build
args: --release --all --features=extra
args: --release --all --features=extra,static-link-openssl
# - name: Strip binaries (nu)
# run: strip target/release/nu
@ -89,14 +89,10 @@ jobs:
- name: Copy files to output
run: |
cp target/release/nu target/release/nu_plugin_* output/
cp README.build.txt output/README.txt
cp README.release.txt output/README.txt
cp LICENSE output/LICENSE
rm output/*.d
# Note: If OpenSSL changes, this path will need to be updated
- name: Copy OpenSSL to output
run: cp /usr/lib/x86_64-linux-gnu/libssl.so.1.1 output/
- name: Upload artifact
uses: actions/upload-artifact@v2
with:
@ -121,7 +117,7 @@ jobs:
uses: actions-rs/cargo@v1
with:
command: build
args: --release --all --features=extra
args: --release --all --features=extra,static-link-openssl
# - name: Strip binaries (nu)
# run: strip target/release/nu
@ -183,7 +179,7 @@ jobs:
- name: Copy files to output
run: |
cp target/release/nu target/release/nu_plugin_* output/
cp README.build.txt output/README.txt
cp README.release.txt output/README.txt
cp LICENSE output/LICENSE
rm output/*.d
@ -217,7 +213,7 @@ jobs:
uses: actions-rs/cargo@v1
with:
command: build
args: --release --all --features=extra
args: --release --all --features=extra,static-link-openssl
# - name: Strip binaries (nu.exe)
# run: strip target/release/nu.exe
@ -288,7 +284,7 @@ jobs:
cp LICENSE output\
cp target\release\LICENSE-for-less.txt output\
cp target\release\nu_plugin_*.exe output\
cp README.build.txt output\README.txt
cp README.release.txt output\README.txt
cp target\release\less.exe output\
# Note: If the version of `less.exe` needs to be changed, update this URL
# Similarly, if `less.exe` is checked into the repo, copy from the local path here
@ -361,7 +357,6 @@ jobs:
- name: Restore Linux File Modes
run: |
chmod 755 ${{ steps.info.outputs.linuxdir }}/${{ steps.info.outputs.innerdir }}/nu*
chmod 755 ${{ steps.info.outputs.linuxdir }}/${{ steps.info.outputs.innerdir }}/libssl*
- name: Create Linux tarball
run: tar -zcvf ${{ steps.info.outputs.linuxdir }}.tar.gz ${{ steps.info.outputs.linuxdir }}

View File

@ -1,6 +1,7 @@
name: Submit Nushell package to Windows Package Manager Community Repository
on:
workflow_dispatch:
release:
types: [published]

5
.gitignore vendored
View File

@ -4,6 +4,7 @@
history.txt
tests/fixtures/nuplayground
crates/*/target
.mailmap
# Debian/Ubuntu
debian/.debhelper/
@ -20,3 +21,7 @@ debian/nu/
# VSCode's IDE items
.vscode/*
# Helix configuration folder
.helix/*
.helix

View File

@ -71,5 +71,5 @@ cargo build
- To view verbose logs when developing, enable the `trace` log level.
```shell
cargo build --release --features=extra && cargo run --release --features=extra -- --loglevel trace
cargo build --release --features=extra && cargo run --release --features=extra -- --log-level trace
```

1297
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -10,7 +10,8 @@ license = "MIT"
name = "nu"
readme = "README.md"
repository = "https://github.com/nushell/nushell"
version = "0.60.0"
rust-version = "1.60"
version = "0.63.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@ -33,32 +34,32 @@ members = [
[dependencies]
chrono = "0.4.19"
crossterm = "0.23.0"
crossterm_winapi = "0.9.0"
ctrlc = "3.2.1"
log = "0.4"
miette = "4.1.0"
nu-ansi-term = "0.45.0"
nu-cli = { path="./crates/nu-cli", version = "0.60.0" }
nu-color-config = { path = "./crates/nu-color-config", version = "0.60.0" }
nu-command = { path="./crates/nu-command", version = "0.60.0" }
nu-engine = { path="./crates/nu-engine", version = "0.60.0" }
nu-json = { path="./crates/nu-json", version = "0.60.0" }
nu-parser = { path="./crates/nu-parser", version = "0.60.0" }
nu-path = { path="./crates/nu-path", version = "0.60.0" }
nu-plugin = { path = "./crates/nu-plugin", optional = true, version = "0.60.0" }
nu-pretty-hex = { path = "./crates/nu-pretty-hex", version = "0.60.0" }
nu-protocol = { path = "./crates/nu-protocol", version = "0.60.0" }
nu-system = { path = "./crates/nu-system", version = "0.60.0" }
nu-table = { path = "./crates/nu-table", version = "0.60.0" }
nu-term-grid = { path = "./crates/nu-term-grid", version = "0.60.0" }
nu-utils = { path = "./crates/nu-utils", version = "0.60.0" }
miette = "4.5.0"
nu-ansi-term = "0.45.1"
nu-cli = { path="./crates/nu-cli", version = "0.63.0" }
nu-color-config = { path = "./crates/nu-color-config", version = "0.63.0" }
nu-command = { path="./crates/nu-command", version = "0.63.0" }
nu-engine = { path="./crates/nu-engine", version = "0.63.0" }
nu-json = { path="./crates/nu-json", version = "0.63.0" }
nu-parser = { path="./crates/nu-parser", version = "0.63.0" }
nu-path = { path="./crates/nu-path", version = "0.63.0" }
nu-plugin = { path = "./crates/nu-plugin", optional = true, version = "0.63.0" }
nu-pretty-hex = { path = "./crates/nu-pretty-hex", version = "0.63.0" }
nu-protocol = { path = "./crates/nu-protocol", version = "0.63.0" }
nu-system = { path = "./crates/nu-system", version = "0.63.0" }
nu-table = { path = "./crates/nu-table", version = "0.63.0" }
nu-term-grid = { path = "./crates/nu-term-grid", version = "0.63.0" }
nu-utils = { path = "./crates/nu-utils", version = "0.63.0" }
openssl = { version = "0.10.38", features = ["vendored"], optional = true }
pretty_env_logger = "0.4.0"
rayon = "1.5.1"
reedline = "0.3.0"
reedline = { version = "0.6.0", features = ["bashisms"]}
is_executable = "1.0.1"
[dev-dependencies]
nu-test-support = { path="./crates/nu-test-support" }
nu-test-support = { path="./crates/nu-test-support", version = "0.63.0" }
tempfile = "3.2.0"
assert_cmd = "2.0.2"
pretty_assertions = "1.0.0"
@ -72,14 +73,15 @@ embed-resource = "1"
[features]
plugin = ["nu-plugin", "nu-cli/plugin", "nu-parser/plugin", "nu-command/plugin", "nu-protocol/plugin", "nu-engine/plugin"]
default = ["plugin", "which", "zip-support", "trash-support"]
default = ["plugin", "which-support", "trash-support"]
stable = ["default"]
extra = ["default", "dataframe"]
extra = ["default", "dataframe", "database"]
wasi = []
# Enable to statically link OpenSSL; otherwise the system version will be used. Not enabled by default because it takes a while to build
static-link-openssl = ["dep:openssl"]
# Stable (Default)
which = ["nu-command/which"]
zip-support = ["nu-command/zip"]
which-support = ["nu-command/which-support"]
trash-support = ["nu-command/trash-support"]
# Extra
@ -87,6 +89,9 @@ trash-support = ["nu-command/trash-support"]
# Dataframe feature for nushell
dataframe = ["nu-command/dataframe"]
# Database commands for nushell
database = ["nu-command/database"]
[profile.release]
opt-level = "s" # Optimize for size
strip = "debuginfo"
@ -99,6 +104,13 @@ inherits = "release"
strip = false
debug = true
# build with `cargo build --profile ci`
# to analyze performance with tooling like linux perf
[profile.ci]
inherits = "dev"
strip = false
debug = false
# Main nu binary
[[bin]]
name = "nu"

View File

@ -1,6 +1,6 @@
MIT License
Copyright (c) 2019 - 2021 The Nushell Project Developers
Copyright (c) 2019 - 2022 The Nushell Project Developers
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View File

@ -1,24 +0,0 @@
[tasks.lalrpop]
install_crate = { crate_name = "lalrpop", binary = "lalrpop", test_arg = "--help" }
command = "lalrpop"
args = ["src/parser/parser.lalrpop"]
[tasks.baseline]
command = "cargo"
args = ["build", "--bins"]
[tasks.run]
command = "cargo"
args = ["run"]
dependencies = ["baseline"]
[tasks.test]
command = "cargo"
args = ["test"]
dependencies = ["baseline"]
[tasks.check]
command = "cargo"
args = ["check"]
dependencies = ["baseline"]

View File

@ -1 +0,0 @@
Nu will look for the plugins in your PATH on startup. While nu will have some functionality without them, for full functionality you'll need to copy them into your path so they can be loaded.

View File

@ -1,7 +1,7 @@
# README
[![Crates.io](https://img.shields.io/crates/v/nu.svg)](https://crates.io/crates/nu)
[![Build Status](https://github.com/nushell/nushell/actions/workflows/ci.yml/badge.svg)](https://github.com/nushell/nushell/actions)
![Build Status](https://img.shields.io/github/workflow/status/nushell/nushell/continuous-integration)
[![Discord](https://img.shields.io/discord/601130461678272522.svg?logo=discord)](https://discord.gg/NtAbbGn)
[![The Changelog #363](https://img.shields.io/badge/The%20Changelog-%23363-61c192.svg)](https://changelog.com/podcast/363)
[![@nu_shell](https://img.shields.io/badge/twitter-@nu_shell-1DA1F3?style=flat-square)](https://twitter.com/nu_shell)
@ -43,7 +43,7 @@ You can also find information on more specific topics in our [cookbook](https://
Up-to-date installation instructions can be found in the [installation chapter of the book](https://www.nushell.sh/book/installation.html). **Windows users**: please note that Nu works on Windows 10 and does not currently have Windows 7/8.1 support.
To build Nu, you will need to use the **latest stable (1.51 or later)** version of the compiler.
To build Nu, you will need to use the **latest stable (1.60 or later)** version of the compiler.
Required dependencies:
@ -273,6 +273,9 @@ Please submit an issue or PR to be added to this list.
### Integrations
- [zoxide](https://github.com/ajeetdsouza/zoxide)
- [starship](https://github.com/starship/starship)
- [oh-my-posh](https://ohmyposh.dev)
- [Couchbase Shell](https://couchbase.sh)
- [virtualenv](https://github.com/pypa/virtualenv)
### Mentions
- [The Python Launcher for Unix](https://github.com/brettcannon/python-launcher#how-do-i-get-a-table-of-python-executables-in-nushell)
@ -283,7 +286,7 @@ See [Contributing](CONTRIBUTING.md) for details.
Thanks to all the people who already contributed!
<a href="https://github.com/nushell/nushell/graphs/contributors">
<img src="https://contributors-img.web.app/image?repo=nushell/nushell" />
<img src="https://contributors-img.web.app/image?repo=nushell/nushell&max=500" />
</a>
## License

3
README.release.txt Normal file
View File

@ -0,0 +1,3 @@
To use Nu plugins, use the register command to tell Nu where to find the plugin. For example:
> register -e json ./nu_plugin_query

Binary file not shown.

Before

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 206 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 167 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 182 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 144 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 146 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 77 KiB

View File

@ -1,10 +1,10 @@
#include <winver.h>
#define VER_FILEVERSION 0,59,1,0
#define VER_FILEVERSION_STR "0.59.1"
#define VER_FILEVERSION 0,62,1,0
#define VER_FILEVERSION_STR "0.62.1"
#define VER_PRODUCTVERSION 0,59,1,0
#define VER_PRODUCTVERSION_STR "0.59.1"
#define VER_PRODUCTVERSION 0,62,1,0
#define VER_PRODUCTVERSION_STR "0.62.1"
#ifdef RC_INVOKED

View File

@ -1,23 +1,28 @@
[package]
name = "nu-cli"
version = "0.60.0"
authors = ["The Nushell Project Developers"]
description = "CLI-related functionality for Nushell"
edition = "2021"
license = "MIT"
name = "nu-cli"
version = "0.63.0"
[dev-dependencies]
nu-test-support = { path="../nu-test-support", version = "0.63.0" }
nu-command = { path = "../nu-command", version = "0.63.0" }
[dependencies]
nu-engine = { path = "../nu-engine", version = "0.60.0" }
nu-path = { path = "../nu-path", version = "0.60.0" }
nu-parser = { path = "../nu-parser", version = "0.60.0" }
nu-protocol = { path = "../nu-protocol", version = "0.60.0" }
nu-utils = { path = "../nu-utils", version = "0.60.0" }
nu-ansi-term = "0.45.0"
nu-color-config = { path = "../nu-color-config" }
nu-engine = { path = "../nu-engine", version = "0.63.0" }
nu-path = { path = "../nu-path", version = "0.63.0" }
nu-parser = { path = "../nu-parser", version = "0.63.0" }
nu-protocol = { path = "../nu-protocol", version = "0.63.0" }
nu-utils = { path = "../nu-utils", version = "0.63.0" }
nu-ansi-term = "0.45.1"
nu-color-config = { path = "../nu-color-config", version = "0.63.0" }
reedline = { version = "0.6.0", features = ["bashisms"]}
crossterm = "0.23.0"
crossterm_winapi = "0.9.0"
miette = { version = "4.1.0", features = ["fancy"] }
miette = { version = "4.5.0", features = ["fancy"] }
thiserror = "1.0.29"
reedline = "0.3.0"
fuzzy-matcher = "0.3.7"
log = "0.4"
is_executable = "1.0.1"

21
crates/nu-cli/LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019 - 2022 The Nushell Project Developers
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -2,11 +2,11 @@ use crate::util::report_error;
use log::info;
use miette::Result;
use nu_engine::{convert_env_values, eval_block};
use nu_parser::{parse, trim_quotes};
use nu_parser::parse;
use nu_protocol::engine::Stack;
use nu_protocol::{
engine::{EngineState, StateDelta, StateWorkingSet},
Config, PipelineData, Spanned,
PipelineData, Spanned, Value,
};
use std::path::Path;
@ -17,21 +17,19 @@ pub fn evaluate_commands(
stack: &mut Stack,
input: PipelineData,
is_perf_true: bool,
table_mode: Option<Value>,
) -> Result<()> {
// Run a command (or commands) given to us by the user
let (block, delta) = {
if let Some(ref t_mode) = table_mode {
let mut config = engine_state.get_config().clone();
config.table_mode = t_mode.as_string()?;
engine_state.set_config(&config);
}
let mut working_set = StateWorkingSet::new(engine_state);
let (input, _) = if commands.item.starts_with('\'') || commands.item.starts_with('"') {
(
trim_quotes(commands.item.as_bytes()),
commands.span.start + 1,
)
} else {
(commands.item.as_bytes(), commands.span.start)
};
let (output, err) = parse(&mut working_set, None, input, false, &[]);
let (output, err) = parse(&mut working_set, None, commands.item.as_bytes(), false, &[]);
if let Some(err) = err {
report_error(&working_set, &err);
@ -46,24 +44,17 @@ pub fn evaluate_commands(
report_error(&working_set, &err);
}
let config = match stack.get_config() {
Ok(config) => config,
Err(e) => {
let working_set = StateWorkingSet::new(engine_state);
report_error(&working_set, &e);
Config::default()
}
};
// Make a note of the exceptions we see for externals that look like math expressions
let exceptions = crate::util::external_exceptions(engine_state, stack);
engine_state.external_exceptions = exceptions;
let mut config = engine_state.get_config().clone();
if let Some(t_mode) = table_mode {
config.table_mode = t_mode.as_string()?;
}
// Merge the delta in case env vars changed in the config
match nu_engine::env::current_dir(engine_state, stack) {
Ok(cwd) => {
if let Err(e) = engine_state.merge_delta(StateDelta::new(), Some(stack), cwd) {
if let Err(e) =
engine_state.merge_delta(StateDelta::new(engine_state), Some(stack), cwd)
{
let working_set = StateWorkingSet::new(engine_state);
report_error(&working_set, &e);
std::process::exit(1);
@ -85,7 +76,7 @@ pub fn evaluate_commands(
match eval_block(engine_state, stack, &block, input, false, false) {
Ok(pipeline_data) => {
crate::eval_file::print_table_or_error(engine_state, stack, pipeline_data, &config)
crate::eval_file::print_table_or_error(engine_state, stack, pipeline_data, &mut config)
}
Err(err) => {
let working_set = StateWorkingSet::new(engine_state);

View File

@ -1,636 +0,0 @@
use nu_engine::eval_call;
use nu_parser::{flatten_expression, parse, trim_quotes, FlatShape};
use nu_protocol::{
ast::{Call, Expr},
engine::{EngineState, Stack, StateWorkingSet},
PipelineData, Span, Value, CONFIG_VARIABLE_ID,
};
use reedline::Completer;
const SEP: char = std::path::MAIN_SEPARATOR;
pub struct CompletionOptions {
case_sensitive: bool,
positional: bool,
sort: bool,
}
impl Default for CompletionOptions {
fn default() -> Self {
Self {
case_sensitive: true,
positional: true,
sort: true,
}
}
}
#[derive(Clone)]
pub struct NuCompleter {
engine_state: EngineState,
config: Option<Value>,
}
impl NuCompleter {
pub fn new(engine_state: EngineState, config: Option<Value>) -> Self {
Self {
engine_state,
config,
}
}
fn external_command_completion(&self, prefix: &str) -> Vec<String> {
let mut executables = vec![];
let paths = self.engine_state.env_vars.get("PATH");
if let Some(paths) = paths {
if let Ok(paths) = paths.as_list() {
for path in paths {
let path = path.as_string().unwrap_or_default();
if let Ok(mut contents) = std::fs::read_dir(path) {
while let Some(Ok(item)) = contents.next() {
if !executables.contains(
&item
.path()
.file_name()
.map(|x| x.to_string_lossy().to_string())
.unwrap_or_default(),
) && matches!(
item.path()
.file_name()
.map(|x| x.to_string_lossy().starts_with(prefix)),
Some(true)
) && is_executable::is_executable(&item.path())
{
if let Ok(name) = item.file_name().into_string() {
executables.push(name);
}
}
}
}
}
}
}
executables
}
fn complete_variables(
&self,
working_set: &StateWorkingSet,
prefix: &[u8],
span: Span,
offset: usize,
) -> Vec<(reedline::Span, String)> {
let mut output = vec![];
let builtins = ["$nu", "$in", "$config", "$env", "$nothing"];
for builtin in builtins {
if builtin.as_bytes().starts_with(prefix) {
output.push((
reedline::Span {
start: span.start - offset,
end: span.end - offset,
},
builtin.to_string(),
));
}
}
for scope in &working_set.delta.scope {
for v in &scope.vars {
if v.0.starts_with(prefix) {
output.push((
reedline::Span {
start: span.start - offset,
end: span.end - offset,
},
String::from_utf8_lossy(v.0).to_string(),
));
}
}
}
for scope in &self.engine_state.scope {
for v in &scope.vars {
if v.0.starts_with(prefix) {
output.push((
reedline::Span {
start: span.start - offset,
end: span.end - offset,
},
String::from_utf8_lossy(v.0).to_string(),
));
}
}
}
output.dedup();
output
}
fn complete_commands(
&self,
working_set: &StateWorkingSet,
span: Span,
offset: usize,
find_externals: bool,
) -> Vec<(reedline::Span, String)> {
let prefix = working_set.get_span_contents(span);
let results = working_set
.find_commands_by_prefix(prefix)
.into_iter()
.map(move |x| {
(
reedline::Span {
start: span.start - offset,
end: span.end - offset,
},
String::from_utf8_lossy(&x).to_string(),
)
});
let results_aliases =
working_set
.find_aliases_by_prefix(prefix)
.into_iter()
.map(move |x| {
(
reedline::Span {
start: span.start - offset,
end: span.end - offset,
},
String::from_utf8_lossy(&x).to_string(),
)
});
let mut results = results.chain(results_aliases).collect::<Vec<_>>();
let prefix = working_set.get_span_contents(span);
let prefix = String::from_utf8_lossy(prefix).to_string();
if find_externals {
let results_external =
self.external_command_completion(&prefix)
.into_iter()
.map(move |x| {
(
reedline::Span {
start: span.start - offset,
end: span.end - offset,
},
x,
)
});
for external in results_external {
if results.contains(&external) {
results.push((external.0, format!("^{}", external.1)))
} else {
results.push(external)
}
}
results
} else {
results
}
}
fn completion_helper(&self, line: &str, pos: usize) -> Vec<(reedline::Span, String)> {
let mut working_set = StateWorkingSet::new(&self.engine_state);
let offset = working_set.next_span_start();
let mut line = line.to_string();
line.insert(pos, 'a');
let pos = offset + pos;
let (output, _err) = parse(
&mut working_set,
Some("completer"),
line.as_bytes(),
false,
&[],
);
for pipeline in output.pipelines.into_iter() {
for expr in pipeline.expressions {
let flattened: Vec<_> = flatten_expression(&working_set, &expr);
for (flat_idx, flat) in flattened.iter().enumerate() {
if pos >= flat.0.start && pos < flat.0.end {
let new_span = Span {
start: flat.0.start,
end: flat.0.end - 1,
};
let mut prefix = working_set.get_span_contents(flat.0).to_vec();
prefix.remove(pos - flat.0.start);
if prefix.starts_with(b"$") {
let mut output =
self.complete_variables(&working_set, &prefix, new_span, offset);
output.sort_by(|a, b| a.1.cmp(&b.1));
return output;
}
if prefix.starts_with(b"-") {
// this might be a flag, let's see
if let Expr::Call(call) = &expr.expr {
let decl = working_set.get_decl(call.decl_id);
let sig = decl.signature();
let mut output = vec![];
for named in &sig.named {
if let Some(short) = named.short {
let mut named = vec![0; short.len_utf8()];
short.encode_utf8(&mut named);
named.insert(0, b'-');
if named.starts_with(&prefix) {
output.push((
reedline::Span {
start: new_span.start - offset,
end: new_span.end - offset,
},
String::from_utf8_lossy(&named).to_string(),
));
}
}
if named.long.is_empty() {
continue;
}
let mut named = named.long.as_bytes().to_vec();
named.insert(0, b'-');
named.insert(0, b'-');
if named.starts_with(&prefix) {
output.push((
reedline::Span {
start: new_span.start - offset,
end: new_span.end - offset,
},
String::from_utf8_lossy(&named).to_string(),
));
}
}
output.sort_by(|a, b| a.1.cmp(&b.1));
return output;
}
}
match &flat.1 {
FlatShape::Custom(decl_id) => {
//let prefix = working_set.get_span_contents(flat.0).to_vec();
let mut stack = Stack::new();
// Set up our initial config to start from
if let Some(conf) = &self.config {
stack.vars.insert(CONFIG_VARIABLE_ID, conf.clone());
} else {
stack.vars.insert(
CONFIG_VARIABLE_ID,
Value::Record {
cols: vec![],
vals: vec![],
span: Span { start: 0, end: 0 },
},
);
}
let result = eval_call(
&self.engine_state,
&mut stack,
&Call {
decl_id: *decl_id,
head: new_span,
positional: vec![],
named: vec![],
redirect_stdout: true,
redirect_stderr: true,
},
PipelineData::new(new_span),
);
fn map_completions<'a>(
list: impl Iterator<Item = &'a Value>,
new_span: Span,
offset: usize,
) -> Vec<(reedline::Span, String)> {
list.filter_map(move |x| {
let s = x.as_string();
match s {
Ok(s) => Some((
reedline::Span {
start: new_span.start - offset,
end: new_span.end - offset,
},
s,
)),
Err(_) => None,
}
})
.collect()
}
let (completions, options) = match result {
Ok(pd) => {
let value = pd.into_value(new_span);
match &value {
Value::Record { .. } => {
let completions = value
.get_data_by_key("completions")
.and_then(|val| {
val.as_list().ok().map(|it| {
map_completions(
it.iter(),
new_span,
offset,
)
})
})
.unwrap_or_default();
let options = value.get_data_by_key("options");
let options =
if let Some(Value::Record { .. }) = &options {
let options = options.unwrap_or_default();
CompletionOptions {
case_sensitive: options
.get_data_by_key("case_sensitive")
.and_then(|val| val.as_bool().ok())
.unwrap_or(true),
positional: options
.get_data_by_key("positional")
.and_then(|val| val.as_bool().ok())
.unwrap_or(true),
sort: options
.get_data_by_key("sort")
.and_then(|val| val.as_bool().ok())
.unwrap_or(true),
}
} else {
CompletionOptions::default()
};
(completions, options)
}
Value::List { vals, .. } => {
let completions =
map_completions(vals.iter(), new_span, offset);
(completions, CompletionOptions::default())
}
_ => (vec![], CompletionOptions::default()),
}
}
_ => (vec![], CompletionOptions::default()),
};
let mut completions: Vec<(reedline::Span, String)> = completions
.into_iter()
.filter(|it| {
// Minimise clones for new functionality
match (options.case_sensitive, options.positional) {
(true, true) => it.1.as_bytes().starts_with(&prefix),
(true, false) => it.1.contains(
std::str::from_utf8(&prefix).unwrap_or(""),
),
(false, positional) => {
let value = it.1.to_lowercase();
let prefix = std::str::from_utf8(&prefix)
.unwrap_or("")
.to_lowercase();
if positional {
value.starts_with(&prefix)
} else {
value.contains(&prefix)
}
}
}
})
.collect();
if options.sort {
completions.sort_by(|a, b| a.1.cmp(&b.1));
}
return completions;
}
FlatShape::Filepath | FlatShape::GlobPattern => {
let cwd = if let Some(d) = self.engine_state.env_vars.get("PWD") {
match d.as_string() {
Ok(s) => s,
Err(_) => "".to_string(),
}
} else {
"".to_string()
};
let prefix = String::from_utf8_lossy(&prefix).to_string();
let mut output: Vec<_> =
file_path_completion(new_span, &prefix, &cwd)
.into_iter()
.map(move |x| {
(
reedline::Span {
start: x.0.start - offset,
end: x.0.end - offset,
},
x.1,
)
})
.collect();
output.sort_by(|a, b| a.1.cmp(&b.1));
return output;
}
flat_shape => {
let last = flattened
.iter()
.rev()
.skip_while(|x| x.0.end > pos)
.take_while(|x| {
matches!(
x.1,
FlatShape::InternalCall
| FlatShape::External
| FlatShape::ExternalArg
| FlatShape::Literal
| FlatShape::String
)
})
.last();
// The last item here would be the earliest shape that could possible by part of this subcommand
let subcommands = if let Some(last) = last {
self.complete_commands(
&working_set,
Span {
start: last.0.start,
end: pos,
},
offset,
false,
)
} else {
vec![]
};
if !subcommands.is_empty() {
return subcommands;
}
let commands =
if matches!(flat_shape, nu_parser::FlatShape::External)
|| matches!(flat_shape, nu_parser::FlatShape::InternalCall)
|| ((new_span.end - new_span.start) == 0)
{
// we're in a gap or at a command
self.complete_commands(&working_set, new_span, offset, true)
} else {
vec![]
};
let cwd = if let Some(d) = self.engine_state.env_vars.get("PWD") {
match d.as_string() {
Ok(s) => s,
Err(_) => "".to_string(),
}
} else {
"".to_string()
};
let preceding_byte = if new_span.start > offset {
working_set
.get_span_contents(Span {
start: new_span.start - 1,
end: new_span.start,
})
.to_vec()
} else {
vec![]
};
// let prefix = working_set.get_span_contents(flat.0);
let prefix = String::from_utf8_lossy(&prefix).to_string();
let mut output = file_path_completion(new_span, &prefix, &cwd)
.into_iter()
.map(move |x| {
if flat_idx == 0 {
// We're in the command position
if x.1.starts_with('"')
&& !matches!(preceding_byte.get(0), Some(b'^'))
{
let trimmed = trim_quotes(x.1.as_bytes());
let trimmed =
String::from_utf8_lossy(trimmed).to_string();
let expanded =
nu_path::canonicalize_with(trimmed, &cwd);
if let Ok(expanded) = expanded {
if is_executable::is_executable(expanded) {
(x.0, format!("^{}", x.1))
} else {
(x.0, x.1)
}
} else {
(x.0, x.1)
}
} else {
(x.0, x.1)
}
} else {
(x.0, x.1)
}
})
.map(move |x| {
(
reedline::Span {
start: x.0.start - offset,
end: x.0.end - offset,
},
x.1,
)
})
.chain(subcommands.into_iter())
.chain(commands.into_iter())
.collect::<Vec<_>>();
//output.dedup_by(|a, b| a.1 == b.1);
output.sort_by(|a, b| a.1.cmp(&b.1));
return output;
}
}
}
}
}
}
vec![]
}
}
impl Completer for NuCompleter {
fn complete(&self, line: &str, pos: usize) -> Vec<(reedline::Span, String)> {
self.completion_helper(line, pos)
}
}
fn file_path_completion(
span: nu_protocol::Span,
partial: &str,
cwd: &str,
) -> Vec<(nu_protocol::Span, String)> {
use std::path::{is_separator, Path};
let partial = partial.replace('\'', "");
let (base_dir_name, partial) = {
// If partial is only a word we want to search in the current dir
let (base, rest) = partial.rsplit_once(is_separator).unwrap_or((".", &partial));
// On windows, this standardizes paths to use \
let mut base = base.replace(is_separator, &SEP.to_string());
// rsplit_once removes the separator
base.push(SEP);
(base, rest)
};
let base_dir = nu_path::expand_path_with(&base_dir_name, cwd);
// This check is here as base_dir.read_dir() with base_dir == "" will open the current dir
// which we don't want in this case (if we did, base_dir would already be ".")
if base_dir == Path::new("") {
return Vec::new();
}
if let Ok(result) = base_dir.read_dir() {
result
.filter_map(|entry| {
entry.ok().and_then(|entry| {
let mut file_name = entry.file_name().to_string_lossy().into_owned();
if matches(partial, &file_name) {
let mut path = format!("{}{}", base_dir_name, file_name);
if entry.path().is_dir() {
path.push(SEP);
file_name.push(SEP);
}
if path.contains(' ') {
path = format!("\'{}\'", path);
}
Some((span, path))
} else {
None
}
})
})
.collect()
} else {
Vec::new()
}
}
fn matches(partial: &str, from: &str) -> bool {
from.to_ascii_lowercase()
.starts_with(&partial.to_ascii_lowercase())
}

View File

@ -0,0 +1,43 @@
use crate::completions::{CompletionOptions, SortBy};
use nu_protocol::{engine::StateWorkingSet, levenshtein_distance, Span};
use reedline::Suggestion;
// Completer trait represents the three stages of the completion
// fetch, filter and sort
pub trait Completer {
fn fetch(
&mut self,
working_set: &StateWorkingSet,
prefix: Vec<u8>,
span: Span,
offset: usize,
pos: usize,
options: &CompletionOptions,
) -> Vec<Suggestion>;
fn get_sort_by(&self) -> SortBy {
SortBy::Ascending
}
fn sort(&self, items: Vec<Suggestion>, prefix: Vec<u8>) -> Vec<Suggestion> {
let prefix_str = String::from_utf8_lossy(&prefix).to_string();
let mut filtered_items = items;
// Sort items
match self.get_sort_by() {
SortBy::LevenshteinDistance => {
filtered_items.sort_by(|a, b| {
let a_distance = levenshtein_distance(&prefix_str, &a.value);
let b_distance = levenshtein_distance(&prefix_str, &b.value);
a_distance.cmp(&b_distance)
});
}
SortBy::Ascending => {
filtered_items.sort_by(|a, b| a.value.cmp(&b.value));
}
SortBy::None => {}
};
filtered_items
}
}

View File

@ -0,0 +1,221 @@
use crate::completions::{Completer, CompletionOptions, MatchAlgorithm, SortBy};
use nu_parser::FlatShape;
use nu_protocol::{
engine::{EngineState, StateWorkingSet},
Span,
};
use reedline::Suggestion;
use std::sync::Arc;
pub struct CommandCompletion {
engine_state: Arc<EngineState>,
flattened: Vec<(Span, FlatShape)>,
flat_shape: FlatShape,
}
impl CommandCompletion {
pub fn new(
engine_state: Arc<EngineState>,
_: &StateWorkingSet,
flattened: Vec<(Span, FlatShape)>,
flat_shape: FlatShape,
) -> Self {
Self {
engine_state,
flattened,
flat_shape,
}
}
fn external_command_completion(
&self,
prefix: &str,
match_algorithm: MatchAlgorithm,
) -> Vec<String> {
let mut executables = vec![];
let paths = self.engine_state.get_env_var("PATH");
if let Some(paths) = paths {
if let Ok(paths) = paths.as_list() {
for path in paths {
let path = path.as_string().unwrap_or_default();
if let Ok(mut contents) = std::fs::read_dir(path) {
while let Some(Ok(item)) = contents.next() {
if !executables.contains(
&item
.path()
.file_name()
.map(|x| x.to_string_lossy().to_string())
.unwrap_or_default(),
) && matches!(
item.path()
.file_name()
.map(|x| match_algorithm
.matches_str(&x.to_string_lossy(), prefix)),
Some(true)
) && is_executable::is_executable(&item.path())
{
if let Ok(name) = item.file_name().into_string() {
executables.push(name);
}
}
}
}
}
}
}
executables
}
fn complete_commands(
&self,
working_set: &StateWorkingSet,
span: Span,
offset: usize,
find_externals: bool,
match_algorithm: MatchAlgorithm,
) -> Vec<Suggestion> {
let partial = working_set.get_span_contents(span);
let filter_predicate = |command: &[u8]| match_algorithm.matches_u8(command, partial);
let results = working_set
.find_commands_by_predicate(filter_predicate)
.into_iter()
.map(move |x| Suggestion {
value: String::from_utf8_lossy(&x.0).to_string(),
description: x.1,
extra: None,
span: reedline::Span {
start: span.start - offset,
end: span.end - offset,
},
append_whitespace: true,
});
let results_aliases = working_set
.find_aliases_by_predicate(filter_predicate)
.into_iter()
.map(move |x| Suggestion {
value: String::from_utf8_lossy(&x).to_string(),
description: None,
extra: None,
span: reedline::Span {
start: span.start - offset,
end: span.end - offset,
},
append_whitespace: true,
});
let mut results = results.chain(results_aliases).collect::<Vec<_>>();
let partial = working_set.get_span_contents(span);
let partial = String::from_utf8_lossy(partial).to_string();
let results = if find_externals {
let results_external = self
.external_command_completion(&partial, match_algorithm)
.into_iter()
.map(move |x| Suggestion {
value: x,
description: None,
extra: None,
span: reedline::Span {
start: span.start - offset,
end: span.end - offset,
},
append_whitespace: true,
});
for external in results_external {
if results.contains(&external) {
results.push(Suggestion {
value: format!("^{}", external.value),
description: None,
extra: None,
span: external.span,
append_whitespace: true,
})
} else {
results.push(external)
}
}
results
} else {
results
};
results
}
}
impl Completer for CommandCompletion {
fn fetch(
&mut self,
working_set: &StateWorkingSet,
_prefix: Vec<u8>,
span: Span,
offset: usize,
pos: usize,
options: &CompletionOptions,
) -> Vec<Suggestion> {
let last = self
.flattened
.iter()
.rev()
.skip_while(|x| x.0.end > pos)
.take_while(|x| {
matches!(
x.1,
FlatShape::InternalCall
| FlatShape::External
| FlatShape::ExternalArg
| FlatShape::Literal
| FlatShape::String
)
})
.last();
// The last item here would be the earliest shape that could possible by part of this subcommand
let subcommands = if let Some(last) = last {
self.complete_commands(
working_set,
Span {
start: last.0.start,
end: pos,
},
offset,
false,
options.match_algorithm,
)
} else {
vec![]
};
if !subcommands.is_empty() {
return subcommands;
}
let commands = if matches!(self.flat_shape, nu_parser::FlatShape::External)
|| matches!(self.flat_shape, nu_parser::FlatShape::InternalCall)
|| ((span.end - span.start) == 0)
{
// we're in a gap or at a command
self.complete_commands(working_set, span, offset, true, options.match_algorithm)
} else {
vec![]
};
subcommands
.into_iter()
.chain(commands.into_iter())
.collect::<Vec<_>>()
}
fn get_sort_by(&self) -> SortBy {
SortBy::LevenshteinDistance
}
}

View File

@ -0,0 +1,277 @@
use crate::completions::{
CommandCompletion, Completer, CompletionOptions, CustomCompletion, DirectoryCompletion,
DotNuCompletion, FileCompletion, FlagCompletion, MatchAlgorithm, VariableCompletion,
};
use nu_parser::{flatten_expression, parse, FlatShape};
use nu_protocol::{
engine::{EngineState, Stack, StateWorkingSet},
Span,
};
use reedline::{Completer as ReedlineCompleter, Suggestion};
use std::str;
use std::sync::Arc;
#[derive(Clone)]
pub struct NuCompleter {
engine_state: Arc<EngineState>,
stack: Stack,
}
impl NuCompleter {
pub fn new(engine_state: Arc<EngineState>, stack: Stack) -> Self {
Self {
engine_state,
stack,
}
}
// Process the completion for a given completer
fn process_completion<T: Completer>(
&self,
completer: &mut T,
working_set: &StateWorkingSet,
prefix: Vec<u8>,
new_span: Span,
offset: usize,
pos: usize,
) -> Vec<Suggestion> {
let config = self.engine_state.get_config();
let mut options = CompletionOptions::default();
if config.completion_algorithm == "fuzzy" {
options.match_algorithm = MatchAlgorithm::Fuzzy;
}
// Fetch
let mut suggestions =
completer.fetch(working_set, prefix.clone(), new_span, offset, pos, &options);
// Sort
suggestions = completer.sort(suggestions, prefix);
suggestions
}
fn completion_helper(&mut self, line: &str, pos: usize) -> Vec<Suggestion> {
let mut working_set = StateWorkingSet::new(&self.engine_state);
let offset = working_set.next_span_start();
let initial_line = line.to_string();
let mut line = line.to_string();
line.insert(pos, 'a');
let pos = offset + pos;
let (output, _err) = parse(
&mut working_set,
Some("completer"),
line.as_bytes(),
false,
&[],
);
for pipeline in output.pipelines.into_iter() {
for expr in pipeline.expressions {
let flattened: Vec<_> = flatten_expression(&working_set, &expr);
for (flat_idx, flat) in flattened.iter().enumerate() {
if pos >= flat.0.start && pos < flat.0.end {
// Context variables
let most_left_var =
most_left_variable(flat_idx, &working_set, flattened.clone());
// Create a new span
let new_span = Span {
start: flat.0.start,
end: flat.0.end - 1,
};
// Parses the prefix
let mut prefix = working_set.get_span_contents(flat.0).to_vec();
prefix.remove(pos - flat.0.start);
// Completions that depends on the previous expression (e.g: use, source)
if flat_idx > 0 {
if let Some(previous_expr) = flattened.get(flat_idx - 1) {
// Read the content for the previous expression
let prev_expr_str =
working_set.get_span_contents(previous_expr.0).to_vec();
// Completion for .nu files
if prev_expr_str == b"use" || prev_expr_str == b"source" {
let mut completer =
DotNuCompletion::new(self.engine_state.clone());
return self.process_completion(
&mut completer,
&working_set,
prefix,
new_span,
offset,
pos,
);
}
}
}
// Variables completion
if prefix.starts_with(b"$") || most_left_var.is_some() {
let mut completer = VariableCompletion::new(
self.engine_state.clone(),
self.stack.clone(),
most_left_var.unwrap_or((vec![], vec![])),
);
return self.process_completion(
&mut completer,
&working_set,
prefix,
new_span,
offset,
pos,
);
}
// Flags completion
if prefix.starts_with(b"-") {
let mut completer = FlagCompletion::new(expr);
return self.process_completion(
&mut completer,
&working_set,
prefix,
new_span,
offset,
pos,
);
}
// Match other types
match &flat.1 {
FlatShape::Custom(decl_id) => {
let mut completer = CustomCompletion::new(
self.engine_state.clone(),
self.stack.clone(),
*decl_id,
initial_line,
);
return self.process_completion(
&mut completer,
&working_set,
prefix,
new_span,
offset,
pos,
);
}
FlatShape::Directory => {
let mut completer =
DirectoryCompletion::new(self.engine_state.clone());
return self.process_completion(
&mut completer,
&working_set,
prefix,
new_span,
offset,
pos,
);
}
flat_shape => {
let mut completer = CommandCompletion::new(
self.engine_state.clone(),
&working_set,
flattened.clone(),
// flat_idx,
flat_shape.clone(),
);
let out: Vec<_> = self.process_completion(
&mut completer,
&working_set,
prefix.clone(),
new_span,
offset,
pos,
);
if out.is_empty() {
let mut completer =
FileCompletion::new(self.engine_state.clone());
return self.process_completion(
&mut completer,
&working_set,
prefix,
new_span,
offset,
pos,
);
}
return out;
}
};
}
}
}
}
return vec![];
}
}
impl ReedlineCompleter for NuCompleter {
fn complete(&mut self, line: &str, pos: usize) -> Vec<Suggestion> {
self.completion_helper(line, pos)
}
}
// reads the most left variable returning it's name (e.g: $myvar)
// and the depth (a.b.c)
fn most_left_variable(
idx: usize,
working_set: &StateWorkingSet<'_>,
flattened: Vec<(Span, FlatShape)>,
) -> Option<(Vec<u8>, Vec<Vec<u8>>)> {
// Reverse items to read the list backwards and truncate
// because the only items that matters are the ones before the current index
let mut rev = flattened;
rev.truncate(idx);
rev = rev.into_iter().rev().collect();
// Store the variables and sub levels found and reverse to correct order
let mut variables_found: Vec<Vec<u8>> = vec![];
let mut found_var = false;
for item in rev.clone() {
let result = working_set.get_span_contents(item.0).to_vec();
match item.1 {
FlatShape::Variable => {
variables_found.push(result);
found_var = true;
break;
}
FlatShape::String => {
variables_found.push(result);
}
_ => {
break;
}
}
}
// If most left var was not found
if !found_var {
return None;
}
// Reverse the order back
variables_found = variables_found.into_iter().rev().collect();
// Extract the variable and the sublevels
let var = variables_found.first().unwrap_or(&vec![]).to_vec();
let sublevels: Vec<Vec<u8>> = variables_found.into_iter().skip(1).collect();
Some((var, sublevels))
}

View File

@ -0,0 +1,137 @@
use std::fmt::Display;
use fuzzy_matcher::{skim::SkimMatcherV2, FuzzyMatcher};
use nu_parser::trim_quotes_str;
#[derive(Copy, Clone)]
pub enum SortBy {
LevenshteinDistance,
Ascending,
None,
}
/// Describes how suggestions should be matched.
#[derive(Copy, Clone, Debug)]
pub enum MatchAlgorithm {
/// Only show suggestions which begin with the given input
///
/// Example:
/// "git switch" is matched by "git sw"
Prefix,
/// Only show suggestions which contain the input chars at any place
///
/// Example:
/// "git checkout" is matched by "gco"
Fuzzy,
}
impl MatchAlgorithm {
/// Returns whether the `needle` search text matches the given `haystack`.
pub fn matches_str(&self, haystack: &str, needle: &str) -> bool {
let haystack = trim_quotes_str(haystack);
let needle = trim_quotes_str(needle);
match *self {
MatchAlgorithm::Prefix => haystack.starts_with(needle),
MatchAlgorithm::Fuzzy => {
let matcher = SkimMatcherV2::default();
matcher.fuzzy_match(haystack, needle).is_some()
}
}
}
/// Returns whether the `needle` search text matches the given `haystack`.
pub fn matches_u8(&self, haystack: &[u8], needle: &[u8]) -> bool {
match *self {
MatchAlgorithm::Prefix => haystack.starts_with(needle),
MatchAlgorithm::Fuzzy => {
let haystack_str = String::from_utf8_lossy(haystack);
let needle_str = String::from_utf8_lossy(needle);
let matcher = SkimMatcherV2::default();
matcher.fuzzy_match(&haystack_str, &needle_str).is_some()
}
}
}
}
impl TryFrom<String> for MatchAlgorithm {
type Error = InvalidMatchAlgorithm;
fn try_from(value: String) -> Result<Self, Self::Error> {
match value.as_str() {
"prefix" => Ok(Self::Prefix),
"fuzzy" => Ok(Self::Fuzzy),
_ => Err(InvalidMatchAlgorithm::Unknown),
}
}
}
#[derive(Debug)]
pub enum InvalidMatchAlgorithm {
Unknown,
}
impl Display for InvalidMatchAlgorithm {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match *self {
InvalidMatchAlgorithm::Unknown => write!(f, "unknown match algorithm"),
}
}
}
impl std::error::Error for InvalidMatchAlgorithm {}
#[derive(Clone)]
pub struct CompletionOptions {
pub case_sensitive: bool,
pub positional: bool,
pub sort_by: SortBy,
pub match_algorithm: MatchAlgorithm,
}
impl Default for CompletionOptions {
fn default() -> Self {
Self {
case_sensitive: true,
positional: true,
sort_by: SortBy::Ascending,
match_algorithm: MatchAlgorithm::Prefix,
}
}
}
#[cfg(test)]
mod test {
use super::MatchAlgorithm;
#[test]
fn match_algorithm_prefix() {
let algorithm = MatchAlgorithm::Prefix;
assert!(algorithm.matches_str("example text", ""));
assert!(algorithm.matches_str("example text", "examp"));
assert!(!algorithm.matches_str("example text", "text"));
assert!(algorithm.matches_u8(&[1, 2, 3], &[]));
assert!(algorithm.matches_u8(&[1, 2, 3], &[1, 2]));
assert!(!algorithm.matches_u8(&[1, 2, 3], &[2, 3]));
}
#[test]
fn match_algorithm_fuzzy() {
let algorithm = MatchAlgorithm::Fuzzy;
assert!(algorithm.matches_str("example text", ""));
assert!(algorithm.matches_str("example text", "examp"));
assert!(algorithm.matches_str("example text", "ext"));
assert!(algorithm.matches_str("example text", "mplxt"));
assert!(!algorithm.matches_str("example text", "mpp"));
assert!(algorithm.matches_u8(&[1, 2, 3], &[]));
assert!(algorithm.matches_u8(&[1, 2, 3], &[1, 2]));
assert!(algorithm.matches_u8(&[1, 2, 3], &[2, 3]));
assert!(algorithm.matches_u8(&[1, 2, 3], &[1, 3]));
assert!(!algorithm.matches_u8(&[1, 2, 3], &[2, 2]));
}
}

View File

@ -0,0 +1,233 @@
use crate::completions::{Completer, CompletionOptions, MatchAlgorithm, SortBy};
use nu_engine::eval_call;
use nu_protocol::{
ast::{Argument, Call, Expr, Expression},
engine::{EngineState, Stack, StateWorkingSet},
PipelineData, Span, Type, Value,
};
use reedline::Suggestion;
use std::sync::Arc;
pub struct CustomCompletion {
engine_state: Arc<EngineState>,
stack: Stack,
decl_id: usize,
line: String,
sort_by: SortBy,
}
impl CustomCompletion {
pub fn new(engine_state: Arc<EngineState>, stack: Stack, decl_id: usize, line: String) -> Self {
Self {
engine_state,
stack,
decl_id,
line,
sort_by: SortBy::None,
}
}
fn map_completions<'a>(
&self,
list: impl Iterator<Item = &'a Value>,
span: Span,
offset: usize,
) -> Vec<Suggestion> {
list.filter_map(move |x| {
// Match for string values
if let Ok(s) = x.as_string() {
return Some(Suggestion {
value: s,
description: None,
extra: None,
span: reedline::Span {
start: span.start - offset,
end: span.end - offset,
},
append_whitespace: false,
});
}
// Match for record values
if let Ok((cols, vals)) = x.as_record() {
let mut suggestion = Suggestion {
value: String::from(""), // Initialize with empty string
description: None,
extra: None,
span: reedline::Span {
start: span.start - offset,
end: span.end - offset,
},
append_whitespace: false,
};
// Iterate the cols looking for `value` and `description`
cols.iter().zip(vals).for_each(|it| {
// Match `value` column
if it.0 == "value" {
// Convert the value to string
if let Ok(val_str) = it.1.as_string() {
// Update the suggestion value
suggestion.value = val_str;
}
}
// Match `description` column
if it.0 == "description" {
// Convert the value to string
if let Ok(desc_str) = it.1.as_string() {
// Update the suggestion value
suggestion.description = Some(desc_str);
}
}
});
return Some(suggestion);
}
None
})
.collect()
}
}
impl Completer for CustomCompletion {
fn fetch(
&mut self,
_: &StateWorkingSet,
prefix: Vec<u8>,
span: Span,
offset: usize,
pos: usize,
completion_options: &CompletionOptions,
) -> Vec<Suggestion> {
// Line position
let line_pos = pos - offset;
// Call custom declaration
let result = eval_call(
&self.engine_state,
&mut self.stack,
&Call {
decl_id: self.decl_id,
head: span,
arguments: vec![
Argument::Positional(Expression {
span: Span { start: 0, end: 0 },
ty: Type::String,
expr: Expr::String(self.line.clone()),
custom_completion: None,
}),
Argument::Positional(Expression {
span: Span { start: 0, end: 0 },
ty: Type::Int,
expr: Expr::Int(line_pos as i64),
custom_completion: None,
}),
],
redirect_stdout: true,
redirect_stderr: true,
},
PipelineData::new(span),
);
let mut custom_completion_options = None;
// Parse result
let suggestions = match result {
Ok(pd) => {
let value = pd.into_value(span);
match &value {
Value::Record { .. } => {
let completions = value
.get_data_by_key("completions")
.and_then(|val| {
val.as_list()
.ok()
.map(|it| self.map_completions(it.iter(), span, offset))
})
.unwrap_or_default();
let options = value.get_data_by_key("options");
if let Some(Value::Record { .. }) = &options {
let options = options.unwrap_or_default();
let should_sort = options
.get_data_by_key("sort")
.and_then(|val| val.as_bool().ok())
.unwrap_or(false);
if should_sort {
self.sort_by = SortBy::Ascending;
}
custom_completion_options = Some(CompletionOptions {
case_sensitive: options
.get_data_by_key("case_sensitive")
.and_then(|val| val.as_bool().ok())
.unwrap_or(true),
positional: options
.get_data_by_key("positional")
.and_then(|val| val.as_bool().ok())
.unwrap_or(true),
sort_by: if should_sort {
SortBy::Ascending
} else {
SortBy::None
},
match_algorithm: match options
.get_data_by_key("completion_algorithm")
{
Some(option) => option
.as_string()
.ok()
.and_then(|option| option.try_into().ok())
.unwrap_or(MatchAlgorithm::Prefix),
None => completion_options.match_algorithm,
},
});
}
completions
}
Value::List { vals, .. } => self.map_completions(vals.iter(), span, offset),
_ => vec![],
}
}
_ => vec![],
};
if let Some(custom_completion_options) = custom_completion_options {
filter(&prefix, suggestions, &custom_completion_options)
} else {
filter(&prefix, suggestions, completion_options)
}
}
fn get_sort_by(&self) -> SortBy {
self.sort_by
}
}
fn filter(prefix: &[u8], items: Vec<Suggestion>, options: &CompletionOptions) -> Vec<Suggestion> {
items
.into_iter()
.filter(|it| match options.match_algorithm {
MatchAlgorithm::Prefix => match (options.case_sensitive, options.positional) {
(true, true) => it.value.as_bytes().starts_with(prefix),
(true, false) => it.value.contains(std::str::from_utf8(prefix).unwrap_or("")),
(false, positional) => {
let value = it.value.to_lowercase();
let prefix = std::str::from_utf8(prefix).unwrap_or("").to_lowercase();
if positional {
value.starts_with(&prefix)
} else {
value.contains(&prefix)
}
}
},
MatchAlgorithm::Fuzzy => options
.match_algorithm
.matches_u8(it.value.as_bytes(), prefix),
})
.collect()
}

View File

@ -0,0 +1,160 @@
use crate::completions::{matches, Completer, CompletionOptions};
use nu_protocol::{
engine::{EngineState, StateWorkingSet},
levenshtein_distance, Span,
};
use reedline::Suggestion;
use std::fs;
use std::path::Path;
use std::sync::Arc;
use super::{partial_from, prepend_base_dir};
const SEP: char = std::path::MAIN_SEPARATOR;
#[derive(Clone)]
pub struct DirectoryCompletion {
engine_state: Arc<EngineState>,
}
impl DirectoryCompletion {
pub fn new(engine_state: Arc<EngineState>) -> Self {
Self { engine_state }
}
}
impl Completer for DirectoryCompletion {
fn fetch(
&mut self,
_: &StateWorkingSet,
prefix: Vec<u8>,
span: Span,
offset: usize,
_: usize,
options: &CompletionOptions,
) -> Vec<Suggestion> {
let cwd = if let Some(d) = self.engine_state.get_env_var("PWD") {
match d.as_string() {
Ok(s) => s,
Err(_) => "".to_string(),
}
} else {
"".to_string()
};
let partial = String::from_utf8_lossy(&prefix).to_string();
// Filter only the folders
let output: Vec<_> = directory_completion(span, &partial, &cwd, options)
.into_iter()
.map(move |x| Suggestion {
value: x.1,
description: None,
extra: None,
span: reedline::Span {
start: x.0.start - offset,
end: x.0.end - offset,
},
append_whitespace: false,
})
.collect();
output
}
// Sort results prioritizing the non hidden folders
fn sort(&self, items: Vec<Suggestion>, prefix: Vec<u8>) -> Vec<Suggestion> {
let prefix_str = String::from_utf8_lossy(&prefix).to_string();
// Sort items
let mut sorted_items = items;
sorted_items.sort_by(|a, b| a.value.cmp(&b.value));
sorted_items.sort_by(|a, b| {
let a_distance = levenshtein_distance(&prefix_str, &a.value);
let b_distance = levenshtein_distance(&prefix_str, &b.value);
a_distance.cmp(&b_distance)
});
// Separate the results between hidden and non hidden
let mut hidden: Vec<Suggestion> = vec![];
let mut non_hidden: Vec<Suggestion> = vec![];
for item in sorted_items.into_iter() {
let item_path = Path::new(&item.value);
if let Some(value) = item_path.file_name() {
if let Some(value) = value.to_str() {
if value.starts_with('.') {
hidden.push(item);
} else {
non_hidden.push(item);
}
}
}
}
// Append the hidden folders to the non hidden vec to avoid creating a new vec
non_hidden.append(&mut hidden);
non_hidden
}
}
pub fn directory_completion(
span: nu_protocol::Span,
partial: &str,
cwd: &str,
options: &CompletionOptions,
) -> Vec<(nu_protocol::Span, String)> {
let original_input = partial;
let (base_dir_name, partial) = partial_from(partial);
let base_dir = nu_path::expand_path_with(&base_dir_name, cwd);
// This check is here as base_dir.read_dir() with base_dir == "" will open the current dir
// which we don't want in this case (if we did, base_dir would already be ".")
if base_dir == Path::new("") {
return Vec::new();
}
if let Ok(result) = base_dir.read_dir() {
return result
.filter_map(|entry| {
entry.ok().and_then(|entry| {
if let Ok(metadata) = fs::metadata(entry.path()) {
if metadata.is_dir() {
let mut file_name = entry.file_name().to_string_lossy().into_owned();
if matches(&partial, &file_name, options) {
let mut path = if prepend_base_dir(original_input, &base_dir_name) {
format!("{}{}", base_dir_name, file_name)
} else {
file_name.to_string()
};
if entry.path().is_dir() {
path.push(SEP);
file_name.push(SEP);
}
// Fix files or folders with quotes
if path.contains('\'') || path.contains('"') || path.contains(' ') {
path = format!("`{}`", path);
}
Some((span, path))
} else {
None
}
} else {
None
}
} else {
None
}
})
})
.collect();
}
Vec::new()
}

View File

@ -0,0 +1,124 @@
use crate::completions::{
file_path_completion, partial_from, Completer, CompletionOptions, SortBy,
};
use nu_protocol::{
engine::{EngineState, StateWorkingSet},
Span,
};
use reedline::Suggestion;
use std::sync::Arc;
const SEP: char = std::path::MAIN_SEPARATOR;
#[derive(Clone)]
pub struct DotNuCompletion {
engine_state: Arc<EngineState>,
}
impl DotNuCompletion {
pub fn new(engine_state: Arc<EngineState>) -> Self {
Self { engine_state }
}
}
impl Completer for DotNuCompletion {
fn fetch(
&mut self,
_: &StateWorkingSet,
prefix: Vec<u8>,
span: Span,
offset: usize,
_: usize,
options: &CompletionOptions,
) -> Vec<Suggestion> {
let prefix_str = String::from_utf8_lossy(&prefix).to_string();
let mut search_dirs: Vec<String> = vec![];
let (base_dir, mut partial) = partial_from(&prefix_str);
let mut is_current_folder = false;
// Fetch the lib dirs
let lib_dirs: Vec<String> =
if let Some(lib_dirs) = self.engine_state.get_env_var("NU_LIB_DIRS") {
lib_dirs
.as_list()
.into_iter()
.flat_map(|it| {
it.iter().map(|x| {
x.as_path()
.expect("internal error: failed to convert lib path")
})
})
.map(|it| {
it.into_os_string()
.into_string()
.expect("internal error: failed to convert OS path")
})
.collect()
} else {
vec![]
};
// Check if the base_dir is a folder
if base_dir != format!(".{}", SEP) {
// Add the base dir into the directories to be searched
search_dirs.push(base_dir.clone());
// Reset the partial adding the basic dir back
// in order to make the span replace work properly
let mut base_dir_partial = base_dir;
base_dir_partial.push_str(&partial);
partial = base_dir_partial;
} else {
// Fetch the current folder
let current_folder = if let Some(d) = self.engine_state.get_env_var("PWD") {
match d.as_string() {
Ok(s) => s,
Err(_) => "".to_string(),
}
} else {
"".to_string()
};
is_current_folder = true;
// Add the current folder and the lib dirs into the
// directories to be searched
search_dirs.push(current_folder);
search_dirs.extend(lib_dirs);
}
// Fetch the files filtering the ones that ends with .nu
// and transform them into suggestions
let output: Vec<Suggestion> = search_dirs
.into_iter()
.flat_map(|it| {
file_path_completion(span, &partial, &it, options)
.into_iter()
.filter(|it| {
// Different base dir, so we list the .nu files or folders
if !is_current_folder {
it.1.ends_with(".nu") || it.1.ends_with(SEP)
} else {
// Lib dirs, so we filter only the .nu files
it.1.ends_with(".nu")
}
})
.map(move |x| Suggestion {
value: x.1,
description: None,
extra: None,
span: reedline::Span {
start: x.0.start - offset,
end: x.0.end - offset,
},
append_whitespace: true,
})
})
.collect();
output
}
fn get_sort_by(&self) -> SortBy {
SortBy::LevenshteinDistance
}
}

View File

@ -0,0 +1,190 @@
use crate::completions::{Completer, CompletionOptions};
use nu_protocol::{
engine::{EngineState, StateWorkingSet},
levenshtein_distance, Span,
};
use reedline::Suggestion;
use std::path::{is_separator, Path};
use std::sync::Arc;
const SEP: char = std::path::MAIN_SEPARATOR;
#[derive(Clone)]
pub struct FileCompletion {
engine_state: Arc<EngineState>,
}
impl FileCompletion {
pub fn new(engine_state: Arc<EngineState>) -> Self {
Self { engine_state }
}
}
impl Completer for FileCompletion {
fn fetch(
&mut self,
_: &StateWorkingSet,
prefix: Vec<u8>,
span: Span,
offset: usize,
_: usize,
options: &CompletionOptions,
) -> Vec<Suggestion> {
let cwd = if let Some(d) = self.engine_state.get_env_var("PWD") {
match d.as_string() {
Ok(s) => s,
Err(_) => "".to_string(),
}
} else {
"".to_string()
};
let prefix = String::from_utf8_lossy(&prefix).to_string();
let output: Vec<_> = file_path_completion(span, &prefix, &cwd, options)
.into_iter()
.map(move |x| Suggestion {
value: x.1,
description: None,
extra: None,
span: reedline::Span {
start: x.0.start - offset,
end: x.0.end - offset,
},
append_whitespace: false,
})
.collect();
output
}
// Sort results prioritizing the non hidden folders
fn sort(&self, items: Vec<Suggestion>, prefix: Vec<u8>) -> Vec<Suggestion> {
let prefix_str = String::from_utf8_lossy(&prefix).to_string();
// Sort items
let mut sorted_items = items;
sorted_items.sort_by(|a, b| a.value.cmp(&b.value));
sorted_items.sort_by(|a, b| {
let a_distance = levenshtein_distance(&prefix_str, &a.value);
let b_distance = levenshtein_distance(&prefix_str, &b.value);
a_distance.cmp(&b_distance)
});
// Separate the results between hidden and non hidden
let mut hidden: Vec<Suggestion> = vec![];
let mut non_hidden: Vec<Suggestion> = vec![];
for item in sorted_items.into_iter() {
let item_path = Path::new(&item.value);
if let Some(value) = item_path.file_name() {
if let Some(value) = value.to_str() {
if value.starts_with('.') {
hidden.push(item);
} else {
non_hidden.push(item);
}
}
}
}
// Append the hidden folders to the non hidden vec to avoid creating a new vec
non_hidden.append(&mut hidden);
non_hidden
}
}
pub fn partial_from(input: &str) -> (String, String) {
let partial = input.replace('`', "");
// If partial is only a word we want to search in the current dir
let (base, rest) = partial.rsplit_once(is_separator).unwrap_or((".", &partial));
// On windows, this standardizes paths to use \
let mut base = base.replace(is_separator, &SEP.to_string());
// rsplit_once removes the separator
base.push(SEP);
(base.to_string(), rest.to_string())
}
pub fn file_path_completion(
span: nu_protocol::Span,
partial: &str,
cwd: &str,
options: &CompletionOptions,
) -> Vec<(nu_protocol::Span, String)> {
let original_input = partial;
let (base_dir_name, partial) = partial_from(partial);
let base_dir = nu_path::expand_path_with(&base_dir_name, cwd);
// This check is here as base_dir.read_dir() with base_dir == "" will open the current dir
// which we don't want in this case (if we did, base_dir would already be ".")
if base_dir == Path::new("") {
return Vec::new();
}
if let Ok(result) = base_dir.read_dir() {
return result
.filter_map(|entry| {
entry.ok().and_then(|entry| {
let mut file_name = entry.file_name().to_string_lossy().into_owned();
if matches(&partial, &file_name, options) {
let mut path = if prepend_base_dir(original_input, &base_dir_name) {
format!("{}{}", base_dir_name, file_name)
} else {
file_name.to_string()
};
if entry.path().is_dir() {
path.push(SEP);
file_name.push(SEP);
}
// Fix files or folders with quotes
if path.contains('\'') || path.contains('"') || path.contains(' ') {
path = format!("`{}`", path);
}
Some((span, path))
} else {
None
}
})
})
.collect();
}
Vec::new()
}
pub fn matches(partial: &str, from: &str, options: &CompletionOptions) -> bool {
// Check for case sensitive
if !options.case_sensitive {
return options
.match_algorithm
.matches_str(&from.to_ascii_lowercase(), &partial.to_ascii_lowercase());
}
options.match_algorithm.matches_str(from, partial)
}
/// Returns whether the base_dir should be prepended to the file path
pub fn prepend_base_dir(input: &str, base_dir: &str) -> bool {
if base_dir == format!(".{}", SEP) {
// if the current base_dir path is the local folder we only add a "./" prefix if the user
// input already includes a local folder prefix.
let manually_entered = {
let mut chars = input.chars();
let first_char = chars.next();
let second_char = chars.next();
first_char == Some('.') && second_char.map(is_separator).unwrap_or(false)
};
manually_entered
} else {
// always prepend the base dir if it is a subfolder
true
}
}

View File

@ -0,0 +1,86 @@
use crate::completions::{Completer, CompletionOptions};
use nu_protocol::{
ast::{Expr, Expression},
engine::StateWorkingSet,
Span,
};
use reedline::Suggestion;
#[derive(Clone)]
pub struct FlagCompletion {
expression: Expression,
}
impl FlagCompletion {
pub fn new(expression: Expression) -> Self {
Self { expression }
}
}
impl Completer for FlagCompletion {
fn fetch(
&mut self,
working_set: &StateWorkingSet,
prefix: Vec<u8>,
span: Span,
offset: usize,
_: usize,
options: &CompletionOptions,
) -> Vec<Suggestion> {
// Check if it's a flag
if let Expr::Call(call) = &self.expression.expr {
let decl = working_set.get_decl(call.decl_id);
let sig = decl.signature();
let mut output = vec![];
for named in &sig.named {
let flag_desc = &named.desc;
if let Some(short) = named.short {
let mut named = vec![0; short.len_utf8()];
short.encode_utf8(&mut named);
named.insert(0, b'-');
if options.match_algorithm.matches_u8(&named, &prefix) {
output.push(Suggestion {
value: String::from_utf8_lossy(&named).to_string(),
description: Some(flag_desc.to_string()),
extra: None,
span: reedline::Span {
start: span.start - offset,
end: span.end - offset,
},
append_whitespace: true,
});
}
}
if named.long.is_empty() {
continue;
}
let mut named = named.long.as_bytes().to_vec();
named.insert(0, b'-');
named.insert(0, b'-');
if options.match_algorithm.matches_u8(&named, &prefix) {
output.push(Suggestion {
value: String::from_utf8_lossy(&named).to_string(),
description: Some(flag_desc.to_string()),
extra: None,
span: reedline::Span {
start: span.start - offset,
end: span.end - offset,
},
append_whitespace: true,
});
}
}
return output;
}
vec![]
}
}

View File

@ -0,0 +1,23 @@
mod base;
mod command_completions;
mod completer;
mod completion_options;
mod custom_completions;
mod directory_completions;
mod dotnu_completions;
mod file_completions;
mod flag_completions;
mod variable_completions;
pub use base::Completer;
pub use command_completions::CommandCompletion;
pub use completer::NuCompleter;
pub use completion_options::{CompletionOptions, MatchAlgorithm, SortBy};
pub use custom_completions::CustomCompletion;
pub use directory_completions::DirectoryCompletion;
pub use dotnu_completions::DotNuCompletion;
pub use file_completions::{
file_path_completion, matches, partial_from, prepend_base_dir, FileCompletion,
};
pub use flag_completions::FlagCompletion;
pub use variable_completions::VariableCompletion;

View File

@ -0,0 +1,259 @@
use crate::completions::{Completer, CompletionOptions};
use nu_engine::eval_variable;
use nu_protocol::{
engine::{EngineState, Stack, StateWorkingSet},
Span, Value,
};
use reedline::Suggestion;
use std::str;
use std::sync::Arc;
#[derive(Clone)]
pub struct VariableCompletion {
engine_state: Arc<EngineState>, // TODO: Is engine state necessary? It's already a part of working set in fetch()
stack: Stack,
var_context: (Vec<u8>, Vec<Vec<u8>>), // tuple with $var and the sublevels (.b.c.d)
}
impl VariableCompletion {
pub fn new(
engine_state: Arc<EngineState>,
stack: Stack,
var_context: (Vec<u8>, Vec<Vec<u8>>),
) -> Self {
Self {
engine_state,
stack,
var_context,
}
}
}
impl Completer for VariableCompletion {
fn fetch(
&mut self,
working_set: &StateWorkingSet,
prefix: Vec<u8>,
span: Span,
offset: usize,
_: usize,
options: &CompletionOptions,
) -> Vec<Suggestion> {
let mut output = vec![];
let builtins = ["$nu", "$in", "$config", "$env", "$nothing"];
let var_str = std::str::from_utf8(&self.var_context.0)
.unwrap_or("")
.to_lowercase();
let var_id = working_set.find_variable(&self.var_context.0);
let current_span = reedline::Span {
start: span.start - offset,
end: span.end - offset,
};
let sublevels_count = self.var_context.1.len();
// Completions for the given variable
if !var_str.is_empty() {
// Completion for $env.<tab>
if var_str.as_str() == "$env" {
let env_vars = self.stack.get_env_vars(&self.engine_state);
// Return nested values
if sublevels_count > 0 {
// Extract the target var ($env.<target-var>)
let target_var = self.var_context.1[0].clone();
let target_var_str =
str::from_utf8(&target_var).unwrap_or_default().to_string();
// Everything after the target var is the nested level ($env.<target-var>.<nested_levels>...)
let nested_levels: Vec<Vec<u8>> =
self.var_context.1.clone().into_iter().skip(1).collect();
if let Some(val) = env_vars.get(&target_var_str) {
return nested_suggestions(val.clone(), nested_levels, current_span);
}
} else {
// No nesting provided, return all env vars
for env_var in env_vars {
if options
.match_algorithm
.matches_u8(env_var.0.as_bytes(), &prefix)
{
output.push(Suggestion {
value: env_var.0,
description: None,
extra: None,
span: current_span,
append_whitespace: false,
});
}
}
return output;
}
}
// Completions for $nu.<tab>
if var_str.as_str() == "$nu" {
// Eval nu var
if let Ok(nuval) = eval_variable(
&self.engine_state,
&self.stack,
nu_protocol::NU_VARIABLE_ID,
nu_protocol::Span {
start: current_span.start,
end: current_span.end,
},
) {
return nested_suggestions(nuval, self.var_context.1.clone(), current_span);
}
}
// Completion other variable types
if let Some(var_id) = var_id {
// Extract the variable value from the stack
let var = self.stack.get_var(
var_id,
Span {
start: span.start,
end: span.end,
},
);
// If the value exists and it's of type Record
if let Ok(value) = var {
return nested_suggestions(value, self.var_context.1.clone(), current_span);
}
}
}
// Variable completion (e.g: $en<tab> to complete $env)
for builtin in builtins {
if options
.match_algorithm
.matches_u8(builtin.as_bytes(), &prefix)
{
output.push(Suggestion {
value: builtin.to_string(),
description: None,
extra: None,
span: current_span,
append_whitespace: false,
});
}
}
// TODO: The following can be refactored (see find_commands_by_predicate() used in
// command_completions).
let mut removed_overlays = vec![];
// Working set scope vars
for scope_frame in working_set.delta.scope.iter().rev() {
for overlay_frame in scope_frame
.active_overlays(&mut removed_overlays)
.iter()
.rev()
{
for v in &overlay_frame.vars {
if options.match_algorithm.matches_u8(v.0, &prefix) {
output.push(Suggestion {
value: String::from_utf8_lossy(v.0).to_string(),
description: None,
extra: None,
span: current_span,
append_whitespace: false,
});
}
}
}
}
// Permanent state vars
// for scope in &self.engine_state.scope {
for overlay_frame in self
.engine_state
.active_overlays(&removed_overlays)
.iter()
.rev()
{
for v in &overlay_frame.vars {
if options.match_algorithm.matches_u8(v.0, &prefix) {
output.push(Suggestion {
value: String::from_utf8_lossy(v.0).to_string(),
description: None,
extra: None,
span: current_span,
append_whitespace: false,
});
}
}
}
output.dedup(); // TODO: Removes only consecutive duplicates, is it intended?
output
}
}
// Find recursively the values for sublevels
// if no sublevels are set it returns the current value
fn nested_suggestions(
val: Value,
sublevels: Vec<Vec<u8>>,
current_span: reedline::Span,
) -> Vec<Suggestion> {
let mut output: Vec<Suggestion> = vec![];
let value = recursive_value(val, sublevels);
match value {
Value::Record {
cols,
vals: _,
span: _,
} => {
// Add all the columns as completion
for item in cols {
output.push(Suggestion {
value: item,
description: None,
extra: None,
span: current_span,
append_whitespace: false,
});
}
output
}
_ => output,
}
}
// Extracts the recursive value (e.g: $var.a.b.c)
fn recursive_value(val: Value, sublevels: Vec<Vec<u8>>) -> Value {
// Go to next sublevel
if let Some(next_sublevel) = sublevels.clone().into_iter().next() {
match val {
Value::Record {
cols,
vals,
span: _,
} => {
for item in cols.into_iter().zip(vals.into_iter()) {
// Check if index matches with sublevel
if item.0.as_bytes().to_vec() == next_sublevel {
// If matches try to fetch recursively the next
return recursive_value(item.1, sublevels.into_iter().skip(1).collect());
}
}
// Current sublevel value not found
return Value::Nothing {
span: Span { start: 0, end: 0 },
};
}
_ => return val,
}
}
val
}

View File

@ -69,7 +69,9 @@ pub fn eval_config_contents(
// Merge the delta in case env vars changed in the config
match nu_engine::env::current_dir(engine_state, stack) {
Ok(cwd) => {
if let Err(e) = engine_state.merge_delta(StateDelta::new(), Some(stack), cwd) {
if let Err(e) =
engine_state.merge_delta(StateDelta::new(engine_state), Some(stack), cwd)
{
let working_set = StateWorkingSet::new(engine_state);
report_error(&working_set, &e);
}

View File

@ -9,7 +9,7 @@ use nu_protocol::{
engine::{EngineState, Stack, StateWorkingSet},
Config, PipelineData, Span, Value,
};
use std::io::Write;
use nu_utils::stdout_write_all_and_flush;
/// Main function used when a file path is found as argument for nu
pub fn evaluate_file(
@ -27,10 +27,6 @@ pub fn evaluate_file(
std::process::exit(1);
}
// Make a note of the exceptions we see for externals that look like math expressions
let exceptions = crate::util::external_exceptions(engine_state, stack);
engine_state.external_exceptions = exceptions;
let file = std::fs::read(&path).into_diagnostic()?;
let mut working_set = StateWorkingSet::new(engine_state);
@ -65,17 +61,20 @@ pub fn evaluate_file(
}
pub fn print_table_or_error(
engine_state: &EngineState,
engine_state: &mut EngineState,
stack: &mut Stack,
mut pipeline_data: PipelineData,
config: &Config,
config: &mut Config,
) {
let exit_code = match &mut pipeline_data {
PipelineData::ExternalStream { exit_code, .. } => exit_code.take(),
_ => None,
};
match engine_state.find_decl("table".as_bytes()) {
// Change the engine_state config to use the passed in configuration
engine_state.set_config(config);
match engine_state.find_decl("table".as_bytes(), &[]) {
Some(decl_id) => {
let table = engine_state.get_decl(decl_id).run(
engine_state,
@ -87,8 +86,6 @@ pub fn print_table_or_error(
match table {
Ok(table) => {
for item in table {
let stdout = std::io::stdout();
if let Value::Error { error } = item {
let working_set = StateWorkingSet::new(engine_state);
@ -100,10 +97,7 @@ pub fn print_table_or_error(
let mut out = item.into_string("\n", config);
out.push('\n');
match stdout.lock().write_all(out.as_bytes()) {
Ok(_) => (),
Err(err) => eprintln!("{}", err),
};
let _ = stdout_write_all_and_flush(out).map_err(|err| eprintln!("{}", err));
}
}
Err(error) => {
@ -117,8 +111,6 @@ pub fn print_table_or_error(
}
None => {
for item in pipeline_data {
let stdout = std::io::stdout();
if let Value::Error { error } = item {
let working_set = StateWorkingSet::new(engine_state);
@ -130,10 +122,7 @@ pub fn print_table_or_error(
let mut out = item.into_string("\n", config);
out.push('\n');
match stdout.lock().write_all(out.as_bytes()) {
Ok(_) => (),
Err(err) => eprintln!("{}", err),
};
let _ = stdout_write_all_and_flush(out).map_err(|err| eprintln!("{}", err));
}
}
};

View File

@ -1,8 +1,8 @@
mod commands;
mod completions;
mod config_files;
mod errors;
mod eval_file;
mod menus;
mod nu_highlight;
mod print;
mod prompt;
@ -14,16 +14,15 @@ mod util;
mod validation;
pub use commands::evaluate_commands;
pub use completions::NuCompleter;
pub use completions::{FileCompletion, NuCompleter};
pub use config_files::eval_config_contents;
pub use errors::CliError;
pub use eval_file::evaluate_file;
pub use menus::{DescriptionMenu, NuHelpCompleter};
pub use nu_highlight::NuHighlight;
pub use print::Print;
pub use prompt::NushellPrompt;
pub use repl::evaluate_repl;
pub use syntax_highlight::NuHighlighter;
pub use util::print_pipeline_data;
pub use util::{eval_source, gather_parent_env_vars, get_init_cwd, report_error};
pub use validation::NuValidator;

View File

@ -0,0 +1,724 @@
use {
nu_ansi_term::{ansi::RESET, Style},
reedline::{
menu_functions::string_difference, Completer, LineBuffer, Menu, MenuEvent, MenuTextStyle,
Painter, Suggestion,
},
};
/// Default values used as reference for the menu. These values are set during
/// the initial declaration of the menu and are always kept as reference for the
/// changeable [`WorkingDetails`]
struct DefaultMenuDetails {
/// Number of columns that the menu will have
pub columns: u16,
/// Column width
pub col_width: Option<usize>,
/// Column padding
pub col_padding: usize,
/// Number of rows for commands
pub selection_rows: u16,
/// Number of rows allowed to display the description
pub description_rows: usize,
}
impl Default for DefaultMenuDetails {
fn default() -> Self {
Self {
columns: 4,
col_width: None,
col_padding: 2,
selection_rows: 4,
description_rows: 10,
}
}
}
/// Represents the actual column conditions of the menu. These conditions change
/// since they need to accommodate possible different line sizes for the column values
#[derive(Default)]
struct WorkingDetails {
/// Number of columns that the menu will have
pub columns: u16,
/// Column width
pub col_width: usize,
/// Number of rows for description
pub description_rows: usize,
}
/// Completion menu definition
pub struct DescriptionMenu {
/// Menu name
name: String,
/// Menu status
active: bool,
/// Menu coloring
color: MenuTextStyle,
/// Default column details that are set when creating the menu
/// These values are the reference for the working details
default_details: DefaultMenuDetails,
/// Number of minimum rows that are displayed when
/// the required lines is larger than the available lines
min_rows: u16,
/// Working column details keep changing based on the collected values
working_details: WorkingDetails,
/// Menu cached values
values: Vec<Suggestion>,
/// column position of the cursor. Starts from 0
col_pos: u16,
/// row position in the menu. Starts from 0
row_pos: u16,
/// Menu marker when active
marker: String,
/// Event sent to the menu
event: Option<MenuEvent>,
/// String collected after the menu is activated
input: Option<String>,
/// Examples to select
examples: Vec<String>,
/// Example index
example_index: Option<usize>,
/// Examples may not be shown if there is not enough space in the screen
show_examples: bool,
/// Skipped description rows
skipped_rows: usize,
/// Calls the completer using only the line buffer difference difference
/// after the menu was activated
only_buffer_difference: bool,
}
impl Default for DescriptionMenu {
fn default() -> Self {
Self {
name: "description_menu".to_string(),
active: false,
color: MenuTextStyle::default(),
default_details: DefaultMenuDetails::default(),
min_rows: 3,
working_details: WorkingDetails::default(),
values: Vec::new(),
col_pos: 0,
row_pos: 0,
marker: "? ".to_string(),
event: None,
input: None,
examples: Vec::new(),
example_index: None,
show_examples: true,
skipped_rows: 0,
only_buffer_difference: true,
}
}
}
// Menu configuration
impl DescriptionMenu {
/// Menu builder with new name
pub fn with_name(mut self, name: &str) -> Self {
self.name = name.into();
self
}
/// Menu builder with new value for text style
pub fn with_text_style(mut self, text_style: Style) -> Self {
self.color.text_style = text_style;
self
}
/// Menu builder with new value for text style
pub fn with_selected_text_style(mut self, selected_text_style: Style) -> Self {
self.color.selected_text_style = selected_text_style;
self
}
/// Menu builder with new value for text style
pub fn with_description_text_style(mut self, description_text_style: Style) -> Self {
self.color.description_style = description_text_style;
self
}
/// Menu builder with new columns value
pub fn with_columns(mut self, columns: u16) -> Self {
self.default_details.columns = columns;
self
}
/// Menu builder with new column width value
pub fn with_column_width(mut self, col_width: Option<usize>) -> Self {
self.default_details.col_width = col_width;
self
}
/// Menu builder with new column width value
pub fn with_column_padding(mut self, col_padding: usize) -> Self {
self.default_details.col_padding = col_padding;
self
}
/// Menu builder with new selection rows value
pub fn with_selection_rows(mut self, selection_rows: u16) -> Self {
self.default_details.selection_rows = selection_rows;
self
}
/// Menu builder with new description rows value
pub fn with_description_rows(mut self, description_rows: usize) -> Self {
self.default_details.description_rows = description_rows;
self
}
/// Menu builder with marker
pub fn with_marker(mut self, marker: String) -> Self {
self.marker = marker;
self
}
/// Menu builder with new only buffer difference
pub fn with_only_buffer_difference(mut self, only_buffer_difference: bool) -> Self {
self.only_buffer_difference = only_buffer_difference;
self
}
}
// Menu functionality
impl DescriptionMenu {
/// Move menu cursor to the next element
fn move_next(&mut self) {
let mut new_col = self.col_pos + 1;
let mut new_row = self.row_pos;
if new_col >= self.get_cols() {
new_row += 1;
new_col = 0;
}
if new_row >= self.get_rows() {
new_row = 0;
new_col = 0;
}
let position = new_row * self.get_cols() + new_col;
if position >= self.get_values().len() as u16 {
self.reset_position();
} else {
self.col_pos = new_col;
self.row_pos = new_row;
}
}
/// Move menu cursor to the previous element
fn move_previous(&mut self) {
let new_col = self.col_pos.checked_sub(1);
let (new_col, new_row) = match new_col {
Some(col) => (col, self.row_pos),
None => match self.row_pos.checked_sub(1) {
Some(row) => (self.get_cols().saturating_sub(1), row),
None => (
self.get_cols().saturating_sub(1),
self.get_rows().saturating_sub(1),
),
},
};
let position = new_row * self.get_cols() + new_col;
if position >= self.get_values().len() as u16 {
self.col_pos = (self.get_values().len() as u16 % self.get_cols()).saturating_sub(1);
self.row_pos = self.get_rows().saturating_sub(1);
} else {
self.col_pos = new_col;
self.row_pos = new_row;
}
}
/// Menu index based on column and row position
fn index(&self) -> usize {
let index = self.row_pos * self.get_cols() + self.col_pos;
index as usize
}
/// Get selected value from the menu
fn get_value(&self) -> Option<Suggestion> {
self.get_values().get(self.index()).cloned()
}
/// Calculates how many rows the Menu will use
fn get_rows(&self) -> u16 {
let values = self.get_values().len() as u16;
if values == 0 {
// When the values are empty the no_records_msg is shown, taking 1 line
return 1;
}
let rows = values / self.get_cols();
if values % self.get_cols() != 0 {
rows + 1
} else {
rows
}
}
/// Returns working details col width
fn get_width(&self) -> usize {
self.working_details.col_width
}
/// Reset menu position
fn reset_position(&mut self) {
self.col_pos = 0;
self.row_pos = 0;
self.skipped_rows = 0;
}
fn no_records_msg(&self, use_ansi_coloring: bool) -> String {
let msg = "TYPE TO START SEARCH";
if use_ansi_coloring {
format!(
"{}{}{}",
self.color.selected_text_style.prefix(),
msg,
RESET
)
} else {
msg.to_string()
}
}
/// Returns working details columns
fn get_cols(&self) -> u16 {
self.working_details.columns.max(1)
}
/// End of line for menu
fn end_of_line(&self, column: u16, index: usize) -> &str {
let is_last = index == self.values.len().saturating_sub(1);
if column == self.get_cols().saturating_sub(1) || is_last {
"\r\n"
} else {
""
}
}
/// Update list of examples from the actual value
fn update_examples(&mut self) {
self.examples = self
.get_value()
.and_then(|suggestion| suggestion.extra)
.unwrap_or_default();
self.example_index = None;
}
/// Creates default string that represents one suggestion from the menu
fn create_entry_string(
&self,
suggestion: &Suggestion,
index: usize,
column: u16,
empty_space: usize,
use_ansi_coloring: bool,
) -> String {
if use_ansi_coloring {
if index == self.index() {
format!(
"{}{}{}{:>empty$}{}",
self.color.selected_text_style.prefix(),
&suggestion.value,
RESET,
"",
self.end_of_line(column, index),
empty = empty_space,
)
} else {
format!(
"{}{}{}{:>empty$}{}",
self.color.text_style.prefix(),
&suggestion.value,
RESET,
"",
self.end_of_line(column, index),
empty = empty_space,
)
}
} else {
// If no ansi coloring is found, then the selection word is
// the line in uppercase
let (marker, empty_space) = if index == self.index() {
(">", empty_space.saturating_sub(1))
} else {
("", empty_space)
};
let line = format!(
"{}{}{:>empty$}{}",
marker,
&suggestion.value,
"",
self.end_of_line(column, index),
empty = empty_space,
);
if index == self.index() {
line.to_uppercase()
} else {
line
}
}
}
/// Description string with color
fn create_description_string(&self, use_ansi_coloring: bool) -> String {
let description = self
.get_value()
.and_then(|suggestion| suggestion.description)
.unwrap_or_else(|| "".to_string())
.lines()
.skip(self.skipped_rows)
.take(self.working_details.description_rows)
.collect::<Vec<&str>>()
.join("\r\n");
if use_ansi_coloring && !description.is_empty() {
format!(
"{}{}{}",
self.color.description_style.prefix(),
description,
RESET,
)
} else {
description
}
}
/// Selectable list of examples from the actual value
fn create_example_string(&self, use_ansi_coloring: bool) -> String {
if !self.show_examples {
return "".into();
}
let examples: String = self
.examples
.iter()
.enumerate()
.map(|(index, example)| {
if let Some(example_index) = self.example_index {
if index == example_index {
format!(
" {}{}{}\r\n",
self.color.selected_text_style.prefix(),
example,
RESET
)
} else {
format!(" {}\r\n", example)
}
} else {
format!(" {}\r\n", example)
}
})
.collect();
if examples.is_empty() {
"".into()
} else if use_ansi_coloring {
format!(
"{}\r\n\r\nExamples:\r\n{}{}",
self.color.description_style.prefix(),
RESET,
examples,
)
} else {
format!("\r\n\r\nExamples:\r\n{}", examples,)
}
}
}
impl Menu for DescriptionMenu {
/// Menu name
fn name(&self) -> &str {
self.name.as_str()
}
/// Menu indicator
fn indicator(&self) -> &str {
self.marker.as_str()
}
/// Deactivates context menu
fn is_active(&self) -> bool {
self.active
}
/// The menu stays active even with one record
fn can_quick_complete(&self) -> bool {
false
}
/// The menu does not need to partially complete
fn can_partially_complete(
&mut self,
_values_updated: bool,
_line_buffer: &mut LineBuffer,
_completer: &mut dyn Completer,
) -> bool {
false
}
/// Selects what type of event happened with the menu
fn menu_event(&mut self, event: MenuEvent) {
match &event {
MenuEvent::Activate(_) => self.active = true,
MenuEvent::Deactivate => {
self.active = false;
self.input = None;
self.values = Vec::new();
}
_ => {}
};
self.event = Some(event);
}
/// Updates menu values
fn update_values(&mut self, line_buffer: &mut LineBuffer, completer: &mut dyn Completer) {
if self.only_buffer_difference {
if let Some(old_string) = &self.input {
let (start, input) = string_difference(line_buffer.get_buffer(), old_string);
if !input.is_empty() {
self.reset_position();
self.values = completer.complete(input, start);
}
}
} else {
let trimmed_buffer = line_buffer.get_buffer().replace('\n', " ");
self.values =
completer.complete(trimmed_buffer.as_str(), line_buffer.insertion_point());
self.reset_position();
}
}
/// The working details for the menu changes based on the size of the lines
/// collected from the completer
fn update_working_details(
&mut self,
line_buffer: &mut LineBuffer,
completer: &mut dyn Completer,
painter: &Painter,
) {
if let Some(event) = self.event.take() {
// Updating all working parameters from the menu before executing any of the
// possible event
let max_width = self.get_values().iter().fold(0, |acc, suggestion| {
let str_len = suggestion.value.len() + self.default_details.col_padding;
if str_len > acc {
str_len
} else {
acc
}
});
// If no default width is found, then the total screen width is used to estimate
// the column width based on the default number of columns
let default_width = if let Some(col_width) = self.default_details.col_width {
col_width
} else {
let col_width = painter.screen_width() / self.default_details.columns;
col_width as usize
};
// Adjusting the working width of the column based the max line width found
// in the menu values
if max_width > default_width {
self.working_details.col_width = max_width;
} else {
self.working_details.col_width = default_width;
};
// The working columns is adjusted based on possible number of columns
// that could be fitted in the screen with the calculated column width
let possible_cols = painter.screen_width() / self.working_details.col_width as u16;
if possible_cols > self.default_details.columns {
self.working_details.columns = self.default_details.columns.max(1);
} else {
self.working_details.columns = possible_cols;
}
// Updating the working rows to display the description
if self.menu_required_lines(painter.screen_width()) <= painter.remaining_lines() {
self.working_details.description_rows = self.default_details.description_rows;
self.show_examples = true;
} else {
self.working_details.description_rows = painter
.remaining_lines()
.saturating_sub(self.default_details.selection_rows + 1)
as usize;
self.show_examples = false;
}
match event {
MenuEvent::Activate(_) => {
self.reset_position();
self.input = Some(line_buffer.get_buffer().to_string());
self.update_values(line_buffer, completer);
}
MenuEvent::Deactivate => self.active = false,
MenuEvent::Edit(_) => {
self.reset_position();
self.update_values(line_buffer, completer);
self.update_examples()
}
MenuEvent::NextElement => {
self.skipped_rows = 0;
self.move_next();
self.update_examples();
}
MenuEvent::PreviousElement => {
self.skipped_rows = 0;
self.move_previous();
self.update_examples();
}
MenuEvent::MoveUp => {
if let Some(example_index) = self.example_index {
if let Some(index) = example_index.checked_sub(1) {
self.example_index = Some(index);
} else {
self.example_index = Some(self.examples.len().saturating_sub(1));
}
} else if !self.examples.is_empty() {
self.example_index = Some(0);
}
}
MenuEvent::MoveDown => {
if let Some(example_index) = self.example_index {
let index = example_index + 1;
if index < self.examples.len() {
self.example_index = Some(index);
} else {
self.example_index = Some(0);
}
} else if !self.examples.is_empty() {
self.example_index = Some(0);
}
}
MenuEvent::MoveLeft => self.skipped_rows = self.skipped_rows.saturating_sub(1),
MenuEvent::MoveRight => {
let skipped = self.skipped_rows + 1;
let description_rows = self
.get_value()
.and_then(|suggestion| suggestion.description)
.unwrap_or_else(|| "".to_string())
.lines()
.count();
let allowed_skips =
description_rows.saturating_sub(self.working_details.description_rows);
if skipped < allowed_skips {
self.skipped_rows = skipped;
} else {
self.skipped_rows = allowed_skips;
}
}
MenuEvent::PreviousPage | MenuEvent::NextPage => {}
}
}
}
/// The buffer gets replaced in the Span location
fn replace_in_buffer(&self, line_buffer: &mut LineBuffer) {
if let Some(Suggestion { value, span, .. }) = self.get_value() {
let start = span.start.min(line_buffer.len());
let end = span.end.min(line_buffer.len());
let string_len = if let Some(example_index) = self.example_index {
let example = self
.examples
.get(example_index)
.expect("the example index is always checked");
line_buffer.replace(start..end, example);
example.len()
} else {
line_buffer.replace(start..end, &value);
value.len()
};
let mut offset = line_buffer.insertion_point();
offset += string_len.saturating_sub(end.saturating_sub(start));
line_buffer.set_insertion_point(offset);
}
}
/// Minimum rows that should be displayed by the menu
fn min_rows(&self) -> u16 {
self.get_rows().min(self.min_rows)
}
/// Gets values from filler that will be displayed in the menu
fn get_values(&self) -> &[Suggestion] {
&self.values
}
fn menu_required_lines(&self, _terminal_columns: u16) -> u16 {
let example_lines = self
.examples
.iter()
.fold(0, |acc, example| example.lines().count() + acc);
self.default_details.selection_rows
+ self.default_details.description_rows as u16
+ example_lines as u16
+ 3
}
fn menu_string(&self, _available_lines: u16, use_ansi_coloring: bool) -> String {
if self.get_values().is_empty() {
self.no_records_msg(use_ansi_coloring)
} else {
// The skip values represent the number of lines that should be skipped
// while printing the menu
let available_lines = self.default_details.selection_rows;
let skip_values = if self.row_pos >= available_lines {
let skip_lines = self.row_pos.saturating_sub(available_lines) + 1;
(skip_lines * self.get_cols()) as usize
} else {
0
};
// It seems that crossterm prefers to have a complete string ready to be printed
// rather than looping through the values and printing multiple things
// This reduces the flickering when printing the menu
let available_values = (available_lines * self.get_cols()) as usize;
let selection_values: String = self
.get_values()
.iter()
.skip(skip_values)
.take(available_values)
.enumerate()
.map(|(index, suggestion)| {
// Correcting the enumerate index based on the number of skipped values
let index = index + skip_values;
let column = index as u16 % self.get_cols();
let empty_space = self.get_width().saturating_sub(suggestion.value.len());
self.create_entry_string(
suggestion,
index,
column,
empty_space,
use_ansi_coloring,
)
})
.collect();
format!(
"{}{}{}",
selection_values,
self.create_description_string(use_ansi_coloring),
self.create_example_string(use_ansi_coloring)
)
}
}
}

View File

@ -0,0 +1,106 @@
use nu_engine::documentation::get_flags_section;
use nu_protocol::{engine::EngineState, levenshtein_distance};
use reedline::{Completer, Suggestion};
use std::sync::Arc;
pub struct NuHelpCompleter(Arc<EngineState>);
impl NuHelpCompleter {
pub fn new(engine_state: Arc<EngineState>) -> Self {
Self(engine_state)
}
fn completion_helper(&self, line: &str, pos: usize) -> Vec<Suggestion> {
let full_commands = self.0.get_signatures_with_examples(false);
//Vec<(Signature, Vec<Example>, bool, bool)> {
let mut commands = full_commands
.iter()
.filter(|(sig, _, _, _)| {
sig.name.to_lowercase().contains(&line.to_lowercase())
|| sig.usage.to_lowercase().contains(&line.to_lowercase())
|| sig
.extra_usage
.to_lowercase()
.contains(&line.to_lowercase())
})
.collect::<Vec<_>>();
commands.sort_by(|(a, _, _, _), (b, _, _, _)| {
let a_distance = levenshtein_distance(line, &a.name);
let b_distance = levenshtein_distance(line, &b.name);
a_distance.cmp(&b_distance)
});
commands
.into_iter()
.map(|(sig, examples, _, _)| {
let mut long_desc = String::new();
let usage = &sig.usage;
if !usage.is_empty() {
long_desc.push_str(usage);
long_desc.push_str("\r\n\r\n");
}
let extra_usage = &sig.extra_usage;
if !extra_usage.is_empty() {
long_desc.push_str(extra_usage);
long_desc.push_str("\r\n\r\n");
}
long_desc.push_str(&format!("Usage:\r\n > {}\r\n", sig.call_signature()));
if !sig.named.is_empty() {
long_desc.push_str(&get_flags_section(sig))
}
if !sig.required_positional.is_empty()
|| !sig.optional_positional.is_empty()
|| sig.rest_positional.is_some()
{
long_desc.push_str("\r\nParameters:\r\n");
for positional in &sig.required_positional {
long_desc
.push_str(&format!(" {}: {}\r\n", positional.name, positional.desc));
}
for positional in &sig.optional_positional {
long_desc.push_str(&format!(
" (optional) {}: {}\r\n",
positional.name, positional.desc
));
}
if let Some(rest_positional) = &sig.rest_positional {
long_desc.push_str(&format!(
" ...{}: {}\r\n",
rest_positional.name, rest_positional.desc
));
}
}
let extra: Vec<String> = examples
.iter()
.map(|example| example.example.to_string())
.collect();
Suggestion {
value: sig.name.clone(),
description: Some(long_desc),
extra: Some(extra),
span: reedline::Span {
start: pos,
end: pos + line.len(),
},
append_whitespace: false,
}
})
.collect()
}
}
impl Completer for NuHelpCompleter {
fn complete(&mut self, line: &str, pos: usize) -> Vec<Suggestion> {
self.completion_helper(line, pos)
}
}

View File

@ -0,0 +1,176 @@
use nu_engine::eval_block;
use nu_protocol::{
engine::{EngineState, Stack},
IntoPipelineData, Span, Value,
};
use reedline::{menu_functions::parse_selection_char, Completer, Suggestion};
use std::sync::Arc;
const SELECTION_CHAR: char = '!';
pub struct NuMenuCompleter {
block_id: usize,
span: Span,
stack: Stack,
engine_state: Arc<EngineState>,
only_buffer_difference: bool,
}
impl NuMenuCompleter {
pub fn new(
block_id: usize,
span: Span,
stack: Stack,
engine_state: Arc<EngineState>,
only_buffer_difference: bool,
) -> Self {
Self {
block_id,
span,
stack,
engine_state,
only_buffer_difference,
}
}
}
impl Completer for NuMenuCompleter {
fn complete(&mut self, line: &str, pos: usize) -> Vec<Suggestion> {
let parsed = parse_selection_char(line, SELECTION_CHAR);
let block = self.engine_state.get_block(self.block_id);
if let Some(buffer) = block.signature.get_positional(0) {
if let Some(buffer_id) = &buffer.var_id {
let line_buffer = Value::String {
val: parsed.remainder.to_string(),
span: self.span,
};
self.stack.add_var(*buffer_id, line_buffer);
}
}
if let Some(position) = block.signature.get_positional(1) {
if let Some(position_id) = &position.var_id {
let line_buffer = Value::Int {
val: pos as i64,
span: self.span,
};
self.stack.add_var(*position_id, line_buffer);
}
}
let input = Value::nothing(self.span).into_pipeline_data();
let res = eval_block(
&self.engine_state,
&mut self.stack,
block,
input,
false,
false,
);
if let Ok(values) = res {
let values = values.into_value(self.span);
convert_to_suggestions(values, line, pos, self.only_buffer_difference)
} else {
Vec::new()
}
}
}
fn convert_to_suggestions(
value: Value,
line: &str,
pos: usize,
only_buffer_difference: bool,
) -> Vec<Suggestion> {
match value {
Value::Record { .. } => {
let text = match value
.get_data_by_key("value")
.and_then(|val| val.as_string().ok())
{
Some(val) => val,
None => "No value key".to_string(),
};
let description = value
.get_data_by_key("description")
.and_then(|val| val.as_string().ok());
let span = match value.get_data_by_key("span") {
Some(span @ Value::Record { .. }) => {
let start = span
.get_data_by_key("start")
.and_then(|val| val.as_integer().ok());
let end = span
.get_data_by_key("end")
.and_then(|val| val.as_integer().ok());
match (start, end) {
(Some(start), Some(end)) => {
let start = start.min(end);
reedline::Span {
start: start as usize,
end: end as usize,
}
}
_ => reedline::Span {
start: if only_buffer_difference { pos } else { 0 },
end: if only_buffer_difference {
pos + line.len()
} else {
line.len()
},
},
}
}
_ => reedline::Span {
start: if only_buffer_difference { pos } else { 0 },
end: if only_buffer_difference {
pos + line.len()
} else {
line.len()
},
},
};
let extra = match value.get_data_by_key("extra") {
Some(Value::List { vals, .. }) => {
let extra: Vec<String> = vals
.into_iter()
.filter_map(|extra| match extra {
Value::String { val, .. } => Some(val),
_ => None,
})
.collect();
Some(extra)
}
_ => None,
};
vec![Suggestion {
value: text,
description,
extra,
span,
append_whitespace: false,
}]
}
Value::List { vals, .. } => vals
.into_iter()
.flat_map(|val| convert_to_suggestions(val, line, pos, only_buffer_difference))
.collect(),
_ => vec![Suggestion {
value: format!("Not a record: {:?}", value),
description: None,
extra: None,
span: reedline::Span {
start: 0,
end: line.len(),
},
append_whitespace: false,
}],
}
}

View File

@ -0,0 +1,7 @@
mod description_menu;
mod help_completions;
mod menu_completions;
pub use description_menu::DescriptionMenu;
pub use help_completions::NuHelpCompleter;
pub use menu_completions::NuMenuCompleter;

View File

@ -22,7 +22,7 @@ impl Command for NuHighlight {
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
@ -30,7 +30,7 @@ impl Command for NuHighlight {
let ctrlc = engine_state.ctrlc.clone();
let engine_state = engine_state.clone();
let config = stack.get_config()?;
let config = engine_state.get_config().clone();
let highlighter = crate::NuHighlighter {
engine_state,

View File

@ -16,6 +16,11 @@ impl Command for Print {
fn signature(&self) -> Signature {
Signature::build("print")
.rest("rest", SyntaxShape::Any, "the values to print")
.switch(
"no_newline",
"print without inserting a newline for the line ending",
Some('n'),
)
.category(Category::Strings)
}
@ -31,10 +36,12 @@ impl Command for Print {
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let args: Vec<Value> = call.rest(engine_state, stack, 0)?;
let no_newline = call.has_flag("no_newline");
let head = call.head;
for arg in args {
crate::util::print_pipeline_data(arg.into_pipeline_data(), engine_state, stack)?;
arg.into_pipeline_data()
.print(engine_state, stack, no_newline)?;
}
Ok(PipelineData::new(head))

View File

@ -12,10 +12,10 @@ use {
pub struct NushellPrompt {
left_prompt_string: Option<String>,
right_prompt_string: Option<String>,
default_prompt_indicator: String,
default_vi_insert_prompt_indicator: String,
default_vi_normal_prompt_indicator: String,
default_multiline_indicator: String,
default_prompt_indicator: Option<String>,
default_vi_insert_prompt_indicator: Option<String>,
default_vi_normal_prompt_indicator: Option<String>,
default_multiline_indicator: Option<String>,
}
impl Default for NushellPrompt {
@ -29,10 +29,10 @@ impl NushellPrompt {
NushellPrompt {
left_prompt_string: None,
right_prompt_string: None,
default_prompt_indicator: "".to_string(),
default_vi_insert_prompt_indicator: ": ".to_string(),
default_vi_normal_prompt_indicator: "".to_string(),
default_multiline_indicator: "::: ".to_string(),
default_prompt_indicator: None,
default_vi_insert_prompt_indicator: None,
default_vi_normal_prompt_indicator: None,
default_multiline_indicator: None,
}
}
@ -44,19 +44,19 @@ impl NushellPrompt {
self.right_prompt_string = prompt_string;
}
pub fn update_prompt_indicator(&mut self, prompt_indicator_string: String) {
pub fn update_prompt_indicator(&mut self, prompt_indicator_string: Option<String>) {
self.default_prompt_indicator = prompt_indicator_string;
}
pub fn update_prompt_vi_insert(&mut self, prompt_vi_insert_string: String) {
pub fn update_prompt_vi_insert(&mut self, prompt_vi_insert_string: Option<String>) {
self.default_vi_insert_prompt_indicator = prompt_vi_insert_string;
}
pub fn update_prompt_vi_normal(&mut self, prompt_vi_normal_string: String) {
pub fn update_prompt_vi_normal(&mut self, prompt_vi_normal_string: Option<String>) {
self.default_vi_normal_prompt_indicator = prompt_vi_normal_string;
}
pub fn update_prompt_multiline(&mut self, prompt_multiline_indicator_string: String) {
pub fn update_prompt_multiline(&mut self, prompt_multiline_indicator_string: Option<String>) {
self.default_multiline_indicator = prompt_multiline_indicator_string;
}
@ -64,18 +64,19 @@ impl NushellPrompt {
&mut self,
left_prompt_string: Option<String>,
right_prompt_string: Option<String>,
prompt_indicator_string: String,
prompt_multiline_indicator_string: String,
prompt_vi: (String, String),
prompt_indicator_string: Option<String>,
prompt_multiline_indicator_string: Option<String>,
prompt_vi: (Option<String>, Option<String>),
) {
let (prompt_vi_insert_string, prompt_vi_normal_string) = prompt_vi;
self.left_prompt_string = left_prompt_string;
self.right_prompt_string = right_prompt_string;
self.default_prompt_indicator = prompt_indicator_string;
self.default_multiline_indicator = prompt_multiline_indicator_string;
self.default_vi_insert_prompt_indicator = prompt_vi_insert_string;
self.default_vi_normal_prompt_indicator = prompt_vi_normal_string;
self.default_multiline_indicator = prompt_multiline_indicator_string;
}
fn default_wrapped_custom_string(&self, str: String) -> String {
@ -112,18 +113,33 @@ impl Prompt for NushellPrompt {
fn render_prompt_indicator(&self, edit_mode: PromptEditMode) -> Cow<str> {
match edit_mode {
PromptEditMode::Default => self.default_prompt_indicator.as_str().into(),
PromptEditMode::Emacs => self.default_prompt_indicator.as_str().into(),
PromptEditMode::Default => match &self.default_prompt_indicator {
Some(indicator) => indicator.as_str().into(),
None => "".into(),
},
PromptEditMode::Emacs => match &self.default_prompt_indicator {
Some(indicator) => indicator.as_str().into(),
None => "".into(),
},
PromptEditMode::Vi(vi_mode) => match vi_mode {
PromptViMode::Normal => self.default_vi_normal_prompt_indicator.as_str().into(),
PromptViMode::Insert => self.default_vi_insert_prompt_indicator.as_str().into(),
PromptViMode::Normal => match &self.default_vi_normal_prompt_indicator {
Some(indicator) => indicator.as_str().into(),
None => ": ".into(),
},
PromptViMode::Insert => match &self.default_vi_insert_prompt_indicator {
Some(indicator) => indicator.as_str().into(),
None => "".into(),
},
},
PromptEditMode::Custom(str) => self.default_wrapped_custom_string(str).into(),
}
}
fn render_prompt_multiline_indicator(&self) -> Cow<str> {
Cow::Borrowed(self.default_multiline_indicator.as_str())
match &self.default_multiline_indicator {
Some(indicator) => indicator.as_str().into(),
None => "::: ".into(),
}
}
fn render_prompt_history_search_indicator(

View File

@ -2,7 +2,6 @@ use crate::util::report_error;
use crate::NushellPrompt;
use log::info;
use nu_engine::eval_subexpression;
use nu_parser::parse;
use nu_protocol::{
engine::{EngineState, Stack, StateWorkingSet},
Config, PipelineData, Span, Value,
@ -17,49 +16,6 @@ pub(crate) const PROMPT_INDICATOR_VI_INSERT: &str = "PROMPT_INDICATOR_VI_INSERT"
pub(crate) const PROMPT_INDICATOR_VI_NORMAL: &str = "PROMPT_INDICATOR_VI_NORMAL";
pub(crate) const PROMPT_MULTILINE_INDICATOR: &str = "PROMPT_MULTILINE_INDICATOR";
pub(crate) fn get_prompt_indicators(
config: &Config,
engine_state: &EngineState,
stack: &Stack,
is_perf_true: bool,
) -> (String, String, String, String) {
let prompt_indicator = match stack.get_env_var(engine_state, PROMPT_INDICATOR) {
Some(pi) => pi.into_string("", config),
None => "".to_string(),
};
let prompt_vi_insert = match stack.get_env_var(engine_state, PROMPT_INDICATOR_VI_INSERT) {
Some(pvii) => pvii.into_string("", config),
None => ": ".to_string(),
};
let prompt_vi_normal = match stack.get_env_var(engine_state, PROMPT_INDICATOR_VI_NORMAL) {
Some(pviv) => pviv.into_string("", config),
None => "".to_string(),
};
let prompt_multiline = match stack.get_env_var(engine_state, PROMPT_MULTILINE_INDICATOR) {
Some(pm) => pm.into_string("", config),
None => "::: ".to_string(),
};
if is_perf_true {
info!(
"get_prompt_indicators {}:{}:{}",
file!(),
line!(),
column!()
);
}
(
prompt_indicator,
prompt_vi_insert,
prompt_vi_normal,
prompt_multiline,
)
}
fn get_prompt_string(
prompt: &str,
config: &Config,
@ -102,28 +58,7 @@ fn get_prompt_string(
}
}
}
Value::String { val: source, .. } => {
let mut working_set = StateWorkingSet::new(engine_state);
let (block, _) = parse(&mut working_set, None, source.as_bytes(), true, &[]);
// Use eval_subexpression to force a redirection of output, so we can use everything in prompt
let ret_val = eval_subexpression(
engine_state,
stack,
&block,
PipelineData::new(Span::new(0, 0)), // Don't try this at home, 0 span is ignored
)
.ok();
if is_perf_true {
info!(
"get_prompt_string (string) {}:{}:{}",
file!(),
line!(),
column!()
);
}
ret_val
}
Value::String { .. } => Some(PipelineData::Value(v.clone(), None)),
_ => None,
})
.and_then(|pipeline_data| {
@ -153,32 +88,60 @@ pub(crate) fn update_prompt<'prompt>(
nu_prompt: &'prompt mut NushellPrompt,
is_perf_true: bool,
) -> &'prompt dyn Prompt {
// get the other indicators
let (
prompt_indicator_string,
prompt_vi_insert_string,
prompt_vi_normal_string,
prompt_multiline_string,
) = get_prompt_indicators(config, engine_state, stack, is_perf_true);
let mut stack = stack.clone();
let left_prompt_string = get_prompt_string(
PROMPT_COMMAND,
config,
engine_state,
&mut stack,
is_perf_true,
);
let right_prompt_string = get_prompt_string(
PROMPT_COMMAND_RIGHT,
config,
engine_state,
&mut stack,
is_perf_true,
);
let prompt_indicator_string = get_prompt_string(
PROMPT_INDICATOR,
config,
engine_state,
&mut stack,
is_perf_true,
);
let prompt_multiline_string = get_prompt_string(
PROMPT_MULTILINE_INDICATOR,
config,
engine_state,
&mut stack,
is_perf_true,
);
let prompt_vi_insert_string = get_prompt_string(
PROMPT_INDICATOR_VI_INSERT,
config,
engine_state,
&mut stack,
is_perf_true,
);
let prompt_vi_normal_string = get_prompt_string(
PROMPT_INDICATOR_VI_NORMAL,
config,
engine_state,
&mut stack,
is_perf_true,
);
// apply the other indicators
nu_prompt.update_all_prompt_strings(
get_prompt_string(
PROMPT_COMMAND,
config,
engine_state,
&mut stack,
is_perf_true,
),
get_prompt_string(
PROMPT_COMMAND_RIGHT,
config,
engine_state,
&mut stack,
is_perf_true,
),
left_prompt_string,
right_prompt_string,
prompt_indicator_string,
prompt_multiline_string,
(prompt_vi_insert_string, prompt_vi_normal_string),

View File

@ -1,147 +1,491 @@
use super::DescriptionMenu;
use crate::{menus::NuMenuCompleter, NuHelpCompleter};
use crossterm::event::{KeyCode, KeyModifiers};
use nu_color_config::lookup_ansi_color_style;
use nu_protocol::{extract_value, Config, ParsedKeybinding, ShellError, Span, Value};
use nu_engine::eval_block;
use nu_parser::parse;
use nu_protocol::{
color_value_string, create_menus,
engine::{EngineState, Stack, StateWorkingSet},
extract_value, Config, IntoPipelineData, ParsedKeybinding, ParsedMenu, PipelineData,
ShellError, Span, Value,
};
use reedline::{
default_emacs_keybindings, default_vi_insert_keybindings, default_vi_normal_keybindings,
CompletionMenu, EditCommand, HistoryMenu, Keybindings, Reedline, ReedlineEvent,
ColumnarMenu, EditCommand, Keybindings, ListMenu, Reedline, ReedlineEvent, ReedlineMenu,
};
use std::sync::Arc;
// Creates an input object for the completion menu based on the dictionary
// stored in the config variable
pub(crate) fn add_completion_menu(line_editor: Reedline, config: &Config) -> Reedline {
let mut completion_menu = CompletionMenu::default();
const DEFAULT_COMPLETION_MENU: &str = r#"
{
name: completion_menu
only_buffer_difference: false
marker: "| "
type: {
layout: columnar
columns: 4
col_width: 20
col_padding: 2
}
style: {
text: green,
selected_text: green_reverse
description_text: yellow
}
}"#;
completion_menu = match config
.menu_config
.get("columns")
.and_then(|value| value.as_integer().ok())
{
Some(value) => completion_menu.with_columns(value as u16),
None => completion_menu,
};
const DEFAULT_HISTORY_MENU: &str = r#"
{
name: history_menu
only_buffer_difference: true
marker: "? "
type: {
layout: list
page_size: 10
}
style: {
text: green,
selected_text: green_reverse
description_text: yellow
}
}"#;
completion_menu = completion_menu.with_column_width(
config
.menu_config
.get("col_width")
.and_then(|value| value.as_integer().ok())
.map(|value| value as usize),
);
const DEFAULT_HELP_MENU: &str = r#"
{
name: help_menu
only_buffer_difference: true
marker: "? "
type: {
layout: description
columns: 4
col_width: 20
col_padding: 2
selection_rows: 4
description_rows: 10
}
style: {
text: green,
selected_text: green_reverse
description_text: yellow
}
}"#;
completion_menu = match config
.menu_config
.get("col_padding")
.and_then(|value| value.as_integer().ok())
{
Some(value) => completion_menu.with_column_padding(value as usize),
None => completion_menu,
};
// Adds all menus to line editor
pub(crate) fn add_menus(
mut line_editor: Reedline,
engine_state: Arc<EngineState>,
stack: &Stack,
config: &Config,
) -> Result<Reedline, ShellError> {
line_editor = line_editor.clear_menus();
completion_menu = match config
.menu_config
.get("text_style")
.and_then(|value| value.as_string().ok())
{
Some(value) => completion_menu.with_text_style(lookup_ansi_color_style(&value)),
None => completion_menu,
};
for menu in &config.menus {
line_editor = add_menu(line_editor, menu, engine_state.clone(), stack, config)?
}
completion_menu = match config
.menu_config
.get("selected_text_style")
.and_then(|value| value.as_string().ok())
{
Some(value) => completion_menu.with_selected_text_style(lookup_ansi_color_style(&value)),
None => completion_menu,
};
// Checking if the default menus have been added from the config file
let default_menus = vec![
("completion_menu", DEFAULT_COMPLETION_MENU),
("history_menu", DEFAULT_HISTORY_MENU),
("help_menu", DEFAULT_HELP_MENU),
];
completion_menu = match config
.menu_config
.get("marker")
.and_then(|value| value.as_string().ok())
{
Some(value) => completion_menu.with_marker(value),
None => completion_menu,
};
for (name, definition) in default_menus {
if !config
.menus
.iter()
.any(|menu| menu.name.into_string("", config) == name)
{
let (block, _) = {
let mut working_set = StateWorkingSet::new(&engine_state);
let (output, _) = parse(
&mut working_set,
Some(name), // format!("entry #{}", entry_num)
definition.as_bytes(),
true,
&[],
);
line_editor.with_menu(Box::new(completion_menu))
(output, working_set.render())
};
let mut temp_stack = Stack::new();
let input = Value::nothing(Span::test_data()).into_pipeline_data();
let res = eval_block(&engine_state, &mut temp_stack, &block, input, false, false)?;
if let PipelineData::Value(value, None) = res {
for menu in create_menus(&value, config)? {
line_editor =
add_menu(line_editor, &menu, engine_state.clone(), stack, config)?;
}
}
}
}
Ok(line_editor)
}
// Creates an input object for the history menu based on the dictionary
// stored in the config variable
pub(crate) fn add_history_menu(line_editor: Reedline, config: &Config) -> Reedline {
let mut history_menu = HistoryMenu::default();
fn add_menu(
line_editor: Reedline,
menu: &ParsedMenu,
engine_state: Arc<EngineState>,
stack: &Stack,
config: &Config,
) -> Result<Reedline, ShellError> {
if let Value::Record { cols, vals, span } = &menu.menu_type {
let layout = extract_value("layout", cols, vals, span)?.into_string("", config);
history_menu = match config
.history_config
.get("page_size")
.and_then(|value| value.as_integer().ok())
{
Some(value) => history_menu.with_page_size(value as usize),
None => history_menu,
};
history_menu = match config
.history_config
.get("selector")
.and_then(|value| value.as_string().ok())
{
Some(value) => {
let char = value.chars().next().unwrap_or('!');
history_menu.with_selection_char(char)
match layout.as_str() {
"columnar" => add_columnar_menu(line_editor, menu, engine_state, stack, config),
"list" => add_list_menu(line_editor, menu, engine_state, stack, config),
"description" => add_description_menu(line_editor, menu, engine_state, stack, config),
_ => Err(ShellError::UnsupportedConfigValue(
"columnar, list or description".to_string(),
menu.menu_type.into_abbreviated_string(config),
menu.menu_type.span()?,
)),
}
None => history_menu,
};
} else {
Err(ShellError::UnsupportedConfigValue(
"only record type".to_string(),
menu.menu_type.into_abbreviated_string(config),
menu.menu_type.span()?,
))
}
}
history_menu = match config
.history_config
.get("text_style")
.and_then(|value| value.as_string().ok())
{
Some(value) => history_menu.with_text_style(lookup_ansi_color_style(&value)),
None => history_menu,
macro_rules! add_style {
// first arm match add!(1,2), add!(2,3) etc
($name:expr, $cols: expr, $vals:expr, $span:expr, $config: expr, $menu:expr, $f:expr) => {
$menu = match extract_value($name, $cols, $vals, $span) {
Ok(text) => {
let text = match text {
Value::String { val, .. } => val.clone(),
Value::Record { cols, vals, span } => {
color_value_string(span, cols, vals, $config).into_string("", $config)
}
_ => "green".to_string(),
};
let style = lookup_ansi_color_style(&text);
$f($menu, style)
}
Err(_) => $menu,
};
};
}
history_menu = match config
.history_config
.get("selected_text_style")
.and_then(|value| value.as_string().ok())
{
Some(value) => history_menu.with_selected_text_style(lookup_ansi_color_style(&value)),
None => history_menu,
};
// Adds a columnar menu to the editor engine
pub(crate) fn add_columnar_menu(
line_editor: Reedline,
menu: &ParsedMenu,
engine_state: Arc<EngineState>,
stack: &Stack,
config: &Config,
) -> Result<Reedline, ShellError> {
let name = menu.name.into_string("", config);
let mut columnar_menu = ColumnarMenu::default().with_name(&name);
history_menu = match config
.history_config
.get("marker")
.and_then(|value| value.as_string().ok())
{
Some(value) => history_menu.with_marker(value),
None => history_menu,
};
if let Value::Record { cols, vals, span } = &menu.menu_type {
columnar_menu = match extract_value("columns", cols, vals, span) {
Ok(columns) => {
let columns = columns.as_integer()?;
columnar_menu.with_columns(columns as u16)
}
Err(_) => columnar_menu,
};
line_editor.with_menu(Box::new(history_menu))
columnar_menu = match extract_value("col_width", cols, vals, span) {
Ok(col_width) => {
let col_width = col_width.as_integer()?;
columnar_menu.with_column_width(Some(col_width as usize))
}
Err(_) => columnar_menu.with_column_width(None),
};
columnar_menu = match extract_value("col_padding", cols, vals, span) {
Ok(col_padding) => {
let col_padding = col_padding.as_integer()?;
columnar_menu.with_column_padding(col_padding as usize)
}
Err(_) => columnar_menu,
};
}
if let Value::Record { cols, vals, span } = &menu.style {
add_style!(
"text",
cols,
vals,
span,
config,
columnar_menu,
ColumnarMenu::with_text_style
);
add_style!(
"selected_text",
cols,
vals,
span,
config,
columnar_menu,
ColumnarMenu::with_selected_text_style
);
add_style!(
"description_text",
cols,
vals,
span,
config,
columnar_menu,
ColumnarMenu::with_description_text_style
);
}
let marker = menu.marker.into_string("", config);
columnar_menu = columnar_menu.with_marker(marker);
let only_buffer_difference = menu.only_buffer_difference.as_bool()?;
columnar_menu = columnar_menu.with_only_buffer_difference(only_buffer_difference);
match &menu.source {
Value::Nothing { .. } => {
Ok(line_editor.with_menu(ReedlineMenu::EngineCompleter(Box::new(columnar_menu))))
}
Value::Block {
val,
captures,
span,
} => {
let menu_completer = NuMenuCompleter::new(
*val,
*span,
stack.captures_to_stack(captures),
engine_state,
only_buffer_difference,
);
Ok(line_editor.with_menu(ReedlineMenu::WithCompleter {
menu: Box::new(columnar_menu),
completer: Box::new(menu_completer),
}))
}
_ => Err(ShellError::UnsupportedConfigValue(
"block or omitted value".to_string(),
menu.source.into_abbreviated_string(config),
menu.source.span()?,
)),
}
}
// Adds a search menu to the line editor
pub(crate) fn add_list_menu(
line_editor: Reedline,
menu: &ParsedMenu,
engine_state: Arc<EngineState>,
stack: &Stack,
config: &Config,
) -> Result<Reedline, ShellError> {
let name = menu.name.into_string("", config);
let mut list_menu = ListMenu::default().with_name(&name);
if let Value::Record { cols, vals, span } = &menu.menu_type {
list_menu = match extract_value("page_size", cols, vals, span) {
Ok(page_size) => {
let page_size = page_size.as_integer()?;
list_menu.with_page_size(page_size as usize)
}
Err(_) => list_menu,
};
}
if let Value::Record { cols, vals, span } = &menu.style {
add_style!(
"text",
cols,
vals,
span,
config,
list_menu,
ListMenu::with_text_style
);
add_style!(
"selected_text",
cols,
vals,
span,
config,
list_menu,
ListMenu::with_selected_text_style
);
add_style!(
"description_text",
cols,
vals,
span,
config,
list_menu,
ListMenu::with_description_text_style
);
}
let marker = menu.marker.into_string("", config);
list_menu = list_menu.with_marker(marker);
let only_buffer_difference = menu.only_buffer_difference.as_bool()?;
list_menu = list_menu.with_only_buffer_difference(only_buffer_difference);
match &menu.source {
Value::Nothing { .. } => {
Ok(line_editor.with_menu(ReedlineMenu::HistoryMenu(Box::new(list_menu))))
}
Value::Block {
val,
captures,
span,
} => {
let menu_completer = NuMenuCompleter::new(
*val,
*span,
stack.captures_to_stack(captures),
engine_state,
only_buffer_difference,
);
Ok(line_editor.with_menu(ReedlineMenu::WithCompleter {
menu: Box::new(list_menu),
completer: Box::new(menu_completer),
}))
}
_ => Err(ShellError::UnsupportedConfigValue(
"block or omitted value".to_string(),
menu.source.into_abbreviated_string(config),
menu.source.span()?,
)),
}
}
// Adds a description menu to the line editor
pub(crate) fn add_description_menu(
line_editor: Reedline,
menu: &ParsedMenu,
engine_state: Arc<EngineState>,
stack: &Stack,
config: &Config,
) -> Result<Reedline, ShellError> {
let name = menu.name.into_string("", config);
let mut description_menu = DescriptionMenu::default().with_name(&name);
if let Value::Record { cols, vals, span } = &menu.menu_type {
description_menu = match extract_value("columns", cols, vals, span) {
Ok(columns) => {
let columns = columns.as_integer()?;
description_menu.with_columns(columns as u16)
}
Err(_) => description_menu,
};
description_menu = match extract_value("col_width", cols, vals, span) {
Ok(col_width) => {
let col_width = col_width.as_integer()?;
description_menu.with_column_width(Some(col_width as usize))
}
Err(_) => description_menu.with_column_width(None),
};
description_menu = match extract_value("col_padding", cols, vals, span) {
Ok(col_padding) => {
let col_padding = col_padding.as_integer()?;
description_menu.with_column_padding(col_padding as usize)
}
Err(_) => description_menu,
};
description_menu = match extract_value("selection_rows", cols, vals, span) {
Ok(selection_rows) => {
let selection_rows = selection_rows.as_integer()?;
description_menu.with_selection_rows(selection_rows as u16)
}
Err(_) => description_menu,
};
description_menu = match extract_value("description_rows", cols, vals, span) {
Ok(description_rows) => {
let description_rows = description_rows.as_integer()?;
description_menu.with_description_rows(description_rows as usize)
}
Err(_) => description_menu,
};
}
if let Value::Record { cols, vals, span } = &menu.style {
add_style!(
"text",
cols,
vals,
span,
config,
description_menu,
DescriptionMenu::with_text_style
);
add_style!(
"selected_text",
cols,
vals,
span,
config,
description_menu,
DescriptionMenu::with_selected_text_style
);
add_style!(
"description_text",
cols,
vals,
span,
config,
description_menu,
DescriptionMenu::with_description_text_style
);
}
let marker = menu.marker.into_string("", config);
description_menu = description_menu.with_marker(marker);
let only_buffer_difference = menu.only_buffer_difference.as_bool()?;
description_menu = description_menu.with_only_buffer_difference(only_buffer_difference);
match &menu.source {
Value::Nothing { .. } => {
let completer = Box::new(NuHelpCompleter::new(engine_state));
Ok(line_editor.with_menu(ReedlineMenu::WithCompleter {
menu: Box::new(description_menu),
completer,
}))
}
Value::Block {
val,
captures,
span,
} => {
let menu_completer = NuMenuCompleter::new(
*val,
*span,
stack.captures_to_stack(captures),
engine_state,
only_buffer_difference,
);
Ok(line_editor.with_menu(ReedlineMenu::WithCompleter {
menu: Box::new(description_menu),
completer: Box::new(menu_completer),
}))
}
_ => Err(ShellError::UnsupportedConfigValue(
"block or omitted value".to_string(),
menu.source.into_abbreviated_string(config),
menu.source.span()?,
)),
}
}
fn add_menu_keybindings(keybindings: &mut Keybindings) {
keybindings.add_binding(
KeyModifiers::CONTROL,
KeyCode::Char('x'),
ReedlineEvent::UntilFound(vec![
ReedlineEvent::Menu("history_menu".to_string()),
ReedlineEvent::MenuPageNext,
]),
);
keybindings.add_binding(
KeyModifiers::CONTROL,
KeyCode::Char('z'),
ReedlineEvent::UntilFound(vec![
ReedlineEvent::MenuPagePrevious,
ReedlineEvent::Edit(vec![EditCommand::Undo]),
]),
);
// Completer menu keybindings
keybindings.add_binding(
KeyModifiers::NONE,
KeyCode::Tab,
@ -156,6 +500,34 @@ fn add_menu_keybindings(keybindings: &mut Keybindings) {
KeyCode::BackTab,
ReedlineEvent::MenuPrevious,
);
keybindings.add_binding(
KeyModifiers::CONTROL,
KeyCode::Char('r'),
ReedlineEvent::Menu("history_menu".to_string()),
);
keybindings.add_binding(
KeyModifiers::CONTROL,
KeyCode::Char('x'),
ReedlineEvent::MenuPageNext,
);
keybindings.add_binding(
KeyModifiers::CONTROL,
KeyCode::Char('z'),
ReedlineEvent::UntilFound(vec![
ReedlineEvent::MenuPagePrevious,
ReedlineEvent::Edit(vec![EditCommand::Undo]),
]),
);
// Help menu keybinding
keybindings.add_binding(
KeyModifiers::NONE,
KeyCode::F(1),
ReedlineEvent::Menu("help_menu".to_string()),
);
}
pub enum KeybindingsMode {
@ -173,6 +545,15 @@ pub(crate) fn create_keybindings(config: &Config) -> Result<KeybindingsMode, She
let mut insert_keybindings = default_vi_insert_keybindings();
let mut normal_keybindings = default_vi_normal_keybindings();
match config.edit_mode.as_str() {
"emacs" => {
add_menu_keybindings(&mut emacs_keybindings);
}
_ => {
add_menu_keybindings(&mut insert_keybindings);
add_menu_keybindings(&mut normal_keybindings);
}
}
for keybinding in parsed_keybindings {
add_keybinding(
&keybinding.mode,
@ -185,20 +566,11 @@ pub(crate) fn create_keybindings(config: &Config) -> Result<KeybindingsMode, She
}
match config.edit_mode.as_str() {
"emacs" => {
add_menu_keybindings(&mut emacs_keybindings);
Ok(KeybindingsMode::Emacs(emacs_keybindings))
}
_ => {
add_menu_keybindings(&mut insert_keybindings);
add_menu_keybindings(&mut normal_keybindings);
Ok(KeybindingsMode::Vi {
insert_keybindings,
normal_keybindings,
})
}
"emacs" => Ok(KeybindingsMode::Emacs(emacs_keybindings)),
_ => Ok(KeybindingsMode::Vi {
insert_keybindings,
normal_keybindings,
}),
}
}
@ -328,10 +700,11 @@ fn add_parsed_keybinding(
))
}
};
let event = parse_event(&keybinding.event, config)?;
keybindings.add_binding(modifier, keycode, event);
if let Some(event) = parse_event(&keybinding.event, config)? {
keybindings.add_binding(modifier, keycode, event);
} else {
keybindings.remove_binding(modifier, keycode);
}
Ok(())
}
@ -356,7 +729,7 @@ impl<'config> EventType<'config> {
}
}
fn parse_event(value: &Value, config: &Config) -> Result<ReedlineEvent, ShellError> {
fn parse_event(value: &Value, config: &Config) -> Result<Option<ReedlineEvent>, ShellError> {
match value {
Value::Record { cols, vals, span } => {
match EventType::try_from_columns(cols, vals, span)? {
@ -366,7 +739,8 @@ fn parse_event(value: &Value, config: &Config) -> Result<ReedlineEvent, ShellErr
vals,
config,
span,
),
)
.map(Some),
EventType::Edit(value) => {
let edit = edit_from_record(
value.into_string("", config).to_lowercase().as_str(),
@ -375,16 +749,26 @@ fn parse_event(value: &Value, config: &Config) -> Result<ReedlineEvent, ShellErr
config,
span,
)?;
Ok(ReedlineEvent::Edit(vec![edit]))
Ok(Some(ReedlineEvent::Edit(vec![edit])))
}
EventType::Until(value) => match value {
Value::List { vals, .. } => {
let events = vals
.iter()
.map(|value| parse_event(value, config))
.map(|value| match parse_event(value, config) {
Ok(inner) => match inner {
None => Err(ShellError::UnsupportedConfigValue(
"List containing valid events".to_string(),
"Nothing value (null)".to_string(),
value.span()?,
)),
Some(event) => Ok(event),
},
Err(e) => Err(e),
})
.collect::<Result<Vec<ReedlineEvent>, ShellError>>()?;
Ok(ReedlineEvent::UntilFound(events))
Ok(Some(ReedlineEvent::UntilFound(events)))
}
v => Err(ShellError::UnsupportedConfigValue(
"list of events".to_string(),
@ -397,13 +781,24 @@ fn parse_event(value: &Value, config: &Config) -> Result<ReedlineEvent, ShellErr
Value::List { vals, .. } => {
let events = vals
.iter()
.map(|value| parse_event(value, config))
.map(|value| match parse_event(value, config) {
Ok(inner) => match inner {
None => Err(ShellError::UnsupportedConfigValue(
"List containing valid events".to_string(),
"Nothing value (null)".to_string(),
value.span()?,
)),
Some(event) => Ok(event),
},
Err(e) => Err(e),
})
.collect::<Result<Vec<ReedlineEvent>, ShellError>>()?;
Ok(ReedlineEvent::Multiple(events))
Ok(Some(ReedlineEvent::Multiple(events)))
}
Value::Nothing { .. } => Ok(None),
v => Err(ShellError::UnsupportedConfigValue(
"record or list of records".to_string(),
"record or list of records, null to unbind key".to_string(),
v.into_abbreviated_string(config),
v.span()?,
)),
@ -421,6 +816,7 @@ fn event_from_record(
"none" => ReedlineEvent::None,
"actionhandler" => ReedlineEvent::ActionHandler,
"clearscreen" => ReedlineEvent::ClearScreen,
"clearscrollback" => ReedlineEvent::ClearScrollback,
"historyhintcomplete" => ReedlineEvent::HistoryHintComplete,
"historyhintwordcomplete" => ReedlineEvent::HistoryHintWordComplete,
"ctrld" => ReedlineEvent::CtrlD,
@ -443,6 +839,7 @@ fn event_from_record(
"menuprevious" => ReedlineEvent::MenuPrevious,
"menupagenext" => ReedlineEvent::MenuPageNext,
"menupageprevious" => ReedlineEvent::MenuPagePrevious,
"openeditor" => ReedlineEvent::OpenEditor,
"menu" => {
let menu = extract_value("name", cols, vals, span)?;
ReedlineEvent::Menu(menu.into_string("", config))
@ -488,6 +885,7 @@ fn edit_from_record(
let value = extract_value("value", cols, vals, span)?;
EditCommand::InsertString(value.into_string("", config))
}
"insertnewline" => EditCommand::InsertNewline,
"backspace" => EditCommand::Backspace,
"delete" => EditCommand::Delete,
"backspaceword" => EditCommand::BackspaceWord,
@ -595,7 +993,7 @@ mod test {
let config = Config::default();
let parsed_event = parse_event(&event, &config).unwrap();
assert_eq!(parsed_event, ReedlineEvent::Enter);
assert_eq!(parsed_event, Some(ReedlineEvent::Enter));
}
#[test]
@ -618,7 +1016,10 @@ mod test {
let config = Config::default();
let parsed_event = parse_event(&event, &config).unwrap();
assert_eq!(parsed_event, ReedlineEvent::Edit(vec![EditCommand::Clear]));
assert_eq!(
parsed_event,
Some(ReedlineEvent::Edit(vec![EditCommand::Clear]))
);
}
#[test]
@ -649,7 +1050,7 @@ mod test {
let parsed_event = parse_event(&event, &config).unwrap();
assert_eq!(
parsed_event,
ReedlineEvent::Menu("history_menu".to_string())
Some(ReedlineEvent::Menu("history_menu".to_string()))
);
}
@ -708,10 +1109,10 @@ mod test {
let parsed_event = parse_event(&event, &config).unwrap();
assert_eq!(
parsed_event,
ReedlineEvent::UntilFound(vec![
Some(ReedlineEvent::UntilFound(vec![
ReedlineEvent::Menu("history_menu".to_string()),
ReedlineEvent::Enter,
])
]))
);
}
@ -759,10 +1160,10 @@ mod test {
let parsed_event = parse_event(&event, &config).unwrap();
assert_eq!(
parsed_event,
ReedlineEvent::Multiple(vec![
Some(ReedlineEvent::Multiple(vec![
ReedlineEvent::Menu("history_menu".to_string()),
ReedlineEvent::Enter,
])
]))
);
}

View File

@ -1,74 +1,39 @@
use crate::reedline_config::{add_completion_menu, add_history_menu};
use crate::{prompt_update, reedline_config};
use crate::{
reedline_config::KeybindingsMode,
completions::NuCompleter,
prompt_update,
reedline_config::{add_menus, create_keybindings, KeybindingsMode},
util::{eval_source, report_error},
NuHighlighter, NuValidator, NushellPrompt,
};
use crate::{NuCompleter, NuHighlighter, NuValidator, NushellPrompt};
use log::info;
use log::trace;
use log::{info, trace};
use miette::{IntoDiagnostic, Result};
use nu_color_config::get_color_config;
use nu_engine::convert_env_values;
use nu_engine::{convert_env_values, eval_block};
use nu_parser::lex;
use nu_protocol::engine::Stack;
use nu_protocol::PipelineData;
use nu_protocol::{
engine::{EngineState, StateWorkingSet},
Config, ShellError, Span, Value, CONFIG_VARIABLE_ID,
engine::{EngineState, Stack, StateWorkingSet},
BlockId, PipelineData, PositionalArg, ShellError, Span, Value,
};
use reedline::{DefaultHinter, Emacs, Vi};
use std::io::{self, Write};
use std::path::PathBuf;
use std::{sync::atomic::Ordering, time::Instant};
const PRE_EXECUTE_MARKER: &str = "\x1b]133;A\x1b\\";
const PRE_PROMPT_MARKER: &str = "\x1b]133;C\x1b\\";
const RESET_APPLICATION_MODE: &str = "\x1b[?1l";
pub fn evaluate_repl(
engine_state: &mut EngineState,
stack: &mut Stack,
history_path: Option<PathBuf>,
is_perf_true: bool,
) -> Result<()> {
// use crate::logger::{configure, logger};
use reedline::{FileBackedHistory, Reedline, Signal};
let mut entry_num = 0;
let mut nu_prompt = NushellPrompt::new();
// let mut stack = nu_protocol::engine::Stack::new();
// First, set up env vars as strings only
// gather_parent_env_vars(engine_state);
// Set up our initial config to start from
// stack.vars.insert(
// CONFIG_VARIABLE_ID,
// Value::Record {
// cols: vec![],
// vals: vec![],
// span: Span::new(0, 0),
// },
// );
if is_perf_true {
info!("read_plugin_file {}:{}:{}", file!(), line!(), column!());
}
// #[cfg(feature = "plugin")]
// config_files::read_plugin_file(engine_state, &mut stack, is_perf_true);
//
// if is_perf_true {
// info!("read_config_file {}:{}:{}", file!(), line!(), column!());
// }
//
// config_files::read_config_file(engine_state, &mut stack, config_file, is_perf_true);
// let history_path = config_files::create_history_path();
// logger(|builder| {
// configure(&config.log_level, builder)?;
// // trace_filters(self, builder)?;
// // debug_filters(self, builder)?;
// Ok(())
// })?;
if is_perf_true {
info!(
@ -85,10 +50,6 @@ pub fn evaluate_repl(
report_error(&working_set, &e);
}
// Make a note of the exceptions we see for externals that look like math expressions
let exceptions = crate::util::external_exceptions(engine_state, stack);
engine_state.external_exceptions = exceptions;
// seed env vars
stack.add_env_var(
"CMD_DURATION_MS".into(),
@ -106,6 +67,37 @@ pub fn evaluate_repl(
},
);
if is_perf_true {
info!(
"load config initially {}:{}:{}",
file!(),
line!(),
column!()
);
}
// Get the config once for the history `max_history_size`
// Updating that will not be possible in one session
let mut config = engine_state.get_config();
if is_perf_true {
info!("setup reedline {}:{}:{}", file!(), line!(), column!());
}
let mut line_editor = Reedline::create();
if let Some(history_path) = history_path.as_deref() {
if is_perf_true {
info!("setup history {}:{}:{}", file!(), line!(), column!());
}
let history = Box::new(
FileBackedHistory::with_file(
config.max_history_size as usize,
history_path.to_path_buf(),
)
.into_diagnostic()?,
);
line_editor = line_editor.with_history(history);
};
loop {
if is_perf_true {
info!(
@ -116,27 +108,24 @@ pub fn evaluate_repl(
);
}
let config = match stack.get_config() {
Ok(config) => config,
Err(e) => {
let working_set = StateWorkingSet::new(engine_state);
report_error(&working_set, &e);
Config::default()
}
};
//Reset the ctrl-c handler
if let Some(ctrlc) = &mut engine_state.ctrlc {
ctrlc.store(false, Ordering::SeqCst);
}
config = engine_state.get_config();
if is_perf_true {
info!("setup line editor {}:{}:{}", file!(), line!(), column!());
info!("setup colors {}:{}:{}", file!(), line!(), column!());
}
let mut line_editor = Reedline::create()
.into_diagnostic()?
let color_hm = get_color_config(config);
if is_perf_true {
info!("update reedline {}:{}:{}", file!(), line!(), column!());
}
let engine_reference = std::sync::Arc::new(engine_state.clone());
line_editor = line_editor
.with_highlighter(Box::new(NuHighlighter {
engine_state: engine_state.clone(),
config: config.clone(),
@ -146,65 +135,64 @@ pub fn evaluate_repl(
engine_state: engine_state.clone(),
}))
.with_completer(Box::new(NuCompleter::new(
engine_state.clone(),
stack.vars.get(&CONFIG_VARIABLE_ID).cloned(),
engine_reference.clone(),
stack.clone(),
)))
.with_quick_completions(config.quick_completions)
.with_partial_completions(config.partial_completions)
.with_ansi_colors(config.use_ansi_coloring);
if is_perf_true {
info!("setup reedline {}:{}:{}", file!(), line!(), column!());
}
line_editor = if config.use_ansi_coloring {
line_editor.with_hinter(Box::new(
DefaultHinter::default().with_style(color_hm["hints"]),
))
} else {
line_editor.disable_hints()
};
line_editor = add_completion_menu(line_editor, &config);
line_editor = add_history_menu(line_editor, &config);
if is_perf_true {
info!("setup colors {}:{}:{}", file!(), line!(), column!());
}
//FIXME: if config.use_ansi_coloring is false then we should
// turn off the hinter but I don't see any way to do that yet.
let color_hm = get_color_config(&config);
if is_perf_true {
info!(
"setup history and hinter {}:{}:{}",
file!(),
line!(),
column!()
);
}
line_editor = if let Some(history_path) = history_path.clone() {
let history = std::fs::read_to_string(&history_path);
if history.is_ok() {
line_editor
.with_hinter(Box::new(
DefaultHinter::default().with_style(color_hm["hints"]),
))
.with_history(Box::new(
FileBackedHistory::with_file(
config.max_history_size as usize,
history_path.clone(),
)
.into_diagnostic()?,
))
.into_diagnostic()?
} else {
line_editor
line_editor = match add_menus(line_editor, engine_reference, stack, config) {
Ok(line_editor) => line_editor,
Err(e) => {
let working_set = StateWorkingSet::new(engine_state);
report_error(&working_set, &e);
Reedline::create()
}
};
let buffer_editor = if !config.buffer_editor.is_empty() {
Some(config.buffer_editor.clone())
} else {
stack
.get_env_var(engine_state, "EDITOR")
.map(|v| v.as_string().unwrap_or_default())
.filter(|v| !v.is_empty())
.or_else(|| {
stack
.get_env_var(engine_state, "VISUAL")
.map(|v| v.as_string().unwrap_or_default())
.filter(|v| !v.is_empty())
})
};
line_editor = if let Some(buffer_editor) = buffer_editor {
line_editor.with_buffer_editor(buffer_editor, "nu".into())
} else {
line_editor
};
if config.sync_history_on_enter {
if is_perf_true {
info!("sync history {}:{}:{}", file!(), line!(), column!());
}
line_editor.sync_history().into_diagnostic()?;
}
if is_perf_true {
info!("setup keybindings {}:{}:{}", file!(), line!(), column!());
}
// Changing the line editor based on the found keybindings
line_editor = match reedline_config::create_keybindings(&config) {
line_editor = match create_keybindings(config) {
Ok(keybindings) => match keybindings {
KeybindingsMode::Emacs(keybindings) => {
let edit_mode = Box::new(Emacs::new(keybindings));
@ -229,13 +217,67 @@ pub fn evaluate_repl(
info!("prompt_update {}:{}:{}", file!(), line!(), column!());
}
let prompt = prompt_update::update_prompt(
&config,
engine_state,
stack,
&mut nu_prompt,
is_perf_true,
);
// Right before we start our prompt and take input from the user,
// fire the "pre_prompt" hook
if let Some(hook) = &config.hooks.pre_prompt {
if let Err(err) = run_hook(engine_state, stack, vec![], hook) {
let working_set = StateWorkingSet::new(engine_state);
report_error(&working_set, &err);
}
}
// Next, check all the environment variables they ask for
// fire the "env_change" hook
if let Some(hook) = config.hooks.env_change.clone() {
match hook {
Value::Record {
cols, vals: blocks, ..
} => {
for (idx, env_var) in cols.iter().enumerate() {
let before = engine_state
.previous_env_vars
.get(env_var)
.cloned()
.unwrap_or_default();
let after = stack.get_env_var(engine_state, env_var).unwrap_or_default();
if before != after {
if let Err(err) = run_hook(
engine_state,
stack,
vec![before, after.clone()],
&blocks[idx],
) {
let working_set = StateWorkingSet::new(engine_state);
report_error(&working_set, &err);
}
engine_state
.previous_env_vars
.insert(env_var.to_string(), after);
}
}
}
x => {
let working_set = StateWorkingSet::new(engine_state);
report_error(
&working_set,
&ShellError::TypeMismatch(
"record for 'env_change' hook".to_string(),
x.span().unwrap_or_else(|_| Span::new(0, 0)),
),
)
}
}
}
config = engine_state.get_config();
if config.shell_integration {
run_ansi_sequence(PRE_EXECUTE_MARKER)?;
}
let prompt =
prompt_update::update_prompt(config, engine_state, stack, &mut nu_prompt, is_perf_true);
entry_num += 1;
@ -249,8 +291,39 @@ pub fn evaluate_repl(
}
let input = line_editor.read_line(prompt);
match input {
Ok(Signal::Success(s)) => {
// Right before we start running the code the user gave us,
// fire the "pre_execution" hook
if let Some(hook) = &config.hooks.pre_execution {
if let Err(err) = run_hook(engine_state, stack, vec![], hook) {
let working_set = StateWorkingSet::new(engine_state);
report_error(&working_set, &err);
}
}
if config.shell_integration {
run_ansi_sequence(RESET_APPLICATION_MODE)?;
run_ansi_sequence(PRE_PROMPT_MARKER)?;
if let Some(cwd) = stack.get_env_var(engine_state, "PWD") {
let path = cwd.as_string()?;
// Try to abbreviate string for windows title
let maybe_abbrev_path = if let Some(p) = nu_path::home_dir() {
path.replace(&p.as_path().display().to_string(), "~")
} else {
path
};
// Set window title too
// https://tldp.org/HOWTO/Xterm-Title-3.html
// ESC]0;stringBEL -- Set icon name and window title to string
// ESC]1;stringBEL -- Set icon name to string
// ESC]2;stringBEL -- Set window title to string
run_ansi_sequence(&format!("\x1b]2;{}\x07", maybe_abbrev_path))?;
}
}
let start_time = Instant::now();
let tokens = lex(s.as_bytes(), 0, &[], &[], false);
// Check if this is a single call to a directory, if so auto-cd
@ -273,10 +346,9 @@ pub fn evaluate_repl(
report_error(
&working_set,
&ShellError::DirectoryNotFound(tokens.0[0].span),
&ShellError::DirectoryNotFound(tokens.0[0].span, None),
);
}
let path = nu_path::canonicalize_with(path, &cwd)
.expect("internal error: cannot canonicalize known path");
(path.to_string_lossy().to_string(), tokens.0[0].span)
@ -322,26 +394,23 @@ pub fn evaluate_repl(
&format!("entry #{}", entry_num),
PipelineData::new(Span::new(0, 0)),
);
stack.add_env_var(
"CMD_DURATION_MS".into(),
Value::String {
val: format!("{}", start_time.elapsed().as_millis()),
span: Span { start: 0, end: 0 },
},
);
}
stack.add_env_var(
"CMD_DURATION_MS".into(),
Value::String {
val: format!("{}", start_time.elapsed().as_millis()),
span: Span { start: 0, end: 0 },
},
);
// FIXME: permanent state changes like this hopefully in time can be removed
// and be replaced by just passing the cwd in where needed
if let Some(cwd) = stack.get_env_var(engine_state, "PWD") {
let path = cwd.as_string()?;
let _ = std::env::set_current_dir(path);
engine_state.env_vars.insert("PWD".into(), cwd);
engine_state.add_env_var("PWD".into(), cwd);
}
// Make a note of the exceptions we see for externals that look like math expressions
let exceptions = crate::util::external_exceptions(engine_state, stack);
engine_state.external_exceptions = exceptions;
}
Ok(Signal::CtrlC) => {
// `Reedline` clears the line content. New prompt is shown
@ -351,9 +420,6 @@ pub fn evaluate_repl(
println!();
break;
}
Ok(Signal::CtrlL) => {
line_editor.clear_screen().into_diagnostic()?;
}
Err(err) => {
let message = err.to_string();
if !message.contains("duration") {
@ -365,3 +431,87 @@ pub fn evaluate_repl(
Ok(())
}
fn run_ansi_sequence(seq: &str) -> Result<(), ShellError> {
match io::stdout().write_all(seq.as_bytes()) {
Ok(it) => it,
Err(err) => {
return Err(ShellError::GenericError(
"Error writing ansi sequence".into(),
err.to_string(),
Some(Span { start: 0, end: 0 }),
None,
Vec::new(),
));
}
};
io::stdout().flush().map_err(|e| {
ShellError::GenericError(
"Error flushing stdio".into(),
e.to_string(),
Some(Span { start: 0, end: 0 }),
None,
Vec::new(),
)
})
}
pub fn run_hook(
engine_state: &EngineState,
stack: &mut Stack,
arguments: Vec<Value>,
value: &Value,
) -> Result<(), ShellError> {
match value {
Value::List { vals, .. } => {
for val in vals {
run_hook(engine_state, stack, arguments.clone(), val)?
}
Ok(())
}
Value::Block {
val: block_id,
span,
..
} => run_hook_block(engine_state, stack, *block_id, arguments, *span),
x => match x.span() {
Ok(span) => Err(ShellError::MissingConfigValue(
"block for hook in config".into(),
span,
)),
_ => Err(ShellError::MissingConfigValue(
"block for hook in config".into(),
Span { start: 0, end: 0 },
)),
},
}
}
pub fn run_hook_block(
engine_state: &EngineState,
stack: &mut Stack,
block_id: BlockId,
arguments: Vec<Value>,
span: Span,
) -> Result<(), ShellError> {
let block = engine_state.get_block(block_id);
let input = PipelineData::new(span);
let mut callee_stack = stack.gather_captures(&block.captures);
for (idx, PositionalArg { var_id, .. }) in
block.signature.required_positional.iter().enumerate()
{
if let Some(var_id) = var_id {
callee_stack.add_var(*var_id, arguments[idx].clone())
}
}
match eval_block(engine_state, &mut callee_stack, block, input, false, false) {
Ok(pipeline_data) => match pipeline_data.into_value(span) {
Value::Error { error } => Err(error),
_ => Ok(()),
},
Err(err) => Err(err),
}
}

View File

@ -178,6 +178,11 @@ impl Highlighter for NuHighlighter {
get_shape_color(shape.1.to_string(), &self.config),
next_token,
)),
FlatShape::Directory => output.push((
// nushell Directory
get_shape_color(shape.1.to_string(), &self.config),
next_token,
)),
FlatShape::GlobPattern => output.push((
// nushell GlobPattern
get_shape_color(shape.1.to_string(), &self.config),

View File

@ -1,188 +1,80 @@
use crate::CliError;
use log::trace;
use nu_engine::eval_block;
use nu_parser::{lex, parse, trim_quotes, Token, TokenContents};
use nu_parser::{escape_quote_string, lex, parse, unescape_unquote_string, Token, TokenContents};
use nu_protocol::engine::StateWorkingSet;
use nu_protocol::CliError;
use nu_protocol::{
ast::Call,
engine::{EngineState, Stack},
PipelineData, ShellError, Span, Value,
};
#[cfg(windows)]
use nu_utils::enable_vt_processing;
use std::io::Write;
use std::path::PathBuf;
pub fn print_pipeline_data(
input: PipelineData,
engine_state: &EngineState,
stack: &mut Stack,
) -> Result<(), ShellError> {
// If the table function is in the declarations, then we can use it
// to create the table value that will be printed in the terminal
let config = stack.get_config().unwrap_or_default();
let stdout = std::io::stdout();
if let PipelineData::ExternalStream {
stdout: stream,
exit_code,
..
} = input
{
if let Some(stream) = stream {
for s in stream {
let _ = stdout.lock().write_all(s?.as_binary()?);
}
}
// Make sure everything has finished
if let Some(exit_code) = exit_code {
let _: Vec<_> = exit_code.into_iter().collect();
}
return Ok(());
}
match engine_state.find_decl("table".as_bytes()) {
Some(decl_id) => {
let table = engine_state.get_decl(decl_id).run(
engine_state,
stack,
&Call::new(Span::new(0, 0)),
input,
)?;
for item in table {
let stdout = std::io::stdout();
if let Value::Error { error } = item {
return Err(error);
}
let mut out = item.into_string("\n", &config);
out.push('\n');
match stdout.lock().write_all(out.as_bytes()) {
Ok(_) => (),
Err(err) => eprintln!("{}", err),
};
}
}
None => {
for item in input {
let stdout = std::io::stdout();
if let Value::Error { error } = item {
return Err(error);
}
let mut out = item.into_string("\n", &config);
out.push('\n');
match stdout.lock().write_all(out.as_bytes()) {
Ok(_) => (),
Err(err) => eprintln!("{}", err),
};
}
}
};
Ok(())
}
// This will collect environment variables from std::env and adds them to a stack.
//
// In order to ensure the values have spans, it first creates a dummy file, writes the collected
// env vars into it (in a "NAME"="value" format, quite similar to the output of the Unix 'env'
// tool), then uses the file to get the spans. The file stays in memory, no filesystem IO is done.
pub fn gather_parent_env_vars(engine_state: &mut EngineState) {
// Some helper functions
fn get_surround_char(s: &str) -> Option<char> {
if s.contains('"') {
if s.contains('\'') {
None
} else {
Some('\'')
}
} else {
Some('\'')
}
}
gather_env_vars(std::env::vars(), engine_state);
}
fn gather_env_vars(vars: impl Iterator<Item = (String, String)>, engine_state: &mut EngineState) {
fn report_capture_error(engine_state: &EngineState, env_str: &str, msg: &str) {
let working_set = StateWorkingSet::new(engine_state);
report_error(
&working_set,
&ShellError::LabeledError(
&ShellError::GenericError(
format!("Environment variable was not captured: {}", env_str),
msg.into(),
"".to_string(),
None,
Some(msg.into()),
Vec::new(),
),
);
}
fn put_env_to_fake_file(
name: &str,
val: &str,
fake_env_file: &mut String,
engine_state: &EngineState,
) {
let (c_name, c_val) =
if let (Some(cn), Some(cv)) = (get_surround_char(name), get_surround_char(val)) {
(cn, cv)
} else {
// environment variable with its name or value containing both ' and " is ignored
report_capture_error(
engine_state,
&format!("{}={}", name, val),
"Name or value should not contain both ' and \" at the same time.",
);
return;
};
fake_env_file.push(c_name);
fake_env_file.push_str(name);
fake_env_file.push(c_name);
fn put_env_to_fake_file(name: &str, val: &str, fake_env_file: &mut String) {
fake_env_file.push_str(&escape_quote_string(name));
fake_env_file.push('=');
fake_env_file.push(c_val);
fake_env_file.push_str(val);
fake_env_file.push(c_val);
fake_env_file.push_str(&escape_quote_string(val));
fake_env_file.push('\n');
}
let mut fake_env_file = String::new();
let mut has_pwd = false;
// Make sure we always have PWD
if std::env::var("PWD").is_err() {
// Write all the env vars into a fake file
for (name, val) in vars {
if name == "PWD" {
has_pwd = true;
}
put_env_to_fake_file(&name, &val, &mut fake_env_file);
}
if !has_pwd {
match std::env::current_dir() {
Ok(cwd) => {
put_env_to_fake_file(
"PWD",
&cwd.to_string_lossy(),
&mut fake_env_file,
engine_state,
);
put_env_to_fake_file("PWD", &cwd.to_string_lossy(), &mut fake_env_file);
}
Err(e) => {
// Could not capture current working directory
let working_set = StateWorkingSet::new(engine_state);
report_error(
&working_set,
&ShellError::LabeledError(
&ShellError::GenericError(
"Current directory not found".to_string(),
format!("Retrieving current directory failed: {:?}", e),
"".to_string(),
None,
Some(format!("Retrieving current directory failed: {:?}", e)),
Vec::new(),
),
);
}
}
}
// Write all the env vars into a fake file
for (name, val) in std::env::vars() {
put_env_to_fake_file(&name, &val, &mut fake_env_file, engine_state);
}
// Lex the fake file, assign spans to all environment variables and add them
// to stack
let span_offset = engine_state.next_span_start();
@ -220,8 +112,19 @@ pub fn gather_parent_env_vars(engine_state: &mut EngineState) {
continue;
}
let bytes = trim_quotes(bytes);
String::from_utf8_lossy(bytes).to_string()
let (bytes, parse_error) = unescape_unquote_string(bytes, *span);
if parse_error.is_some() {
report_capture_error(
engine_state,
&String::from_utf8_lossy(contents),
"Got unparsable name.",
);
continue;
}
bytes
} else {
report_capture_error(
engine_state,
@ -249,10 +152,20 @@ pub fn gather_parent_env_vars(engine_state: &mut EngineState) {
continue;
}
let bytes = trim_quotes(bytes);
let (bytes, parse_error) = unescape_unquote_string(bytes, *span);
if parse_error.is_some() {
report_capture_error(
engine_state,
&String::from_utf8_lossy(contents),
"Got unparsable value.",
);
continue;
}
Value::String {
val: String::from_utf8_lossy(bytes).to_string(),
val: bytes,
span: *span,
}
} else {
@ -266,7 +179,7 @@ pub fn gather_parent_env_vars(engine_state: &mut EngineState) {
};
// stack.add_env_var(name, value);
engine_state.env_vars.insert(name, value);
engine_state.add_env_var(name, value);
}
}
}
@ -290,6 +203,7 @@ pub fn eval_source(
&[],
);
if let Some(err) = err {
set_last_exit_code(stack, 1);
report_error(&working_set, &err);
return false;
}
@ -297,8 +211,8 @@ pub fn eval_source(
(output, working_set.render())
};
let cwd = match nu_engine::env::current_dir_str(engine_state, stack) {
Ok(p) => PathBuf::from(p),
let cwd = match nu_engine::env::current_dir(engine_state, stack) {
Ok(p) => p,
Err(e) => {
let working_set = StateWorkingSet::new(engine_state);
report_error(&working_set, &e);
@ -306,10 +220,7 @@ pub fn eval_source(
}
};
if let Err(err) = engine_state.merge_delta(delta, Some(stack), &cwd) {
let working_set = StateWorkingSet::new(engine_state);
report_error(&working_set, &err);
}
let _ = engine_state.merge_delta(delta, Some(stack), &cwd);
match eval_block(engine_state, stack, &block, input, false, false) {
Ok(mut pipeline_data) => {
@ -317,25 +228,13 @@ pub fn eval_source(
if let Some(exit_code) = exit_code.take().and_then(|it| it.last()) {
stack.add_env_var("LAST_EXIT_CODE".to_string(), exit_code);
} else {
stack.add_env_var(
"LAST_EXIT_CODE".to_string(),
Value::Int {
val: 0,
span: Span { start: 0, end: 0 },
},
);
set_last_exit_code(stack, 0);
}
} else {
stack.add_env_var(
"LAST_EXIT_CODE".to_string(),
Value::Int {
val: 0,
span: Span { start: 0, end: 0 },
},
);
set_last_exit_code(stack, 0);
}
if let Err(err) = print_pipeline_data(pipeline_data, engine_state, stack) {
if let Err(err) = pipeline_data.print(engine_state, stack, false) {
let working_set = StateWorkingSet::new(engine_state);
report_error(&working_set, &err);
@ -350,13 +249,7 @@ pub fn eval_source(
}
}
Err(err) => {
stack.add_env_var(
"LAST_EXIT_CODE".to_string(),
Value::Int {
val: 1,
span: Span { start: 0, end: 0 },
},
);
set_last_exit_code(stack, 1);
let working_set = StateWorkingSet::new(engine_state);
@ -369,96 +262,14 @@ pub fn eval_source(
true
}
fn seems_like_number(bytes: &[u8]) -> bool {
if bytes.is_empty() {
false
} else {
let b = bytes[0];
b == b'0'
|| b == b'1'
|| b == b'2'
|| b == b'3'
|| b == b'4'
|| b == b'5'
|| b == b'6'
|| b == b'7'
|| b == b'8'
|| b == b'9'
|| b == b'('
|| b == b'{'
|| b == b'['
|| b == b'$'
|| b == b'"'
|| b == b'\''
|| b == b'-'
}
}
/// Finds externals that have names that look like math expressions
pub fn external_exceptions(engine_state: &EngineState, stack: &Stack) -> Vec<Vec<u8>> {
let mut executables = vec![];
if let Some(path) = stack.get_env_var(engine_state, "PATH") {
match path {
Value::List { vals, .. } => {
for val in vals {
let path = val.as_string();
if let Ok(path) = path {
if let Ok(mut contents) = std::fs::read_dir(path) {
while let Some(Ok(item)) = contents.next() {
if is_executable::is_executable(&item.path()) {
if let Ok(name) = item.file_name().into_string() {
if seems_like_number(name.as_bytes()) {
let name = name.as_bytes().to_vec();
executables.push(name);
}
}
if let Some(name) = item.path().file_stem() {
let name = name.to_string_lossy();
if seems_like_number(name.as_bytes()) {
let name = name.as_bytes().to_vec();
executables.push(name);
}
}
}
}
}
}
}
}
Value::String { val, .. } => {
for path in std::env::split_paths(&val) {
let path = path.to_string_lossy().to_string();
if let Ok(mut contents) = std::fs::read_dir(path) {
while let Some(Ok(item)) = contents.next() {
if is_executable::is_executable(&item.path()) {
if let Ok(name) = item.file_name().into_string() {
if seems_like_number(name.as_bytes()) {
let name = name.as_bytes().to_vec();
executables.push(name);
}
}
if let Some(name) = item.path().file_stem() {
let name = name.to_string_lossy();
if seems_like_number(name.as_bytes()) {
let name = name.as_bytes().to_vec();
executables.push(name);
}
}
}
}
}
}
}
_ => {}
}
}
executables
fn set_last_exit_code(stack: &mut Stack, exit_code: i64) {
stack.add_env_var(
"LAST_EXIT_CODE".to_string(),
Value::Int {
val: exit_code,
span: Span { start: 0, end: 0 },
},
);
}
pub fn report_error(
@ -485,3 +296,38 @@ pub fn get_init_cwd() -> PathBuf {
},
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_gather_env_vars() {
let mut engine_state = EngineState::new();
let symbols = r##" !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"##;
gather_env_vars(
[
("FOO".into(), "foo".into()),
("SYMBOLS".into(), symbols.into()),
(symbols.into(), "symbols".into()),
]
.into_iter(),
&mut engine_state,
);
let env = engine_state.render_env_vars();
assert!(
matches!(env.get(&"FOO".to_string()), Some(&Value::String { val, .. }) if val == "foo")
);
assert!(
matches!(env.get(&"SYMBOLS".to_string()), Some(&Value::String { val, .. }) if val == symbols)
);
assert!(
matches!(env.get(&symbols.to_string()), Some(&Value::String { val, .. }) if val == "symbols")
);
assert!(env.get(&"PWD".to_string()).is_some());
assert_eq!(env.len(), 4);
}
}

View File

@ -0,0 +1,29 @@
pub mod support;
use nu_cli::NuCompleter;
use reedline::Completer;
use support::{match_suggestions, new_engine};
#[test]
fn variables_completions() {
// Create a new engine
let (dir, _, mut engine, mut stack) = new_engine();
// Add record value as example
let record = r#"def animals [] { ["cat", "dog", "eel" ] }
def my-command [animal: string@animals] { print $animal }"#;
assert!(support::merge_input(record.as_bytes(), &mut engine, &mut stack, dir).is_ok());
// Instatiate a new completer
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
// Test completions for $nu
let suggestions = completer.complete("my-command ".into(), 11);
assert_eq!(3, suggestions.len());
let expected: Vec<String> = vec!["cat".into(), "dog".into(), "eel".into()];
// Match results
match_suggestions(expected, suggestions);
}

View File

@ -0,0 +1,28 @@
pub mod support;
use nu_cli::NuCompleter;
use reedline::Completer;
use support::new_engine;
#[test]
fn dotnu_completions() {
// Create a new engine
let (_, _, engine, stack) = new_engine();
// Instatiate a new completer
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
// Test source completion
let completion_str = "source ".to_string();
let suggestions = completer.complete(&completion_str, completion_str.len());
assert_eq!(1, suggestions.len());
assert_eq!("custom_completion.nu", suggestions.get(0).unwrap().value);
// Test use completion
let completion_str = "use ".to_string();
let suggestions = completer.complete(&completion_str, completion_str.len());
assert_eq!(1, suggestions.len());
assert_eq!("custom_completion.nu", suggestions.get(0).unwrap().value);
}

View File

@ -0,0 +1,42 @@
pub mod support;
use nu_cli::NuCompleter;
use reedline::Completer;
use support::{file, folder, match_suggestions, new_engine};
#[test]
fn file_completions() {
// Create a new engine
let (dir, dir_str, engine, stack) = new_engine();
// Instatiate a new completer
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
// Test completions for the current folder
let target_dir = format!("cp {}", dir_str);
let suggestions = completer.complete(&target_dir, target_dir.len());
// Create the expected values
let expected_paths: Vec<String> = vec![
file(dir.join("nushell")),
folder(dir.join("test_a")),
folder(dir.join("test_b")),
folder(dir.join("another")),
file(dir.join("custom_completion.nu")),
file(dir.join(".hidden_file")),
folder(dir.join(".hidden_folder")),
];
// Match the results
match_suggestions(expected_paths, suggestions);
// Test completions for the completions/another folder
let target_dir = format!("cd {}", folder(dir.join("another")));
let suggestions = completer.complete(&target_dir, target_dir.len());
// Create the expected values
let expected_paths: Vec<String> = vec![file(dir.join("another").join("newfile"))];
// Match the results
match_suggestions(expected_paths, suggestions);
}

View File

@ -0,0 +1,36 @@
pub mod support;
use nu_cli::NuCompleter;
use reedline::Completer;
use support::{match_suggestions, new_engine};
#[test]
fn flag_completions() {
// Create a new engine
let (_, _, engine, stack) = new_engine();
// Instatiate a new completer
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
// Test completions for the 'ls' flags
let suggestions = completer.complete("ls -".into(), 4);
assert_eq!(12, suggestions.len());
let expected: Vec<String> = vec![
"--all".into(),
"--du".into(),
"--full-paths".into(),
"--help".into(),
"--long".into(),
"--short-names".into(),
"-a".into(),
"-d".into(),
"-f".into(),
"-h".into(),
"-l".into(),
"-s".into(),
];
// Match results
match_suggestions(expected, suggestions);
}

View File

@ -0,0 +1,29 @@
pub mod support;
use nu_cli::NuCompleter;
use reedline::Completer;
use support::{folder, match_suggestions, new_engine};
#[test]
fn folder_completions() {
// Create a new engine
let (dir, dir_str, engine, stack) = new_engine();
// Instatiate a new completer
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
// Test completions for the current folder
let target_dir = format!("cd {}", dir_str);
let suggestions = completer.complete(&target_dir, target_dir.len());
// Create the expected values
let expected_paths: Vec<String> = vec![
folder(dir.join("test_a")),
folder(dir.join("test_b")),
folder(dir.join("another")),
folder(dir.join(".hidden_folder")),
];
// Match the results
match_suggestions(expected_paths, suggestions);
}

View File

@ -0,0 +1,107 @@
use std::path::PathBuf;
use nu_command::create_default_context;
use nu_engine::eval_block;
use nu_parser::parse;
use nu_protocol::{
engine::{EngineState, Stack, StateDelta, StateWorkingSet},
PipelineData, ShellError, Span, Value,
};
use nu_test_support::fs;
use reedline::Suggestion;
const SEP: char = std::path::MAIN_SEPARATOR;
// creates a new engine with the current path into the completions fixtures folder
pub fn new_engine() -> (PathBuf, String, EngineState, Stack) {
// Target folder inside assets
let dir = fs::fixtures().join("completions");
let mut dir_str = dir
.clone()
.into_os_string()
.into_string()
.unwrap_or_default();
dir_str.push(SEP);
// Create a new engine with default context
let mut engine_state = create_default_context(&dir);
// New stack
let mut stack = Stack::new();
// New delta state
let delta = StateDelta::new(&engine_state);
// Add pwd as env var
stack.add_env_var(
"PWD".to_string(),
Value::String {
val: dir_str.clone(),
span: nu_protocol::Span {
start: 0,
end: dir_str.len(),
},
},
);
// Merge delta
let merge_result = engine_state.merge_delta(delta, Some(&mut stack), &dir);
assert!(merge_result.is_ok());
(dir, dir_str, engine_state, stack)
}
// match a list of suggestions with the expected values
pub fn match_suggestions(expected: Vec<String>, suggestions: Vec<Suggestion>) {
expected.iter().zip(suggestions).for_each(|it| {
assert_eq!(it.0, &it.1.value);
});
}
// append the separator to the converted path
pub fn folder(path: PathBuf) -> String {
let mut converted_path = file(path);
converted_path.push(SEP);
converted_path
}
// convert a given path to string
pub fn file(path: PathBuf) -> String {
path.into_os_string().into_string().unwrap_or_default()
}
// merge_input executes the given input into the engine
// and merges the state
pub fn merge_input(
input: &[u8],
engine_state: &mut EngineState,
stack: &mut Stack,
dir: PathBuf,
) -> Result<(), ShellError> {
let (block, delta) = {
let mut working_set = StateWorkingSet::new(&engine_state);
let (block, err) = parse(&mut working_set, None, input, false, &[]);
assert!(err.is_none());
(block, working_set.render())
};
assert!(eval_block(
&engine_state,
stack,
&block,
PipelineData::Value(
Value::Nothing {
span: Span { start: 0, end: 0 },
},
None
),
false,
false
)
.is_ok());
// Merge delta
engine_state.merge_delta(delta, Some(stack), &dir)
}

View File

@ -0,0 +1,3 @@
pub mod completions_helpers;
pub use completions_helpers::{file, folder, match_suggestions, merge_input, new_engine};

View File

@ -0,0 +1,57 @@
pub mod support;
use nu_cli::NuCompleter;
use reedline::Completer;
use support::{match_suggestions, new_engine};
#[test]
fn variables_completions() {
// Create a new engine
let (dir, _, mut engine, mut stack) = new_engine();
// Add record value as example
let record = "let actor = { name: 'Tom Hardy', age: 44 }";
assert!(support::merge_input(record.as_bytes(), &mut engine, &mut stack, dir).is_ok());
// Instatiate a new completer
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
// Test completions for $nu
let suggestions = completer.complete("$nu.".into(), 4);
assert_eq!(8, suggestions.len());
let expected: Vec<String> = vec![
"config-path".into(),
"env-path".into(),
"history-path".into(),
"home-path".into(),
"os-info".into(),
"pid".into(),
"scope".into(),
"temp-path".into(),
];
// Match results
match_suggestions(expected, suggestions);
// Test completions for custom var
let suggestions = completer.complete("$actor.".into(), 7);
assert_eq!(2, suggestions.len());
let expected: Vec<String> = vec!["age".into(), "name".into()];
// Match results
match_suggestions(expected, suggestions);
// Test completions for $env
let suggestions = completer.complete("$env.".into(), 5);
assert_eq!(1, suggestions.len());
let expected: Vec<String> = vec!["PWD".into()];
// Match results
match_suggestions(expected, suggestions);
}

View File

@ -1,13 +1,14 @@
[package]
name = "nu-color-config"
version = "0.60.0"
authors = ["The Nushell Project Developers"]
description = "Color configuration code used by Nushell"
edition = "2021"
license = "MIT"
name = "nu-color-config"
version = "0.63.0"
[dependencies]
nu-protocol = { path = "../nu-protocol", version = "0.60.0" }
nu-ansi-term = "0.45.0"
nu-json = { path = "../nu-json", version = "0.60.0" }
nu-table = { path = "../nu-table", version = "0.60.0" }
nu-protocol = { path = "../nu-protocol", version = "0.63.0" }
nu-ansi-term = "0.45.1"
nu-json = { path = "../nu-json", version = "0.63.0" }
nu-table = { path = "../nu-table", version = "0.63.0" }
serde = { version="1.0.123", features=["derive"] }

View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019 - 2022 The Nushell Project Developers
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -161,6 +161,13 @@ pub fn lookup_ansi_color_style(s: &str) -> Style {
"dgrbl" | "dark_gray_blink" => Color::DarkGray.blink(),
"dgrst" | "dark_gray_strike" => Color::DarkGray.strikethrough(),
"def" | "default" => Color::Default.normal(),
"defb" | "default_bold" => Color::Default.bold(),
"defu" | "default_underline" => Color::Default.underline(),
"defi" | "default_italic" => Color::Default.italic(),
"defd" | "default_dimmed" => Color::Default.dimmed(),
"defr" | "default_reverse" => Color::Default.reverse(),
_ => Color::White.normal(),
}
}

View File

@ -29,6 +29,7 @@ pub fn get_shape_color(shape: String, conf: &Config) -> Style {
"shape_record" => Style::new().fg(Color::Cyan).bold(),
"shape_block" => Style::new().fg(Color::Blue).bold(),
"shape_filepath" => Style::new().fg(Color::Cyan),
"shape_directory" => Style::new().fg(Color::Cyan),
"shape_globpattern" => Style::new().fg(Color::Cyan).bold(),
"shape_variable" => Style::new().fg(Color::Purple),
"shape_flag" => Style::new().fg(Color::Blue).bold(),

View File

@ -1,43 +1,47 @@
[package]
name = "nu-command"
version = "0.60.0"
authors = ["The Nushell Project Developers"]
description = "Nushell's built-in commands"
edition = "2021"
license = "MIT"
name = "nu-command"
version = "0.63.0"
build = "build.rs"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
nu-color-config = { path = "../nu-color-config", version = "0.60.0" }
nu-engine = { path = "../nu-engine", version = "0.60.0" }
nu-glob = { path = "../nu-glob", version = "0.60.0" }
nu-json = { path = "../nu-json", version = "0.60.0" }
nu-parser = { path = "../nu-parser", version = "0.60.0" }
nu-path = { path = "../nu-path", version = "0.60.0" }
nu-pretty-hex = { path = "../nu-pretty-hex", version = "0.60.0" }
nu-protocol = { path = "../nu-protocol", version = "0.60.0" }
nu-system = { path = "../nu-system", version = "0.60.0" }
nu-table = { path = "../nu-table", version = "0.60.0" }
nu-term-grid = { path = "../nu-term-grid", version = "0.60.0" }
nu-test-support = { path = "../nu-test-support", version = "0.60.0" }
nu-utils = { path = "../nu-utils", version = "0.60.0" }
nu-ansi-term = "0.45.0"
nu-color-config = { path = "../nu-color-config", version = "0.63.0" }
nu-engine = { path = "../nu-engine", version = "0.63.0" }
nu-glob = { path = "../nu-glob", version = "0.63.0" }
nu-json = { path = "../nu-json", version = "0.63.0" }
nu-parser = { path = "../nu-parser", version = "0.63.0" }
nu-path = { path = "../nu-path", version = "0.63.0" }
nu-pretty-hex = { path = "../nu-pretty-hex", version = "0.63.0" }
nu-protocol = { path = "../nu-protocol", version = "0.63.0" }
nu-system = { path = "../nu-system", version = "0.63.0" }
nu-table = { path = "../nu-table", version = "0.63.0" }
nu-term-grid = { path = "../nu-term-grid", version = "0.63.0" }
nu-test-support = { path = "../nu-test-support", version = "0.63.0" }
nu-utils = { path = "../nu-utils", version = "0.63.0" }
nu-ansi-term = "0.45.1"
# Potential dependencies for extras
alphanumeric-sort = "1.4.4"
base64 = "0.13.0"
bytesize = "1.1.0"
calamine = "0.18.0"
chrono = { version = "0.4.19", features = ["serde"] }
chrono-humanize = "0.2.1"
chrono-tz = "0.6.0"
chrono-tz = "0.6.1"
crossterm = "0.23.0"
csv = "1.1.3"
csv = "1.1.6"
dialoguer = "0.9.0"
digest = "0.10.0"
dtparse = "1.2.0"
eml-parser = "0.1.0"
encoding_rs = "0.8.30"
filesize = "0.2.0"
filetime = "0.2.15"
fs_extra = "1.2.0"
htmlescape = "0.3.1"
ical = "0.7.0"
@ -50,8 +54,10 @@ lscolors = { version = "0.9.0", features = ["crossterm"]}
md5 = { package = "md-5", version = "0.10.0" }
meval = "0.2.0"
mime = "0.3.16"
notify = "4.0.17"
num = { version = "0.4.0", optional = true }
pathdiff = "0.2.1"
powierza-coefficient = "1.0"
quick-xml = "0.22"
rand = "0.8"
rayon = "1.5.1"
@ -64,42 +70,52 @@ serde_ini = "0.2.0"
serde_urlencoded = "0.7.0"
serde_yaml = "0.8.16"
sha2 = "0.10.0"
shadow-rs = "0.8.1"
# Disable default features b/c the default features build Git (very slow to compile)
shadow-rs = { version = "0.11.0", default-features = false }
strip-ansi-escapes = "0.1.1"
sysinfo = "0.23.5"
terminal_size = "0.1.17"
thiserror = "1.0.29"
titlecase = "1.1.0"
toml = "0.5.8"
trash = { version = "2.0.2", optional = true }
unicode-segmentation = "1.8.0"
url = "2.2.1"
uuid = { version = "0.8.2", features = ["v4"] }
which = { version = "4.2.2", optional = true }
reedline = "0.3.0"
zip = { version="0.5.9", optional = true }
reedline = { version = "0.6.0", features = ["bashisms"]}
wax = { version = "0.4.0", features = ["diagnostics"] }
rusqlite = { version = "0.27.0", features = ["bundled"], optional = true }
sqlparser = { version = "0.16.0", features = ["serde"], optional = true }
[target.'cfg(unix)'.dependencies]
umask = "1.0.0"
umask = "2.0.0"
users = "0.11.0"
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies.trash]
version = "2.1.3"
optional = true
[dependencies.polars]
version = "0.20.0"
version = "0.21.1"
# path = "../../../../polars/polars"
optional = true
features = [
"default", "parquet", "json", "serde", "object",
"checked_arithmetic", "strings", "cum_agg", "is_in",
"default", "to_dummies", "parquet", "json", "serde", "serde-lazy",
"object", "checked_arithmetic", "strings", "cum_agg", "is_in",
"rolling_window", "strings", "rows", "random",
"dtype-datetime"
"dtype-datetime", "dtype-struct", "lazy", "cross_join",
"dynamic_groupby"
]
[features]
trash-support = ["trash"]
which-support = ["which"]
plugin = ["nu-parser/plugin"]
dataframe = ["polars", "num"]
database = ["sqlparser", "rusqlite"]
[build-dependencies]
shadow-rs = "0.8.1"
shadow-rs = { version = "0.11.0", default-features = false }
[dev-dependencies]
hamcrest2 = "0.3.0"

21
crates/nu-command/LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019 - 2022 The Nushell Project Developers
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

File diff suppressed because one or more lines are too long

View File

@ -1,3 +1,18 @@
use std::process::Command;
fn main() -> shadow_rs::SdResult<()> {
// Look up the current Git commit ourselves instead of relying on shadow_rs,
// because shadow_rs does it in a really slow-to-compile way (it builds libgit2)
let hash = get_git_hash().expect("failed to get latest git commit hash");
println!("cargo:rustc-env=NU_COMMIT_HASH={}", hash);
shadow_rs::new()
}
fn get_git_hash() -> Result<String, std::io::Error> {
let out = Command::new("git").args(["rev-parse", "HEAD"]).output()?;
Ok(String::from_utf8(out.stdout)
.expect("could not convert stdout to string")
.trim()
.to_string())
}

View File

@ -0,0 +1,317 @@
use chrono::{DateTime, FixedOffset};
use nu_protocol::{ShellError, Span, Value};
use std::hash::{Hash, Hasher};
/// A subset of [Value](crate::Value), which is hashable.
/// And it means that we can put the value into something like [HashMap](std::collections::HashMap) or [HashSet](std::collections::HashSet)
/// for further usage like value statistics.
///
/// For now the main way to crate a [HashableValue] is using [from_value](HashableValue::from_value)
///
/// Please note that although each variant contains `span` field, but during hashing, this field will not be concerned.
/// Which means that the following will be true:
/// ```text
/// assert_eq!(HashableValue::Bool {val: true, span: Span{start: 0, end: 1}}, HashableValue::Bool {val: true, span: Span{start: 90, end: 1000}})
/// ```
#[derive(Eq, Debug)]
pub enum HashableValue {
Bool {
val: bool,
span: Span,
},
Int {
val: i64,
span: Span,
},
Float {
val: [u8; 8], // because f64 is not hashable, we save it as [u8;8] array to make it hashable.
span: Span,
},
Filesize {
val: i64,
span: Span,
},
Duration {
val: i64,
span: Span,
},
Date {
val: DateTime<FixedOffset>,
span: Span,
},
String {
val: String,
span: Span,
},
Binary {
val: Vec<u8>,
span: Span,
},
}
impl Default for HashableValue {
fn default() -> Self {
HashableValue::Bool {
val: false,
span: Span { start: 0, end: 0 },
}
}
}
impl HashableValue {
/// Try to convert from `value` to self
///
/// A `span` is required because when there is an error in value, it may not contain `span` field.
///
/// If the given value is not hashable(mainly because of it is structured data), an error will returned.
pub fn from_value(value: Value, span: Span) -> Result<Self, ShellError> {
match value {
Value::Bool { val, span } => Ok(HashableValue::Bool { val, span }),
Value::Int { val, span } => Ok(HashableValue::Int { val, span }),
Value::Filesize { val, span } => Ok(HashableValue::Filesize { val, span }),
Value::Duration { val, span } => Ok(HashableValue::Duration { val, span }),
Value::Date { val, span } => Ok(HashableValue::Date { val, span }),
Value::Float { val, span } => Ok(HashableValue::Float {
val: val.to_ne_bytes(),
span,
}),
Value::String { val, span } => Ok(HashableValue::String { val, span }),
Value::Binary { val, span } => Ok(HashableValue::Binary { val, span }),
_ => {
let input_span = value.span().unwrap_or(span);
Err(ShellError::UnsupportedInput(
format!("input value {value:?} is not hashable"),
input_span,
))
}
}
}
/// Convert from self to nu's core data type `Value`.
pub fn into_value(self) -> Value {
match self {
HashableValue::Bool { val, span } => Value::Bool { val, span },
HashableValue::Int { val, span } => Value::Int { val, span },
HashableValue::Filesize { val, span } => Value::Filesize { val, span },
HashableValue::Duration { val, span } => Value::Duration { val, span },
HashableValue::Date { val, span } => Value::Date { val, span },
HashableValue::Float { val, span } => Value::Float {
val: f64::from_ne_bytes(val),
span,
},
HashableValue::String { val, span } => Value::String { val, span },
HashableValue::Binary { val, span } => Value::Binary { val, span },
}
}
}
impl Hash for HashableValue {
fn hash<H: Hasher>(&self, state: &mut H) {
match self {
HashableValue::Bool { val, .. } => val.hash(state),
HashableValue::Int { val, .. } => val.hash(state),
HashableValue::Filesize { val, .. } => val.hash(state),
HashableValue::Duration { val, .. } => val.hash(state),
HashableValue::Date { val, .. } => val.hash(state),
HashableValue::Float { val, .. } => val.hash(state),
HashableValue::String { val, .. } => val.hash(state),
HashableValue::Binary { val, .. } => val.hash(state),
}
}
}
impl PartialEq for HashableValue {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(HashableValue::Bool { val: lhs, .. }, HashableValue::Bool { val: rhs, .. }) => {
lhs == rhs
}
(HashableValue::Int { val: lhs, .. }, HashableValue::Int { val: rhs, .. }) => {
lhs == rhs
}
(
HashableValue::Filesize { val: lhs, .. },
HashableValue::Filesize { val: rhs, .. },
) => lhs == rhs,
(
HashableValue::Duration { val: lhs, .. },
HashableValue::Duration { val: rhs, .. },
) => lhs == rhs,
(HashableValue::Date { val: lhs, .. }, HashableValue::Date { val: rhs, .. }) => {
lhs == rhs
}
(HashableValue::Float { val: lhs, .. }, HashableValue::Float { val: rhs, .. }) => {
lhs == rhs
}
(HashableValue::String { val: lhs, .. }, HashableValue::String { val: rhs, .. }) => {
lhs == rhs
}
(HashableValue::Binary { val: lhs, .. }, HashableValue::Binary { val: rhs, .. }) => {
lhs == rhs
}
_ => false,
}
}
}
#[cfg(test)]
mod test {
use super::*;
use nu_protocol::ast::{CellPath, PathMember};
use std::collections::{HashMap, HashSet};
#[test]
fn from_value() {
let span = Span::test_data();
let values = vec![
(
Value::Bool { val: true, span },
HashableValue::Bool { val: true, span },
),
(
Value::Int { val: 1, span },
HashableValue::Int { val: 1, span },
),
(
Value::Filesize { val: 1, span },
HashableValue::Filesize { val: 1, span },
),
(
Value::Duration { val: 1, span },
HashableValue::Duration { val: 1, span },
),
(
Value::Date {
val: DateTime::<FixedOffset>::parse_from_rfc2822(
"Wed, 18 Feb 2015 23:16:09 GMT",
)
.unwrap(),
span,
},
HashableValue::Date {
val: DateTime::<FixedOffset>::parse_from_rfc2822(
"Wed, 18 Feb 2015 23:16:09 GMT",
)
.unwrap(),
span,
},
),
(
Value::String {
val: "1".to_string(),
span,
},
HashableValue::String {
val: "1".to_string(),
span,
},
),
(
Value::Binary { val: vec![1], span },
HashableValue::Binary { val: vec![1], span },
),
];
for (val, expect_hashable_val) in values.into_iter() {
assert_eq!(
HashableValue::from_value(val, Span { start: 0, end: 0 }).unwrap(),
expect_hashable_val
);
}
}
#[test]
fn from_unhashable_value() {
let span = Span::test_data();
let values = [
Value::List {
vals: vec![Value::Bool { val: true, span }],
span,
},
Value::Block {
val: 0,
captures: HashMap::new(),
span,
},
Value::Nothing { span },
Value::Error {
error: ShellError::DidYouMean("what?".to_string(), span),
},
Value::CellPath {
val: CellPath {
members: vec![PathMember::Int { val: 0, span }],
},
span,
},
];
for v in values {
assert!(HashableValue::from_value(v, Span { start: 0, end: 0 }).is_err())
}
}
#[test]
fn from_to_tobe_same() {
let span = Span::test_data();
let values = vec![
Value::Bool { val: true, span },
Value::Int { val: 1, span },
Value::Filesize { val: 1, span },
Value::Duration { val: 1, span },
Value::String {
val: "1".to_string(),
span,
},
Value::Binary { val: vec![1], span },
];
for val in values.into_iter() {
let expected_val = val.clone();
assert_eq!(
HashableValue::from_value(val, Span { start: 0, end: 0 })
.unwrap()
.into_value(),
expected_val
);
}
}
#[test]
fn hashable_value_eq_without_concern_span() {
assert_eq!(
HashableValue::Bool {
val: true,
span: Span { start: 0, end: 1 }
},
HashableValue::Bool {
val: true,
span: Span {
start: 90,
end: 1000
}
}
)
}
#[test]
fn put_to_hashset() {
let span = Span::test_data();
let mut set = HashSet::new();
set.insert(HashableValue::Bool { val: true, span });
assert!(set.contains(&HashableValue::Bool { val: true, span }));
// hashable value doesn't care about span.
let diff_span = Span { start: 1, end: 2 };
set.insert(HashableValue::Bool {
val: true,
span: diff_span,
});
assert!(set.contains(&HashableValue::Bool { val: true, span }));
assert!(set.contains(&HashableValue::Bool {
val: true,
span: diff_span
}));
assert_eq!(set.len(), 1);
set.insert(HashableValue::Int { val: 2, span });
assert_eq!(set.len(), 2);
}
}

View File

@ -0,0 +1,256 @@
use super::hashable_value::HashableValue;
use nu_engine::CallExt;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Example, IntoPipelineData, PipelineData, ShellError, Signature, Span, Spanned, SyntaxShape,
Value,
};
use std::collections::HashMap;
use std::iter;
#[derive(Clone)]
pub struct Histogram;
enum PercentageCalcMethod {
Normalize,
Relative,
}
impl Command for Histogram {
fn name(&self) -> &str {
"histogram"
}
fn signature(&self) -> Signature {
Signature::build("histogram")
.optional("column-name", SyntaxShape::String, "column name to calc frequency, no need to provide if input is just a list")
.optional("frequency-column-name", SyntaxShape::String, "histogram's frequency column, default to be frequency column output")
.named("percentage-type", SyntaxShape::String, "percentage calculate method, can be 'normalize' or 'relative', in 'normalize', defaults to be 'normalize'", Some('t'))
}
fn usage(&self) -> &str {
"Creates a new table with a histogram based on the column name passed in."
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Get a histogram for the types of files",
example: "ls | histogram type",
result: None,
},
Example {
description:
"Get a histogram for the types of files, with frequency column named freq",
example: "ls | histogram type freq",
result: None,
},
Example {
description: "Get a histogram for a list of numbers",
example: "echo [1 2 3 1 1 1 2 2 1 1] | histogram",
result: None,
},
Example {
description: "Get a histogram for a list of numbers, and percentage is based on the maximum value",
example: "echo [1 2 3 1 1 1 2 2 1 1] | histogram --percentage-type relative",
result: None,
}
]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
// input check.
let column_name: Option<Spanned<String>> = call.opt(engine_state, stack, 0)?;
let frequency_name_arg = call.opt::<Spanned<String>>(engine_state, stack, 1)?;
let frequency_column_name = match frequency_name_arg {
Some(inner) => {
let span = inner.span;
if ["value", "count", "quantile", "percentage"].contains(&inner.item.as_str()) {
return Err(ShellError::UnsupportedInput(
"frequency-column-name can't be 'value', 'count' or 'percentage'"
.to_string(),
span,
));
}
inner.item
}
None => "frequency".to_string(),
};
let calc_method: Option<Spanned<String>> =
call.get_flag(engine_state, stack, "percentage-type")?;
let calc_method = match calc_method {
None => PercentageCalcMethod::Normalize,
Some(inner) => match inner.item.as_str() {
"normalize" => PercentageCalcMethod::Normalize,
"relative" => PercentageCalcMethod::Relative,
_ => {
return Err(ShellError::UnsupportedInput(
"calc method can only be 'normalize' or 'relative'".to_string(),
inner.span,
))
}
},
};
let span = call.head;
let data_as_value = input.into_value(span);
// `input` is not a list, here we can return an error.
match data_as_value.as_list() {
Ok(list_value) => run_histogram(
list_value.to_vec(),
column_name,
frequency_column_name,
calc_method,
span,
),
Err(e) => Err(e),
}
}
}
fn run_histogram(
values: Vec<Value>,
column_name: Option<Spanned<String>>,
freq_column: String,
calc_method: PercentageCalcMethod,
head_span: Span,
) -> Result<PipelineData, ShellError> {
let mut inputs = vec![];
// convert from inputs to hashable values.
match column_name {
None => {
// some invalid input scenario needs to handle:
// Expect input is a list of hashable value, if one value is not hashable, throw out error.
for v in values {
let current_span = v.span().unwrap_or(head_span);
inputs.push(HashableValue::from_value(v, head_span).map_err(|_| {
ShellError::UnsupportedInput(
"--column-name is not provided, can only support a list of simple value."
.to_string(),
current_span,
)
})?);
}
}
Some(ref col) => {
// some invalid input scenario needs to handle:
// * item in `input` is not a record, just skip it.
// * a record doesn't contain specific column, just skip it.
// * all records don't contain specific column, throw out error, indicate at least one row should contains specific column.
// * a record contain a value which can't be hashed, skip it.
let col_name = &col.item;
for v in values {
match v {
// parse record, and fill valid value to actual input.
Value::Record { cols, vals, .. } => {
for (c, v) in iter::zip(cols, vals) {
if &c == col_name {
if let Ok(v) = HashableValue::from_value(v, head_span) {
inputs.push(v);
}
}
}
}
_ => continue,
}
}
if inputs.is_empty() {
return Err(ShellError::UnsupportedInput(
format!("expect input is table, and inputs doesn't contain any value which has {col_name} column"),
head_span,
));
}
}
}
let value_column_name = column_name
.map(|x| x.item)
.unwrap_or_else(|| "value".to_string());
Ok(histogram_impl(
inputs,
&value_column_name,
calc_method,
&freq_column,
head_span,
))
}
fn histogram_impl(
inputs: Vec<HashableValue>,
value_column_name: &str,
calc_method: PercentageCalcMethod,
freq_column: &str,
span: Span,
) -> PipelineData {
// here we can make sure that inputs is not empty, and every elements
// is a simple val and ok to make count.
let mut counter = HashMap::new();
let mut max_cnt = 0;
let total_cnt = inputs.len();
for i in inputs {
let new_cnt = *counter.get(&i).unwrap_or(&0) + 1;
counter.insert(i, new_cnt);
if new_cnt > max_cnt {
max_cnt = new_cnt;
}
}
let mut result = vec![];
let result_cols = vec![
value_column_name.to_string(),
"count".to_string(),
"quantile".to_string(),
"percentage".to_string(),
freq_column.to_string(),
];
const MAX_FREQ_COUNT: f64 = 100.0;
for (val, count) in counter.into_iter() {
let quantile = match calc_method {
PercentageCalcMethod::Normalize => (count as f64 / total_cnt as f64),
PercentageCalcMethod::Relative => (count as f64 / max_cnt as f64),
};
let percentage = format!("{:.2}%", quantile * 100_f64);
let freq = "*".repeat((MAX_FREQ_COUNT * quantile).floor() as usize);
result.push(Value::Record {
cols: result_cols.clone(),
vals: vec![
val.into_value(),
Value::Int { val: count, span },
Value::Float {
val: quantile,
span,
},
Value::String {
val: percentage,
span,
},
Value::String { val: freq, span },
],
span,
});
}
Value::List { vals: result, span }.into_pipeline_data()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(Histogram)
}
}

View File

@ -0,0 +1,4 @@
mod hashable_value;
mod histogram;
pub use histogram::Histogram;

View File

@ -14,16 +14,20 @@ impl Command for Fmt {
}
fn usage(&self) -> &str {
"format numbers"
"Format a number"
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build("fmt").category(Category::Conversions)
}
fn search_terms(&self) -> Vec<&str> {
vec!["display", "render", "format"]
}
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "format numbers",
description: "Get a record containing multiple formats for the number 42",
example: "42 | fmt",
result: Some(Value::Record {
cols: vec![

View File

@ -28,6 +28,10 @@ impl Command for SubCommand {
"Convert value to a binary primitive"
}
fn search_terms(&self) -> Vec<&str> {
vec!["convert", "binary", "bytes", "bin"]
}
fn run(
&self,
engine_state: &EngineState,

View File

@ -27,6 +27,10 @@ impl Command for SubCommand {
"Convert value to boolean"
}
fn search_terms(&self) -> Vec<&str> {
vec!["convert", "boolean", "true", "false", "1", "0"]
}
fn run(
&self,
engine_state: &EngineState,
@ -140,6 +144,10 @@ fn string_to_boolean(s: &str, span: Span) -> Result<bool, ShellError> {
"boolean".to_string(),
"string".to_string(),
span,
Some(
r#"the strings "true" and "false" can be converted into a bool"#
.to_string(),
),
)),
}
}

View File

@ -18,7 +18,7 @@ impl Command for Into {
}
fn usage(&self) -> &str {
"Apply into function."
"Commands to convert data from one type to another."
}
fn run(

View File

@ -24,13 +24,13 @@ enum Zone {
Local,
East(u8),
West(u8),
Error, // we want the nullshell to cast it instead of rust
Error, // we want Nushell to cast it instead of Rust
}
impl Zone {
fn new(i: i64) -> Self {
if i.abs() <= 12 {
// guanranteed here
// guaranteed here
if i >= 0 {
Self::East(i as u8) // won't go out of range
} else {
@ -59,29 +59,29 @@ impl Command for SubCommand {
fn signature(&self) -> Signature {
Signature::build("into datetime")
.switch(
"list",
"lists strftime cheatsheet",
Some('l'),
)
.named(
"timezone",
SyntaxShape::String,
"Specify timezone if the input is timestamp, like 'UTC/u' or 'LOCAL/l'",
"Specify timezone if the input is a Unix timestamp. Valid options: 'UTC' ('u') or 'LOCAL' ('l')",
Some('z'),
)
.named(
"offset",
SyntaxShape::Int,
"Specify timezone by offset if the input is timestamp, like '+8', '-4', prior than timezone",
"Specify timezone by offset from UTC if the input is a Unix timestamp, like '+8', '-4'",
Some('o'),
)
.named(
"format",
SyntaxShape::String,
"Specify date and time formatting",
"Specify an expected format for parsing strings to datetimes. Use --list to see all possible options",
Some('f'),
)
.switch(
"list",
"Show all possible variables for use with the --format flag",
Some('l'),
)
.rest(
"rest",
SyntaxShape::CellPath,
@ -101,35 +101,51 @@ impl Command for SubCommand {
}
fn usage(&self) -> &str {
"converts text into datetime"
"Convert text into a datetime"
}
fn search_terms(&self) -> Vec<&str> {
vec!["convert", "date", "time", "timezone", "UTC"]
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Convert to datetime",
example: "'16.11.1984 8:00 am +0000' | into datetime",
result: None,
example: "'27.02.2021 1:55 pm +0000' | into datetime",
result: Some(Value::Date {
val: Utc.timestamp(1614434100, 0).into(),
span: Span::test_data(),
}),
},
Example {
description: "Convert to datetime",
example: "'2020-08-04T16:39:18+00:00' | into datetime",
result: None,
example: "'2021-02-27T13:55:40+00:00' | into datetime",
result: Some(Value::Date {
val: Utc.timestamp(1614434140, 0).into(),
span: Span::test_data(),
}),
},
Example {
description: "Convert to datetime using a custom format",
example: "'20200904_163918+0000' | into datetime -f '%Y%m%d_%H%M%S%z'",
result: None,
example: "'20210227_135540+0000' | into datetime -f '%Y%m%d_%H%M%S%z'",
result: Some(Value::Date {
val: Utc.timestamp(1614434140, 0).into(),
span: Span::test_data(),
}),
},
Example {
description: "Convert timestamp (no larger than 8e+12) to datetime using a specified timezone",
example: "'1614434140' | into datetime -z 'UTC'",
result: None,
description: "Convert timestamp (no larger than 8e+12) to a UTC datetime",
example: "1614434140 | into datetime",
result: Some(Value::Date {
val: Utc.timestamp(1614434140, 0).into(),
span: Span::test_data(),
}),
},
Example {
description:
"Convert timestamp (no larger than 8e+12) to datetime using a specified timezone offset (between -12 and 12)",
example: "'1614434140' | into datetime -o +9",
example: "1614434140 | into datetime -o +9",
result: None,
},
]
@ -205,58 +221,78 @@ fn action(
dateformat: &Option<DatetimeFormat>,
head: Span,
) -> Value {
match input {
Value::String { val: s, span } => {
let ts = s.parse::<i64>();
// if timezone if specified, first check if the input is a timestamp.
if let Some(tz) = timezone {
const TIMESTAMP_BOUND: i64 = 8.2e+12 as i64;
// Since the timestamp method of chrono itself don't throw an error (it just panicked)
// We have to manually guard it.
if let Ok(t) = ts {
if t.abs() > TIMESTAMP_BOUND {
return Value::Error{error: ShellError::UnsupportedInput(
"Given timestamp is out of range, it should between -8e+12 and 8e+12".to_string(),
head,
)};
}
const HOUR: i32 = 3600;
let stampout = match tz.item {
Zone::Utc => Value::Date {
val: Utc.timestamp(t, 0).into(),
span: head,
},
Zone::Local => Value::Date {
val: Local.timestamp(t, 0).into(),
span: head,
},
Zone::East(i) => {
let eastoffset = FixedOffset::east((i as i32) * HOUR);
Value::Date {
val: eastoffset.timestamp(t, 0),
span: head,
}
}
Zone::West(i) => {
let westoffset = FixedOffset::west((i as i32) * HOUR);
Value::Date {
val: westoffset.timestamp(t, 0),
span: head,
}
}
Zone::Error => Value::Error {
error: ShellError::UnsupportedInput(
"Cannot convert given timezone or offset to timestamp".to_string(),
tz.span,
),
},
};
return stampout;
}
// Check to see if input looks like a Unix timestamp (i.e. can it be parsed to an int?)
let timestamp = match input {
Value::Int { val, .. } => Ok(*val),
Value::String { val, .. } => val.parse::<i64>(),
other => {
return Value::Error {
error: ShellError::UnsupportedInput(
format!("Expected string or int, got {} instead", other.get_type()),
head,
),
};
// if it's not, continue and default to the system's local timezone.
let out = match dateformat {
Some(dt) => match DateTime::parse_from_str(s, &dt.0) {
}
};
if let Ok(ts) = timestamp {
const TIMESTAMP_BOUND: i64 = 8.2e+12 as i64;
const HOUR: i32 = 3600;
if ts.abs() > TIMESTAMP_BOUND {
return Value::Error {
error: ShellError::UnsupportedInput(
"Given timestamp is out of range, it should between -8e+12 and 8e+12"
.to_string(),
head,
),
};
}
return match timezone {
// default to UTC
None => Value::Date {
val: Utc.timestamp(ts, 0).into(),
span: head,
},
Some(Spanned { item, span }) => match item {
Zone::Utc => Value::Date {
val: Utc.timestamp(ts, 0).into(),
span: head,
},
Zone::Local => Value::Date {
val: Local.timestamp(ts, 0).into(),
span: head,
},
Zone::East(i) => {
let eastoffset = FixedOffset::east((*i as i32) * HOUR);
Value::Date {
val: eastoffset.timestamp(ts, 0),
span: head,
}
}
Zone::West(i) => {
let westoffset = FixedOffset::west((*i as i32) * HOUR);
Value::Date {
val: westoffset.timestamp(ts, 0),
span: head,
}
}
Zone::Error => Value::Error {
error: ShellError::UnsupportedInput(
"Cannot convert given timezone or offset to timestamp".to_string(),
*span,
),
},
},
};
}
// If input is not a timestamp, try parsing it as a string
match input {
Value::String { val, span } => {
match dateformat {
Some(dt) => match DateTime::parse_from_str(val, &dt.0) {
Ok(d) => Value::Date { val: d, span: head },
Err(reason) => {
return Value::Error {
@ -264,6 +300,7 @@ fn action(
format!("could not parse as datetime using format '{}'", dt.0),
reason.to_string(),
head,
Some("you can use `into datetime` without a format string to enable flexible parsing".to_string())
),
}
}
@ -271,23 +308,21 @@ fn action(
// Tries to automatically parse the date
// (i.e. without a format string)
// and assumes the system's local timezone if none is specified
None => match parse_date_from_string(s, *span) {
None => match parse_date_from_string(val, *span) {
Ok(date) => Value::Date {
val: date,
span: *span,
},
Err(err) => err,
},
};
out
}
other => {
let got = format!("Expected string, got {} instead", other.get_type());
Value::Error {
error: ShellError::UnsupportedInput(got, head),
}
}
other => Value::Error {
error: ShellError::UnsupportedInput(
format!("Expected string, got {} instead", other.get_type()),
head,
),
},
}
}
@ -346,6 +381,23 @@ mod tests {
assert_eq!(actual, expected)
}
#[test]
fn takes_timestamp_offset_as_int() {
let date_int = Value::test_int(1614434140);
let timezone_option = Some(Spanned {
item: Zone::East(8),
span: Span::test_data(),
});
let actual = action(&date_int, &timezone_option, &None, Span::test_data());
let expected = Value::Date {
val: DateTime::parse_from_str("2021-02-27 21:55:40 +08:00", "%Y-%m-%d %H:%M:%S %z")
.unwrap(),
span: Span::test_data(),
};
assert_eq!(actual, expected)
}
#[test]
fn takes_timestamp() {
let date_str = Value::test_string("1614434140");
@ -362,6 +414,20 @@ mod tests {
assert_eq!(actual, expected)
}
#[test]
fn takes_timestamp_without_timezone() {
let date_str = Value::test_string("1614434140");
let timezone_option = None;
let actual = action(&date_str, &timezone_option, &None, Span::test_data());
let expected = Value::Date {
val: Utc.timestamp(1614434140, 0).into(),
span: Span::test_data(),
};
assert_eq!(actual, expected)
}
#[test]
fn takes_invalid_timestamp() {
let date_str = Value::test_string("10440970000000");

View File

@ -22,7 +22,11 @@ impl Command for SubCommand {
}
fn usage(&self) -> &str {
"converts text into decimal"
"Convert text into a decimal"
}
fn search_terms(&self) -> Vec<&str> {
vec!["convert", "number", "floating"]
}
fn run(
@ -101,7 +105,12 @@ fn action(input: &Value, head: Span) -> Value {
match other.parse::<f64>() {
Ok(x) => Value::Float { val: x, span: head },
Err(reason) => Value::Error {
error: ShellError::CantConvert("float".to_string(), reason.to_string(), *span),
error: ShellError::CantConvert(
"float".to_string(),
reason.to_string(),
*span,
None,
),
},
}
}

View File

@ -28,6 +28,10 @@ impl Command for SubCommand {
"Convert value to duration"
}
fn search_terms(&self) -> Vec<&str> {
vec!["convert", "time", "period"]
}
fn run(
&self,
engine_state: &EngineState,
@ -155,6 +159,7 @@ fn string_to_duration(s: &str, span: Span) -> Result<i64, ShellError> {
"duration".to_string(),
"string".to_string(),
span,
Some("supported units are ns, us, ms, sec, min, hr, day, and wk".to_string()),
))
}

View File

@ -27,6 +27,10 @@ impl Command for SubCommand {
"Convert value to filesize"
}
fn search_terms(&self) -> Vec<&str> {
vec!["convert", "number", "size", "bytes"]
}
fn run(
&self,
engine_state: &EngineState,
@ -129,6 +133,10 @@ pub fn action(input: &Value, span: Span) -> Value {
},
Err(error) => Value::Error { error },
},
Value::Nothing { .. } => Value::Filesize {
val: 0,
span: value_span,
},
_ => Value::Error {
error: ShellError::UnsupportedInput(
"'into filesize' for unsupported type".into(),
@ -148,7 +156,12 @@ pub fn action(input: &Value, span: Span) -> Value {
fn int_from_string(a_string: &str, span: Span) -> Result<i64, ShellError> {
match a_string.trim().parse::<bytesize::ByteSize>() {
Ok(n) => Ok(n.0 as i64),
Err(_) => Err(ShellError::CantConvert("int".into(), "string".into(), span)),
Err(_) => Err(ShellError::CantConvert(
"int".into(),
"string".into(),
span,
None,
)),
}
}

View File

@ -33,6 +33,10 @@ impl Command for SubCommand {
"Convert value to integer"
}
fn search_terms(&self) -> Vec<&str> {
vec!["convert", "number", "natural"]
}
fn run(
&self,
engine_state: &EngineState,
@ -81,6 +85,11 @@ impl Command for SubCommand {
span: Span::test_data(),
}),
},
Example {
description: "Convert date to integer (Unix timestamp)",
example: "2022-02-02 | into int",
result: Some(Value::test_int(1643760000)),
},
Example {
description: "Convert to integer from binary",
example: "'1101' | into int -r 2",
@ -177,6 +186,10 @@ pub fn action(input: &Value, span: Span, radix: u32) -> Value {
Value::Int { val: 0, span }
}
}
Value::Date { val, .. } => Value::Int {
val: val.timestamp(),
span,
},
_ => Value::Error {
error: ShellError::UnsupportedInput("'into int' for unsupported type".into(), span),
},
@ -206,8 +219,8 @@ fn convert_int(input: &Value, head: Span, radix: u32) -> Value {
};
match i64::from_str_radix(&i, radix) {
Ok(n) => Value::Int { val: n, span: head },
Err(reason) => Value::Error {
error: ShellError::CantConvert("".to_string(), reason.to_string(), head),
Err(_reason) => Value::Error {
error: ShellError::CantConvert("int".to_string(), "string".to_string(), head, None),
},
}
}
@ -218,27 +231,31 @@ fn int_from_string(a_string: &str, span: Span) -> Result<i64, ShellError> {
b if b.starts_with("0b") => {
let num = match i64::from_str_radix(b.trim_start_matches("0b"), 2) {
Ok(n) => n,
Err(reason) => {
Err(_reason) => {
return Err(ShellError::CantConvert(
"could not parse as integer".to_string(),
reason.to_string(),
"int".to_string(),
"string".to_string(),
span,
Some(r#"digits following "0b" can only be 0 or 1"#.to_string()),
))
}
};
Ok(num)
}
h if h.starts_with("0x") => {
let num = match i64::from_str_radix(h.trim_start_matches("0x"), 16) {
Ok(n) => n,
Err(reason) => {
return Err(ShellError::CantConvert(
"could not parse as int".to_string(),
reason.to_string(),
let num =
match i64::from_str_radix(h.trim_start_matches("0x"), 16) {
Ok(n) => n,
Err(_reason) => return Err(ShellError::CantConvert(
"int".to_string(),
"string".to_string(),
span,
))
}
};
Some(
r#"hexadecimal digits following "0x" should be in 0-9, a-f, or A-F"#
.to_string(),
),
)),
};
Ok(num)
}
_ => match a_string.parse::<i64>() {
@ -246,9 +263,10 @@ fn int_from_string(a_string: &str, span: Span) -> Result<i64, ShellError> {
Err(_) => match a_string.parse::<f64>() {
Ok(f) => Ok(f as i64),
_ => Err(ShellError::CantConvert(
"into int".to_string(),
"int".to_string(),
"string".to_string(),
span,
None,
)),
},
},

View File

@ -37,6 +37,10 @@ impl Command for SubCommand {
"Convert value to string"
}
fn search_terms(&self) -> Vec<&str> {
vec!["convert", "str", "text"]
}
fn run(
&self,
engine_state: &EngineState,
@ -138,7 +142,7 @@ fn string_helper(
let head = call.head;
let decimals_value: Option<i64> = call.get_flag(engine_state, stack, "decimals")?;
let column_paths: Vec<CellPath> = call.rest(engine_state, stack, 0)?;
let config = stack.get_config().unwrap_or_default();
let config = engine_state.get_config().clone();
if let Some(decimal_val) = decimals_value {
if decimals && decimal_val.is_negative() {
@ -244,7 +248,7 @@ pub fn action(
span,
},
Value::Nothing { .. } => Value::String {
val: "nothing".to_string(),
val: "".to_string(),
span,
},
Value::Record {
@ -257,8 +261,21 @@ pub fn action(
span,
),
},
Value::Binary { .. } => Value::Error {
error: ShellError::CantConvert(
"string".into(),
"binary".into(),
span,
Some("try using the `decode` command".into()),
),
},
x => Value::Error {
error: ShellError::CantConvert(String::from("string"), x.get_type().to_string(), span),
error: ShellError::CantConvert(
String::from("string"),
x.get_type().to_string(),
span,
None,
),
},
}
}

View File

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

View File

@ -25,12 +25,12 @@ impl Command for Debug {
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let config = stack.get_config().unwrap_or_default();
let config = engine_state.get_config().clone();
let raw = call.has_flag("raw");
input.map(

View File

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

View File

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

View File

@ -35,8 +35,13 @@ impl Command for Describe {
))
} else {
let value = input.into_value(call.head);
let description = match value {
Value::CustomValue { val, .. } => val.value_string(),
_ => value.get_type().to_string(),
};
Ok(Value::String {
val: value.get_type().to_string(),
val: description,
span: head,
}
.into_pipeline_data())

View File

@ -17,7 +17,6 @@ impl Command for Do {
fn signature(&self) -> nu_protocol::Signature {
Signature::build("do")
.desc(self.usage())
.required("block", SyntaxShape::Any, "the block to run")
.switch(
"ignore-errors",

View File

@ -36,26 +36,30 @@ impl Command for ErrorMake {
let arg: Option<Value> = call.opt(engine_state, stack, 0)?;
if let Some(arg) = arg {
Ok(make_error(&arg)
Ok(make_error(&arg, span)
.map(|err| Value::Error { error: err })
.unwrap_or_else(|| Value::Error {
error: ShellError::SpannedLabeledError(
error: ShellError::GenericError(
"Creating error value not supported.".into(),
"unsupported error format".into(),
span,
Some(span),
None,
Vec::new(),
),
})
.into_pipeline_data())
} else {
input.map(
move |value| {
make_error(&value)
make_error(&value, span)
.map(|err| Value::Error { error: err })
.unwrap_or_else(|| Value::Error {
error: ShellError::SpannedLabeledError(
error: ShellError::GenericError(
"Creating error value not supported.".into(),
"unsupported error format".into(),
span,
Some(span),
None,
Vec::new(),
),
})
},
@ -85,7 +89,7 @@ impl Command for ErrorMake {
}
}
fn make_error(value: &Value) -> Option<ShellError> {
fn make_error(value: &Value, throw_span: Span) -> Option<ShellError> {
if let Value::Record { .. } = &value {
let msg = value.get_data_by_key("msg");
let label = value.get_data_by_key("label");
@ -103,20 +107,39 @@ fn make_error(value: &Value) -> Option<ShellError> {
Some(Value::String {
val: label_text, ..
}),
) => Some(ShellError::SpannedLabeledError(
) => Some(ShellError::GenericError(
message,
label_text,
Span {
Some(Span {
start: start as usize,
end: end as usize,
},
}),
None,
Vec::new(),
)),
(
None,
None,
Some(Value::String {
val: label_text, ..
}),
) => Some(ShellError::GenericError(
message,
label_text,
Some(throw_span),
None,
Vec::new(),
)),
_ => None,
}
}
(Some(Value::String { val: message, .. }), None) => {
Some(ShellError::UnlabeledError(message))
}
(Some(Value::String { val: message, .. }), None) => Some(ShellError::GenericError(
message,
"originates from here".to_string(),
Some(throw_span),
None,
Vec::new(),
)),
_ => None,
}
} else {

View File

@ -21,6 +21,15 @@ impl Command for ExportCommand {
"Export custom commands or environment variables from a module."
}
fn extra_usage(&self) -> &str {
r#"This command is a parser keyword. For details, check
https://www.nushell.sh/book/thinking_in_nushell.html#parsing-and-evaluation-are-different-stages"#
}
fn is_parser_keyword(&self) -> bool {
true
}
fn run(
&self,
engine_state: &EngineState,

View File

@ -15,7 +15,7 @@ impl Command for ExportAlias {
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build("export def")
Signature::build("export alias")
.required("name", SyntaxShape::String, "name of the alias")
.required(
"initial_value",
@ -25,6 +25,15 @@ impl Command for ExportAlias {
.category(Category::Core)
}
fn extra_usage(&self) -> &str {
r#"This command is a parser keyword. For details, check
https://www.nushell.sh/book/thinking_in_nushell.html#parsing-and-evaluation-are-different-stages"#
}
fn is_parser_keyword(&self) -> bool {
true
}
fn run(
&self,
_engine_state: &EngineState,

View File

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

View File

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

View File

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

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