Compare commits

...

125 Commits

Author SHA1 Message Date
88f06c81b2 Update Cargo.toml 2020-04-22 06:34:32 +12:00
e6b315f05b Bump ichwh to version 0.3.4 (#1627)
Fixes #1626 and [this ichwh issue](https://gitlab.com/avandesa/ichwh-rs/-/issues/3)
2020-04-22 05:37:14 +12:00
01ef6b0732 Add config to disable table index column (#1623) 2020-04-21 18:09:22 +12:00
c7e11a5a28 bump to 0.13.0 (#1625) 2020-04-21 17:01:03 +12:00
ce0231049e Fix the panic running a bad alias (#1624) 2020-04-21 16:11:34 +12:00
0f7b270740 Add exit code verification (#1622) 2020-04-21 15:14:18 +12:00
72cf57dd99 Add booleans and fix semicolon shortcircuit (#1620) 2020-04-21 12:30:01 +12:00
e4fdb36511 External vars (#1615)
* fix empty table and missing spans

* wip

* WIP

* WIP

* working version with vars

* tidying

* WIP

* Fix external quoting issue
2020-04-21 09:45:11 +12:00
2ffb14c7d0 fix empty table and missing spans (#1614) 2020-04-20 19:44:19 +12:00
eec94e4016 Semicolon (#1613)
* WIP on blocks

* Getting further

* add some tests
2020-04-20 18:41:51 +12:00
6412bfd58d Move alias arguments to optional arguments (#1612)
This will allow people to use more variables to capture more, if necessary, without having to implement required/optional/rest
2020-04-20 16:04:40 +12:00
522a828687 Move external closer to internal (#1611)
* Refactor InputStream and affected commands.

First, making `values` private and leaning on the `Stream` implementation makes
consumes of `InputStream` less likely to have to change in the future, if we
change what an `InputStream` is internally.

Second, we're dropping `Option<InputStream>` as the input to pipelines,
internals, and externals. Instead, `InputStream.is_empty` can be used to check
for "emptiness". Empty streams are typically only ever used as the first input
to a pipeline.

* Add run_external internal command.

We want to push external commands closer to internal commands, eventually
eliminating the concept of "external" completely. This means we can consolidate
a couple of things:

- Variable evaluation (for example, `$it`, `$nu`, alias vars)
- Behaviour of whole stream vs per-item external execution

It should also make it easier for us to start introducing argument signatures
for external commands,

* Update run_external.rs

* Update run_external.rs

* Update run_external.rs

* Update run_external.rs

Co-authored-by: Jonathan Turner <jonathandturner@users.noreply.github.com>
2020-04-20 15:30:44 +12:00
6b8c6dec0e Bump ichwh minimum version to 0.3.3 (#1607)
The new version includes a fix for [this issue]

[this issue]: https://gitlab.com/avandesa/ichwh-rs/-/issues/2
2020-04-19 13:38:14 +12:00
2b0212880e Simplify cp command and allow multiple recursive copying (#1580)
* Better message error

* Use custom canonicalize in FileStructure build

* Better glob error in ls

* Use custom canonicalize, remove some duplicate code in cd.

* Enable recursive copying with patterns.

* Change test to fit new error message

* Test recursive with glob pattern

* Show that not matches were found in cp

* Fix typo in message error

* Change old canonicalize usage, follow newest changes
2020-04-19 11:05:24 +12:00
a16a91ede8 Fix precedence parsing of parens. Limit use (#1606) 2020-04-19 06:39:06 +12:00
c2a9bc3bf4 Add better docs to parser (#1604) 2020-04-19 05:30:40 +12:00
e5a79d09df Fix the versions up a bit to prevent breakage (#1602)
* Fix the versions up a bit to prevent breakage

* fix up the quickcheck test to not fail on parse error
2020-04-18 15:31:57 +12:00
7974e09eeb Math operators (#1601)
* Add some math operations

* WIP for adding compound expressions

* precedence parsing

* paren expressions

* better lhs handling

* add compound comparisons and shorthand lefthand parsing

* Add or comparison and shorthand paths
2020-04-18 13:50:58 +12:00
52d2d2b888 A random set of fixes (#1600) 2020-04-17 18:19:49 +12:00
ee778d2b03 WIP fix for the error bubbling (#1597) 2020-04-16 16:25:24 +12:00
928188b18e Redesign custom canonicalize, enable multiple dots expansion earlier. (#1588)
* Expand n dots early where tilde was also expanded.

* Remove normalize, not needed.
New function absolutize, doesn't follow links neither checks existence.
Renamed canonicalize_existing to canonicalize, works as expected.

* Remove normalize usages, change canonicalize.

* Treat strings as paths
2020-04-16 11:29:22 +12:00
59d516064c Add alias support to scripts and -c (#1593) 2020-04-16 05:50:35 +12:00
bd5836e25d Aliases (#1589)
* WIP getting scopes right

* finish adding initial support

* Finish with alias and add startup commands
2020-04-15 17:43:23 +12:00
e3da037b80 Canonical expr block (#1584)
* Add the canonical form for an expression block

* Remove commented out code
2020-04-14 06:59:33 +12:00
08a09e2273 Pipeline blocks (#1579)
* Making Commands match what UntaggedValue needs

* WIP

* WIP

* WIP

* Moved to expressions for conditions

* Add 'each' command to use command blocks

* More cleanup

* Add test for 'each'

* Instead use an expression block
2020-04-13 19:59:57 +12:00
85d6b24be3 Add more cmd builtins (#1583) 2020-04-13 13:46:59 +12:00
ed583bd79b Bump to latest ichwh (#1582) 2020-04-13 08:01:23 +12:00
e0fc09ac52 move rustyline to 6.1.1 to fix windows crash (#1581) 2020-04-13 07:01:44 +12:00
38b2846024 Split canonicalize function in two for missing and existing behavior (#1576)
* Split allow missing logic in two functions

* Replace use of old canonicalize
2020-04-12 20:33:38 +12:00
57c62de66f Remove erronous GPL license header (#1578) 2020-04-12 20:16:50 +12:00
dd4935fb23 Add quickcheck (#1574)
* Move uptime to being a duration value

* Adds our first quickcheck test
2020-04-12 07:05:59 +12:00
18dd009ca8 Unified path expansion under new module and better canonicalize (#1571)
* New 'path' module under nu-cli.
Added normalize and canonicalize method.
Added some unit tests.

* Replace old usages of normalize and canonicalize.

* Fix reading symlinks and existence logic.

* Better explained
2020-04-12 07:05:29 +12:00
c0dda36217 Update CONTRIBUTING.md 2020-04-12 06:54:16 +12:00
75b72f844e Create CONTRIBUTING.md (#998)
* Create CONTRIBUTING.md

* mention gitpod

* Update CONTRIBUTING.md

* mention community supports

* fix capitalization issues
2020-04-12 06:52:53 +12:00
fbddc12c02 Move uptime to being a duration value (#1573) 2020-04-11 19:40:56 +12:00
8e7e8c17e1 Make trash support optional (#1572) 2020-04-11 18:53:53 +12:00
8ac9d781fd Remove source text where not needed (#1567) 2020-04-10 19:56:48 +12:00
c86cf31aac some minor improvements and removing dead code (#1563) 2020-04-10 07:48:10 +12:00
2c513d1883 More dep bumps (#1562) 2020-04-09 10:28:20 +12:00
04702530a3 Bump a lot of deps (#1560) 2020-04-07 19:51:17 +12:00
c9f424977e actually bump version (#1559) 2020-04-07 07:18:47 +12:00
183c8407de fix nu variable. tweak shells (#1558) 2020-04-07 05:30:54 +12:00
d0618b0b32 Enable the use of multiple dots in FS Shell commands (#1547)
Every dot after `..` means another parent directory.
2020-04-06 07:28:56 -04:00
c4daa2e40f Add experimental new parser (#1554)
Move to an experimental new parser
2020-04-06 19:16:14 +12:00
0a198b9bd0 Have FilesystemShell#rm correctly delete symlinks (#1550) 2020-04-05 17:17:52 -04:00
6a604491f5 ci(docker-publish): force remove non-executable (#1540) 2020-04-02 04:20:18 +13:00
791f7dd9c3 Bump to 0.12.0 (#1538) 2020-04-01 06:25:21 +13:00
a4c1b092ba Add configurations for table headers (#1537)
* Add configurations for table headers

* lint

Co-authored-by: Amanita-Muscaria <nope>
2020-03-31 12:19:48 +13:00
6e71c1008d Change get to remove blanks (#1534)
Remove blank values when getting a column of values
2020-03-30 15:36:21 +13:00
906d0b920f A few improvements to du implementation: (#1533)
1. Fixed a bug where `--all` wasn't showing files at the root directories.
2. More use of `Result`'s `map` and `map_err` methods.
3. Making tables be homogeneous so one can, for example, `get directories`.
2020-03-29 21:16:09 -04:00
efbf4f48c6 Fix poor message for executable that user doesn't have permissi… (#1535)
Previously, if the user didn't have the appropriate permissions to execute the
binary/script, they would see "command not found", which is confusing.

This commit eliminates the `which` crate in favour of `ichwh`, which deals
better with permissions by not dealing with them at all! This is closer to the
behaviour of `which` in many shells. Permission checks are then left up to the
caller to deal with.
2020-03-29 21:15:55 -04:00
2ddab3e8ce Some small improvements to du readability.
Mostly, making more use of `map` and `map_err` in `Result`. One benefit
is that at least one location had duplicated logic for how to map the
error, which is no longer the case after this commit.
2020-03-29 17:03:01 -04:00
35dc7438a5 Make use of interruptible stream in various places 2020-03-29 17:03:01 -04:00
2a54ee0c54 Introduce InterruptibleStream type.
An interruptible stream can query an `AtomicBool. If that bool is true,
the stream will no longer produce any values.

Also introducing the `Interruptible` trait, which extends any `Stream`
with the `interruptible` function, to simplify the construction and
allow chaining.
2020-03-29 17:03:01 -04:00
cad2741e9e Split input and output streams into separate modules 2020-03-29 17:03:01 -04:00
ae5f3c8210 WIP: 1486/first row as headers (#1530)
* headers plugin

* Remove plugin

* Add non-functioning headers command

* Add ability to extract headers from first row

* Refactor header extraction

* Rebuild indexmap with proper headers

* Rebuild result properly

* Compiling, probably wrapped too much?

* Refactoring

* Deal with case of empty header cell

* Deal with case of empty header cell

* Fix formatting

* Fix linting, attempt 2.

* Move whole_stream_command(Headers) to more appropriate section

* ... more linting

* Return Err(ShellError...) instead of panic, yield each row instead of entire table

* Insert Column[index] if no header info is found.

* Update error description

* Add initial test

* Add tests for headers command

* Lint test cases in headers

* Change ShellError for headers, Add sample_headers file to utils.rs

* Add empty sheet to test file

* Revert "Add empty sheet to test file"

This reverts commit a4bf38a31d.

* Show error message when given empty table
2020-03-29 15:05:57 +13:00
a5e97ca549 Respect CARGO_TARGET_DIR when set (#1528)
This makes the `binaries` function respect the `CARGO_TARGET_DIR` environment variable when set. If it's not present it falls back to the regular target directory used by Cargo.
2020-03-27 17:13:59 -04:00
06f87cfbe8 Add support for removing multiple files at once (#1526) 2020-03-25 16:19:01 -04:00
d4e78c6f47 Improve the rotated row wrap (#1524) 2020-03-25 06:27:16 +13:00
3653400ebc testing fix to matrix to define all variables (#1522)
there is currently a bug with invalid syntax for some of the
docker build steps, and I think this is because there are build
variables in the matrix that are not defined. This PR will
attempt to resolve this issue by defining all missing variables
for each row in the matrix.

Signed-off-by: vsoch <vsochat@stanford.edu>
2020-03-24 16:20:39 +13:00
81a48d6d0e Fix '/' and '..' not being valid mv targets (#1519)
* Fix '/' and '..' not being valid mv targets

If `/` or `../` is specified as the destination for `mv`, it will fail with an error message saying it's not a valid destination. This fixes it to account for the fact that `Path::file_name` return `None` when the file name evaluates to `/` or `..`. It will only take the slow(er) path if `Path::file_name` returns `None` in its initial check.

Fixes #1291

* Add test
2020-03-24 14:00:48 +13:00
f030ab3f12 Add experimental auto-rotate (#1516) 2020-03-23 09:55:30 +13:00
0dc0c6a10a Add quickstart option to Docker section in README (#1515) 2020-03-23 09:18:50 +13:00
53c8185af3 Fixes the crash for ps --full in Windows (#1514)
* Fixes the crash for `ps --full` in Windows

* Update ps.rs
2020-03-23 08:28:02 +13:00
36b5d063c1 Simplify and improve listing for which. (#1510)
* Simplified implementation
* Show executables, even if the current user doesn't have permissions to
  execute them.
2020-03-22 09:11:39 -04:00
a7ec00a037 Add documentation for from-ics and from-vcf (#1509) 2020-03-21 14:50:13 +13:00
918822ae0d Fix numeric comparison with nothing (#1508) 2020-03-21 11:02:49 +13:00
ab5e24a0e7 WIP: Add vcard/ical support (#1504)
* Initial from-ical implementation

* Initial from-vcard implementation

* Rename from-ics and from-vcf for autoconvert

* Remove redundant clones

* Add from-vcf and from-ics tests

Co-authored-by: Jonathan Turner <jonathandturner@users.noreply.github.com>
2020-03-21 08:35:09 +13:00
b5ea522f0e Add a --full mode to ps (#1507)
* Add a --full mode to ps

* Use a slightly older heim
2020-03-20 20:53:49 +13:00
afa963fd50 Add is_dir check to auto-cd (#1506)
* Add markdown output

* Add is_dir() check
2020-03-20 16:57:36 +13:00
1e343ff00c Add markdown output (#1503) 2020-03-20 08:18:24 +13:00
21a543a901 Make sum plugin as internal command. (#1501) 2020-03-18 18:46:00 -05:00
390deb4ff7 Windows needs to remember auto-cd paths when changing drives (#1500)
* Windows needs to remember auto-cd paths when changing drives

* Windows needs to remember auto-cd paths when changing drives
2020-03-18 15:10:45 +13:00
1c4cb30d64 Add documentation for skip and skip-while (#1499) 2020-03-18 14:22:35 +13:00
1ec2ec72b5 Add automatic change directory (#1496)
* Allow automatic cd in cli mode

* Set correct priority for auto-cd and add test
2020-03-18 07:13:38 +13:00
0d244a9701 Open fails silently, fix #1493 (#1495)
* Fix #1493

The error was wrongfully discarded

* Run cargo fmt
2020-03-17 17:40:04 +13:00
b36d21e76f Infer types from regular delimited plain text unstructured files. (#1494)
* Infer types from regular delimited plain text unstructured files.

* Nothing resolves to an empty string.
2020-03-16 15:50:45 -05:00
d8c4565413 Csv errors (#1490)
* Add error message for csv parsing failures

* Add csv error prettyfier

* Improve readability of the error

Line 2: error is easier to understand than:
Line 2, error

* Remove unnecessary use of the format! macro

Replacing it with .to_string() fixes a clippy warning

* Improve consistency with JSON parsing errors
2020-03-16 12:32:02 -05:00
22ba4c2a2f Add svg support to to-html (#1492) 2020-03-16 20:19:18 +13:00
8d19b21b9f Custom canonicalize method on Filesystem Shell. (#1485)
* Custom canonicalize method for FilesystemShell.

* Use custom canonicalize method.
Fixed missing import.

* Move function body to already impl body.

* Create test that aims to resolve.
2020-03-16 19:28:18 +13:00
45a3afdc79 Update Cargo.toml 2020-03-16 06:12:28 +13:00
2d078849cb Add simple to-html output and bump version (#1487) 2020-03-15 16:04:44 +13:00
b6363f3ce1 Added new flag '--all/-a' for Ls, also refactor some code (#1483)
* Utility function to detect hidden folders.
Implemented for Unix and Windows.

* Rename function argument.

* Revert "Rename function argument."

This reverts commit e7ab70f0f0.

* Add flag '--all/-a' to Ls

* Rename function argument.

* Check if flag '--all/-a' is present and path is hidden.
Replace match with map_err for glob result.
Remove redundancy in stream body.
Included comments on new stream body.
Replace async_stream::stream with async_stream::try_stream.
Minor tweaks to is_empty_dir.
Fix and refactor is_hidden_dir.

* Fix "implicit" bool coerse

* Fixed clippy errors
2020-03-14 06:27:04 +13:00
5ca9e12b7f Fix whitespace and typos (#1481)
* Remove EOL whitespace in files other than docs

* Break paragraphs into lines

See http://rhodesmill.org/brandon/2012/one-sentence-per-line/ for the rationale

* Fix various typos

* Remove EOL whitespace in docs/commands/*.md
2020-03-14 06:23:41 +13:00
5b0b2f1ddd Fixes #1204 : sys | get host.users displays the same user (#1480)
account twice while only one exists (macOS)

- renamed host.users to host.sessions
2020-03-12 14:01:55 +13:00
3afb53b8ce fix typo in calc command documentation (#1477)
minimumum -> minimum
2020-03-11 11:20:22 -04:00
b40d16310c More relaxed file modes for now. (#1476) 2020-03-11 13:19:15 +13:00
d3718d00db Merge shuffle nu plugin as core command. (#1475) 2020-03-10 17:00:08 -05:00
f716f61fc1 Update Cargo.lock 2020-03-11 08:53:26 +13:00
b2ce669791 Update Cargo.toml 2020-03-11 08:51:53 +13:00
cd155f63e1 Update Cargo.toml 2020-03-11 08:51:17 +13:00
9eaa6877f3 Update Cargo.toml 2020-03-11 08:50:51 +13:00
a6b6afbca9 Update Cargo.toml 2020-03-11 08:08:13 +13:00
62666bebc9 Bump to 0.11.0 (#1474) 2020-03-11 06:34:19 +13:00
d1fcce0cd3 Fixes #1427: Prints help message with -h switch (#1454)
For some commands like `which` -h flag would trigger an error asking for
missing required parameters instead of printing the help message as it
does with --help. This commit adds a check in the command parser to
avoid that.
2020-03-11 05:59:50 +13:00
a2443fbe02 Remove unused parsing logic. (#1473)
* Remove unused parsing logic.

* Run tokens iteration tests baseline.

* Pass lint.

* lifetimes can be elided without being explicit.
2020-03-10 04:31:42 -05:00
db16b56fe1 Columnpath support when passing fields for formatting. (#1472) 2020-03-10 01:55:03 -05:00
54bf671a50 Fix deleting / showing ls named pipes and other fs objects no… (#1461)
* Fix deleting named pipes
* Use std::os::unix::fs::FileTypeExt to show correct type for unix-specific fs objects; Fix formatting

Co-authored-by: Linards Kalvāns <linards.kalvans@twino.eu>
2020-03-09 09:02:53 -04:00
755d0e648b Eliminate some compiler warnings (#1468)
- Unnecessary parentheses
- Deprecated `description()` method
2020-03-09 08:19:07 +13:00
e440d8c939 Bump some deps (#1467) 2020-03-09 08:18:44 +13:00
01dd358a18 Don't emit a newline in autoview. (#1466)
The extra newline character makes it hard to use nu as part of an
external processing pipeline, since the extra character could taint the
results. For example:

```
$ nu -c 'echo test | xxd'
00000000: 7465 7374                                test
```

versus

```
nu -c 'echo test' | xxd
00000000: 7465 7374 0a                             test.
```
2020-03-09 08:18:24 +13:00
50fb97f6b7 Merge env into $nu and simplify table/get (#1463) 2020-03-08 18:33:30 +13:00
ebf139f5e5 Auto-detect string / binary in save command (#1459)
* Auto-detect string / binary in save command

* Linter
2020-03-08 07:33:29 +13:00
8925ca5da3 Move to bytes/string hybrid codec (#1457)
* WIP: move to bytes codec

* Progress on adding collect helpers

* Progress on adding collect helpers

* Add in line splitting back to lines

* Lines outputting line primitives

* Close to ready?

* Finish fixing lines

* clippy fixes

* fmt fixes

* removed unused code

* Cleanup a few bits

* Cleanup a few bits

* Cleanup a few more bits

* Fix failing test with corrected test case
2020-03-07 05:06:39 +13:00
287652573b Fix and refactor cd for Filesystem Shell. (#1452)
* Fix and refactor cd for Filesystem Shell.
Reorder check conditions, don't check existence twice.
If building for unix check exec bit on folder.

* Import PermissionsExt only on unix target.

* It seems that this is the correct way?
2020-03-06 20:13:47 +13:00
db24ad8f36 Add --num parameter to limit the number of output lines (#1455)
Add `--num` parameter to limit the numer of returned elements
2020-03-05 05:26:46 -05:00
f88674f353 Nu internals are logged under nu filter. (#1451) 2020-03-05 05:18:53 -05:00
59cb0ba381 Color appropiately commands. (#1453) 2020-03-04 23:22:42 -05:00
c4cfab5e16 Make feature options available downstream to nu-cli subcrate. (#1450) 2020-03-04 15:31:12 -05:00
b2c5af457e Move most of the root package into a subcrate. (#1445)
This improves incremental build time when working on what was previously
the root package. For example, previously all plugins would be rebuilt
with a change to `src/commands/classified/external.rs`, but now only
`nu-cli` will have to be rebuilt (and anything that depends on it).
2020-03-04 13:58:20 -05:00
c731a5b628 Columns can be renamed. (#1447) 2020-03-03 16:01:24 -05:00
f97f9d4af3 Update deps locklfile (#1446)
Update deps lockfile
2020-03-03 15:34:22 -05:00
ed7d3fed66 Add shuffle plugin (#1443)
* Add shuffle plugin

see #1437

* Change plugin to integrate into nu structure and build system
2020-03-03 08:44:12 +13:00
7304d06c0b Use threads to avoid blocking reads/writes in externals. (#1440)
In particular, one thing that we can't (properly) do before this commit
is consuming an infinite input stream. For example:

```
yes | grep y | head -n10
```

will give 10 "y"s in most shells, but blocks indefinitely in nu. This PR
resolves that by doing blocking I/O in threads, and reducing the `await`
calls we currently have in our pipeline code.
2020-03-02 06:19:09 +13:00
ca615d9389 Bump to 0.10.1 (#1442) 2020-03-01 20:59:13 +13:00
6d096206b6 Add support for compound shorthand flags (#1414)
* Break multicharacter shorthand flags into single character flags

* Remove shorthand flag test
2020-03-01 13:20:42 +13:00
2a8cb24309 Add support for downloading unsupported mime types (#1441) 2020-03-01 13:14:36 +13:00
8d38743e27 Add docs for debug (#1438)
* Add docs for `debug`

* Put debug docs in right folder
Also fixed minor spacing problem
2020-03-01 04:09:28 +13:00
eabfa2de54 Let ls ignore permission errors (#1435)
* Create a function to create an empty directory entry

* Print an empty directory entry if permission is denied

* Fix rustfmt whitespace issues.

* Made metadata optional for `dir_entry_dict`.

Removed `empty_dir_entry_dict` as its not needed anymore.
2020-02-29 14:33:52 +13:00
a86a0abb90 Plugin documentation (#1431)
* Add very basic documentation. Need to play with rest of the api to figure out what it does

* Add some documentation to more of the Plugin API methods

* fmt
2020-02-24 15:28:46 +13:00
adcda450d5 Update LICENSE 2020-02-21 10:49:46 +13:00
147b9d4436 Add Better-TOML (#1417) 2020-02-19 16:59:42 -05:00
c43a58d9d6 Fix incorrect display for zero-size files (#1422) 2020-02-19 09:57:58 -05:00
e38442782e Command documentation for du (#1416) 2020-02-19 09:55:22 +13:00
b98f893217 add a touch command (#1399) 2020-02-19 09:54:32 +13:00
421 changed files with 11576 additions and 17253 deletions

View File

@ -59,4 +59,3 @@ steps:
- bash: cargo fmt --all -- --check - bash: cargo fmt --all -- --check
condition: eq(variables['style'], 'fmt') condition: eq(variables['style'], 'fmt')
displayName: Lint displayName: Lint

View File

@ -1,3 +1,3 @@
[build] [build]
#rustflags = ["--cfg", "coloring_in_tokens"] #rustflags = ["--cfg", "data_processing_primitives"]

1
.dockerignore Normal file
View File

@ -0,0 +1 @@
target

View File

@ -24,7 +24,7 @@ jobs:
run: | run: |
cross build --target ${{ matrix.arch }} --release cross build --target ${{ matrix.arch }} --release
# leave only the executable file # leave only the executable file
rm -rd target/${{ matrix.arch }}/release/{*/*,*.d,*.rlib,.fingerprint} rm -frd target/${{ matrix.arch }}/release/{*/*,*.d,*.rlib,.fingerprint}
find . -empty -delete find . -empty -delete
- uses: actions/upload-artifact@master - uses: actions/upload-artifact@master
with: with:
@ -52,15 +52,15 @@ jobs:
- glibc - glibc
- musl - musl
include: include:
- { tag: alpine, base-image: alpine, arch: x86_64-unknown-linux-musl, plugin: true } - { tag: alpine, base-image: alpine, arch: x86_64-unknown-linux-musl, plugin: true, use-patch: false}
- { tag: slim, base-image: 'debian:stable-slim', arch: x86_64-unknown-linux-gnu, plugin: true } - { tag: slim, base-image: 'debian:stable-slim', arch: x86_64-unknown-linux-gnu, plugin: true, use-patch: false}
- { tag: debian, base-image: debian, arch: x86_64-unknown-linux-gnu, plugin: true } - { tag: debian, base-image: debian, arch: x86_64-unknown-linux-gnu, plugin: true, use-patch: false}
- { tag: glibc-busybox, base-image: 'busybox:glibc', arch: x86_64-unknown-linux-gnu, use-patch: true } - { tag: glibc-busybox, base-image: 'busybox:glibc', arch: x86_64-unknown-linux-gnu, plugin: false, use-patch: true }
- { tag: musl-busybox, base-image: 'busybox:musl', arch: x86_64-unknown-linux-musl, } - { tag: musl-busybox, base-image: 'busybox:musl', arch: x86_64-unknown-linux-musl, plugin: false, use-patch: false}
- { tag: musl-distroless, base-image: 'gcr.io/distroless/static', arch: x86_64-unknown-linux-musl, } - { tag: musl-distroless, base-image: 'gcr.io/distroless/static', arch: x86_64-unknown-linux-musl, plugin: false, use-patch: false}
- { tag: glibc-distroless, base-image: 'gcr.io/distroless/cc', arch: x86_64-unknown-linux-gnu, use-patch: true } - { tag: glibc-distroless, base-image: 'gcr.io/distroless/cc', arch: x86_64-unknown-linux-gnu, plugin: false, use-patch: true }
- { tag: glibc, base-image: scratch, arch: x86_64-unknown-linux-gnu, } - { tag: glibc, base-image: scratch, arch: x86_64-unknown-linux-gnu, plugin: false, use-patch: false}
- { tag: musl, base-image: scratch, arch: x86_64-unknown-linux-musl, } - { tag: musl, base-image: scratch, arch: x86_64-unknown-linux-musl, plugin: false, use-patch: false}
steps: steps:
- uses: actions/checkout@v1 - uses: actions/checkout@v1
- uses: actions/download-artifact@master - uses: actions/download-artifact@master

1
.gitignore vendored
View File

@ -4,6 +4,7 @@
history.txt history.txt
tests/fixtures/nuplayground tests/fixtures/nuplayground
crates/*/target crates/*/target
# Debian/Ubuntu # Debian/Ubuntu
debian/.debhelper/ debian/.debhelper/
debian/debhelper-build-stamp debian/debhelper-build-stamp

View File

@ -26,3 +26,4 @@ vscode:
- serayuzgur.crates@0.4.7:HMkoguLcXp9M3ud7ac3eIw== - serayuzgur.crates@0.4.7:HMkoguLcXp9M3ud7ac3eIw==
- belfz.search-crates-io@1.2.1:kSLnyrOhXtYPjQpKnMr4eQ== - belfz.search-crates-io@1.2.1:kSLnyrOhXtYPjQpKnMr4eQ==
- vadimcn.vscode-lldb@1.4.5:lwHCNwtm0kmOBXeQUIPGMQ== - vadimcn.vscode-lldb@1.4.5:lwHCNwtm0kmOBXeQUIPGMQ==
- bungcip.better-toml@0.3.2:3QfgGxxYtGHfJKQU7H0nEw==

11
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,11 @@
Welcome to nushell!
*Note: for a more complete guide see [The nu contributor book](https://github.com/nushell/contributor-book)*
For speedy contributions open it in Gitpod, nu will be pre-installed with the latest build in a VSCode like editor all from your browser.
[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/nushell/nushell)
To get live support from the community see our [Discord](https://discordapp.com/invite/NtAbbGn), [Twitter](https://twitter.com/nu_shell) or file an issue or feature request here on [GitHub](https://github.com/nushell/nushell/issues/new/choose)!
<!--WIP-->

1640
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,8 +1,8 @@
[package] [package]
name = "nu" name = "nu"
version = "0.10.0" version = "0.13.0"
authors = ["Yehuda Katz <wycats@gmail.com>", "Jonathan Turner <jonathan.d.turner@gmail.com>", "Andrés N. Robalino <andres@androbtech.com>"] authors = ["The Nu Project Contributors"]
description = "A shell for the GitHub era" description = "A new type of shell"
license = "MIT" license = "MIT"
edition = "2018" edition = "2018"
readme = "README.md" readme = "README.md"
@ -13,140 +13,59 @@ documentation = "https://www.nushell.sh/book/"
exclude = ["images"] exclude = ["images"]
[workspace] [workspace]
members = ["crates/*/"]
members = [
"crates/nu-macros",
"crates/nu-errors",
"crates/nu-source",
"crates/nu_plugin_average",
"crates/nu_plugin_binaryview",
"crates/nu_plugin_fetch",
"crates/nu_plugin_inc",
"crates/nu_plugin_match",
"crates/nu_plugin_post",
"crates/nu_plugin_ps",
"crates/nu_plugin_str",
"crates/nu_plugin_sum",
"crates/nu_plugin_sys",
"crates/nu_plugin_textview",
"crates/nu_plugin_tree",
"crates/nu-protocol",
"crates/nu-plugin",
"crates/nu-parser",
"crates/nu-value-ext",
"crates/nu-build"
]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
nu-source = { version = "0.10.0", path = "./crates/nu-source" } nu-cli = { version = "0.13.0", path = "./crates/nu-cli" }
nu-plugin = { version = "0.10.0", path = "./crates/nu-plugin" } nu-source = { version = "0.13.0", path = "./crates/nu-source" }
nu-protocol = { version = "0.10.0", path = "./crates/nu-protocol" } nu-plugin = { version = "0.13.0", path = "./crates/nu-plugin" }
nu-errors = { version = "0.10.0", path = "./crates/nu-errors" } nu-protocol = { version = "0.13.0", path = "./crates/nu-protocol" }
nu-parser = { version = "0.10.0", path = "./crates/nu-parser" } nu-errors = { version = "0.13.0", path = "./crates/nu-errors" }
nu-value-ext = { version = "0.10.0", path = "./crates/nu-value-ext" } nu-parser = { version = "0.13.0", path = "./crates/nu-parser" }
nu_plugin_average = { version = "0.10.0", path = "./crates/nu_plugin_average", optional=true } nu-value-ext = { version = "0.13.0", path = "./crates/nu-value-ext" }
nu_plugin_binaryview = { version = "0.10.0", path = "./crates/nu_plugin_binaryview", optional=true } nu_plugin_average = { version = "0.13.0", path = "./crates/nu_plugin_average", optional=true }
nu_plugin_fetch = { version = "0.10.0", path = "./crates/nu_plugin_fetch", optional=true } nu_plugin_binaryview = { version = "0.13.0", path = "./crates/nu_plugin_binaryview", optional=true }
nu_plugin_inc = { version = "0.10.0", path = "./crates/nu_plugin_inc", optional=true } nu_plugin_fetch = { version = "0.13.0", path = "./crates/nu_plugin_fetch", optional=true }
nu_plugin_match = { version = "0.10.0", path = "./crates/nu_plugin_match", optional=true } nu_plugin_inc = { version = "0.13.0", path = "./crates/nu_plugin_inc", optional=true }
nu_plugin_post = { version = "0.10.0", path = "./crates/nu_plugin_post", optional=true } nu_plugin_match = { version = "0.13.0", path = "./crates/nu_plugin_match", optional=true }
nu_plugin_ps = { version = "0.10.0", path = "./crates/nu_plugin_ps", optional=true } nu_plugin_post = { version = "0.13.0", path = "./crates/nu_plugin_post", optional=true }
nu_plugin_str = { version = "0.10.0", path = "./crates/nu_plugin_str", optional=true } nu_plugin_ps = { version = "0.13.0", path = "./crates/nu_plugin_ps", optional=true }
nu_plugin_sum = { version = "0.10.0", path = "./crates/nu_plugin_sum", optional=true } nu_plugin_str = { version = "0.13.0", path = "./crates/nu_plugin_str", optional=true }
nu_plugin_sys = { version = "0.10.0", path = "./crates/nu_plugin_sys", optional=true } nu_plugin_sys = { version = "0.13.0", path = "./crates/nu_plugin_sys", optional=true }
nu_plugin_textview = { version = "0.10.0", path = "./crates/nu_plugin_textview", optional=true } nu_plugin_textview = { version = "0.13.0", path = "./crates/nu_plugin_textview", optional=true }
nu_plugin_tree = { version = "0.10.0", path = "./crates/nu_plugin_tree", optional=true } nu_plugin_tree = { version = "0.13.0", path = "./crates/nu_plugin_tree", optional=true }
nu-macros = { version = "0.10.0", path = "./crates/nu-macros" }
query_interface = "0.3.5" crossterm = { version = "0.17.2", optional = true }
typetag = "0.1.4" semver = { version = "0.9.0", optional = true }
rustyline = "6.0.0" syntect = { version = "4.1", default-features = false, features = ["default-fancy"], optional = true}
chrono = { version = "0.4.10", features = ["serde"] } url = { version = "2.1.1", optional = true }
derive-new = "0.5.8"
prettytable-rs = "0.8.0" clap = "2.33.0"
itertools = "0.8.2" ctrlc = "3.1.4"
ansi_term = "0.12.1"
nom = "5.0.1"
dunce = "1.0.0" dunce = "1.0.0"
indexmap = { version = "1.3.2", features = ["serde-1"] }
byte-unit = "3.0.3"
base64 = "0.11"
futures = { version = "0.3", features = ["compat", "io-compat"] } futures = { version = "0.3", features = ["compat", "io-compat"] }
async-stream = "0.2"
futures_codec = "0.4"
num-traits = "0.2.11"
term = "0.5.2"
bytes = "0.4.12"
log = "0.4.8" log = "0.4.8"
pretty_env_logger = "0.4.0" pretty_env_logger = "0.4.0"
serde = { version = "1.0.104", features = ["derive"] }
bson = { version = "0.14.0", features = ["decimal128"] } [dev-dependencies]
serde_json = "1.0.47" nu-test-support = { version = "0.13.0", path = "./crates/nu-test-support" }
serde-hjson = "0.9.1"
serde_yaml = "0.8" [build-dependencies]
serde_bytes = "0.11.3"
getset = "0.0.9"
language-reporting = "0.4.0"
app_dirs = "1.2.1"
csv = "1.1"
toml = "0.5.6" toml = "0.5.6"
clap = "2.33.0" serde = { version = "1.0.106", features = ["derive"] }
git2 = { version = "0.11.0", default_features = false } nu-build = { version = "0.13.0", path = "./crates/nu-build" }
dirs = "2.0.2"
glob = "0.3.0"
ctrlc = "3.1.3"
roxmltree = "0.9.1"
nom_locate = "1.0.0"
nom-tracable = "0.4.1"
unicode-xid = "0.2.0"
serde_ini = "0.2.0"
pretty-hex = "0.1.1"
hex = "0.4"
tempfile = "3.1.0"
which = "3.1.0"
ichwh = "0.3"
textwrap = {version = "0.11.0", features = ["term_size"]}
shellexpand = "1.1.1"
pin-utils = "0.1.0-alpha.4"
num-bigint = { version = "0.2.6", features = ["serde"] }
bigdecimal = { version = "0.1.0", features = ["serde"] }
serde_urlencoded = "0.6.1"
trash = "1.0.0"
regex = "1"
cfg-if = "0.1"
strip-ansi-escapes = "0.1.0"
calamine = "0.16"
umask = "0.1"
futures-util = "0.3.4"
termcolor = "1.1.0"
natural = "0.3.0"
parking_lot = "0.10.0"
meval = "0.2"
clipboard = {version = "0.5", optional = true }
ptree = {version = "0.2" }
starship = { version = "0.35.1", optional = true}
syntect = {version = "3.2.0", optional = true }
onig_sys = {version = "=69.1.0", optional = true }
crossterm = {version = "0.16.0", optional = true}
url = {version = "2.1.1", optional = true}
semver = {version = "0.9.0", optional = true}
filesize = "0.1.0"
[target.'cfg(unix)'.dependencies]
users = "0.9"
[features] [features]
# Test executables # Test executables
test-bins = [] test-bins = []
default = ["sys", "ps", "textview", "inc", "str"] default = ["sys", "ps", "textview", "inc", "str"]
stable = ["default", "starship-prompt", "binaryview", "match", "tree", "average", "sum", "post", "fetch", "clipboard"] stable = ["default", "starship-prompt", "binaryview", "match", "tree", "average", "post", "fetch", "clipboard-cli", "trash-support"]
# Default # Default
textview = ["crossterm", "syntect", "onig_sys", "url", "nu_plugin_textview"] textview = ["crossterm", "syntect", "url", "nu_plugin_textview"]
sys = ["nu_plugin_sys"] sys = ["nu_plugin_sys"]
ps = ["nu_plugin_ps"] ps = ["nu_plugin_ps"]
inc = ["semver", "nu_plugin_inc"] inc = ["semver", "nu_plugin_inc"]
@ -158,28 +77,12 @@ binaryview = ["nu_plugin_binaryview"]
fetch = ["nu_plugin_fetch"] fetch = ["nu_plugin_fetch"]
match = ["nu_plugin_match"] match = ["nu_plugin_match"]
post = ["nu_plugin_post"] post = ["nu_plugin_post"]
starship-prompt = ["starship"]
sum = ["nu_plugin_sum"]
trace = ["nu-parser/trace"] trace = ["nu-parser/trace"]
tree = ["nu_plugin_tree"] tree = ["nu_plugin_tree"]
[dependencies.rusqlite] clipboard-cli = ["nu-cli/clipboard-cli"]
version = "0.20.0" starship-prompt = ["nu-cli/starship-prompt"]
features = ["bundled", "blob"] trash-support = ["nu-cli/trash-support"]
[dev-dependencies]
pretty_assertions = "0.6.1"
nu-test-support = { version = "0.10.0", path = "./crates/nu-test-support" }
[build-dependencies]
toml = "0.5.6"
serde = { version = "1.0.104", features = ["derive"] }
nu-build = { version = "0.10.0", path = "./crates/nu-build" }
[lib]
name = "nu"
doctest = false
path = "src/lib.rs"
[[bin]] [[bin]]
name = "fail" name = "fail"
@ -201,6 +104,11 @@ name = "nonu"
path = "crates/nu-test-support/src/bins/nonu.rs" path = "crates/nu-test-support/src/bins/nonu.rs"
required-features = ["test-bins"] required-features = ["test-bins"]
[[bin]]
name = "iecho"
path = "crates/nu-test-support/src/bins/iecho.rs"
required-features = ["test-bins"]
# Core plugins that ship with `cargo install nu` by default # Core plugins that ship with `cargo install nu` by default
# Currently, Cargo limits us to installing only one binary # Currently, Cargo limits us to installing only one binary
# unless we use [[bin]], so we use this as a workaround # unless we use [[bin]], so we use this as a workaround
@ -255,11 +163,6 @@ name = "nu_plugin_stable_post"
path = "src/plugins/nu_plugin_stable_post.rs" path = "src/plugins/nu_plugin_stable_post.rs"
required-features = ["post"] required-features = ["post"]
[[bin]]
name = "nu_plugin_stable_sum"
path = "src/plugins/nu_plugin_stable_sum.rs"
required-features = ["sum"]
[[bin]] [[bin]]
name = "nu_plugin_stable_tree" name = "nu_plugin_stable_tree"
path = "src/plugins/nu_plugin_stable_tree.rs" path = "src/plugins/nu_plugin_stable_tree.rs"

View File

@ -1,6 +1,6 @@
MIT License MIT License
Copyright (c) 2019 Yehuda Katz, Jonathan Turner Copyright (c) 2019 - 2020 Yehuda Katz, Jonathan Turner
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

View File

@ -13,15 +13,22 @@ A new type of shell.
# Status # Status
This project has reached a minimum-viable product level of quality. While contributors dogfood it as their daily driver, it may be unstable for some commands. Future releases will work to fill out missing features and improve stability. Its design is also subject to change as it matures. This project has reached a minimum-viable product level of quality.
While contributors dogfood it as their daily driver, it may be unstable for some commands.
Future releases will work to fill out missing features and improve stability.
Its design is also subject to change as it matures.
Nu comes with a set of built-in commands (listed below). If a command is unknown, the command will shell-out and execute it (using cmd on Windows or bash on Linux and macOS), correctly passing through stdin, stdout, and stderr, so things like your daily git workflows and even `vim` will work just fine. Nu comes with a set of built-in commands (listed below).
If a command is unknown, the command will shell-out and execute it (using cmd on Windows or bash on Linux and macOS), correctly passing through stdin, stdout, and stderr, so things like your daily git workflows and even `vim` will work just fine.
# Learning more # Learning more
There are a few good resources to learn about Nu. There is a [book](https://www.nushell.sh/book/) about Nu that is currently in progress. The book focuses on using Nu and its core concepts. There are a few good resources to learn about Nu.
There is a [book](https://www.nushell.sh/book/) about Nu that is currently in progress.
The book focuses on using Nu and its core concepts.
If you're a developer who would like to contribute to Nu, we're also working on a [book for developers](https://www.nushell.sh/contributor-book/) to help you get started. There are also [good first issues](https://github.com/nushell/nushell/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) to help you dive in. If you're a developer who would like to contribute to Nu, we're also working on a [book for developers](https://www.nushell.sh/contributor-book/) to help you get started.
There are also [good first issues](https://github.com/nushell/nushell/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) to help you dive in.
We also have an active [Discord](https://discord.gg/NtAbbGn) and [Twitter](https://twitter.com/nu_shell) if you'd like to come and chat with us. We also have an active [Discord](https://discord.gg/NtAbbGn) and [Twitter](https://twitter.com/nu_shell) if you'd like to come and chat with us.
@ -63,6 +70,16 @@ cargo build --workspace --features=stable
## Docker ## Docker
### Quickstart
Want to try Nu right away? Execute the following to get started.
```bash
docker run -it quay.io/nushell/nu:latest
```
### Guide
If you want to pull a pre-built container, you can browse tags for the [nushell organization](https://quay.io/organization/nushell) If you want to pull a pre-built container, you can browse tags for the [nushell organization](https://quay.io/organization/nushell)
on Quay.io. Pulling a container would come down to: on Quay.io. Pulling a container would come down to:
@ -107,11 +124,18 @@ The second container is a bit smaller if the size is important to you.
# Philosophy # Philosophy
Nu draws inspiration from projects like PowerShell, functional programming languages, and modern CLI tools. Rather than thinking of files and services as raw streams of text, Nu looks at each input as something with structure. For example, when you list the contents of a directory, what you get back is a table of rows, where each row represents an item in that directory. These values can be piped through a series of steps, in a series of commands called a 'pipeline'. Nu draws inspiration from projects like PowerShell, functional programming languages, and modern CLI tools.
Rather than thinking of files and services as raw streams of text, Nu looks at each input as something with structure.
For example, when you list the contents of a directory, what you get back is a table of rows, where each row represents an item in that directory.
These values can be piped through a series of steps, in a series of commands called a 'pipeline'.
## Pipelines ## Pipelines
In Unix, it's common to pipe between commands to split up a sophisticated command over multiple steps. Nu takes this a step further and builds heavily on the idea of _pipelines_. Just as the Unix philosophy, Nu allows commands to output from stdout and read from stdin. Additionally, commands can output structured data (you can think of this as a third kind of stream). Commands that work in the pipeline fit into one of three categories: In Unix, it's common to pipe between commands to split up a sophisticated command over multiple steps.
Nu takes this a step further and builds heavily on the idea of _pipelines_.
Just as the Unix philosophy, Nu allows commands to output from stdout and read from stdin.
Additionally, commands can output structured data (you can think of this as a third kind of stream).
Commands that work in the pipeline fit into one of three categories:
* Commands that produce a stream (eg, `ls`) * Commands that produce a stream (eg, `ls`)
* Commands that filter a stream (eg, `where type == "Directory"`) * Commands that filter a stream (eg, `where type == "Directory"`)
@ -135,13 +159,15 @@ Commands are separated by the pipe symbol (`|`) to denote a pipeline flowing lef
────┴───────────┴───────────┴──────────┴────────┴──────────────┴──────────────── ────┴───────────┴───────────┴──────────┴────────┴──────────────┴────────────────
``` ```
Because most of the time you'll want to see the output of a pipeline, `autoview` is assumed. We could have also written the above: Because most of the time you'll want to see the output of a pipeline, `autoview` is assumed.
We could have also written the above:
``` ```
/home/jonathan/Source/nushell(master)> ls | where type == Directory /home/jonathan/Source/nushell(master)> ls | where type == Directory
``` ```
Being able to use the same commands and compose them differently is an important philosophy in Nu. For example, we could use the built-in `ps` command as well to get a list of the running processes, using the same `where` as above. Being able to use the same commands and compose them differently is an important philosophy in Nu.
For example, we could use the built-in `ps` command as well to get a list of the running processes, using the same `where` as above.
```text ```text
/home/jonathan/Source/nushell(master)> ps | where cpu > 0 /home/jonathan/Source/nushell(master)> ps | where cpu > 0
@ -157,7 +183,8 @@ Being able to use the same commands and compose them differently is an important
## Opening files ## Opening files
Nu can load file and URL contents as raw text or as structured data (if it recognizes the format). For example, you can load a .toml file as structured data and explore it: Nu can load file and URL contents as raw text or as structured data (if it recognizes the format).
For example, you can load a .toml file as structured data and explore it:
``` ```
/home/jonathan/Source/nushell(master)> open Cargo.toml /home/jonathan/Source/nushell(master)> open Cargo.toml
@ -210,19 +237,26 @@ To set one of these variables, you can use `config --set`. For example:
## Shells ## Shells
Nu will work inside of a single directory and allow you to navigate around your filesystem by default. Nu also offers a way of adding additional working directories that you can jump between, allowing you to work in multiple directories at the same time. Nu will work inside of a single directory and allow you to navigate around your filesystem by default.
Nu also offers a way of adding additional working directories that you can jump between, allowing you to work in multiple directories at the same time.
To do so, use the `enter` command, which will allow you create a new "shell" and enter it at the specified path. You can toggle between this new shell and the original shell with the `p` (for previous) and `n` (for next), allowing you to navigate around a ring buffer of shells. Once you're done with a shell, you can `exit` it and remove it from the ring buffer. To do so, use the `enter` command, which will allow you create a new "shell" and enter it at the specified path.
You can toggle between this new shell and the original shell with the `p` (for previous) and `n` (for next), allowing you to navigate around a ring buffer of shells.
Once you're done with a shell, you can `exit` it and remove it from the ring buffer.
Finally, to get a list of all the current shells, you can use the `shells` command. Finally, to get a list of all the current shells, you can use the `shells` command.
## Plugins ## Plugins
Nu supports plugins that offer additional functionality to the shell and follow the same structured data model that built-in commands use. This allows you to extend nu for your needs. Nu supports plugins that offer additional functionality to the shell and follow the same structured data model that built-in commands use.
This allows you to extend nu for your needs.
There are a few examples in the `plugins` directory. There are a few examples in the `plugins` directory.
Plugins are binaries that are available in your path and follow a `nu_plugin_*` naming convention. These binaries interact with nu via a simple JSON-RPC protocol where the command identifies itself and passes along its configuration, which then makes it available for use. If the plugin is a filter, data streams to it one element at a time, and it can stream data back in return via stdin/stdout. If the plugin is a sink, it is given the full vector of final data and is given free reign over stdin/stdout to use as it pleases. Plugins are binaries that are available in your path and follow a `nu_plugin_*` naming convention.
These binaries interact with nu via a simple JSON-RPC protocol where the command identifies itself and passes along its configuration, which then makes it available for use.
If the plugin is a filter, data streams to it one element at a time, and it can stream data back in return via stdin/stdout.
If the plugin is a sink, it is given the full vector of final data and is given free reign over stdin/stdout to use as it pleases.
# Goals # Goals
@ -244,5 +278,5 @@ You can find a list of Nu commands, complete with documentation, in [quick comma
# License # License
The project is made available under the MIT license. See "LICENSE" for more information. The project is made available under the MIT license. See the `LICENSE` file for more information.

View File

@ -1,7 +1,7 @@
[package] [package]
name = "nu-build" name = "nu-build"
version = "0.10.0" version = "0.13.0"
authors = ["Yehuda Katz <wycats@gmail.com>", "Jonathan Turner <jonathan.d.turner@gmail.com>", "Andrés N. Robalino <andres@androbtech.com>"] authors = ["The Nu Project Contributors"]
edition = "2018" edition = "2018"
description = "Core build system for nushell" description = "Core build system for nushell"
license = "MIT" license = "MIT"
@ -10,7 +10,7 @@ license = "MIT"
doctest = false doctest = false
[dependencies] [dependencies]
serde = { version = "1.0.103", features = ["derive"] } serde = { version = "1.0.106", features = ["derive"] }
lazy_static = "1.4.0" lazy_static = "1.4.0"
serde_json = "1.0.44" serde_json = "1.0.51"
toml = "0.5.5" toml = "0.5.6"

108
crates/nu-cli/Cargo.toml Normal file
View File

@ -0,0 +1,108 @@
[package]
name = "nu-cli"
version = "0.13.0"
authors = ["The Nu Project Contributors"]
description = "CLI for nushell"
edition = "2018"
license = "MIT"
[lib]
doctest = false
[dependencies]
nu-source = { version = "0.13.0", path = "../nu-source" }
nu-plugin = { version = "0.13.0", path = "../nu-plugin" }
nu-protocol = { version = "0.13.0", path = "../nu-protocol" }
nu-errors = { version = "0.13.0", path = "../nu-errors" }
nu-parser = { version = "0.13.0", path = "../nu-parser" }
nu-value-ext = { version = "0.13.0", path = "../nu-value-ext" }
nu-test-support = { version = "0.13.0", path = "../nu-test-support" }
ansi_term = "0.12.1"
app_dirs = "1.2.1"
async-stream = "0.2"
base64 = "0.12.0"
bigdecimal = { version = "0.1.0", features = ["serde"] }
bson = { version = "0.14.1", features = ["decimal128"] }
byte-unit = "3.0.3"
bytes = "0.5.4"
calamine = "0.16"
cfg-if = "0.1"
chrono = { version = "0.4.11", features = ["serde"] }
clap = "2.33.0"
csv = "1.1"
ctrlc = "3.1.4"
derive-new = "0.5.8"
dirs = "2.0.2"
dunce = "1.0.0"
filesize = "0.2.0"
futures = { version = "0.3", features = ["compat", "io-compat"] }
futures-util = "0.3.4"
futures_codec = "0.4"
getset = "0.1.0"
git2 = { version = "0.13.1", default_features = false }
glob = "0.3.0"
hex = "0.4"
htmlescape = "0.3.1"
ical = "0.6.*"
ichwh = "0.3.4"
indexmap = { version = "1.3.2", features = ["serde-1"] }
itertools = "0.9.0"
language-reporting = "0.4.0"
log = "0.4.8"
meval = "0.2"
natural = "0.5.0"
num-bigint = { version = "0.2.6", features = ["serde"] }
num-traits = "0.2.11"
parking_lot = "0.10.0"
pin-utils = "0.1.0-alpha.4"
pretty-hex = "0.1.1"
pretty_env_logger = "0.4.0"
prettytable-rs = "0.8.0"
ptree = {version = "0.2" }
query_interface = "0.3.5"
rand = "0.7"
regex = "1"
roxmltree = "0.10.1"
rustyline = "6.1.1"
serde = { version = "1.0.106", features = ["derive"] }
serde-hjson = "0.9.1"
serde_bytes = "0.11.3"
serde_ini = "0.2.0"
serde_json = "1.0.51"
serde_urlencoded = "0.6.1"
serde_yaml = "0.8"
shellexpand = "2.0.0"
strip-ansi-escapes = "0.1.0"
tempfile = "3.1.0"
term = "0.5.2"
termcolor = "1.1.0"
textwrap = {version = "0.11.0", features = ["term_size"]}
toml = "0.5.6"
typetag = "0.1.4"
umask = "0.1"
unicode-xid = "0.2.0"
trash = { version = "1.0.0", optional = true }
clipboard = { version = "0.5", optional = true }
starship = { version = "0.39.0", optional = true }
[target.'cfg(unix)'.dependencies]
users = "0.10.0"
[dependencies.rusqlite]
version = "0.22.0"
features = ["bundled", "blob"]
[build-dependencies]
nu-build = { version = "0.13.0", path = "../nu-build" }
[dev-dependencies]
quickcheck = "0.9"
quickcheck_macros = "0.9"
[features]
stable = []
starship-prompt = ["starship"]
clipboard-cli = ["clipboard"]
trash-support = ["trash"]

View File

@ -1,4 +1,5 @@
use crate::commands::classified::pipeline::run_pipeline; use crate::commands::classified::block::run_block;
use crate::commands::classified::external::{MaybeTextCodec, StringOrBinary};
use crate::commands::plugin::JsonRpc; use crate::commands::plugin::JsonRpc;
use crate::commands::plugin::{PluginCommand, PluginSink}; use crate::commands::plugin::{PluginCommand, PluginSink};
use crate::commands::whole_stream_command; use crate::commands::whole_stream_command;
@ -6,12 +7,13 @@ use crate::context::Context;
#[cfg(not(feature = "starship-prompt"))] #[cfg(not(feature = "starship-prompt"))]
use crate::git::current_branch; use crate::git::current_branch;
use crate::prelude::*; use crate::prelude::*;
use futures_codec::{FramedRead, LinesCodec}; use futures_codec::FramedRead;
use nu_errors::ShellError;
use nu_parser::{ClassifiedPipeline, PipelineShape, SpannedToken, TokensIterator};
use nu_protocol::{Primitive, ReturnSuccess, Signature, UntaggedValue, Value};
use log::{debug, log_enabled, trace}; use nu_errors::ShellError;
use nu_protocol::hir::{ClassifiedCommand, Expression, InternalCommand, Literal, NamedArguments};
use nu_protocol::{Primitive, ReturnSuccess, Scope, Signature, UntaggedValue, Value};
use log::{debug, trace};
use rustyline::error::ReadlineError; use rustyline::error::ReadlineError;
use rustyline::{ use rustyline::{
self, config::Configurer, config::EditMode, At, Cmd, ColorMode, CompletionType, Config, Editor, self, config::Configurer, config::EditMode, At, Cmd, ColorMode, CompletionType, Config, Editor,
@ -93,44 +95,27 @@ fn load_plugin(path: &std::path::Path, context: &mut Context) -> Result<(), Shel
} }
fn search_paths() -> Vec<std::path::PathBuf> { fn search_paths() -> Vec<std::path::PathBuf> {
use std::env;
let mut search_paths = Vec::new(); let mut search_paths = Vec::new();
#[cfg(debug_assertions)] // Automatically add path `nu` is in as a search path
{ if let Ok(exe_path) = env::current_exe() {
// Use our debug plugins in debug mode if let Some(exe_dir) = exe_path.parent() {
let mut path = std::path::PathBuf::from("."); search_paths.push(exe_dir.to_path_buf());
path.push("target");
path.push("debug");
if path.exists() {
search_paths.push(path);
} }
} }
#[cfg(not(debug_assertions))] #[cfg(not(debug_assertions))]
{ {
use std::env;
match env::var_os("PATH") { match env::var_os("PATH") {
Some(paths) => { Some(paths) => {
search_paths = env::split_paths(&paths).collect::<Vec<_>>(); search_paths.extend(env::split_paths(&paths).collect::<Vec<_>>());
} }
None => println!("PATH is not defined in the environment."), None => println!("PATH is not defined in the environment."),
} }
// Use our release plugins in release mode
let mut path = std::path::PathBuf::from(".");
path.push("target");
path.push("release");
if path.exists() {
search_paths.push(path);
}
} }
// permit Nu finding and picking up development plugins
// if there are any first.
search_paths.reverse();
search_paths search_paths
} }
@ -255,13 +240,13 @@ pub fn create_default_context(
per_item_command(Ls), per_item_command(Ls),
per_item_command(Du), per_item_command(Du),
whole_stream_command(Cd), whole_stream_command(Cd),
whole_stream_command(Env),
per_item_command(Remove), per_item_command(Remove),
per_item_command(Open), per_item_command(Open),
whole_stream_command(Config), whole_stream_command(Config),
per_item_command(Help), per_item_command(Help),
per_item_command(History), per_item_command(History),
whole_stream_command(Save), whole_stream_command(Save),
per_item_command(Touch),
per_item_command(Cpy), per_item_command(Cpy),
whole_stream_command(Date), whole_stream_command(Date),
per_item_command(Calc), per_item_command(Calc),
@ -273,6 +258,7 @@ pub fn create_default_context(
whole_stream_command(What), whole_stream_command(What),
whole_stream_command(Which), whole_stream_command(Which),
whole_stream_command(Debug), whole_stream_command(Debug),
per_item_command(Alias),
// Statistics // Statistics
whole_stream_command(Size), whole_stream_command(Size),
whole_stream_command(Count), whole_stream_command(Count),
@ -317,18 +303,25 @@ pub fn create_default_context(
whole_stream_command(Default), whole_stream_command(Default),
whole_stream_command(SkipWhile), whole_stream_command(SkipWhile),
whole_stream_command(Range), whole_stream_command(Range),
whole_stream_command(Rename),
whole_stream_command(Uniq), whole_stream_command(Uniq),
per_item_command(Each),
// Table manipulation // Table manipulation
whole_stream_command(Shuffle),
whole_stream_command(Wrap), whole_stream_command(Wrap),
whole_stream_command(Pivot), whole_stream_command(Pivot),
whole_stream_command(Headers),
// Data processing // Data processing
whole_stream_command(Histogram), whole_stream_command(Histogram),
whole_stream_command(Sum),
// File format output // File format output
whole_stream_command(ToBSON), whole_stream_command(ToBSON),
whole_stream_command(ToCSV), whole_stream_command(ToCSV),
whole_stream_command(ToHTML),
whole_stream_command(ToJSON), whole_stream_command(ToJSON),
whole_stream_command(ToSQLite), whole_stream_command(ToSQLite),
whole_stream_command(ToDB), whole_stream_command(ToDB),
whole_stream_command(ToMarkdown),
whole_stream_command(ToTOML), whole_stream_command(ToTOML),
whole_stream_command(ToTSV), whole_stream_command(ToTSV),
whole_stream_command(ToURL), whole_stream_command(ToURL),
@ -349,6 +342,10 @@ pub fn create_default_context(
whole_stream_command(FromXML), whole_stream_command(FromXML),
whole_stream_command(FromYAML), whole_stream_command(FromYAML),
whole_stream_command(FromYML), whole_stream_command(FromYML),
whole_stream_command(FromIcs),
whole_stream_command(FromVcf),
// "Private" commands (not intended to be accessed directly)
whole_stream_command(RunExternalCommand),
]); ]);
cfg_if::cfg_if! { cfg_if::cfg_if! {
@ -373,12 +370,66 @@ pub fn create_default_context(
Ok(context) Ok(context)
} }
pub async fn run_vec_of_pipelines(
pipelines: Vec<String>,
redirect_stdin: bool,
) -> Result<(), Box<dyn Error>> {
let mut syncer = crate::EnvironmentSyncer::new();
let mut context = crate::create_default_context(&mut syncer)?;
let _ = crate::load_plugins(&mut context);
let cc = context.ctrl_c.clone();
ctrlc::set_handler(move || {
cc.store(true, Ordering::SeqCst);
})
.expect("Error setting Ctrl-C handler");
if context.ctrl_c.load(Ordering::SeqCst) {
context.ctrl_c.store(false, Ordering::SeqCst);
}
// before we start up, let's run our startup commands
if let Ok(config) = crate::data::config::config(Tag::unknown()) {
if let Some(commands) = config.get("startup") {
match commands {
Value {
value: UntaggedValue::Table(pipelines),
..
} => {
for pipeline in pipelines {
if let Ok(pipeline_string) = pipeline.as_string() {
let _ = run_pipeline_standalone(
pipeline_string,
false,
&mut context,
false,
)
.await;
}
}
}
_ => {
println!("warning: expected a table of pipeline strings as startup commands");
}
}
}
}
for pipeline in pipelines {
run_pipeline_standalone(pipeline, redirect_stdin, &mut context, true).await?;
}
Ok(())
}
pub async fn run_pipeline_standalone( pub async fn run_pipeline_standalone(
pipeline: String, pipeline: String,
redirect_stdin: bool, redirect_stdin: bool,
context: &mut Context, context: &mut Context,
exit_on_error: bool,
) -> Result<(), Box<dyn Error>> { ) -> Result<(), Box<dyn Error>> {
let line = process_line(Ok(pipeline), context, redirect_stdin).await; let line = process_line(Ok(pipeline), context, redirect_stdin, false).await;
match line { match line {
LineResult::Success(line) => { LineResult::Success(line) => {
@ -405,8 +456,10 @@ pub async fn run_pipeline_standalone(
}); });
context.maybe_print_errors(Text::from(line)); context.maybe_print_errors(Text::from(line));
if exit_on_error {
std::process::exit(1); std::process::exit(1);
} }
}
_ => {} _ => {}
} }
@ -448,6 +501,34 @@ pub async fn cli() -> Result<(), Box<dyn Error>> {
}) })
.expect("Error setting Ctrl-C handler"); .expect("Error setting Ctrl-C handler");
let mut ctrlcbreak = false; let mut ctrlcbreak = false;
// before we start up, let's run our startup commands
if let Ok(config) = crate::data::config::config(Tag::unknown()) {
if let Some(commands) = config.get("startup") {
match commands {
Value {
value: UntaggedValue::Table(pipelines),
..
} => {
for pipeline in pipelines {
if let Ok(pipeline_string) = pipeline.as_string() {
let _ = run_pipeline_standalone(
pipeline_string,
false,
&mut context,
false,
)
.await;
}
}
}
_ => {
println!("warning: expected a table of pipeline strings as startup commands");
}
}
}
}
loop { loop {
if context.ctrl_c.load(Ordering::SeqCst) { if context.ctrl_c.load(Ordering::SeqCst) {
context.ctrl_c.store(false, Ordering::SeqCst); context.ctrl_c.store(false, Ordering::SeqCst);
@ -527,7 +608,7 @@ pub async fn cli() -> Result<(), Box<dyn Error>> {
initial_command = None; initial_command = None;
} }
let line = process_line(readline, &mut context, false).await; let line = process_line(readline, &mut context, false, true).await;
// Check the config to see if we need to update the path // Check the config to see if we need to update the path
// TODO: make sure config is cached so we don't path this load every call // TODO: make sure config is cached so we don't path this load every call
@ -610,6 +691,7 @@ async fn process_line(
readline: Result<String, ReadlineError>, readline: Result<String, ReadlineError>,
ctx: &mut Context, ctx: &mut Context,
redirect_stdin: bool, redirect_stdin: bool,
cli_mode: bool,
) -> LineResult { ) -> LineResult {
match &readline { match &readline {
Ok(line) if line.trim() == "" => LineResult::Success(line.clone()), Ok(line) if line.trim() == "" => LineResult::Success(line.clone()),
@ -617,9 +699,9 @@ async fn process_line(
Ok(line) => { Ok(line) => {
let line = chomp_newline(line); let line = chomp_newline(line);
let result = match nu_parser::parse(&line) { let result = match nu_parser::lite_parse(&line, 0) {
Err(err) => { Err(err) => {
return LineResult::Error(line.to_string(), err); return LineResult::Error(line.to_string(), err.into());
} }
Ok(val) => val, Ok(val) => val,
@ -628,33 +710,127 @@ async fn process_line(
debug!("=== Parsed ==="); debug!("=== Parsed ===");
debug!("{:#?}", result); debug!("{:#?}", result);
let pipeline = classify_pipeline(&result, ctx, &Text::from(line)); let classified_block = nu_parser::classify_block(&result, ctx.registry());
if let Some(failure) = pipeline.failed { debug!("{:#?}", classified_block);
//println!("{:#?}", pipeline);
if let Some(failure) = classified_block.failed {
return LineResult::Error(line.to_string(), failure.into()); return LineResult::Error(line.to_string(), failure.into());
} }
let input_stream = if redirect_stdin { // There's a special case to check before we process the pipeline:
let file = futures::io::AllowStdIo::new( // If we're giving a path by itself
crate::commands::classified::external::StdoutWithNewline::new(std::io::stdin()), // ...and it's not a command in the path
); // ...and it doesn't have any arguments
let stream = FramedRead::new(file, LinesCodec).map(|line| { // ...and we're in the CLI
if let Ok(line) = line { // ...then change to this directory
Ok(Value { if cli_mode
value: UntaggedValue::Primitive(Primitive::String(line)), && classified_block.block.block.len() == 1
tag: Tag::unknown(), && classified_block.block.block[0].list.len() == 1
{
if let ClassifiedCommand::Internal(InternalCommand {
ref name, ref args, ..
}) = classified_block.block.block[0].list[0]
{
let internal_name = name;
let name = args
.positional
.as_ref()
.and_then(|potionals| {
potionals.get(0).map(|e| {
if let Expression::Literal(Literal::String(ref s)) = e.expr {
&s
} else {
""
}
}) })
})
.unwrap_or("");
if internal_name == "run_external"
&& args
.positional
.as_ref()
.map(|ref v| v.len() == 1)
.unwrap_or(true)
&& args
.named
.as_ref()
.map(NamedArguments::is_empty)
.unwrap_or(true)
&& dunce::canonicalize(&name).is_ok()
&& PathBuf::from(&name).is_dir()
&& ichwh::which(&name).await.unwrap_or(None).is_none()
{
// Here we work differently if we're in Windows because of the expected Windows behavior
#[cfg(windows)]
{
if name.ends_with(':') {
// This looks like a drive shortcut. We need to a) switch drives and b) go back to the previous directory we were viewing on that drive
// But first, we need to save where we are now
let current_path = ctx.shell_manager.path();
let split_path: Vec<_> = current_path.split(':').collect();
if split_path.len() > 1 {
ctx.windows_drives_previous_cwd
.lock()
.insert(split_path[0].to_string(), current_path);
}
let name = name.to_uppercase();
let new_drive: Vec<_> = name.split(':').collect();
if let Some(val) =
ctx.windows_drives_previous_cwd.lock().get(new_drive[0])
{
ctx.shell_manager.set_path(val.to_string());
return LineResult::Success(line.to_string());
} else {
ctx.shell_manager.set_path(name.to_string());
return LineResult::Success(line.to_string());
}
} else {
ctx.shell_manager.set_path(name.to_string());
return LineResult::Success(line.to_string());
}
}
#[cfg(not(windows))]
{
ctx.shell_manager.set_path(name.to_string());
return LineResult::Success(line.to_string());
}
}
}
}
let input_stream = if redirect_stdin {
let file = futures::io::AllowStdIo::new(std::io::stdin());
let stream = FramedRead::new(file, MaybeTextCodec).map(|line| {
if let Ok(line) = line {
match line {
StringOrBinary::String(s) => Ok(Value {
value: UntaggedValue::Primitive(Primitive::String(s)),
tag: Tag::unknown(),
}),
StringOrBinary::Binary(b) => Ok(Value {
value: UntaggedValue::Primitive(Primitive::Binary(
b.into_iter().collect(),
)),
tag: Tag::unknown(),
}),
}
} else { } else {
panic!("Internal error: could not read lines of text from stdin") panic!("Internal error: could not read lines of text from stdin")
} }
}); });
Some(stream.to_input_stream()) stream.to_input_stream()
} else { } else {
None InputStream::empty()
}; };
match run_pipeline(pipeline, ctx, input_stream, line).await { match run_block(&classified_block.block, ctx, input_stream, &Scope::empty()).await {
Ok(Some(input)) => { Ok(input) => {
// Running a pipeline gives us back a stream that we can then // Running a pipeline gives us back a stream that we can then
// work through. At the top level, we just want to pull on the // work through. At the top level, we just want to pull on the
// values to compute them. // values to compute them.
@ -665,9 +841,8 @@ async fn process_line(
shell_manager: ctx.shell_manager.clone(), shell_manager: ctx.shell_manager.clone(),
host: ctx.host.clone(), host: ctx.host.clone(),
ctrl_c: ctx.ctrl_c.clone(), ctrl_c: ctx.ctrl_c.clone(),
commands: ctx.registry.clone(), registry: ctx.registry.clone(),
name: Tag::unknown(), name: Tag::unknown(),
source: Text::from(String::new()),
}; };
if let Ok(mut output_stream) = crate::commands::autoview::autoview(context) { if let Ok(mut output_stream) = crate::commands::autoview::autoview(context) {
@ -682,16 +857,14 @@ async fn process_line(
break; break;
} }
} }
_ => { Ok(None) => break,
break; Err(e) => return LineResult::Error(line.to_string(), e),
}
} }
} }
} }
LineResult::Success(line.to_string()) LineResult::Success(line.to_string())
} }
Ok(None) => LineResult::Success(line.to_string()),
Err(err) => LineResult::Error(line.to_string(), err), Err(err) => LineResult::Error(line.to_string(), err),
} }
} }
@ -704,29 +877,8 @@ async fn process_line(
} }
} }
pub fn classify_pipeline(
pipeline: &SpannedToken,
context: &Context,
source: &Text,
) -> ClassifiedPipeline {
let pipeline_list = vec![pipeline.clone()];
let expand_context = context.expand_context(source);
let mut iterator = TokensIterator::new(&pipeline_list, expand_context, pipeline.span());
let result = iterator.expand_infallible(PipelineShape);
if log_enabled!(target: "nu::expand_syntax", log::Level::Debug) {
outln!("");
let _ = ptree::print_tree(&iterator.expand_tracer().print(source.clone()));
outln!("");
}
result
}
pub fn print_err(err: ShellError, host: &dyn Host, source: &Text) { pub fn print_err(err: ShellError, host: &dyn Host, source: &Text) {
let diag = err.into_diagnostic(); if let Some(diag) = err.into_diagnostic() {
let writer = host.err_termcolor(); let writer = host.err_termcolor();
let mut source = source.to_string(); let mut source = source.to_string();
source.push_str(" "); source.push_str(" ");
@ -739,4 +891,18 @@ pub fn print_err(err: ShellError, host: &dyn Host, source: &Text) {
&language_reporting::DefaultConfig, &language_reporting::DefaultConfig,
); );
}); });
}
}
#[cfg(test)]
mod tests {
#[quickcheck]
fn quickcheck_parse(data: String) -> bool {
if let Ok(lite_block) = nu_parser::lite_parse(&data, 0) {
let context = crate::context::Context::basic().unwrap();
let _ = nu_parser::classify_block(&lite_block, context.registry());
}
true
}
} }

View File

@ -4,6 +4,7 @@ pub(crate) mod macros;
mod from_delimited_data; mod from_delimited_data;
mod to_delimited_data; mod to_delimited_data;
pub(crate) mod alias;
pub(crate) mod append; pub(crate) mod append;
pub(crate) mod args; pub(crate) mod args;
pub(crate) mod autoview; pub(crate) mod autoview;
@ -20,10 +21,10 @@ pub(crate) mod date;
pub(crate) mod debug; pub(crate) mod debug;
pub(crate) mod default; pub(crate) mod default;
pub(crate) mod du; pub(crate) mod du;
pub(crate) mod each;
pub(crate) mod echo; pub(crate) mod echo;
pub(crate) mod edit; pub(crate) mod edit;
pub(crate) mod enter; pub(crate) mod enter;
pub(crate) mod env;
#[allow(unused)] #[allow(unused)]
pub(crate) mod evaluate_by; pub(crate) mod evaluate_by;
pub(crate) mod exit; pub(crate) mod exit;
@ -31,6 +32,7 @@ pub(crate) mod first;
pub(crate) mod format; pub(crate) mod format;
pub(crate) mod from_bson; pub(crate) mod from_bson;
pub(crate) mod from_csv; pub(crate) mod from_csv;
pub(crate) mod from_ics;
pub(crate) mod from_ini; pub(crate) mod from_ini;
pub(crate) mod from_json; pub(crate) mod from_json;
pub(crate) mod from_ods; pub(crate) mod from_ods;
@ -39,11 +41,13 @@ pub(crate) mod from_ssv;
pub(crate) mod from_toml; pub(crate) mod from_toml;
pub(crate) mod from_tsv; pub(crate) mod from_tsv;
pub(crate) mod from_url; pub(crate) mod from_url;
pub(crate) mod from_vcf;
pub(crate) mod from_xlsx; pub(crate) mod from_xlsx;
pub(crate) mod from_xml; pub(crate) mod from_xml;
pub(crate) mod from_yaml; pub(crate) mod from_yaml;
pub(crate) mod get; pub(crate) mod get;
pub(crate) mod group_by; pub(crate) mod group_by;
pub(crate) mod headers;
pub(crate) mod help; pub(crate) mod help;
pub(crate) mod histogram; pub(crate) mod histogram;
pub(crate) mod history; pub(crate) mod history;
@ -69,10 +73,14 @@ pub(crate) mod range;
#[allow(unused)] #[allow(unused)]
pub(crate) mod reduce_by; pub(crate) mod reduce_by;
pub(crate) mod reject; pub(crate) mod reject;
pub(crate) mod rename;
pub(crate) mod reverse; pub(crate) mod reverse;
pub(crate) mod rm; pub(crate) mod rm;
pub(crate) mod run_alias;
pub(crate) mod run_external;
pub(crate) mod save; pub(crate) mod save;
pub(crate) mod shells; pub(crate) mod shells;
pub(crate) mod shuffle;
pub(crate) mod size; pub(crate) mod size;
pub(crate) mod skip; pub(crate) mod skip;
pub(crate) mod skip_while; pub(crate) mod skip_while;
@ -80,13 +88,16 @@ pub(crate) mod sort_by;
pub(crate) mod split_by; pub(crate) mod split_by;
pub(crate) mod split_column; pub(crate) mod split_column;
pub(crate) mod split_row; pub(crate) mod split_row;
pub(crate) mod sum;
#[allow(unused)] #[allow(unused)]
pub(crate) mod t_sort_by; pub(crate) mod t_sort_by;
pub(crate) mod table; pub(crate) mod table;
pub(crate) mod tags; pub(crate) mod tags;
pub(crate) mod to_bson; pub(crate) mod to_bson;
pub(crate) mod to_csv; pub(crate) mod to_csv;
pub(crate) mod to_html;
pub(crate) mod to_json; pub(crate) mod to_json;
pub(crate) mod to_md;
pub(crate) mod to_sqlite; pub(crate) mod to_sqlite;
pub(crate) mod to_toml; pub(crate) mod to_toml;
pub(crate) mod to_tsv; pub(crate) mod to_tsv;
@ -107,6 +118,7 @@ pub(crate) use command::{
WholeStreamCommand, WholeStreamCommand,
}; };
pub(crate) use alias::Alias;
pub(crate) use append::Append; pub(crate) use append::Append;
pub(crate) use calc::Calc; pub(crate) use calc::Calc;
pub(crate) use compact::Compact; pub(crate) use compact::Compact;
@ -117,14 +129,15 @@ pub(crate) use date::Date;
pub(crate) use debug::Debug; pub(crate) use debug::Debug;
pub(crate) use default::Default; pub(crate) use default::Default;
pub(crate) use du::Du; pub(crate) use du::Du;
pub(crate) use each::Each;
pub(crate) use echo::Echo; pub(crate) use echo::Echo;
pub(crate) use edit::Edit; pub(crate) use edit::Edit;
pub(crate) mod kill; pub(crate) mod kill;
pub(crate) use kill::Kill; pub(crate) use kill::Kill;
pub(crate) mod clear; pub(crate) mod clear;
pub(crate) use clear::Clear; pub(crate) use clear::Clear;
pub(crate) mod touch;
pub(crate) use enter::Enter; pub(crate) use enter::Enter;
pub(crate) use env::Env;
#[allow(unused_imports)] #[allow(unused_imports)]
pub(crate) use evaluate_by::EvaluateBy; pub(crate) use evaluate_by::EvaluateBy;
pub(crate) use exit::Exit; pub(crate) use exit::Exit;
@ -132,6 +145,7 @@ pub(crate) use first::First;
pub(crate) use format::Format; pub(crate) use format::Format;
pub(crate) use from_bson::FromBSON; pub(crate) use from_bson::FromBSON;
pub(crate) use from_csv::FromCSV; pub(crate) use from_csv::FromCSV;
pub(crate) use from_ics::FromIcs;
pub(crate) use from_ini::FromINI; pub(crate) use from_ini::FromINI;
pub(crate) use from_json::FromJSON; pub(crate) use from_json::FromJSON;
pub(crate) use from_ods::FromODS; pub(crate) use from_ods::FromODS;
@ -141,12 +155,14 @@ pub(crate) use from_ssv::FromSSV;
pub(crate) use from_toml::FromTOML; pub(crate) use from_toml::FromTOML;
pub(crate) use from_tsv::FromTSV; pub(crate) use from_tsv::FromTSV;
pub(crate) use from_url::FromURL; pub(crate) use from_url::FromURL;
pub(crate) use from_vcf::FromVcf;
pub(crate) use from_xlsx::FromXLSX; pub(crate) use from_xlsx::FromXLSX;
pub(crate) use from_xml::FromXML; pub(crate) use from_xml::FromXML;
pub(crate) use from_yaml::FromYAML; pub(crate) use from_yaml::FromYAML;
pub(crate) use from_yaml::FromYML; pub(crate) use from_yaml::FromYML;
pub(crate) use get::Get; pub(crate) use get::Get;
pub(crate) use group_by::GroupBy; pub(crate) use group_by::GroupBy;
pub(crate) use headers::Headers;
pub(crate) use help::Help; pub(crate) use help::Help;
pub(crate) use histogram::Histogram; pub(crate) use histogram::Histogram;
pub(crate) use history::History; pub(crate) use history::History;
@ -171,10 +187,13 @@ pub(crate) use range::Range;
#[allow(unused_imports)] #[allow(unused_imports)]
pub(crate) use reduce_by::ReduceBy; pub(crate) use reduce_by::ReduceBy;
pub(crate) use reject::Reject; pub(crate) use reject::Reject;
pub(crate) use rename::Rename;
pub(crate) use reverse::Reverse; pub(crate) use reverse::Reverse;
pub(crate) use rm::Remove; pub(crate) use rm::Remove;
pub(crate) use run_external::RunExternalCommand;
pub(crate) use save::Save; pub(crate) use save::Save;
pub(crate) use shells::Shells; pub(crate) use shells::Shells;
pub(crate) use shuffle::Shuffle;
pub(crate) use size::Size; pub(crate) use size::Size;
pub(crate) use skip::Skip; pub(crate) use skip::Skip;
pub(crate) use skip_while::SkipWhile; pub(crate) use skip_while::SkipWhile;
@ -182,19 +201,23 @@ pub(crate) use sort_by::SortBy;
pub(crate) use split_by::SplitBy; pub(crate) use split_by::SplitBy;
pub(crate) use split_column::SplitColumn; pub(crate) use split_column::SplitColumn;
pub(crate) use split_row::SplitRow; pub(crate) use split_row::SplitRow;
pub(crate) use sum::Sum;
#[allow(unused_imports)] #[allow(unused_imports)]
pub(crate) use t_sort_by::TSortBy; pub(crate) use t_sort_by::TSortBy;
pub(crate) use table::Table; pub(crate) use table::Table;
pub(crate) use tags::Tags; pub(crate) use tags::Tags;
pub(crate) use to_bson::ToBSON; pub(crate) use to_bson::ToBSON;
pub(crate) use to_csv::ToCSV; pub(crate) use to_csv::ToCSV;
pub(crate) use to_html::ToHTML;
pub(crate) use to_json::ToJSON; pub(crate) use to_json::ToJSON;
pub(crate) use to_md::ToMarkdown;
pub(crate) use to_sqlite::ToDB; pub(crate) use to_sqlite::ToDB;
pub(crate) use to_sqlite::ToSQLite; pub(crate) use to_sqlite::ToSQLite;
pub(crate) use to_toml::ToTOML; pub(crate) use to_toml::ToTOML;
pub(crate) use to_tsv::ToTSV; pub(crate) use to_tsv::ToTSV;
pub(crate) use to_url::ToURL; pub(crate) use to_url::ToURL;
pub(crate) use to_yaml::ToYAML; pub(crate) use to_yaml::ToYAML;
pub(crate) use touch::Touch;
pub(crate) use trim::Trim; pub(crate) use trim::Trim;
pub(crate) use uniq::Uniq; pub(crate) use uniq::Uniq;
pub(crate) use version::Version; pub(crate) use version::Version;

View File

@ -0,0 +1,65 @@
use crate::commands::PerItemCommand;
use crate::context::CommandRegistry;
use crate::prelude::*;
use nu_errors::ShellError;
use nu_protocol::{
CallInfo, CommandAction, Primitive, ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value,
};
pub struct Alias;
impl PerItemCommand for Alias {
fn name(&self) -> &str {
"alias"
}
fn signature(&self) -> Signature {
Signature::build("alias")
.required("name", SyntaxShape::String, "the name of the alias")
.required("args", SyntaxShape::Table, "the arguments to the alias")
.required("block", SyntaxShape::Block, "the block to run on each row")
}
fn usage(&self) -> &str {
"Run a block on each row of the table."
}
fn run(
&self,
call_info: &CallInfo,
_registry: &CommandRegistry,
_raw_args: &RawCommandArgs,
_input: Value,
) -> Result<OutputStream, ShellError> {
let call_info = call_info.clone();
let stream = async_stream! {
match (call_info.args.expect_nth(0)?, call_info.args.expect_nth(1)?, call_info.args.expect_nth(2)?) {
(Value {value: UntaggedValue::Primitive(Primitive::String(name)), .. },
Value { value: UntaggedValue::Table(list), .. },
Value {
value: UntaggedValue::Block(block),
tag
}) => {
let mut args: Vec<String> = vec![];
for item in list.iter() {
if let Ok(string) = item.as_string() {
args.push(format!("${}", string));
} else {
yield Err(ShellError::labeled_error("Expected a string", "expected a string", item.tag()));
}
}
yield ReturnSuccess::action(CommandAction::AddAlias(name.to_string(), args, block.clone()))
}
_ => {
yield Err(ShellError::labeled_error(
"Expected `name [args] {block}",
"needs a name, args, and a block",
call_info.name_tag,
))
}
};
};
Ok(stream.to_output_stream())
}
}

View File

@ -45,5 +45,5 @@ fn append(
after.push_back(row); after.push_back(row);
let after = futures::stream::iter(after); let after = futures::stream::iter(after);
Ok(OutputStream::from_input(input.values.chain(after))) Ok(OutputStream::from_input(input.chain(after)))
} }

View File

@ -2,8 +2,8 @@ use crate::commands::UnevaluatedCallInfo;
use crate::commands::WholeStreamCommand; use crate::commands::WholeStreamCommand;
use crate::prelude::*; use crate::prelude::*;
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_parser::{hir, hir::Expression, hir::Literal, hir::SpannedExpression}; use nu_protocol::{hir, hir::Expression, hir::Literal, hir::SpannedExpression};
use nu_protocol::{Primitive, ReturnSuccess, Signature, UntaggedValue, Value}; use nu_protocol::{Primitive, ReturnSuccess, Scope, Signature, UntaggedValue, Value};
use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering; use std::sync::atomic::Ordering;
@ -29,10 +29,9 @@ impl WholeStreamCommand for Autoview {
) -> Result<OutputStream, ShellError> { ) -> Result<OutputStream, ShellError> {
autoview(RunnableContext { autoview(RunnableContext {
input: args.input, input: args.input,
commands: registry.clone(), registry: registry.clone(),
shell_manager: args.shell_manager, shell_manager: args.shell_manager,
host: args.host, host: args.host,
source: args.call_info.source,
ctrl_c: args.ctrl_c, ctrl_c: args.ctrl_c,
name: args.call_info.name_tag, name: args.call_info.name_tag,
}) })
@ -42,9 +41,8 @@ impl WholeStreamCommand for Autoview {
pub struct RunnableContextWithoutInput { pub struct RunnableContextWithoutInput {
pub shell_manager: ShellManager, pub shell_manager: ShellManager,
pub host: Arc<parking_lot::Mutex<Box<dyn Host>>>, pub host: Arc<parking_lot::Mutex<Box<dyn Host>>>,
pub source: Text,
pub ctrl_c: Arc<AtomicBool>, pub ctrl_c: Arc<AtomicBool>,
pub commands: CommandRegistry, pub registry: CommandRegistry,
pub name: Tag, pub name: Tag,
} }
@ -53,9 +51,8 @@ impl RunnableContextWithoutInput {
let new_context = RunnableContextWithoutInput { let new_context = RunnableContextWithoutInput {
shell_manager: context.shell_manager, shell_manager: context.shell_manager,
host: context.host, host: context.host,
source: context.source,
ctrl_c: context.ctrl_c, ctrl_c: context.ctrl_c,
commands: context.commands, registry: context.registry,
name: context.name, name: context.name,
}; };
(context.input, new_context) (context.input, new_context)
@ -92,9 +89,10 @@ pub fn autoview(context: RunnableContext) -> Result<OutputStream, ShellError> {
} }
}; };
let stream = stream.to_input_stream(); let stream = stream.to_input_stream();
if let Some(table) = table { if let Some(table) = table {
let command_args = create_default_command_args(&context).with_input(stream); let command_args = create_default_command_args(&context).with_input(stream);
let result = table.run(command_args, &context.commands); let result = table.run(command_args, &context.registry);
result.collect::<Vec<_>>().await; result.collect::<Vec<_>>().await;
} }
} }
@ -108,17 +106,17 @@ pub fn autoview(context: RunnableContext) -> Result<OutputStream, ShellError> {
let mut stream = VecDeque::new(); let mut stream = VecDeque::new();
stream.push_back(UntaggedValue::string(s).into_value(Tag { anchor, span })); stream.push_back(UntaggedValue::string(s).into_value(Tag { anchor, span }));
let command_args = create_default_command_args(&context).with_input(stream); let command_args = create_default_command_args(&context).with_input(stream);
let result = text.run(command_args, &context.commands); let result = text.run(command_args, &context.registry);
result.collect::<Vec<_>>().await; result.collect::<Vec<_>>().await;
} else { } else {
outln!("{}", s); out!("{}", s);
} }
} }
Value { Value {
value: UntaggedValue::Primitive(Primitive::String(s)), value: UntaggedValue::Primitive(Primitive::String(s)),
.. ..
} => { } => {
outln!("{}", s); out!("{}", s);
} }
Value { Value {
value: UntaggedValue::Primitive(Primitive::Line(ref s)), value: UntaggedValue::Primitive(Primitive::Line(ref s)),
@ -128,35 +126,41 @@ pub fn autoview(context: RunnableContext) -> Result<OutputStream, ShellError> {
let mut stream = VecDeque::new(); let mut stream = VecDeque::new();
stream.push_back(UntaggedValue::string(s).into_value(Tag { anchor, span })); stream.push_back(UntaggedValue::string(s).into_value(Tag { anchor, span }));
let command_args = create_default_command_args(&context).with_input(stream); let command_args = create_default_command_args(&context).with_input(stream);
let result = text.run(command_args, &context.commands); let result = text.run(command_args, &context.registry);
result.collect::<Vec<_>>().await; result.collect::<Vec<_>>().await;
} else { } else {
outln!("{}\n", s); out!("{}\n", s);
} }
} }
Value { Value {
value: UntaggedValue::Primitive(Primitive::Line(s)), value: UntaggedValue::Primitive(Primitive::Line(s)),
.. ..
} => { } => {
outln!("{}\n", s); out!("{}\n", s);
} }
Value { Value {
value: UntaggedValue::Primitive(Primitive::Path(s)), value: UntaggedValue::Primitive(Primitive::Path(s)),
.. ..
} => { } => {
outln!("{}", s.display()); out!("{}", s.display());
} }
Value { Value {
value: UntaggedValue::Primitive(Primitive::Int(n)), value: UntaggedValue::Primitive(Primitive::Int(n)),
.. ..
} => { } => {
outln!("{}", n); out!("{}", n);
} }
Value { Value {
value: UntaggedValue::Primitive(Primitive::Decimal(n)), value: UntaggedValue::Primitive(Primitive::Decimal(n)),
.. ..
} => { } => {
outln!("{}", n); out!("{}", n);
}
Value {
value: UntaggedValue::Primitive(Primitive::Boolean(b)),
..
} => {
out!("{}", b);
} }
Value { value: UntaggedValue::Primitive(Primitive::Binary(ref b)), .. } => { Value { value: UntaggedValue::Primitive(Primitive::Binary(ref b)), .. } => {
@ -164,26 +168,96 @@ pub fn autoview(context: RunnableContext) -> Result<OutputStream, ShellError> {
let mut stream = VecDeque::new(); let mut stream = VecDeque::new();
stream.push_back(x); stream.push_back(x);
let command_args = create_default_command_args(&context).with_input(stream); let command_args = create_default_command_args(&context).with_input(stream);
let result = binary.run(command_args, &context.commands); let result = binary.run(command_args, &context.registry);
result.collect::<Vec<_>>().await; result.collect::<Vec<_>>().await;
} else { } else {
use pretty_hex::*; use pretty_hex::*;
outln!("{:?}", b.hex_dump()); out!("{:?}", b.hex_dump());
} }
} }
Value { value: UntaggedValue::Error(e), .. } => { Value { value: UntaggedValue::Error(e), .. } => {
yield Err(e); yield Err(e);
} }
Value { value: UntaggedValue::Row(row), ..} => {
use prettytable::format::{FormatBuilder, LinePosition, LineSeparator};
use prettytable::{color, Attr, Cell, Row, Table};
use crate::data::value::{format_leaf, style_leaf};
use textwrap::fill;
let termwidth = std::cmp::max(textwrap::termwidth(), 20);
enum TableMode {
Light,
Normal,
}
let mut table = Table::new();
let table_mode = crate::data::config::config(Tag::unknown());
let table_mode = if let Some(s) = table_mode?.get("table_mode") {
match s.as_string() {
Ok(typ) if typ == "light" => TableMode::Light,
_ => TableMode::Normal,
}
} else {
TableMode::Normal
};
match table_mode {
TableMode::Light => {
table.set_format(
FormatBuilder::new()
.separator(LinePosition::Title, LineSeparator::new('─', '─', ' ', ' '))
.padding(1, 1)
.build(),
);
}
_ => {
table.set_format(
FormatBuilder::new()
.column_separator('│')
.separator(LinePosition::Top, LineSeparator::new('─', '┬', ' ', ' '))
.separator(LinePosition::Title, LineSeparator::new('─', '┼', ' ', ' '))
.separator(LinePosition::Bottom, LineSeparator::new('─', '┴', ' ', ' '))
.padding(1, 1)
.build(),
);
}
}
let mut max_key_len = 0;
for (key, _) in row.entries.iter() {
max_key_len = std::cmp::max(max_key_len, key.chars().count());
}
if max_key_len > (termwidth/2 - 1) {
max_key_len = termwidth/2 - 1;
}
let max_val_len = termwidth - max_key_len - 5;
for (key, value) in row.entries.iter() {
table.add_row(Row::new(vec![Cell::new(&fill(&key, max_key_len)).with_style(Attr::ForegroundColor(color::GREEN)).with_style(Attr::Bold),
Cell::new(&fill(&format_leaf(value).plain_string(100_000), max_val_len))]));
}
table.printstd();
// table.print_term(&mut *context.host.lock().out_terminal().ok_or_else(|| ShellError::untagged_runtime_error("Could not open terminal for output"))?)
// .map_err(|_| ShellError::untagged_runtime_error("Internal error: could not print to terminal (for unix systems check to make sure TERM is set)"))?;
}
Value { value: ref item, .. } => { Value { value: ref item, .. } => {
if let Some(table) = table { if let Some(table) = table {
let mut stream = VecDeque::new(); let mut stream = VecDeque::new();
stream.push_back(x); stream.push_back(x);
let command_args = create_default_command_args(&context).with_input(stream); let command_args = create_default_command_args(&context).with_input(stream);
let result = table.run(command_args, &context.commands); let result = table.run(command_args, &context.registry);
result.collect::<Vec<_>>().await; result.collect::<Vec<_>>().await;
} else { } else {
outln!("{:?}", item); out!("{:?}", item);
} }
} }
} }
@ -191,7 +265,7 @@ pub fn autoview(context: RunnableContext) -> Result<OutputStream, ShellError> {
} }
} }
_ => { _ => {
//outln!("<no results>"); //out!("<no results>");
} }
} }
@ -211,15 +285,16 @@ fn create_default_command_args(context: &RunnableContextWithoutInput) -> RawComm
call_info: UnevaluatedCallInfo { call_info: UnevaluatedCallInfo {
args: hir::Call { args: hir::Call {
head: Box::new(SpannedExpression::new( head: Box::new(SpannedExpression::new(
Expression::Literal(Literal::String(span)), Expression::Literal(Literal::String(String::new())),
span, span,
)), )),
positional: None, positional: None,
named: None, named: None,
span, span,
is_last: true,
}, },
source: context.source.clone(),
name_tag: context.name.clone(), name_tag: context.name.clone(),
scope: Scope::empty(),
}, },
} }
} }

View File

@ -1,7 +1,6 @@
use crate::commands::WholeStreamCommand; use crate::commands::WholeStreamCommand;
use crate::prelude::*; use crate::prelude::*;
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_macros::signature;
use nu_protocol::{Signature, SyntaxShape}; use nu_protocol::{Signature, SyntaxShape};
pub struct Cd; pub struct Cd;
@ -12,17 +11,11 @@ impl WholeStreamCommand for Cd {
} }
fn signature(&self) -> Signature { fn signature(&self) -> Signature {
signature! { Signature::build("cd").optional(
def cd { "directory",
"the directory to change to" SyntaxShape::Path,
directory(optional Path) - "the directory to change to" "the directory to change to",
} )
}
// Signature::build("cd").optional(
// "directory",
// SyntaxShape::Path,
// "the directory to change to",
// )
} }
fn usage(&self) -> &str { fn usage(&self) -> &str {

View File

@ -0,0 +1,96 @@
use crate::commands::classified::expr::run_expression_block;
//use crate::commands::classified::external::run_external_command;
use crate::commands::classified::internal::run_internal_command;
use crate::context::Context;
use crate::prelude::*;
use crate::stream::InputStream;
use futures::stream::TryStreamExt;
use nu_errors::ShellError;
use nu_protocol::hir::{Block, ClassifiedCommand, Commands};
use nu_protocol::{ReturnSuccess, Scope, UntaggedValue, Value};
use std::sync::atomic::Ordering;
pub(crate) async fn run_block(
block: &Block,
ctx: &mut Context,
mut input: InputStream,
scope: &Scope,
) -> Result<InputStream, ShellError> {
let mut output: Result<InputStream, ShellError> = Ok(InputStream::empty());
for pipeline in &block.block {
match output {
Ok(inp) if inp.is_empty() => {}
Ok(inp) => {
let mut output_stream = inp.to_output_stream();
loop {
match output_stream.try_next().await {
Ok(Some(ReturnSuccess::Value(Value {
value: UntaggedValue::Error(e),
..
}))) => return Err(e),
Ok(Some(_item)) => {
if let Some(err) = ctx.get_errors().get(0) {
ctx.clear_errors();
return Err(err.clone());
}
if ctx.ctrl_c.load(Ordering::SeqCst) {
break;
}
}
Ok(None) => {
if let Some(err) = ctx.get_errors().get(0) {
ctx.clear_errors();
return Err(err.clone());
}
break;
}
Err(e) => return Err(e),
}
}
}
Err(e) => {
return Err(e);
}
}
output = run_pipeline(pipeline, ctx, input, scope).await;
input = InputStream::empty();
}
output
}
async fn run_pipeline(
commands: &Commands,
ctx: &mut Context,
mut input: InputStream,
scope: &Scope,
) -> Result<InputStream, ShellError> {
let mut iter = commands.list.clone().into_iter().peekable();
loop {
let item: Option<ClassifiedCommand> = iter.next();
let next: Option<&ClassifiedCommand> = iter.peek();
input = match (item, next) {
(Some(ClassifiedCommand::Dynamic(_)), _) | (_, Some(ClassifiedCommand::Dynamic(_))) => {
return Err(ShellError::unimplemented("Dynamic commands"))
}
(Some(ClassifiedCommand::Expr(expr)), _) => {
run_expression_block(*expr, ctx, input, scope)?
}
(Some(ClassifiedCommand::Error(err)), _) => return Err(err.into()),
(_, Some(ClassifiedCommand::Error(err))) => return Err(err.clone().into()),
(Some(ClassifiedCommand::Internal(left)), _) => {
run_internal_command(left, ctx, input, scope)?
}
(None, _) => break,
};
}
Ok(input)
}

View File

@ -1,7 +1,7 @@
use derive_new::new; use derive_new::new;
use nu_parser::hir; use nu_protocol::hir;
#[derive(new, Debug, Eq, PartialEq)] #[derive(new, Debug)]
pub(crate) struct Command { pub(crate) struct Command {
pub(crate) args: hir::Call, pub(crate) args: hir::Call,
} }

View File

@ -0,0 +1,29 @@
use crate::evaluate::evaluate_baseline_expr;
use crate::prelude::*;
use log::{log_enabled, trace};
use nu_errors::ShellError;
use nu_protocol::hir::SpannedExpression;
use nu_protocol::Scope;
pub(crate) fn run_expression_block(
expr: SpannedExpression,
context: &mut Context,
input: InputStream,
scope: &Scope,
) -> Result<InputStream, ShellError> {
if log_enabled!(log::Level::Trace) {
trace!(target: "nu::run::expr", "->");
trace!(target: "nu::run::expr", "{:?}", expr);
}
let scope = scope.clone();
let registry = context.registry().clone();
let stream = input.map(move |row| {
let scope = scope.clone().set_it(row);
evaluate_baseline_expr(&expr, &registry, &scope)
});
Ok(stream.to_input_stream())
}

View File

@ -0,0 +1,682 @@
use crate::evaluate::evaluate_baseline_expr;
use crate::futures::ThreadedReceiver;
use crate::prelude::*;
use std::io::Write;
use std::ops::Deref;
use std::process::{Command, Stdio};
use std::sync::mpsc;
use bytes::{BufMut, Bytes, BytesMut};
use futures::executor::block_on_stream;
use futures::stream::StreamExt;
use futures_codec::FramedRead;
use log::trace;
use nu_errors::ShellError;
use nu_protocol::hir::ExternalCommand;
use nu_protocol::{Primitive, Scope, ShellTypeName, UntaggedValue, Value};
use nu_source::Tag;
pub enum StringOrBinary {
String(String),
Binary(Vec<u8>),
}
pub struct MaybeTextCodec;
impl futures_codec::Encoder for MaybeTextCodec {
type Item = StringOrBinary;
type Error = std::io::Error;
fn encode(&mut self, item: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error> {
match item {
StringOrBinary::String(s) => {
dst.reserve(s.len());
dst.put(s.as_bytes());
Ok(())
}
StringOrBinary::Binary(b) => {
dst.reserve(b.len());
dst.put(Bytes::from(b));
Ok(())
}
}
}
}
impl futures_codec::Decoder for MaybeTextCodec {
type Item = StringOrBinary;
type Error = std::io::Error;
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
let v: Vec<u8> = src.to_vec();
match String::from_utf8(v) {
Ok(s) => {
src.clear();
if s.is_empty() {
Ok(None)
} else {
Ok(Some(StringOrBinary::String(s)))
}
}
Err(err) => {
// Note: the longest UTF-8 character per Unicode spec is currently 6 bytes. If we fail somewhere earlier than the last 6 bytes,
// we know that we're failing to understand the string encoding and not just seeing a partial character. When this happens, let's
// fall back to assuming it's a binary buffer.
if src.is_empty() {
Ok(None)
} else if src.len() > 6 && (src.len() - err.utf8_error().valid_up_to() > 6) {
// Fall back to assuming binary
let buf = src.to_vec();
src.clear();
Ok(Some(StringOrBinary::Binary(buf)))
} else {
// Looks like a utf-8 string, so let's assume that
let buf = src.split_to(err.utf8_error().valid_up_to() + 1);
String::from_utf8(buf.to_vec())
.map(|x| Some(StringOrBinary::String(x)))
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
}
}
}
}
}
pub fn nu_value_to_string(name_tag: &Tag, from: &Value) -> Result<String, ShellError> {
match &from.value {
UntaggedValue::Primitive(Primitive::Int(i)) => Ok(i.to_string()),
UntaggedValue::Primitive(Primitive::String(s))
| UntaggedValue::Primitive(Primitive::Line(s)) => Ok(s.clone()),
UntaggedValue::Primitive(Primitive::Path(p)) => Ok(p.to_string_lossy().to_string()),
unsupported => Err(ShellError::labeled_error(
format!("needs string data (given: {})", unsupported.type_name()),
"expected a string",
name_tag,
)),
}
}
pub(crate) async fn run_external_command(
command: ExternalCommand,
context: &mut Context,
input: InputStream,
scope: &Scope,
is_last: bool,
) -> Result<InputStream, ShellError> {
trace!(target: "nu::run::external", "-> {}", command.name);
if !did_find_command(&command.name).await {
return Err(ShellError::labeled_error(
"Command not found",
"command not found",
&command.name_tag,
));
}
if command.has_it_argument() {
run_with_iterator_arg(command, context, input, scope, is_last)
} else {
run_with_stdin(command, context, input, scope, is_last)
}
}
fn run_with_iterator_arg(
command: ExternalCommand,
context: &mut Context,
input: InputStream,
scope: &Scope,
is_last: bool,
) -> Result<InputStream, ShellError> {
let path = context.shell_manager.path();
let mut inputs: InputStream =
trace_stream!(target: "nu::trace_stream::external::it", "input" = input);
let name_tag = command.name_tag.clone();
let scope = scope.clone();
let context = context.clone();
let stream = async_stream! {
while let Some(value) = inputs.next().await {
// Evaluate the expressions into values, and from values into strings for each iteration
let mut command_args = vec![];
let scope = scope.clone().set_it(value);
for arg in command.args.iter() {
let value = evaluate_baseline_expr(arg, &context.registry, &scope)?;
command_args.push(nu_value_to_string(&name_tag, &value)?);
}
let process_args = command_args
.iter()
.map(|arg| {
let arg = expand_tilde(arg.deref(), dirs::home_dir);
#[cfg(not(windows))]
{
if argument_contains_whitespace(&arg) && argument_is_quoted(&arg) {
if let Some(unquoted) = remove_quotes(&arg) {
format!(r#""{}""#, unquoted)
} else {
arg.as_ref().to_string()
}
} else {
arg.as_ref().to_string()
}
}
#[cfg(windows)]
{
if let Some(unquoted) = remove_quotes(&arg) {
unquoted.to_string()
} else {
arg.as_ref().to_string()
}
}
})
.collect::<Vec<String>>();
match spawn(&command, &path, &process_args[..], InputStream::empty(), is_last) {
Ok(mut res) => {
while let Some(item) = res.next().await {
yield Ok(item)
}
}
Err(reason) => {
yield Ok(Value {
value: UntaggedValue::Error(reason),
tag: name_tag
});
return;
}
}
}
};
Ok(stream.to_input_stream())
}
fn run_with_stdin(
command: ExternalCommand,
context: &mut Context,
input: InputStream,
scope: &Scope,
is_last: bool,
) -> Result<InputStream, ShellError> {
let path = context.shell_manager.path();
let input = trace_stream!(target: "nu::trace_stream::external::stdin", "input" = input);
let mut command_args = vec![];
for arg in command.args.iter() {
let value = evaluate_baseline_expr(arg, &context.registry, scope)?;
command_args.push(value.as_string()?);
}
let process_args = command_args
.iter()
.map(|arg| {
let arg = expand_tilde(arg.deref(), dirs::home_dir);
#[cfg(not(windows))]
{
if argument_contains_whitespace(&arg) && !argument_is_quoted(&arg) {
add_quotes(&arg)
} else {
arg.as_ref().to_string()
}
}
#[cfg(windows)]
{
if let Some(unquoted) = remove_quotes(&arg) {
unquoted.to_string()
} else {
arg.as_ref().to_string()
}
}
})
.collect::<Vec<String>>();
spawn(&command, &path, &process_args[..], input, is_last)
}
fn spawn(
command: &ExternalCommand,
path: &str,
args: &[String],
input: InputStream,
is_last: bool,
) -> Result<InputStream, ShellError> {
let command = command.clone();
let mut process = {
#[cfg(windows)]
{
let mut process = Command::new("cmd");
process.arg("/c");
process.arg(&command.name);
for arg in args {
// Clean the args before we use them:
let arg = arg.replace("|", "\\|");
process.arg(&arg);
}
process
}
#[cfg(not(windows))]
{
let cmd_with_args = vec![command.name.clone(), args.join(" ")].join(" ");
let mut process = Command::new("sh");
process.arg("-c").arg(cmd_with_args);
process
}
};
process.current_dir(path);
trace!(target: "nu::run::external", "cwd = {:?}", &path);
// We want stdout regardless of what
// we are doing ($it case or pipe stdin)
if !is_last {
process.stdout(Stdio::piped());
trace!(target: "nu::run::external", "set up stdout pipe");
}
// open since we have some contents for stdin
if !input.is_empty() {
process.stdin(Stdio::piped());
trace!(target: "nu::run::external", "set up stdin pipe");
}
trace!(target: "nu::run::external", "built command {:?}", process);
// TODO Switch to async_std::process once it's stabilized
if let Ok(mut child) = process.spawn() {
let (tx, rx) = mpsc::sync_channel(0);
let mut stdin = child.stdin.take();
let stdin_write_tx = tx.clone();
let stdout_read_tx = tx;
let stdin_name_tag = command.name_tag.clone();
let stdout_name_tag = command.name_tag;
std::thread::spawn(move || {
if !input.is_empty() {
let mut stdin_write = stdin
.take()
.expect("Internal error: could not get stdin pipe for external command");
for value in block_on_stream(input) {
match &value.value {
UntaggedValue::Primitive(Primitive::Nothing) => continue,
UntaggedValue::Primitive(Primitive::String(s))
| UntaggedValue::Primitive(Primitive::Line(s)) => {
if let Err(e) = stdin_write.write(s.as_bytes()) {
let message = format!("Unable to write to stdin (error = {})", e);
let _ = stdin_write_tx.send(Ok(Value {
value: UntaggedValue::Error(ShellError::labeled_error(
message,
"application may have closed before completing pipeline",
&stdin_name_tag,
)),
tag: stdin_name_tag,
}));
return Err(());
}
}
UntaggedValue::Primitive(Primitive::Binary(b)) => {
if let Err(e) = stdin_write.write(b) {
let message = format!("Unable to write to stdin (error = {})", e);
let _ = stdin_write_tx.send(Ok(Value {
value: UntaggedValue::Error(ShellError::labeled_error(
message,
"application may have closed before completing pipeline",
&stdin_name_tag,
)),
tag: stdin_name_tag,
}));
return Err(());
}
}
unsupported => {
let _ = stdin_write_tx.send(Ok(Value {
value: UntaggedValue::Error(ShellError::labeled_error(
format!(
"Received unexpected type from pipeline ({})",
unsupported.type_name()
),
"expected a string",
stdin_name_tag.clone(),
)),
tag: stdin_name_tag,
}));
return Err(());
}
};
}
}
Ok(())
});
std::thread::spawn(move || {
if !is_last {
let stdout = if let Some(stdout) = child.stdout.take() {
stdout
} else {
let _ = stdout_read_tx.send(Ok(Value {
value: UntaggedValue::Error(ShellError::labeled_error(
"Can't redirect the stdout for external command",
"can't redirect stdout",
&stdout_name_tag,
)),
tag: stdout_name_tag,
}));
return Err(());
};
let file = futures::io::AllowStdIo::new(stdout);
let stream = FramedRead::new(file, MaybeTextCodec);
for line in block_on_stream(stream) {
match line {
Ok(line) => match line {
StringOrBinary::String(s) => {
let result = stdout_read_tx.send(Ok(Value {
value: UntaggedValue::Primitive(Primitive::String(s.clone())),
tag: stdout_name_tag.clone(),
}));
if result.is_err() {
break;
}
}
StringOrBinary::Binary(b) => {
let result = stdout_read_tx.send(Ok(Value {
value: UntaggedValue::Primitive(Primitive::Binary(
b.into_iter().collect(),
)),
tag: stdout_name_tag.clone(),
}));
if result.is_err() {
break;
}
}
},
Err(_) => {
let _ = stdout_read_tx.send(Ok(Value {
value: UntaggedValue::Error(ShellError::labeled_error(
"Unable to read from stdout.",
"unable to read from stdout",
&stdout_name_tag,
)),
tag: stdout_name_tag.clone(),
}));
break;
}
}
}
}
// We can give an error when we see a non-zero exit code, but this is different
// than what other shells will do.
let external_failed = match child.wait() {
Err(_) => true,
Ok(exit_status) => match exit_status.code() {
Some(e) if e != 0 => true,
_ => false,
},
};
if external_failed {
let cfg = crate::data::config::config(Tag::unknown());
if let Ok(cfg) = cfg {
if cfg.contains_key("nonzero_exit_errors") {
let _ = stdout_read_tx.send(Ok(Value {
value: UntaggedValue::Error(ShellError::labeled_error(
"External command failed",
"command failed",
&stdout_name_tag,
)),
tag: stdout_name_tag.clone(),
}));
}
}
let _ = stdout_read_tx.send(Ok(Value {
value: UntaggedValue::Error(ShellError::external_non_zero()),
tag: stdout_name_tag,
}));
}
Ok(())
});
let stream = ThreadedReceiver::new(rx);
Ok(stream.to_input_stream())
} else {
Err(ShellError::labeled_error(
"Failed to spawn process",
"failed to spawn",
&command.name_tag,
))
}
}
async fn did_find_command(name: &str) -> bool {
#[cfg(not(windows))]
{
ichwh::which(name).await.unwrap_or(None).is_some()
}
#[cfg(windows)]
{
if ichwh::which(name).await.unwrap_or(None).is_some() {
true
} else {
let cmd_builtins = [
"call", "cls", "color", "date", "dir", "echo", "find", "hostname", "pause",
"start", "time", "title", "ver", "copy", "mkdir", "rename", "rd", "rmdir", "type",
"mklink",
];
cmd_builtins.contains(&name)
}
}
}
fn expand_tilde<SI: ?Sized, P, HD>(input: &SI, home_dir: HD) -> std::borrow::Cow<str>
where
SI: AsRef<str>,
P: AsRef<std::path::Path>,
HD: FnOnce() -> Option<P>,
{
shellexpand::tilde_with_context(input, home_dir)
}
#[allow(unused)]
pub fn argument_contains_whitespace(argument: &str) -> bool {
argument.chars().any(|c| c.is_whitespace())
}
fn argument_is_quoted(argument: &str) -> bool {
if argument.len() < 2 {
return false;
}
(argument.starts_with('"') && argument.ends_with('"'))
|| (argument.starts_with('\'') && argument.ends_with('\''))
}
#[allow(unused)]
fn add_quotes(argument: &str) -> String {
format!("\"{}\"", argument)
}
fn remove_quotes(argument: &str) -> Option<&str> {
if !argument_is_quoted(argument) {
return None;
}
let size = argument.len();
Some(&argument[1..size - 1])
}
#[allow(unused)]
fn shell_os_paths() -> Vec<std::path::PathBuf> {
let mut original_paths = vec![];
if let Some(paths) = std::env::var_os("PATH") {
original_paths = std::env::split_paths(&paths).collect::<Vec<_>>();
}
original_paths
}
#[cfg(test)]
mod tests {
use super::{
add_quotes, argument_contains_whitespace, argument_is_quoted, expand_tilde, remove_quotes,
run_external_command, Context, InputStream,
};
use futures::executor::block_on;
use nu_errors::ShellError;
use nu_protocol::Scope;
use nu_test_support::commands::ExternalBuilder;
// async fn read(mut stream: OutputStream) -> Option<Value> {
// match stream.try_next().await {
// Ok(val) => {
// if let Some(val) = val {
// val.raw_value()
// } else {
// None
// }
// }
// Err(_) => None,
// }
// }
async fn non_existent_run() -> Result<(), ShellError> {
let cmd = ExternalBuilder::for_name("i_dont_exist.exe").build();
let input = InputStream::empty();
let mut ctx = Context::basic().expect("There was a problem creating a basic context.");
assert!(
run_external_command(cmd, &mut ctx, input, &Scope::empty(), false)
.await
.is_err()
);
Ok(())
}
// async fn failure_run() -> Result<(), ShellError> {
// let cmd = ExternalBuilder::for_name("fail").build();
// let mut ctx = Context::basic().expect("There was a problem creating a basic context.");
// let stream = run_external_command(cmd, &mut ctx, None, false)
// .await?
// .expect("There was a problem running the external command.");
// match read(stream.into()).await {
// Some(Value {
// value: UntaggedValue::Error(_),
// ..
// }) => {}
// None | _ => panic!("Command didn't fail."),
// }
// Ok(())
// }
// #[test]
// fn identifies_command_failed() -> Result<(), ShellError> {
// block_on(failure_run())
// }
#[test]
fn identifies_command_not_found() -> Result<(), ShellError> {
block_on(non_existent_run())
}
#[test]
fn checks_contains_whitespace_from_argument_to_be_passed_in() {
assert_eq!(argument_contains_whitespace("andrés"), false);
assert_eq!(argument_contains_whitespace("and rés"), true);
assert_eq!(argument_contains_whitespace(r#"and\ rés"#), true);
}
#[test]
fn checks_quotes_from_argument_to_be_passed_in() {
assert_eq!(argument_is_quoted(""), false);
assert_eq!(argument_is_quoted("'"), false);
assert_eq!(argument_is_quoted("'a"), false);
assert_eq!(argument_is_quoted("a"), false);
assert_eq!(argument_is_quoted("a'"), false);
assert_eq!(argument_is_quoted("''"), true);
assert_eq!(argument_is_quoted(r#"""#), false);
assert_eq!(argument_is_quoted(r#""a"#), false);
assert_eq!(argument_is_quoted(r#"a"#), false);
assert_eq!(argument_is_quoted(r#"a""#), false);
assert_eq!(argument_is_quoted(r#""""#), true);
assert_eq!(argument_is_quoted("'andrés"), false);
assert_eq!(argument_is_quoted("andrés'"), false);
assert_eq!(argument_is_quoted(r#""andrés"#), false);
assert_eq!(argument_is_quoted(r#"andrés""#), false);
assert_eq!(argument_is_quoted("'andrés'"), true);
assert_eq!(argument_is_quoted(r#""andrés""#), true);
}
#[test]
fn adds_quotes_to_argument_to_be_passed_in() {
assert_eq!(add_quotes("andrés"), "\"andrés\"");
//assert_eq!(add_quotes("\"andrés\""), "\"andrés\"");
}
#[test]
fn strips_quotes_from_argument_to_be_passed_in() {
assert_eq!(remove_quotes(""), None);
assert_eq!(remove_quotes("'"), None);
assert_eq!(remove_quotes("'a"), None);
assert_eq!(remove_quotes("a"), None);
assert_eq!(remove_quotes("a'"), None);
assert_eq!(remove_quotes("''"), Some(""));
assert_eq!(remove_quotes(r#"""#), None);
assert_eq!(remove_quotes(r#""a"#), None);
assert_eq!(remove_quotes(r#"a"#), None);
assert_eq!(remove_quotes(r#"a""#), None);
assert_eq!(remove_quotes(r#""""#), Some(""));
assert_eq!(remove_quotes("'andrés"), None);
assert_eq!(remove_quotes("andrés'"), None);
assert_eq!(remove_quotes(r#""andrés"#), None);
assert_eq!(remove_quotes(r#"andrés""#), None);
assert_eq!(remove_quotes("'andrés'"), Some("andrés"));
assert_eq!(remove_quotes(r#""andrés""#), Some("andrés"));
}
#[test]
fn expands_tilde_if_starts_with_tilde_character() {
assert_eq!(
expand_tilde("~", || Some(std::path::Path::new("the_path_to_nu_light"))),
"the_path_to_nu_light"
);
}
#[test]
fn does_not_expand_tilde_if_tilde_is_not_first_character() {
assert_eq!(
expand_tilde("1~1", || Some(std::path::Path::new("the_path_to_nu_light"))),
"1~1"
);
}
}

View File

@ -1,42 +1,37 @@
use crate::commands::command::per_item_command;
use crate::commands::run_alias::AliasCommand;
use crate::commands::UnevaluatedCallInfo; use crate::commands::UnevaluatedCallInfo;
use crate::prelude::*; use crate::prelude::*;
use log::{log_enabled, trace}; use log::{log_enabled, trace};
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_parser::InternalCommand; use nu_protocol::hir::InternalCommand;
use nu_protocol::{CommandAction, Primitive, ReturnSuccess, UntaggedValue, Value}; use nu_protocol::{CommandAction, Primitive, ReturnSuccess, Scope, UntaggedValue, Value};
pub(crate) async fn run_internal_command( pub(crate) fn run_internal_command(
command: InternalCommand, command: InternalCommand,
context: &mut Context, context: &mut Context,
input: Option<InputStream>, input: InputStream,
source: Text, scope: &Scope,
) -> Result<Option<InputStream>, ShellError> { ) -> Result<InputStream, ShellError> {
if log_enabled!(log::Level::Trace) { if log_enabled!(log::Level::Trace) {
trace!(target: "nu::run::internal", "->"); trace!(target: "nu::run::internal", "->");
trace!(target: "nu::run::internal", "{}", command.name); trace!(target: "nu::run::internal", "{}", command.name);
trace!(target: "nu::run::internal", "{}", command.args.debug(&source));
} }
let objects: InputStream = if let Some(input) = input { let objects: InputStream = trace_stream!(target: "nu::trace_stream::internal", "input" = input);
trace_stream!(target: "nu::trace_stream::internal", "input" = input)
} else {
InputStream::empty()
};
let internal_command = context.expect_command(&command.name); let internal_command = context.expect_command(&command.name);
let result = { let result = {
context.run_command( context.run_command(
internal_command?, internal_command?,
command.name_tag.clone(), Tag::unknown_anchor(command.name_span),
command.args.clone(), command.args.clone(),
&source, scope,
objects, objects,
) )
}; };
let result = trace_out_stream!(target: "nu::trace_stream::internal", "output" = result); let mut result = trace_out_stream!(target: "nu::trace_stream::internal", "output" = result);
let mut result = result.values;
let mut context = context.clone(); let mut context = context.clone();
let stream = async_stream! { let stream = async_stream! {
@ -64,14 +59,15 @@ pub(crate) async fn run_internal_command(
ctrl_c: context.ctrl_c.clone(), ctrl_c: context.ctrl_c.clone(),
shell_manager: context.shell_manager.clone(), shell_manager: context.shell_manager.clone(),
call_info: UnevaluatedCallInfo { call_info: UnevaluatedCallInfo {
args: nu_parser::hir::Call { args: nu_protocol::hir::Call {
head: command.args.head, head: command.args.head,
positional: None, positional: None,
named: None, named: None,
span: Span::unknown() span: Span::unknown(),
is_last: false,
}, },
source: source.clone(), name_tag: Tag::unknown_anchor(command.name_span),
name_tag: command.name_tag, scope: Scope::empty(),
} }
}; };
let mut result = converter.run(new_args.with_input(vec![tagged_contents]), &context.registry); let mut result = converter.run(new_args.with_input(vec![tagged_contents]), &context.registry);
@ -124,6 +120,15 @@ pub(crate) async fn run_internal_command(
FilesystemShell::with_location(location, context.registry().clone()), FilesystemShell::with_location(location, context.registry().clone()),
)); ));
} }
CommandAction::AddAlias(name, args, block) => {
context.add_commands(vec![
per_item_command(AliasCommand::new(
name,
args,
block,
))
]);
}
CommandAction::PreviousShell => { CommandAction::PreviousShell => {
context.shell_manager.prev(); context.shell_manager.prev();
} }
@ -142,7 +147,8 @@ pub(crate) async fn run_internal_command(
value: UntaggedValue::Error(err), value: UntaggedValue::Error(err),
.. ..
})) => { })) => {
context.error(err); context.error(err.clone());
yield Err(err);
break; break;
} }
@ -175,5 +181,5 @@ pub(crate) async fn run_internal_command(
} }
}; };
Ok(Some(stream.to_input_stream())) Ok(stream.to_input_stream())
} }

View File

@ -1,7 +1,8 @@
pub(crate) mod block;
mod dynamic; mod dynamic;
pub(crate) mod expr;
pub(crate) mod external; pub(crate) mod external;
pub(crate) mod internal; pub(crate) mod internal;
pub(crate) mod pipeline;
#[allow(unused_imports)] #[allow(unused_imports)]
pub(crate) use dynamic::Command as DynamicCommand; pub(crate) use dynamic::Command as DynamicCommand;

View File

@ -41,7 +41,7 @@ pub mod clipboard {
RunnableContext { input, name, .. }: RunnableContext, RunnableContext { input, name, .. }: RunnableContext,
) -> Result<OutputStream, ShellError> { ) -> Result<OutputStream, ShellError> {
let stream = async_stream! { let stream = async_stream! {
let values: Vec<Value> = input.values.collect().await; let values: Vec<Value> = input.collect().await;
let mut clip_stream = inner_clip(values, name).await; let mut clip_stream = inner_clip(values, name).await;
while let Some(value) = clip_stream.next().await { while let Some(value) = clip_stream.next().await {

View File

@ -6,7 +6,7 @@ use crate::prelude::*;
use derive_new::new; use derive_new::new;
use getset::Getters; use getset::Getters;
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_parser::hir; use nu_protocol::hir;
use nu_protocol::{CallInfo, EvaluatedArgs, ReturnValue, Scope, Signature, Value}; use nu_protocol::{CallInfo, EvaluatedArgs, ReturnValue, Scope, Signature, Value};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::ops::Deref; use std::ops::Deref;
@ -15,17 +15,28 @@ use std::sync::atomic::AtomicBool;
#[derive(Deserialize, Serialize, Debug, Clone)] #[derive(Deserialize, Serialize, Debug, Clone)]
pub struct UnevaluatedCallInfo { pub struct UnevaluatedCallInfo {
pub args: hir::Call, pub args: hir::Call,
pub source: Text,
pub name_tag: Tag, pub name_tag: Tag,
pub scope: Scope,
} }
impl UnevaluatedCallInfo { impl UnevaluatedCallInfo {
pub fn evaluate( pub fn evaluate(self, registry: &CommandRegistry) -> Result<CallInfo, ShellError> {
let args = evaluate_args(&self.args, registry, &self.scope)?;
Ok(CallInfo {
args,
name_tag: self.name_tag,
})
}
pub fn evaluate_with_new_it(
self, self,
registry: &CommandRegistry, registry: &CommandRegistry,
scope: &Scope, it: &Value,
) -> Result<CallInfo, ShellError> { ) -> Result<CallInfo, ShellError> {
let args = evaluate_args(&self.args, registry, scope, &self.source)?; let mut scope = self.scope.clone();
scope = scope.set_it(it.clone());
let args = evaluate_args(&self.args, registry, &scope)?;
Ok(CallInfo { Ok(CallInfo {
args, args,
@ -114,7 +125,7 @@ impl CommandArgs {
let ctrl_c = self.ctrl_c.clone(); let ctrl_c = self.ctrl_c.clone();
let shell_manager = self.shell_manager.clone(); let shell_manager = self.shell_manager.clone();
let input = self.input; let input = self.input;
let call_info = self.call_info.evaluate(registry, &Scope::empty())?; let call_info = self.call_info.evaluate(registry)?;
Ok(EvaluatedWholeStreamCommandArgs::new( Ok(EvaluatedWholeStreamCommandArgs::new(
host, host,
@ -134,7 +145,12 @@ impl CommandArgs {
let ctrl_c = self.ctrl_c.clone(); let ctrl_c = self.ctrl_c.clone();
let shell_manager = self.shell_manager.clone(); let shell_manager = self.shell_manager.clone();
let input = self.input; let input = self.input;
let call_info = self.call_info.evaluate(registry, scope)?; let call_info = UnevaluatedCallInfo {
name_tag: self.call_info.name_tag,
args: self.call_info.args,
scope: scope.clone(),
};
let call_info = call_info.evaluate(registry)?;
Ok(EvaluatedWholeStreamCommandArgs::new( Ok(EvaluatedWholeStreamCommandArgs::new(
host, host,
@ -145,10 +161,6 @@ impl CommandArgs {
)) ))
} }
pub fn source(&self) -> Text {
self.call_info.source.clone()
}
pub fn process<'de, T: Deserialize<'de>, O: ToOutputStream>( pub fn process<'de, T: Deserialize<'de>, O: ToOutputStream>(
self, self,
registry: &CommandRegistry, registry: &CommandRegistry,
@ -156,7 +168,6 @@ impl CommandArgs {
) -> Result<RunnableArgs<T, O>, ShellError> { ) -> Result<RunnableArgs<T, O>, ShellError> {
let shell_manager = self.shell_manager.clone(); let shell_manager = self.shell_manager.clone();
let host = self.host.clone(); let host = self.host.clone();
let source = self.source();
let ctrl_c = self.ctrl_c.clone(); let ctrl_c = self.ctrl_c.clone();
let args = self.evaluate_once(registry)?; let args = self.evaluate_once(registry)?;
let call_info = args.call_info.clone(); let call_info = args.call_info.clone();
@ -168,8 +179,7 @@ impl CommandArgs {
args: T::deserialize(&mut deserializer)?, args: T::deserialize(&mut deserializer)?,
context: RunnableContext { context: RunnableContext {
input, input,
commands: registry.clone(), registry: registry.clone(),
source,
shell_manager, shell_manager,
name: name_tag, name: name_tag,
host, host,
@ -193,7 +203,6 @@ impl CommandArgs {
let shell_manager = self.shell_manager.clone(); let shell_manager = self.shell_manager.clone();
let host = self.host.clone(); let host = self.host.clone();
let source = self.source();
let ctrl_c = self.ctrl_c.clone(); let ctrl_c = self.ctrl_c.clone();
let args = self.evaluate_once(registry)?; let args = self.evaluate_once(registry)?;
let call_info = args.call_info.clone(); let call_info = args.call_info.clone();
@ -206,8 +215,7 @@ impl CommandArgs {
args: T::deserialize(&mut deserializer)?, args: T::deserialize(&mut deserializer)?,
context: RunnableContext { context: RunnableContext {
input, input,
commands: registry.clone(), registry: registry.clone(),
source,
shell_manager, shell_manager,
name: name_tag, name: name_tag,
host, host,
@ -229,15 +237,14 @@ pub struct RunnableContext {
pub input: InputStream, pub input: InputStream,
pub shell_manager: ShellManager, pub shell_manager: ShellManager,
pub host: Arc<parking_lot::Mutex<Box<dyn Host>>>, pub host: Arc<parking_lot::Mutex<Box<dyn Host>>>,
pub source: Text,
pub ctrl_c: Arc<AtomicBool>, pub ctrl_c: Arc<AtomicBool>,
pub commands: CommandRegistry, pub registry: CommandRegistry,
pub name: Tag, pub name: Tag,
} }
impl RunnableContext { impl RunnableContext {
pub fn get_command(&self, name: &str) -> Option<Arc<Command>> { pub fn get_command(&self, name: &str) -> Option<Arc<Command>> {
self.commands.get_command(name) self.registry.get_command(name)
} }
} }
@ -374,6 +381,14 @@ impl EvaluatedCommandArgs {
self.call_info.args.nth(pos) self.call_info.args.nth(pos)
} }
/// Get the nth positional argument, error if not possible
pub fn expect_nth(&self, pos: usize) -> Result<&Value, ShellError> {
match self.call_info.args.nth(pos) {
None => Err(ShellError::unimplemented("Better error: expect_nth")),
Some(item) => Ok(item),
}
}
pub fn get(&self, name: &str) -> Option<&Value> { pub fn get(&self, name: &str) -> Option<&Value> {
self.call_info.args.get(name) self.call_info.args.get(name)
} }
@ -515,12 +530,17 @@ impl Command {
let out = args let out = args
.input .input
.values
.map(move |x| { .map(move |x| {
let call_info = raw_args let call_info = UnevaluatedCallInfo {
.clone() args: raw_args.call_info.args.clone(),
.call_info name_tag: raw_args.call_info.name_tag.clone(),
.evaluate(&registry, &Scope::it_value(x.clone())); scope: raw_args.call_info.scope.clone().set_it(x.clone()),
}
.evaluate(&registry);
// let call_info = raw_args
// .clone()
// .call_info
// .evaluate(&registry, &Scope::it_value(x.clone()));
match call_info { match call_info {
Ok(call_info) => match command.run(&call_info, &registry, &raw_args, x) { Ok(call_info) => match command.run(&call_info, &registry, &raw_args, x) {
@ -576,9 +596,9 @@ impl WholeStreamCommand for FnFilterCommand {
let registry: CommandRegistry = registry.clone(); let registry: CommandRegistry = registry.clone();
let func = self.func; let func = self.func;
let result = input.values.map(move |it| { let result = input.map(move |it| {
let registry = registry.clone(); let registry = registry.clone();
let call_info = match call_info.clone().evaluate(&registry, &Scope::it_value(it)) { let call_info = match call_info.clone().evaluate_with_new_it(&registry, &it) {
Err(err) => return OutputStream::from(vec![Err(err)]).values, Err(err) => return OutputStream::from(vec![Err(err)]).values,
Ok(args) => args, Ok(args) => args,
}; };

View File

@ -39,7 +39,7 @@ pub fn compact(
CompactArgs { rest: columns }: CompactArgs, CompactArgs { rest: columns }: CompactArgs,
RunnableContext { input, .. }: RunnableContext, RunnableContext { input, .. }: RunnableContext,
) -> Result<OutputStream, ShellError> { ) -> Result<OutputStream, ShellError> {
let objects = input.values.filter(move |item| { let objects = input.filter(move |item| {
let keep = if columns.is_empty() { let keep = if columns.is_empty() {
item.is_some() item.is_some()
} else { } else {

View File

@ -41,7 +41,7 @@ impl WholeStreamCommand for Config {
) )
.named( .named(
"set_into", "set_into",
SyntaxShape::Member, SyntaxShape::String,
"sets a variable from values in the pipeline", "sets a variable from values in the pipeline",
Some('i'), Some('i'),
) )
@ -124,7 +124,7 @@ pub fn config(
yield ReturnSuccess::value(UntaggedValue::Row(result.into()).into_value(&value.tag)); yield ReturnSuccess::value(UntaggedValue::Row(result.into()).into_value(&value.tag));
} }
else if let Some(v) = set_into { else if let Some(v) = set_into {
let rows: Vec<Value> = input.values.collect().await; let rows: Vec<Value> = input.collect().await;
let key = v.to_string(); let key = v.to_string();
if rows.len() == 0 { if rows.len() == 0 {

View File

@ -37,7 +37,7 @@ pub fn count(
RunnableContext { input, name, .. }: RunnableContext, RunnableContext { input, name, .. }: RunnableContext,
) -> Result<OutputStream, ShellError> { ) -> Result<OutputStream, ShellError> {
let stream = async_stream! { let stream = async_stream! {
let rows: Vec<Value> = input.values.collect().await; let rows: Vec<Value> = input.collect().await;
yield ReturnSuccess::value(UntaggedValue::int(rows.len()).into_value(name)) yield ReturnSuccess::value(UntaggedValue::int(rows.len()).into_value(name))
}; };

View File

@ -37,7 +37,6 @@ fn debug_value(
RunnableContext { input, .. }: RunnableContext, RunnableContext { input, .. }: RunnableContext,
) -> Result<impl ToOutputStream, ShellError> { ) -> Result<impl ToOutputStream, ShellError> {
Ok(input Ok(input
.values
.map(move |v| { .map(move |v| {
if raw { if raw {
ReturnSuccess::value( ReturnSuccess::value(

View File

@ -47,7 +47,6 @@ fn default(
RunnableContext { input, .. }: RunnableContext, RunnableContext { input, .. }: RunnableContext,
) -> Result<OutputStream, ShellError> { ) -> Result<OutputStream, ShellError> {
let stream = input let stream = input
.values
.map(move |item| { .map(move |item| {
let mut result = VecDeque::new(); let mut result = VecDeque::new();

View File

@ -9,7 +9,6 @@ use nu_errors::ShellError;
use nu_protocol::{CallInfo, ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value}; use nu_protocol::{CallInfo, ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value};
use nu_source::Tagged; use nu_source::Tagged;
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::atomic::Ordering;
const NAME: &str = "du"; const NAME: &str = "du";
const GLOB_PARAMS: MatchOptions = MatchOptions { const GLOB_PARAMS: MatchOptions = MatchOptions {
@ -42,7 +41,7 @@ impl PerItemCommand for Du {
.optional("path", SyntaxShape::Pattern, "starting directory") .optional("path", SyntaxShape::Pattern, "starting directory")
.switch( .switch(
"all", "all",
"Output File sizes as well as directory sizes", "Output file sizes as well as directory sizes",
Some('a'), Some('a'),
) )
.switch( .switch(
@ -90,51 +89,33 @@ impl PerItemCommand for Du {
fn du(args: DuArgs, ctx: &RunnablePerItemContext) -> Result<OutputStream, ShellError> { fn du(args: DuArgs, ctx: &RunnablePerItemContext) -> Result<OutputStream, ShellError> {
let tag = ctx.name.clone(); let tag = ctx.name.clone();
let exclude = args let exclude = args.exclude.map_or(Ok(None), move |x| {
.exclude Pattern::new(&x.item)
.clone() .map(Option::Some)
.map_or(Ok(None), move |x| match Pattern::new(&x.item) { .map_err(|e| ShellError::labeled_error(e.msg, "glob error", x.tag.clone()))
Ok(p) => Ok(Some(p)),
Err(e) => Err(ShellError::labeled_error(
e.msg,
"Glob error",
x.tag.clone(),
)),
})?; })?;
let path = args.path.clone();
let filter_files = path.is_none(); let include_files = args.all;
let paths = match path { let paths = match args.path {
Some(p) => match glob::glob_with( Some(p) => {
p.item.to_str().expect("Why isn't this encoded properly?"), let p = p.item.to_str().expect("Why isn't this encoded properly?");
GLOB_PARAMS, glob::glob_with(p, GLOB_PARAMS)
) { }
Ok(g) => Ok(g), None => glob::glob_with("*", GLOB_PARAMS),
Err(e) => Err(ShellError::labeled_error( }
e.msg, .map_err(|e| ShellError::labeled_error(e.msg, "glob error", tag.clone()))?
"Glob error",
p.tag.clone(),
)),
},
None => match glob::glob_with("*", GLOB_PARAMS) {
Ok(g) => Ok(g),
Err(e) => Err(ShellError::labeled_error(e.msg, "Glob error", tag.clone())),
},
}?
.filter(move |p| { .filter(move |p| {
if filter_files { if include_files {
true
} else {
match p { match p {
Ok(f) if f.is_dir() => true, Ok(f) if f.is_dir() => true,
Err(e) if e.path().is_dir() => true, Err(e) if e.path().is_dir() => true,
_ => false, _ => false,
} }
} else {
true
} }
}) })
.map(move |p| match p { .map(|v| v.map_err(glob_err_into));
Err(e) => Err(glob_err_into(e)),
Ok(s) => Ok(s),
});
let ctrl_c = ctx.ctrl_c.clone(); let ctrl_c = ctx.ctrl_c.clone();
let all = args.all; let all = args.all;
@ -142,35 +123,29 @@ fn du(args: DuArgs, ctx: &RunnablePerItemContext) -> Result<OutputStream, ShellE
let max_depth = args.max_depth.map(|f| f.item); let max_depth = args.max_depth.map(|f| f.item);
let min_size = args.min_size.map(|f| f.item); let min_size = args.min_size.map(|f| f.item);
let stream = async_stream! {
let params = DirBuilder { let params = DirBuilder {
tag: tag.clone(), tag: tag.clone(),
min: min_size, min: min_size,
deref, deref,
ex: exclude, exclude,
all, all,
}; };
for path in paths {
if ctrl_c.load(Ordering::SeqCst) { let stream = futures::stream::iter(paths)
break; .interruptible(ctrl_c)
} .map(move |path| match path {
match path {
Ok(p) => { Ok(p) => {
if p.is_dir() { if p.is_dir() {
yield Ok(ReturnSuccess::Value( Ok(ReturnSuccess::Value(
DirInfo::new(p, &params, max_depth).into(), DirInfo::new(p, &params, max_depth).into(),
)); ))
} else { } else {
match FileInfo::new(p, deref, tag.clone()) { FileInfo::new(p, deref, tag.clone()).map(|v| ReturnSuccess::Value(v.into()))
Ok(f) => yield Ok(ReturnSuccess::Value(f.into())),
Err(e) => yield Err(e)
} }
} }
} Err(e) => Err(e),
Err(e) => yield Err(e), });
}
}
};
Ok(stream.to_output_stream()) Ok(stream.to_output_stream())
} }
@ -178,7 +153,7 @@ struct DirBuilder {
tag: Tag, tag: Tag,
min: Option<u64>, min: Option<u64>,
deref: bool, deref: bool,
ex: Option<Pattern>, exclude: Option<Pattern>,
all: bool, all: bool,
} }
@ -243,15 +218,11 @@ impl DirInfo {
for f in d { for f in d {
match f { match f {
Ok(i) => match i.file_type() { Ok(i) => match i.file_type() {
Ok(t) if t.is_dir() => { Ok(t) if t.is_dir() => s = s.add_dir(i.path(), depth, &params),
s = s.add_dir(i.path(), depth, &params); Ok(_t) => s = s.add_file(i.path(), &params),
} Err(e) => s = s.add_error(e.into()),
Ok(_t) => {
s = s.add_file(i.path(), &params);
}
Err(e) => s = s.add_error(ShellError::from(e)),
}, },
Err(e) => s = s.add_error(ShellError::from(e)), Err(e) => s = s.add_error(e.into()),
} }
} }
} }
@ -283,8 +254,11 @@ impl DirInfo {
fn add_file(mut self, f: impl Into<PathBuf>, params: &DirBuilder) -> Self { fn add_file(mut self, f: impl Into<PathBuf>, params: &DirBuilder) -> Self {
let f = f.into(); let f = f.into();
let ex = params.ex.as_ref().map_or(false, |x| x.matches_path(&f)); let include = params
if !ex { .exclude
.as_ref()
.map_or(true, |x| !x.matches_path(&f));
if include {
match FileInfo::new(f, params.deref, self.tag.clone()) { match FileInfo::new(f, params.deref, self.tag.clone()) {
Ok(file) => { Ok(file) => {
let inc = params.min.map_or(true, |s| file.size >= s); let inc = params.min.map_or(true, |s| file.size >= s);
@ -313,55 +287,51 @@ fn glob_err_into(e: GlobError) -> ShellError {
ShellError::from(e) ShellError::from(e)
} }
fn value_from_vec<V>(vec: Vec<V>, tag: &Tag) -> Value
where
V: Into<Value>,
{
if vec.is_empty() {
UntaggedValue::nothing()
} else {
let values = vec.into_iter().map(Into::into).collect::<Vec<Value>>();
UntaggedValue::Table(values)
}
.retag(tag)
}
impl From<DirInfo> for Value { impl From<DirInfo> for Value {
fn from(d: DirInfo) -> Self { fn from(d: DirInfo) -> Self {
let mut r: IndexMap<String, Value> = IndexMap::new(); let mut r: IndexMap<String, Value> = IndexMap::new();
r.insert( r.insert(
"path".to_string(), "path".to_string(),
UntaggedValue::path(d.path).retag(d.tag.clone()), UntaggedValue::path(d.path).retag(&d.tag),
); );
r.insert( r.insert(
"apparent".to_string(), "apparent".to_string(),
UntaggedValue::bytes(d.size).retag(d.tag.clone()), UntaggedValue::bytes(d.size).retag(&d.tag),
); );
r.insert( r.insert(
"physical".to_string(), "physical".to_string(),
UntaggedValue::bytes(d.blocks).retag(d.tag.clone()), UntaggedValue::bytes(d.blocks).retag(&d.tag),
); );
if !d.files.is_empty() {
let v = Value { r.insert("directories".to_string(), value_from_vec(d.dirs, &d.tag));
value: UntaggedValue::Table(
d.files r.insert("files".to_string(), value_from_vec(d.files, &d.tag));
.into_iter()
.map(move |f| f.into())
.collect::<Vec<Value>>(),
),
tag: d.tag.clone(),
};
r.insert("files".to_string(), v);
}
if !d.dirs.is_empty() {
let v = Value {
value: UntaggedValue::Table(
d.dirs
.into_iter()
.map(move |d| d.into())
.collect::<Vec<Value>>(),
),
tag: d.tag.clone(),
};
r.insert("directories".to_string(), v);
}
if !d.errors.is_empty() { if !d.errors.is_empty() {
let v = Value { let v = UntaggedValue::Table(
value: UntaggedValue::Table(
d.errors d.errors
.into_iter() .into_iter()
.map(move |e| UntaggedValue::Error(e).into_untagged_value()) .map(move |e| UntaggedValue::Error(e).into_untagged_value())
.collect::<Vec<Value>>(), .collect::<Vec<Value>>(),
), )
tag: d.tag.clone(), .retag(&d.tag);
};
r.insert("errors".to_string(), v); r.insert("errors".to_string(), v);
} }
@ -375,22 +345,32 @@ impl From<DirInfo> for Value {
impl From<FileInfo> for Value { impl From<FileInfo> for Value {
fn from(f: FileInfo) -> Self { fn from(f: FileInfo) -> Self {
let mut r: IndexMap<String, Value> = IndexMap::new(); let mut r: IndexMap<String, Value> = IndexMap::new();
r.insert( r.insert(
"path".to_string(), "path".to_string(),
UntaggedValue::path(f.path).retag(f.tag.clone()), UntaggedValue::path(f.path).retag(&f.tag),
); );
r.insert( r.insert(
"apparent".to_string(), "apparent".to_string(),
UntaggedValue::bytes(f.size).retag(f.tag.clone()), UntaggedValue::bytes(f.size).retag(&f.tag),
); );
let b = match f.blocks {
Some(k) => UntaggedValue::bytes(k).retag(f.tag.clone()), let b = f
None => UntaggedValue::nothing().retag(f.tag.clone()), .blocks
}; .map(UntaggedValue::bytes)
.unwrap_or_else(UntaggedValue::nothing)
.retag(&f.tag);
r.insert("physical".to_string(), b); r.insert("physical".to_string(), b);
Value {
value: UntaggedValue::row(r), r.insert(
tag: f.tag, "directories".to_string(),
} UntaggedValue::nothing().retag(&f.tag),
);
r.insert("files".to_string(), UntaggedValue::nothing().retag(&f.tag));
UntaggedValue::row(r).retag(&f.tag)
} }
} }

View File

@ -0,0 +1,86 @@
use crate::commands::classified::block::run_block;
use crate::commands::PerItemCommand;
use crate::context::CommandRegistry;
use crate::prelude::*;
use futures::stream::once;
use nu_errors::ShellError;
use nu_protocol::{CallInfo, ReturnSuccess, Scope, Signature, SyntaxShape, UntaggedValue, Value};
pub struct Each;
impl PerItemCommand for Each {
fn name(&self) -> &str {
"each"
}
fn signature(&self) -> Signature {
Signature::build("each").required(
"block",
SyntaxShape::Block,
"the block to run on each row",
)
}
fn usage(&self) -> &str {
"Run a block on each row of the table."
}
fn run(
&self,
call_info: &CallInfo,
registry: &CommandRegistry,
raw_args: &RawCommandArgs,
input: Value,
) -> Result<OutputStream, ShellError> {
let call_info = call_info.clone();
let registry = registry.clone();
let raw_args = raw_args.clone();
let stream = async_stream! {
match call_info.args.expect_nth(0)? {
Value {
value: UntaggedValue::Block(block),
tag
} => {
let mut context = Context::from_raw(&raw_args, &registry);
let input_clone = input.clone();
let input_stream = once(async { Ok(input) }).to_input_stream();
let result = run_block(
block,
&mut context,
input_stream,
&Scope::new(input_clone),
).await;
match result {
Ok(mut stream) => {
let errors = context.get_errors();
if let Some(error) = errors.first() {
yield Err(error.clone());
return;
}
while let Some(result) = stream.next().await {
yield Ok(ReturnSuccess::Value(result));
}
}
Err(e) => {
yield Err(e);
}
}
}
Value { tag, .. } => {
yield Err(ShellError::labeled_error(
"Expected a block",
"each needs a block",
tag,
))
}
};
};
Ok(stream.to_output_stream())
}
}

View File

@ -97,14 +97,15 @@ impl PerItemCommand for Enter {
ctrl_c: raw_args.ctrl_c, ctrl_c: raw_args.ctrl_c,
shell_manager: raw_args.shell_manager, shell_manager: raw_args.shell_manager,
call_info: UnevaluatedCallInfo { call_info: UnevaluatedCallInfo {
args: nu_parser::hir::Call { args: nu_protocol::hir::Call {
head: raw_args.call_info.args.head, head: raw_args.call_info.args.head,
positional: None, positional: None,
named: None, named: None,
span: Span::unknown() span: Span::unknown(),
is_last: false,
}, },
source: raw_args.call_info.source,
name_tag: raw_args.call_info.name_tag, name_tag: raw_args.call_info.name_tag,
scope: raw_args.call_info.scope.clone()
}, },
}; };
let mut result = converter.run( let mut result = converter.run(

View File

@ -45,7 +45,7 @@ pub fn evaluate_by(
RunnableContext { input, name, .. }: RunnableContext, RunnableContext { input, name, .. }: RunnableContext,
) -> Result<OutputStream, ShellError> { ) -> Result<OutputStream, ShellError> {
let stream = async_stream! { let stream = async_stream! {
let values: Vec<Value> = input.values.collect().await; let values: Vec<Value> = input.collect().await;
if values.is_empty() { if values.is_empty() {
yield Err(ShellError::labeled_error( yield Err(ShellError::labeled_error(

View File

@ -48,7 +48,5 @@ fn first(
1 1
}; };
Ok(OutputStream::from_input( Ok(OutputStream::from_input(context.input.take(rows_desired)))
context.input.values.take(rows_desired),
))
} }

View File

@ -0,0 +1,157 @@
use crate::commands::PerItemCommand;
use crate::context::CommandRegistry;
use crate::prelude::*;
use nu_errors::ShellError;
use nu_protocol::{
CallInfo, ColumnPath, ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value,
};
use nu_source::Tagged;
use nu_value_ext::{as_column_path, get_data_by_column_path};
use std::borrow::Borrow;
pub struct Format;
impl PerItemCommand for Format {
fn name(&self) -> &str {
"format"
}
fn signature(&self) -> Signature {
Signature::build("format").required(
"pattern",
SyntaxShape::Any,
"the pattern to output. Eg) \"{foo}: {bar}\"",
)
}
fn usage(&self) -> &str {
"Format columns into a string using a simple pattern."
}
fn run(
&self,
call_info: &CallInfo,
_registry: &CommandRegistry,
_raw_args: &RawCommandArgs,
value: Value,
) -> Result<OutputStream, ShellError> {
//let value_tag = value.tag();
let pattern = call_info.args.expect_nth(0)?;
let pattern_tag = pattern.tag.clone();
let pattern = pattern.as_string()?;
let format_pattern = format(&pattern);
let commands = format_pattern;
let output = match value {
value
@
Value {
value: UntaggedValue::Row(_),
..
} => {
let mut output = String::new();
for command in &commands {
match command {
FormatCommand::Text(s) => {
output.push_str(&s);
}
FormatCommand::Column(c) => {
let key = to_column_path(&c, &pattern_tag)?;
let fetcher = get_data_by_column_path(
&value,
&key,
Box::new(move |(_, _, error)| error),
);
if let Ok(c) = fetcher {
output
.push_str(&value::format_leaf(c.borrow()).plain_string(100_000))
}
// That column doesn't match, so don't emit anything
}
}
}
output
}
_ => String::new(),
};
Ok(futures::stream::iter(vec![ReturnSuccess::value(
UntaggedValue::string(output).into_untagged_value(),
)])
.to_output_stream())
}
}
#[derive(Debug)]
enum FormatCommand {
Text(String),
Column(String),
}
fn format(input: &str) -> Vec<FormatCommand> {
let mut output = vec![];
let mut loop_input = input.chars();
loop {
let mut before = String::new();
while let Some(c) = loop_input.next() {
if c == '{' {
break;
}
before.push(c);
}
if !before.is_empty() {
output.push(FormatCommand::Text(before.to_string()));
}
// Look for column as we're now at one
let mut column = String::new();
while let Some(c) = loop_input.next() {
if c == '}' {
break;
}
column.push(c);
}
if !column.is_empty() {
output.push(FormatCommand::Column(column.to_string()));
}
if before.is_empty() && column.is_empty() {
break;
}
}
output
}
fn to_column_path(
path_members: &str,
tag: impl Into<Tag>,
) -> Result<Tagged<ColumnPath>, ShellError> {
let tag = tag.into();
as_column_path(
&UntaggedValue::Table(
path_members
.split('.')
.map(|x| {
let member = match x.parse::<u64>() {
Ok(v) => UntaggedValue::int(v),
Err(_) => UntaggedValue::string(x),
};
member.into_value(&tag)
})
.collect(),
)
.into_value(&tag),
)
}

View File

@ -205,13 +205,9 @@ fn from_bson(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStre
let input = args.input; let input = args.input;
let stream = async_stream! { let stream = async_stream! {
let values: Vec<Value> = input.values.collect().await; let bytes = input.collect_binary(tag.clone()).await?;
for value in values { match from_bson_bytes_to_value(bytes.item, tag.clone()) {
let value_tag = &value.tag;
match value.value {
UntaggedValue::Primitive(Primitive::Binary(vb)) =>
match from_bson_bytes_to_value(vb, tag.clone()) {
Ok(x) => yield ReturnSuccess::value(x), Ok(x) => yield ReturnSuccess::value(x),
Err(_) => { Err(_) => {
yield Err(ShellError::labeled_error_with_secondary( yield Err(ShellError::labeled_error_with_secondary(
@ -219,20 +215,10 @@ fn from_bson(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStre
"input cannot be parsed as BSON", "input cannot be parsed as BSON",
tag.clone(), tag.clone(),
"value originates from here", "value originates from here",
value_tag, bytes.tag,
)) ))
} }
} }
_ => yield Err(ShellError::labeled_error_with_secondary(
"Expected a string from pipeline",
"requires string input",
tag.clone(),
"value originates from here",
value_tag,
)),
}
}
}; };
Ok(stream.to_output_stream()) Ok(stream.to_output_stream())

View File

@ -1,7 +1,7 @@
use crate::prelude::*; use crate::prelude::*;
use csv::ReaderBuilder; use csv::{ErrorKind, ReaderBuilder};
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_protocol::{Primitive, ReturnSuccess, TaggedDictBuilder, UntaggedValue, Value}; use nu_protocol::{ReturnSuccess, TaggedDictBuilder, UntaggedValue, Value};
fn from_delimited_string_to_value( fn from_delimited_string_to_value(
s: String, s: String,
@ -27,10 +27,13 @@ fn from_delimited_string_to_value(
for row in reader.records() { for row in reader.records() {
let mut tagged_row = TaggedDictBuilder::new(&tag); let mut tagged_row = TaggedDictBuilder::new(&tag);
for (value, header) in row?.iter().zip(headers.iter()) { for (value, header) in row?.iter().zip(headers.iter()) {
tagged_row.insert_value( if let Ok(i) = value.parse::<i64>() {
header, tagged_row.insert_value(header, UntaggedValue::int(i).into_value(&tag))
UntaggedValue::Primitive(Primitive::String(String::from(value))).into_value(&tag), } else if let Ok(f) = value.parse::<f64>() {
) tagged_row.insert_value(header, UntaggedValue::decimal(f).into_value(&tag))
} else {
tagged_row.insert_value(header, UntaggedValue::string(value).into_value(&tag))
}
} }
rows.push(tagged_row.into_value()); rows.push(tagged_row.into_value());
} }
@ -47,28 +50,9 @@ pub fn from_delimited_data(
let name_tag = name; let name_tag = name;
let stream = async_stream! { let stream = async_stream! {
let values: Vec<Value> = input.values.collect().await; let concat_string = input.collect_string(name_tag.clone()).await?;
let mut concat_string = String::new(); match from_delimited_string_to_value(concat_string.item, headerless, sep, name_tag.clone()) {
let mut latest_tag: Option<Tag> = None;
for value in values {
let value_tag = &value.tag;
latest_tag = Some(value_tag.clone());
if let Ok(s) = value.as_string() {
concat_string.push_str(&s);
} else {
yield Err(ShellError::labeled_error_with_secondary(
"Expected a string from pipeline",
"requires string input",
name_tag.clone(),
"value originates from here",
value_tag.clone(),
))
}
}
match from_delimited_string_to_value(concat_string, headerless, sep, name_tag.clone()) {
Ok(x) => match x { Ok(x) => match x {
Value { value: UntaggedValue::Table(list), .. } => { Value { value: UntaggedValue::Table(list), .. } => {
for l in list { for l in list {
@ -77,15 +61,18 @@ pub fn from_delimited_data(
} }
x => yield ReturnSuccess::value(x), x => yield ReturnSuccess::value(x),
}, },
Err(_) => if let Some(last_tag) = latest_tag { Err(err) => {
let line_one = format!("Could not parse as {}", format_name); let line_one = match pretty_csv_error(err) {
Some(pretty) => format!("Could not parse as {} ({})", format_name,pretty),
None => format!("Could not parse as {}", format_name),
};
let line_two = format!("input cannot be parsed as {}", format_name); let line_two = format!("input cannot be parsed as {}", format_name);
yield Err(ShellError::labeled_error_with_secondary( yield Err(ShellError::labeled_error_with_secondary(
line_one, line_one,
line_two, line_two,
name_tag.clone(), name_tag.clone(),
"value originates from here", "value originates from here",
last_tag.clone(), concat_string.tag,
)) ))
} , } ,
} }
@ -93,3 +80,26 @@ pub fn from_delimited_data(
Ok(stream.to_output_stream()) Ok(stream.to_output_stream())
} }
fn pretty_csv_error(err: csv::Error) -> Option<String> {
match err.kind() {
ErrorKind::UnequalLengths {
pos,
expected_len,
len,
} => {
if let Some(pos) = pos {
Some(format!(
"Line {}: expected {} fields, found {}",
pos.line(),
expected_len,
len
))
} else {
Some(format!("Expected {} fields, found {}", expected_len, len))
}
}
ErrorKind::Seek => Some("Internal error while parsing csv".to_string()),
_ => None,
}
}

View File

@ -0,0 +1,240 @@
extern crate ical;
use crate::commands::WholeStreamCommand;
use crate::prelude::*;
use ical::parser::ical::component::*;
use ical::property::Property;
use nu_errors::ShellError;
use nu_protocol::{Primitive, ReturnSuccess, Signature, TaggedDictBuilder, UntaggedValue, Value};
use std::io::BufReader;
pub struct FromIcs;
impl WholeStreamCommand for FromIcs {
fn name(&self) -> &str {
"from-ics"
}
fn signature(&self) -> Signature {
Signature::build("from-ics")
}
fn usage(&self) -> &str {
"Parse text as .ics and create table."
}
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
from_ics(args, registry)
}
}
fn from_ics(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
let args = args.evaluate_once(registry)?;
let tag = args.name_tag();
let input = args.input;
let stream = async_stream! {
let input_string = input.collect_string(tag.clone()).await?.item;
let input_bytes = input_string.as_bytes();
let buf_reader = BufReader::new(input_bytes);
let parser = ical::IcalParser::new(buf_reader);
for calendar in parser {
match calendar {
Ok(c) => yield ReturnSuccess::value(calendar_to_value(c, tag.clone())),
Err(_) => yield Err(ShellError::labeled_error(
"Could not parse as .ics",
"input cannot be parsed as .ics",
tag.clone()
)),
}
}
};
Ok(stream.to_output_stream())
}
fn calendar_to_value(calendar: IcalCalendar, tag: Tag) -> Value {
let mut row = TaggedDictBuilder::new(tag.clone());
row.insert_untagged(
"properties",
properties_to_value(calendar.properties, tag.clone()),
);
row.insert_untagged("events", events_to_value(calendar.events, tag.clone()));
row.insert_untagged("alarms", alarms_to_value(calendar.alarms, tag.clone()));
row.insert_untagged("to-Dos", todos_to_value(calendar.todos, tag.clone()));
row.insert_untagged(
"journals",
journals_to_value(calendar.journals, tag.clone()),
);
row.insert_untagged(
"free-busys",
free_busys_to_value(calendar.free_busys, tag.clone()),
);
row.insert_untagged("timezones", timezones_to_value(calendar.timezones, tag));
row.into_value()
}
fn events_to_value(events: Vec<IcalEvent>, tag: Tag) -> UntaggedValue {
UntaggedValue::table(
&events
.into_iter()
.map(|event| {
let mut row = TaggedDictBuilder::new(tag.clone());
row.insert_untagged(
"properties",
properties_to_value(event.properties, tag.clone()),
);
row.insert_untagged("alarms", alarms_to_value(event.alarms, tag.clone()));
row.into_value()
})
.collect::<Vec<Value>>(),
)
}
fn alarms_to_value(alarms: Vec<IcalAlarm>, tag: Tag) -> UntaggedValue {
UntaggedValue::table(
&alarms
.into_iter()
.map(|alarm| {
let mut row = TaggedDictBuilder::new(tag.clone());
row.insert_untagged(
"properties",
properties_to_value(alarm.properties, tag.clone()),
);
row.into_value()
})
.collect::<Vec<Value>>(),
)
}
fn todos_to_value(todos: Vec<IcalTodo>, tag: Tag) -> UntaggedValue {
UntaggedValue::table(
&todos
.into_iter()
.map(|todo| {
let mut row = TaggedDictBuilder::new(tag.clone());
row.insert_untagged(
"properties",
properties_to_value(todo.properties, tag.clone()),
);
row.insert_untagged("alarms", alarms_to_value(todo.alarms, tag.clone()));
row.into_value()
})
.collect::<Vec<Value>>(),
)
}
fn journals_to_value(journals: Vec<IcalJournal>, tag: Tag) -> UntaggedValue {
UntaggedValue::table(
&journals
.into_iter()
.map(|journal| {
let mut row = TaggedDictBuilder::new(tag.clone());
row.insert_untagged(
"properties",
properties_to_value(journal.properties, tag.clone()),
);
row.into_value()
})
.collect::<Vec<Value>>(),
)
}
fn free_busys_to_value(free_busys: Vec<IcalFreeBusy>, tag: Tag) -> UntaggedValue {
UntaggedValue::table(
&free_busys
.into_iter()
.map(|free_busy| {
let mut row = TaggedDictBuilder::new(tag.clone());
row.insert_untagged(
"properties",
properties_to_value(free_busy.properties, tag.clone()),
);
row.into_value()
})
.collect::<Vec<Value>>(),
)
}
fn timezones_to_value(timezones: Vec<IcalTimeZone>, tag: Tag) -> UntaggedValue {
UntaggedValue::table(
&timezones
.into_iter()
.map(|timezone| {
let mut row = TaggedDictBuilder::new(tag.clone());
row.insert_untagged(
"properties",
properties_to_value(timezone.properties, tag.clone()),
);
row.insert_untagged(
"transitions",
timezone_transitions_to_value(timezone.transitions, tag.clone()),
);
row.into_value()
})
.collect::<Vec<Value>>(),
)
}
fn timezone_transitions_to_value(
transitions: Vec<IcalTimeZoneTransition>,
tag: Tag,
) -> UntaggedValue {
UntaggedValue::table(
&transitions
.into_iter()
.map(|transition| {
let mut row = TaggedDictBuilder::new(tag.clone());
row.insert_untagged(
"properties",
properties_to_value(transition.properties, tag.clone()),
);
row.into_value()
})
.collect::<Vec<Value>>(),
)
}
fn properties_to_value(properties: Vec<Property>, tag: Tag) -> UntaggedValue {
UntaggedValue::table(
&properties
.into_iter()
.map(|prop| {
let mut row = TaggedDictBuilder::new(tag.clone());
let name = UntaggedValue::string(prop.name);
let value = match prop.value {
Some(val) => UntaggedValue::string(val),
None => UntaggedValue::Primitive(Primitive::Nothing),
};
let params = match prop.params {
Some(param_list) => params_to_value(param_list, tag.clone()).into(),
None => UntaggedValue::Primitive(Primitive::Nothing),
};
row.insert_untagged("name", name);
row.insert_untagged("value", value);
row.insert_untagged("params", params);
row.into_value()
})
.collect::<Vec<Value>>(),
)
}
fn params_to_value(params: Vec<(String, Vec<String>)>, tag: Tag) -> Value {
let mut row = TaggedDictBuilder::new(tag);
for (param_name, param_values) in params {
let values: Vec<Value> = param_values.into_iter().map(|val| val.into()).collect();
let values = UntaggedValue::table(&values);
row.insert_untagged(param_name, values);
}
row.into_value()
}

View File

@ -66,32 +66,12 @@ pub fn from_ini_string_to_value(
fn from_ini(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> { fn from_ini(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
let args = args.evaluate_once(registry)?; let args = args.evaluate_once(registry)?;
let tag = args.name_tag(); let tag = args.name_tag();
let span = tag.span;
let input = args.input; let input = args.input;
let stream = async_stream! { let stream = async_stream! {
let values: Vec<Value> = input.values.collect().await; let concat_string = input.collect_string(tag.clone()).await?;
let mut concat_string = String::new(); match from_ini_string_to_value(concat_string.item, tag.clone()) {
let mut latest_tag: Option<Tag> = None;
for value in values {
latest_tag = Some(value.tag.clone());
let value_span = value.tag.span;
if let Ok(s) = value.as_string() {
concat_string.push_str(&s);
} else {
yield Err(ShellError::labeled_error_with_secondary(
"Expected a string from pipeline",
"requires string input",
span,
"value originates from here",
value_span,
))
}
}
match from_ini_string_to_value(concat_string, tag.clone()) {
Ok(x) => match x { Ok(x) => match x {
Value { value: UntaggedValue::Table(list), .. } => { Value { value: UntaggedValue::Table(list), .. } => {
for l in list { for l in list {
@ -100,15 +80,15 @@ fn from_ini(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStrea
} }
x => yield ReturnSuccess::value(x), x => yield ReturnSuccess::value(x),
}, },
Err(_) => if let Some(last_tag) = latest_tag { Err(_) => {
yield Err(ShellError::labeled_error_with_secondary( yield Err(ShellError::labeled_error_with_secondary(
"Could not parse as INI", "Could not parse as INI",
"input cannot be parsed as INI", "input cannot be parsed as INI",
&tag, &tag,
"value originates from here", "value originates from here",
last_tag, concat_string.tag,
)) ))
} , }
} }
}; };

View File

@ -74,35 +74,13 @@ fn from_json(
FromJSONArgs { objects }: FromJSONArgs, FromJSONArgs { objects }: FromJSONArgs,
RunnableContext { input, name, .. }: RunnableContext, RunnableContext { input, name, .. }: RunnableContext,
) -> Result<OutputStream, ShellError> { ) -> Result<OutputStream, ShellError> {
let name_span = name.span;
let name_tag = name; let name_tag = name;
let stream = async_stream! { let stream = async_stream! {
let values: Vec<Value> = input.values.collect().await; let concat_string = input.collect_string(name_tag.clone()).await?;
let mut concat_string = String::new();
let mut latest_tag: Option<Tag> = None;
for value in values {
latest_tag = Some(value.tag.clone());
let value_span = value.tag.span;
if let Ok(s) = value.as_string() {
concat_string.push_str(&s);
} else {
yield Err(ShellError::labeled_error_with_secondary(
"Expected a string from pipeline",
"requires string input",
name_span,
"value originates from here",
value_span,
))
}
}
if objects { if objects {
for json_str in concat_string.lines() { for json_str in concat_string.item.lines() {
if json_str.is_empty() { if json_str.is_empty() {
continue; continue;
} }
@ -111,7 +89,6 @@ fn from_json(
Ok(x) => Ok(x) =>
yield ReturnSuccess::value(x), yield ReturnSuccess::value(x),
Err(e) => { Err(e) => {
if let Some(ref last_tag) = latest_tag {
let mut message = "Could not parse as JSON (".to_string(); let mut message = "Could not parse as JSON (".to_string();
message.push_str(&e.to_string()); message.push_str(&e.to_string());
message.push_str(")"); message.push_str(")");
@ -121,13 +98,12 @@ fn from_json(
"input cannot be parsed as JSON", "input cannot be parsed as JSON",
&name_tag, &name_tag,
"value originates from here", "value originates from here",
last_tag)) concat_string.tag.clone()))
}
} }
} }
} }
} else { } else {
match from_json_string_to_value(concat_string, name_tag.clone()) { match from_json_string_to_value(concat_string.item, name_tag.clone()) {
Ok(x) => Ok(x) =>
match x { match x {
Value { value: UntaggedValue::Table(list), .. } => { Value { value: UntaggedValue::Table(list), .. } => {
@ -138,7 +114,6 @@ fn from_json(
x => yield ReturnSuccess::value(x), x => yield ReturnSuccess::value(x),
} }
Err(e) => { Err(e) => {
if let Some(last_tag) = latest_tag {
let mut message = "Could not parse as JSON (".to_string(); let mut message = "Could not parse as JSON (".to_string();
message.push_str(&e.to_string()); message.push_str(&e.to_string());
message.push_str(")"); message.push_str(")");
@ -148,8 +123,7 @@ fn from_json(
"input cannot be parsed as JSON", "input cannot be parsed as JSON",
name_tag, name_tag,
"value originates from here", "value originates from here",
last_tag)) concat_string.tag))
}
} }
} }
} }

View File

@ -0,0 +1,98 @@
use crate::commands::WholeStreamCommand;
use crate::prelude::*;
use crate::TaggedListBuilder;
use calamine::*;
use nu_errors::ShellError;
use nu_protocol::{ReturnSuccess, Signature, TaggedDictBuilder, UntaggedValue};
use std::io::Cursor;
pub struct FromODS;
#[derive(Deserialize)]
pub struct FromODSArgs {
headerless: bool,
}
impl WholeStreamCommand for FromODS {
fn name(&self) -> &str {
"from-ods"
}
fn signature(&self) -> Signature {
Signature::build("from-ods").switch(
"headerless",
"don't treat the first row as column names",
None,
)
}
fn usage(&self) -> &str {
"Parse OpenDocument Spreadsheet(.ods) data and create table."
}
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
args.process(registry, from_ods)?.run()
}
}
fn from_ods(
FromODSArgs {
headerless: _headerless,
}: FromODSArgs,
runnable_context: RunnableContext,
) -> Result<OutputStream, ShellError> {
let input = runnable_context.input;
let tag = runnable_context.name;
let stream = async_stream! {
let bytes = input.collect_binary(tag.clone()).await?;
let mut buf: Cursor<Vec<u8>> = Cursor::new(bytes.item);
let mut ods = Ods::<_>::new(buf).map_err(|_| ShellError::labeled_error(
"Could not load ods file",
"could not load ods file",
&tag))?;
let mut dict = TaggedDictBuilder::new(&tag);
let sheet_names = ods.sheet_names().to_owned();
for sheet_name in &sheet_names {
let mut sheet_output = TaggedListBuilder::new(&tag);
if let Some(Ok(current_sheet)) = ods.worksheet_range(sheet_name) {
for row in current_sheet.rows() {
let mut row_output = TaggedDictBuilder::new(&tag);
for (i, cell) in row.iter().enumerate() {
let value = match cell {
DataType::Empty => UntaggedValue::nothing(),
DataType::String(s) => UntaggedValue::string(s),
DataType::Float(f) => UntaggedValue::decimal(*f),
DataType::Int(i) => UntaggedValue::int(*i),
DataType::Bool(b) => UntaggedValue::boolean(*b),
_ => UntaggedValue::nothing(),
};
row_output.insert_untagged(&format!("Column{}", i), value);
}
sheet_output.push_untagged(row_output.into_untagged_value());
}
dict.insert_untagged(sheet_name, sheet_output.into_untagged_value());
} else {
yield Err(ShellError::labeled_error(
"Could not load sheet",
"could not load sheet",
&tag));
}
}
yield ReturnSuccess::value(dict.into_value());
};
Ok(stream.to_output_stream())
}

View File

@ -138,13 +138,8 @@ fn from_sqlite(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputSt
let input = args.input; let input = args.input;
let stream = async_stream! { let stream = async_stream! {
let values: Vec<Value> = input.values.collect().await; let bytes = input.collect_binary(tag.clone()).await?;
match from_sqlite_bytes_to_value(bytes.item, tag.clone()) {
for value in values {
let value_tag = &value.tag;
match value.value {
UntaggedValue::Primitive(Primitive::Binary(vb)) =>
match from_sqlite_bytes_to_value(vb, tag.clone()) {
Ok(x) => match x { Ok(x) => match x {
Value { value: UntaggedValue::Table(list), .. } => { Value { value: UntaggedValue::Table(list), .. } => {
for l in list { for l in list {
@ -160,20 +155,10 @@ fn from_sqlite(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputSt
"input cannot be parsed as SQLite", "input cannot be parsed as SQLite",
&tag, &tag,
"value originates from here", "value originates from here",
value_tag, bytes.tag,
)) ))
} }
} }
_ => yield Err(ShellError::labeled_error_with_secondary(
"Expected binary data from pipeline",
"requires binary data input",
&tag,
"value originates from here",
value_tag,
)),
}
}
}; };
Ok(stream.to_output_stream()) Ok(stream.to_output_stream())

View File

@ -259,45 +259,26 @@ fn from_ssv(
RunnableContext { input, name, .. }: RunnableContext, RunnableContext { input, name, .. }: RunnableContext,
) -> Result<OutputStream, ShellError> { ) -> Result<OutputStream, ShellError> {
let stream = async_stream! { let stream = async_stream! {
let values: Vec<Value> = input.values.collect().await; let concat_string = input.collect_string(name.clone()).await?;
let mut concat_string = String::new();
let mut latest_tag: Option<Tag> = None;
let split_at = match minimum_spaces { let split_at = match minimum_spaces {
Some(number) => number.item, Some(number) => number.item,
None => DEFAULT_MINIMUM_SPACES None => DEFAULT_MINIMUM_SPACES
}; };
for value in values { match from_ssv_string_to_value(&concat_string.item, headerless, aligned_columns, split_at, name.clone()) {
let value_tag = value.tag.clone();
latest_tag = Some(value_tag.clone());
if let Ok(s) = value.as_string() {
concat_string.push_str(&s);
}
else {
yield Err(ShellError::labeled_error_with_secondary (
"Expected a string from pipeline",
"requires string input",
&name,
"value originates from here",
&value_tag
))
}
}
match from_ssv_string_to_value(&concat_string, headerless, aligned_columns, split_at, name.clone()) {
Some(x) => match x { Some(x) => match x {
Value { value: UntaggedValue::Table(list), ..} => { Value { value: UntaggedValue::Table(list), ..} => {
for l in list { yield ReturnSuccess::value(l) } for l in list { yield ReturnSuccess::value(l) }
} }
x => yield ReturnSuccess::value(x) x => yield ReturnSuccess::value(x)
}, },
None => if let Some(tag) = latest_tag { None => {
yield Err(ShellError::labeled_error_with_secondary( yield Err(ShellError::labeled_error_with_secondary(
"Could not parse as SSV", "Could not parse as SSV",
"input cannot be parsed ssv", "input cannot be parsed ssv",
&name, &name,
"value originates from here", "value originates from here",
&tag, &concat_string.tag,
)) ))
}, },
} }

View File

@ -69,33 +69,11 @@ pub fn from_toml(
) -> Result<OutputStream, ShellError> { ) -> Result<OutputStream, ShellError> {
let args = args.evaluate_once(registry)?; let args = args.evaluate_once(registry)?;
let tag = args.name_tag(); let tag = args.name_tag();
let name_span = tag.span;
let input = args.input; let input = args.input;
let stream = async_stream! { let stream = async_stream! {
let values: Vec<Value> = input.values.collect().await; let concat_string = input.collect_string(tag.clone()).await?;
match from_toml_string_to_value(concat_string.item, tag.clone()) {
let mut concat_string = String::new();
let mut latest_tag: Option<Tag> = None;
for value in values {
latest_tag = Some(value.tag.clone());
let value_span = value.tag.span;
if let Ok(s) = value.as_string() {
concat_string.push_str(&s);
}
else {
yield Err(ShellError::labeled_error_with_secondary(
"Expected a string from pipeline",
"requires string input",
name_span,
"value originates from here",
value_span,
))
}
}
match from_toml_string_to_value(concat_string, tag.clone()) {
Ok(x) => match x { Ok(x) => match x {
Value { value: UntaggedValue::Table(list), .. } => { Value { value: UntaggedValue::Table(list), .. } => {
for l in list { for l in list {
@ -104,15 +82,15 @@ pub fn from_toml(
} }
x => yield ReturnSuccess::value(x), x => yield ReturnSuccess::value(x),
}, },
Err(_) => if let Some(last_tag) = latest_tag { Err(_) => {
yield Err(ShellError::labeled_error_with_secondary( yield Err(ShellError::labeled_error_with_secondary(
"Could not parse as TOML", "Could not parse as TOML",
"input cannot be parsed as TOML", "input cannot be parsed as TOML",
&tag, &tag,
"value originates from here", "value originates from here",
last_tag, concat_string.tag,
)) ))
} , }
} }
}; };

View File

@ -1,7 +1,7 @@
use crate::commands::WholeStreamCommand; use crate::commands::WholeStreamCommand;
use crate::prelude::*; use crate::prelude::*;
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_protocol::{ReturnSuccess, Signature, TaggedDictBuilder, UntaggedValue, Value}; use nu_protocol::{ReturnSuccess, Signature, TaggedDictBuilder, UntaggedValue};
pub struct FromURL; pub struct FromURL;
@ -30,32 +30,12 @@ impl WholeStreamCommand for FromURL {
fn from_url(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> { fn from_url(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
let args = args.evaluate_once(registry)?; let args = args.evaluate_once(registry)?;
let tag = args.name_tag(); let tag = args.name_tag();
let name_span = tag.span;
let input = args.input; let input = args.input;
let stream = async_stream! { let stream = async_stream! {
let values: Vec<Value> = input.values.collect().await; let concat_string = input.collect_string(tag.clone()).await?;
let mut concat_string = String::new(); let result = serde_urlencoded::from_str::<Vec<(String, String)>>(&concat_string.item);
let mut latest_tag: Option<Tag> = None;
for value in values {
latest_tag = Some(value.tag.clone());
let value_span = value.tag.span;
if let Ok(s) = value.as_string() {
concat_string.push_str(&s);
} else {
yield Err(ShellError::labeled_error_with_secondary(
"Expected a string from pipeline",
"requires string input",
name_span,
"value originates from here",
value_span,
))
}
}
let result = serde_urlencoded::from_str::<Vec<(String, String)>>(&concat_string);
match result { match result {
Ok(result) => { Ok(result) => {
@ -68,17 +48,15 @@ fn from_url(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStrea
yield ReturnSuccess::value(row.into_value()); yield ReturnSuccess::value(row.into_value());
} }
_ => { _ => {
if let Some(last_tag) = latest_tag {
yield Err(ShellError::labeled_error_with_secondary( yield Err(ShellError::labeled_error_with_secondary(
"String not compatible with url-encoding", "String not compatible with url-encoding",
"input not url-encoded", "input not url-encoded",
tag, tag,
"value originates from here", "value originates from here",
last_tag, concat_string.tag,
)); ));
} }
} }
}
}; };
Ok(stream.to_output_stream()) Ok(stream.to_output_stream())

View File

@ -0,0 +1,102 @@
extern crate ical;
use crate::commands::WholeStreamCommand;
use crate::prelude::*;
use ical::parser::vcard::component::*;
use ical::property::Property;
use nu_errors::ShellError;
use nu_protocol::{Primitive, ReturnSuccess, Signature, TaggedDictBuilder, UntaggedValue, Value};
use std::io::BufReader;
pub struct FromVcf;
impl WholeStreamCommand for FromVcf {
fn name(&self) -> &str {
"from-vcf"
}
fn signature(&self) -> Signature {
Signature::build("from-vcf")
}
fn usage(&self) -> &str {
"Parse text as .vcf and create table."
}
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
from_vcf(args, registry)
}
}
fn from_vcf(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
let args = args.evaluate_once(registry)?;
let tag = args.name_tag();
let input = args.input;
let stream = async_stream! {
let input_string = input.collect_string(tag.clone()).await?.item;
let input_bytes = input_string.as_bytes();
let buf_reader = BufReader::new(input_bytes);
let parser = ical::VcardParser::new(buf_reader);
for contact in parser {
match contact {
Ok(c) => yield ReturnSuccess::value(contact_to_value(c, tag.clone())),
Err(_) => yield Err(ShellError::labeled_error(
"Could not parse as .vcf",
"input cannot be parsed as .vcf",
tag.clone()
)),
}
}
};
Ok(stream.to_output_stream())
}
fn contact_to_value(contact: VcardContact, tag: Tag) -> Value {
let mut row = TaggedDictBuilder::new(tag.clone());
row.insert_untagged("properties", properties_to_value(contact.properties, tag));
row.into_value()
}
fn properties_to_value(properties: Vec<Property>, tag: Tag) -> UntaggedValue {
UntaggedValue::table(
&properties
.into_iter()
.map(|prop| {
let mut row = TaggedDictBuilder::new(tag.clone());
let name = UntaggedValue::string(prop.name);
let value = match prop.value {
Some(val) => UntaggedValue::string(val),
None => UntaggedValue::Primitive(Primitive::Nothing),
};
let params = match prop.params {
Some(param_list) => params_to_value(param_list, tag.clone()).into(),
None => UntaggedValue::Primitive(Primitive::Nothing),
};
row.insert_untagged("name", name);
row.insert_untagged("value", value);
row.insert_untagged("params", params);
row.into_value()
})
.collect::<Vec<Value>>(),
)
}
fn params_to_value(params: Vec<(String, Vec<String>)>, tag: Tag) -> Value {
let mut row = TaggedDictBuilder::new(tag);
for (param_name, param_values) in params {
let values: Vec<Value> = param_values.into_iter().map(|val| val.into()).collect();
let values = UntaggedValue::table(&values);
row.insert_untagged(param_name, values);
}
row.into_value()
}

View File

@ -0,0 +1,99 @@
use crate::commands::WholeStreamCommand;
use crate::prelude::*;
use crate::TaggedListBuilder;
use calamine::*;
use nu_errors::ShellError;
use nu_protocol::{ReturnSuccess, Signature, TaggedDictBuilder, UntaggedValue};
use std::io::Cursor;
pub struct FromXLSX;
#[derive(Deserialize)]
pub struct FromXLSXArgs {
headerless: bool,
}
impl WholeStreamCommand for FromXLSX {
fn name(&self) -> &str {
"from-xlsx"
}
fn signature(&self) -> Signature {
Signature::build("from-xlsx").switch(
"headerless",
"don't treat the first row as column names",
None,
)
}
fn usage(&self) -> &str {
"Parse binary Excel(.xlsx) data and create table."
}
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
args.process(registry, from_xlsx)?.run()
}
}
fn from_xlsx(
FromXLSXArgs {
headerless: _headerless,
}: FromXLSXArgs,
runnable_context: RunnableContext,
) -> Result<OutputStream, ShellError> {
let input = runnable_context.input;
let tag = runnable_context.name;
let stream = async_stream! {
let value = input.collect_binary(tag.clone()).await?;
let mut buf: Cursor<Vec<u8>> = Cursor::new(value.item);
let mut xls = Xlsx::<_>::new(buf).map_err(|_| {
ShellError::labeled_error("Could not load xlsx file", "could not load xlsx file", &tag)
})?;
let mut dict = TaggedDictBuilder::new(&tag);
let sheet_names = xls.sheet_names().to_owned();
for sheet_name in &sheet_names {
let mut sheet_output = TaggedListBuilder::new(&tag);
if let Some(Ok(current_sheet)) = xls.worksheet_range(sheet_name) {
for row in current_sheet.rows() {
let mut row_output = TaggedDictBuilder::new(&tag);
for (i, cell) in row.iter().enumerate() {
let value = match cell {
DataType::Empty => UntaggedValue::nothing(),
DataType::String(s) => UntaggedValue::string(s),
DataType::Float(f) => UntaggedValue::decimal(*f),
DataType::Int(i) => UntaggedValue::int(*i),
DataType::Bool(b) => UntaggedValue::boolean(*b),
_ => UntaggedValue::nothing(),
};
row_output.insert_untagged(&format!("Column{}", i), value);
}
sheet_output.push_untagged(row_output.into_untagged_value());
}
dict.insert_untagged(sheet_name, sheet_output.into_untagged_value());
} else {
yield Err(ShellError::labeled_error(
"Could not load sheet",
"could not load sheet",
&tag,
));
}
}
yield ReturnSuccess::value(dict.into_value());
};
Ok(stream.to_output_stream())
}

View File

@ -101,34 +101,12 @@ pub fn from_xml_string_to_value(s: String, tag: impl Into<Tag>) -> Result<Value,
fn from_xml(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> { fn from_xml(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
let args = args.evaluate_once(registry)?; let args = args.evaluate_once(registry)?;
let tag = args.name_tag(); let tag = args.name_tag();
let name_span = tag.span;
let input = args.input; let input = args.input;
let stream = async_stream! { let stream = async_stream! {
let values: Vec<Value> = input.values.collect().await; let concat_string = input.collect_string(tag.clone()).await?;
let mut concat_string = String::new(); match from_xml_string_to_value(concat_string.item, tag.clone()) {
let mut latest_tag: Option<Tag> = None;
for value in values {
latest_tag = Some(value.tag.clone());
let value_span = value.tag.span;
if let Ok(s) = value.as_string() {
concat_string.push_str(&s);
}
else {
yield Err(ShellError::labeled_error_with_secondary(
"Expected a string from pipeline",
"requires string input",
name_span,
"value originates from here",
value_span,
))
}
}
match from_xml_string_to_value(concat_string, tag.clone()) {
Ok(x) => match x { Ok(x) => match x {
Value { value: UntaggedValue::Table(list), .. } => { Value { value: UntaggedValue::Table(list), .. } => {
for l in list { for l in list {
@ -137,13 +115,13 @@ fn from_xml(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStrea
} }
x => yield ReturnSuccess::value(x), x => yield ReturnSuccess::value(x),
}, },
Err(_) => if let Some(last_tag) = latest_tag { Err(_) => {
yield Err(ShellError::labeled_error_with_secondary( yield Err(ShellError::labeled_error_with_secondary(
"Could not parse as XML", "Could not parse as XML",
"input cannot be parsed as XML", "input cannot be parsed as XML",
&tag, &tag,
"value originates from here", "value originates from here",
&last_tag, &concat_string.tag,
)) ))
} , } ,
} }

View File

@ -121,34 +121,12 @@ pub fn from_yaml_string_to_value(s: String, tag: impl Into<Tag>) -> Result<Value
fn from_yaml(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> { fn from_yaml(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
let args = args.evaluate_once(registry)?; let args = args.evaluate_once(registry)?;
let tag = args.name_tag(); let tag = args.name_tag();
let name_span = tag.span;
let input = args.input; let input = args.input;
let stream = async_stream! { let stream = async_stream! {
let values: Vec<Value> = input.values.collect().await; let concat_string = input.collect_string(tag.clone()).await?;
let mut concat_string = String::new(); match from_yaml_string_to_value(concat_string.item, tag.clone()) {
let mut latest_tag: Option<Tag> = None;
for value in values {
latest_tag = Some(value.tag.clone());
let value_span = value.tag.span;
if let Ok(s) = value.as_string() {
concat_string.push_str(&s);
}
else {
yield Err(ShellError::labeled_error_with_secondary(
"Expected a string from pipeline",
"requires string input",
name_span,
"value originates from here",
value_span,
))
}
}
match from_yaml_string_to_value(concat_string, tag.clone()) {
Ok(x) => match x { Ok(x) => match x {
Value { value: UntaggedValue::Table(list), .. } => { Value { value: UntaggedValue::Table(list), .. } => {
for l in list { for l in list {
@ -157,15 +135,15 @@ fn from_yaml(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStre
} }
x => yield ReturnSuccess::value(x), x => yield ReturnSuccess::value(x),
}, },
Err(_) => if let Some(last_tag) = latest_tag { Err(_) => {
yield Err(ShellError::labeled_error_with_secondary( yield Err(ShellError::labeled_error_with_secondary(
"Could not parse as YAML", "Could not parse as YAML",
"input cannot be parsed as YAML", "input cannot be parsed as YAML",
&tag, &tag,
"value originates from here", "value originates from here",
&last_tag, &concat_string.tag,
)) ))
} , }
} }
}; };

View File

@ -1,13 +1,11 @@
use crate::commands::WholeStreamCommand; use crate::commands::WholeStreamCommand;
use crate::data::base::shape::Shapes;
use crate::prelude::*; use crate::prelude::*;
use futures_util::pin_mut;
use indexmap::set::IndexSet; use indexmap::set::IndexSet;
use log::trace; use log::trace;
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_protocol::{ use nu_protocol::{
did_you_mean, ColumnPath, PathMember, ReturnSuccess, ReturnValue, Signature, SyntaxShape, did_you_mean, ColumnPath, PathMember, Primitive, ReturnSuccess, ReturnValue, Signature,
UnspannedPathMember, UntaggedValue, Value, SyntaxShape, UnspannedPathMember, UntaggedValue, Value,
}; };
use nu_source::span_for_spanned_list; use nu_source::span_for_spanned_list;
use nu_value_ext::get_data_by_column_path; use nu_value_ext::get_data_by_column_path;
@ -180,23 +178,15 @@ pub fn get_column_path(path: &ColumnPath, obj: &Value) -> Result<Value, ShellErr
pub fn get( pub fn get(
GetArgs { rest: mut fields }: GetArgs, GetArgs { rest: mut fields }: GetArgs,
RunnableContext { input, .. }: RunnableContext, RunnableContext { mut input, .. }: RunnableContext,
) -> Result<OutputStream, ShellError> { ) -> Result<OutputStream, ShellError> {
if fields.is_empty() { if fields.is_empty() {
let stream = async_stream! { let stream = async_stream! {
let values = input.values; let mut vec = input.drain_vec().await;
pin_mut!(values);
let mut shapes = Shapes::new(); let descs = nu_protocol::merge_descriptors(&vec);
let mut index = 0; for desc in descs {
yield ReturnSuccess::value(desc);
while let Some(row) = values.next().await {
shapes.add(&row, index);
index += 1;
}
for row in shapes.to_values() {
yield ReturnSuccess::value(row);
} }
}; };
@ -207,7 +197,6 @@ pub fn get(
let member = fields.remove(0); let member = fields.remove(0);
trace!("get {:?} {:?}", member, fields); trace!("get {:?} {:?}", member, fields);
let stream = input let stream = input
.values
.map(move |item| { .map(move |item| {
let mut result = VecDeque::new(); let mut result = VecDeque::new();
@ -231,6 +220,10 @@ pub fn get(
result.push_back(ReturnSuccess::value(item.clone())); result.push_back(ReturnSuccess::value(item.clone()));
} }
} }
Value {
value: UntaggedValue::Primitive(Primitive::Nothing),
..
} => {}
other => result.push_back(ReturnSuccess::value(other.clone())), other => result.push_back(ReturnSuccess::value(other.clone())),
}, },
Err(reason) => result.push_back(ReturnSuccess::value( Err(reason) => result.push_back(ReturnSuccess::value(

View File

@ -43,7 +43,7 @@ pub fn group_by(
RunnableContext { input, name, .. }: RunnableContext, RunnableContext { input, name, .. }: RunnableContext,
) -> Result<OutputStream, ShellError> { ) -> Result<OutputStream, ShellError> {
let stream = async_stream! { let stream = async_stream! {
let values: Vec<Value> = input.values.collect().await; let values: Vec<Value> = input.collect().await;
if values.is_empty() { if values.is_empty() {
yield Err(ShellError::labeled_error( yield Err(ShellError::labeled_error(

View File

@ -0,0 +1,80 @@
use crate::commands::WholeStreamCommand;
use crate::context::CommandRegistry;
use crate::prelude::*;
use futures::stream::StreamExt;
use indexmap::IndexMap;
use nu_errors::ShellError;
use nu_protocol::Dictionary;
use nu_protocol::{ReturnSuccess, Signature, UntaggedValue, Value};
pub struct Headers;
#[derive(Deserialize)]
pub struct HeadersArgs {}
impl WholeStreamCommand for Headers {
fn name(&self) -> &str {
"headers"
}
fn signature(&self) -> Signature {
Signature::build("headers")
}
fn usage(&self) -> &str {
"Use the first row of the table as column names"
}
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
args.process(registry, headers)?.run()
}
}
pub fn headers(
HeadersArgs {}: HeadersArgs,
RunnableContext { input, .. }: RunnableContext,
) -> Result<OutputStream, ShellError> {
let stream = async_stream! {
let rows: Vec<Value> = input.collect().await;
if rows.len() < 1 {
yield Err(ShellError::untagged_runtime_error("Couldn't find headers, was the input a properly formatted, non-empty table?"));
}
//the headers are the first row in the table
let headers: Vec<String> = match &rows[0].value {
UntaggedValue::Row(d) => {
Ok(d.entries.iter().map(|(k, v)| {
match v.as_string() {
Ok(s) => s,
Err(_) => { //If a cell that should contain a header name is empty, we name the column Column[index]
match d.entries.get_full(k) {
Some((index, _, _)) => format!("Column{}", index),
None => "unknownColumn".to_string()
}
}
}
}).collect())
}
_ => Err(ShellError::unexpected_eof("Could not get headers, is the table empty?", rows[0].tag.span))
}?;
//Each row is a dictionary with the headers as keys
for r in rows.iter().skip(1) {
match &r.value {
UntaggedValue::Row(d) => {
let mut i = 0;
let mut entries = IndexMap::new();
for (_, v) in d.entries.iter() {
entries.insert(headers[i].clone(), v.clone());
i += 1;
}
yield Ok(ReturnSuccess::Value(UntaggedValue::Row(Dictionary{entries}).into_value(r.tag.clone())))
}
_ => yield Err(ShellError::unexpected_eof("Couldn't iterate through rows, was the input a properly formatted table?", r.tag.span))
}
}
};
Ok(stream.to_output_stream())
}

View File

@ -76,6 +76,12 @@ impl PerItemCommand for Help {
return Ok( return Ok(
get_help(&command.name(), &command.usage(), command.signature()).into(), get_help(&command.name(), &command.usage(), command.signature()).into(),
); );
} else {
return Err(ShellError::labeled_error(
"Can't find command (use 'help commands' for full list)",
"can't find command",
tag,
));
} }
let help = futures::stream::iter(help); let help = futures::stream::iter(help);
Ok(help.to_output_stream()) Ok(help.to_output_stream())
@ -87,8 +93,8 @@ Here are some tips to help you get started.
* help commands - list all available commands * help commands - list all available commands
* help <command name> - display help about a particular command * help <command name> - display help about a particular command
Nushell works on the idea of a "pipeline". Pipelines are commands connected with the '|' character. Each stage Nushell works on the idea of a "pipeline". Pipelines are commands connected with the '|' character.
in the pipeline works together to load, parse, and display information to you. Each stage in the pipeline works together to load, parse, and display information to you.
[Examples] [Examples]

View File

@ -30,7 +30,7 @@ impl WholeStreamCommand for Histogram {
"the name of the column to graph by", "the name of the column to graph by",
) )
.rest( .rest(
SyntaxShape::Member, SyntaxShape::String,
"column name to give the histogram's frequency column", "column name to give the histogram's frequency column",
) )
} }
@ -53,7 +53,7 @@ pub fn histogram(
RunnableContext { input, name, .. }: RunnableContext, RunnableContext { input, name, .. }: RunnableContext,
) -> Result<OutputStream, ShellError> { ) -> Result<OutputStream, ShellError> {
let stream = async_stream! { let stream = async_stream! {
let values: Vec<Value> = input.values.collect().await; let values: Vec<Value> = input.collect().await;
let Tagged { item: group_by, .. } = column_name.clone(); let Tagged { item: group_by, .. } = column_name.clone();

View File

@ -0,0 +1,116 @@
use crate::commands::WholeStreamCommand;
use crate::prelude::*;
use nu_errors::ShellError;
use nu_protocol::{Primitive, ReturnSuccess, Signature, UntaggedValue, Value};
pub struct Lines;
impl WholeStreamCommand for Lines {
fn name(&self) -> &str {
"lines"
}
fn signature(&self) -> Signature {
Signature::build("lines")
}
fn usage(&self) -> &str {
"Split single string into rows, one per line."
}
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
lines(args, registry)
}
}
fn ends_with_line_ending(st: &str) -> bool {
let mut temp = st.to_string();
let last = temp.pop();
if let Some(c) = last {
c == '\n'
} else {
false
}
}
fn lines(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
let args = args.evaluate_once(registry)?;
let tag = args.name_tag();
let name_span = tag.span;
let mut input = args.input;
let mut leftover = vec![];
let mut leftover_string = String::new();
let stream = async_stream! {
loop {
match input.next().await {
Some(Value { value: UntaggedValue::Primitive(Primitive::String(st)), ..}) => {
let mut st = leftover_string.clone() + &st;
leftover.clear();
let mut lines: Vec<String> = st.lines().map(|x| x.to_string()).collect();
if !ends_with_line_ending(&st) {
if let Some(last) = lines.pop() {
leftover_string = last;
} else {
leftover_string.clear();
}
} else {
leftover_string.clear();
}
let success_lines: Vec<_> = lines.iter().map(|x| ReturnSuccess::value(UntaggedValue::line(x).into_untagged_value())).collect();
yield futures::stream::iter(success_lines)
}
Some(Value { value: UntaggedValue::Primitive(Primitive::Line(st)), ..}) => {
let mut st = leftover_string.clone() + &st;
leftover.clear();
let mut lines: Vec<String> = st.lines().map(|x| x.to_string()).collect();
if !ends_with_line_ending(&st) {
if let Some(last) = lines.pop() {
leftover_string = last;
} else {
leftover_string.clear();
}
} else {
leftover_string.clear();
}
let success_lines: Vec<_> = lines.iter().map(|x| ReturnSuccess::value(UntaggedValue::line(x).into_untagged_value())).collect();
yield futures::stream::iter(success_lines)
}
Some( Value { tag: value_span, ..}) => {
yield futures::stream::iter(vec![Err(ShellError::labeled_error_with_secondary(
"Expected a string from pipeline",
"requires string input",
name_span,
"value originates from here",
value_span,
))]);
}
None => {
if !leftover.is_empty() {
let mut st = leftover_string.clone();
if let Ok(extra) = String::from_utf8(leftover) {
st.push_str(&extra);
}
yield futures::stream::iter(vec![ReturnSuccess::value(UntaggedValue::string(st).into_untagged_value())])
}
break;
}
}
}
if !leftover_string.is_empty() {
yield futures::stream::iter(vec![ReturnSuccess::value(UntaggedValue::string(leftover_string).into_untagged_value())]);
}
}
.flatten();
Ok(stream.to_output_stream())
}

View File

@ -10,6 +10,7 @@ pub struct Ls;
#[derive(Deserialize)] #[derive(Deserialize)]
pub struct LsArgs { pub struct LsArgs {
pub path: Option<Tagged<PathBuf>>, pub path: Option<Tagged<PathBuf>>,
pub all: bool,
pub full: bool, pub full: bool,
#[serde(rename = "short-names")] #[serde(rename = "short-names")]
pub short_names: bool, pub short_names: bool,
@ -29,6 +30,7 @@ impl PerItemCommand for Ls {
SyntaxShape::Pattern, SyntaxShape::Pattern,
"a path to get the directory contents from", "a path to get the directory contents from",
) )
.switch("all", "also show hidden files", Some('a'))
.switch( .switch(
"full", "full",
"list all available columns for each entry", "list all available columns for each entry",

View File

@ -46,7 +46,7 @@ pub fn map_max_by(
RunnableContext { input, name, .. }: RunnableContext, RunnableContext { input, name, .. }: RunnableContext,
) -> Result<OutputStream, ShellError> { ) -> Result<OutputStream, ShellError> {
let stream = async_stream! { let stream = async_stream! {
let values: Vec<Value> = input.values.collect().await; let values: Vec<Value> = input.collect().await;
if values.is_empty() { if values.is_empty() {

View File

@ -22,7 +22,7 @@ impl WholeStreamCommand for Nth {
Signature::build("nth") Signature::build("nth")
.required( .required(
"row number", "row number",
SyntaxShape::Any, SyntaxShape::Int,
"the number of the row to return", "the number of the row to return",
) )
.rest(SyntaxShape::Any, "Optionally return more rows") .rest(SyntaxShape::Any, "Optionally return more rows")
@ -49,7 +49,6 @@ fn nth(
RunnableContext { input, .. }: RunnableContext, RunnableContext { input, .. }: RunnableContext,
) -> Result<OutputStream, ShellError> { ) -> Result<OutputStream, ShellError> {
let stream = input let stream = input
.values
.enumerate() .enumerate()
.map(move |(idx, item)| { .map(move |(idx, item)| {
let row_number = vec![row_number.clone()]; let row_number = vec![row_number.clone()];

View File

@ -6,10 +6,6 @@ use nu_protocol::{
CallInfo, ReturnSuccess, Signature, SyntaxShape, TaggedDictBuilder, UntaggedValue, Value, CallInfo, ReturnSuccess, Signature, SyntaxShape, TaggedDictBuilder, UntaggedValue, Value,
}; };
use nom::{
bytes::complete::{tag, take_while},
IResult,
};
use regex::Regex; use regex::Regex;
#[derive(Debug)] #[derive(Debug)]
@ -18,32 +14,44 @@ enum ParseCommand {
Column(String), Column(String),
} }
fn parse(input: &str) -> IResult<&str, Vec<ParseCommand>> { fn parse(input: &str) -> Vec<ParseCommand> {
let mut output = vec![]; let mut output = vec![];
let mut loop_input = input; //let mut loop_input = input;
let mut loop_input = input.chars();
loop { loop {
let (input, before) = take_while(|c| c != '{')(loop_input)?; let mut before = String::new();
while let Some(c) = loop_input.next() {
if c == '{' {
break;
}
before.push(c);
}
if !before.is_empty() { if !before.is_empty() {
output.push(ParseCommand::Text(before.to_string())); output.push(ParseCommand::Text(before.to_string()));
} }
if input != "" {
// Look for column as we're now at one // Look for column as we're now at one
let (input, _) = tag("{")(input)?; let mut column = String::new();
let (input, column) = take_while(|c| c != '}')(input)?;
let (input, _) = tag("}")(input)?;
output.push(ParseCommand::Column(column.to_string())); while let Some(c) = loop_input.next() {
loop_input = input; if c == '}' {
} else { break;
loop_input = input;
} }
if loop_input == "" { column.push(c);
}
if !column.is_empty() {
output.push(ParseCommand::Column(column.to_string()));
}
if before.is_empty() && column.is_empty() {
break; break;
} }
} }
Ok((loop_input, output)) output
} }
fn column_names(commands: &[ParseCommand]) -> Vec<String> { fn column_names(commands: &[ParseCommand]) -> Vec<String> {
@ -103,16 +111,10 @@ impl PerItemCommand for Parse {
//let value_tag = value.tag(); //let value_tag = value.tag();
let pattern = call_info.args.expect_nth(0)?.as_string()?; let pattern = call_info.args.expect_nth(0)?.as_string()?;
let parse_pattern = parse(&pattern).map_err(|_| { let parse_pattern = parse(&pattern);
ShellError::labeled_error( let parse_regex = build_regex(&parse_pattern);
"Could not create parse pattern",
"could not create parse pattern",
&value.tag,
)
})?;
let parse_regex = build_regex(&parse_pattern.1);
let column_names = column_names(&parse_pattern.1); let column_names = column_names(&parse_pattern);
let regex = Regex::new(&parse_regex).map_err(|_| { let regex = Regex::new(&parse_regex).map_err(|_| {
ShellError::labeled_error("Could not parse regex", "could not parse regex", &value.tag) ShellError::labeled_error("Could not parse regex", "could not parse regex", &value.tag)
})?; })?;

View File

@ -1,7 +1,6 @@
use crate::commands::WholeStreamCommand; use crate::commands::WholeStreamCommand;
use crate::context::CommandRegistry; use crate::context::CommandRegistry;
use crate::prelude::*; use crate::prelude::*;
use futures_util::pin_mut;
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_protocol::{ use nu_protocol::{
ColumnPath, PathMember, Primitive, ReturnSuccess, ReturnValue, Signature, SyntaxShape, ColumnPath, PathMember, Primitive, ReturnSuccess, ReturnValue, Signature, SyntaxShape,
@ -44,7 +43,9 @@ impl WholeStreamCommand for Pick {
fn pick( fn pick(
PickArgs { rest: mut fields }: PickArgs, PickArgs { rest: mut fields }: PickArgs,
RunnableContext { input, name, .. }: RunnableContext, RunnableContext {
mut input, name, ..
}: RunnableContext,
) -> Result<OutputStream, ShellError> { ) -> Result<OutputStream, ShellError> {
if fields.is_empty() { if fields.is_empty() {
return Err(ShellError::labeled_error( return Err(ShellError::labeled_error(
@ -64,13 +65,10 @@ fn pick(
.collect::<Vec<ColumnPath>>(); .collect::<Vec<ColumnPath>>();
let stream = async_stream! { let stream = async_stream! {
let values = input.values;
pin_mut!(values);
let mut empty = true; let mut empty = true;
let mut bring_back: indexmap::IndexMap<String, Vec<Value>> = indexmap::IndexMap::new(); let mut bring_back: indexmap::IndexMap<String, Vec<Value>> = indexmap::IndexMap::new();
while let Some(value) = values.next().await { while let Some(value) = input.next().await {
for path in &column_paths { for path in &column_paths {
let path_members_span = span_for_spanned_list(path.members().iter().map(|p| p.span)); let path_members_span = span_for_spanned_list(path.members().iter().map(|p| p.span));
@ -80,7 +78,7 @@ fn pick(
"No data to fetch.", "No data to fetch.",
format!("Couldn't pick column \"{}\"", column), format!("Couldn't pick column \"{}\"", column),
path_member_tried.span, path_member_tried.span,
format!("How about exploring it with \"get\"? Check the input is appropiate originating from here"), format!("How about exploring it with \"get\"? Check the input is appropriate originating from here"),
obj_source.tag.span) obj_source.tag.span)
} }

View File

@ -1,7 +1,9 @@
use crate::commands::WholeStreamCommand; use crate::commands::WholeStreamCommand;
use crate::prelude::*; use crate::prelude::*;
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_protocol::{ReturnSuccess, Signature, SyntaxShape, TaggedDictBuilder, UntaggedValue, Value}; use nu_protocol::{
merge_descriptors, ReturnSuccess, Signature, SyntaxShape, TaggedDictBuilder, UntaggedValue,
};
use nu_source::{SpannedItem, Tagged}; use nu_source::{SpannedItem, Tagged};
use nu_value_ext::get_data_by_key; use nu_value_ext::get_data_by_key;
@ -52,18 +54,6 @@ impl WholeStreamCommand for Pivot {
} }
} }
fn merge_descriptors(values: &[Value]) -> Vec<String> {
let mut ret = vec![];
for value in values {
for desc in value.data_descriptors() {
if !ret.contains(&desc) {
ret.push(desc);
}
}
}
ret
}
pub fn pivot(args: PivotArgs, context: RunnableContext) -> Result<OutputStream, ShellError> { pub fn pivot(args: PivotArgs, context: RunnableContext) -> Result<OutputStream, ShellError> {
let stream = async_stream! { let stream = async_stream! {
let input = context.input.into_vec().await; let input = context.input.into_vec().await;

View File

@ -3,7 +3,7 @@ use crate::prelude::*;
use derive_new::new; use derive_new::new;
use log::trace; use log::trace;
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_protocol::{Primitive, ReturnSuccess, ReturnValue, Scope, Signature, UntaggedValue, Value}; use nu_protocol::{Primitive, ReturnSuccess, ReturnValue, Signature, UntaggedValue, Value};
use serde::{self, Deserialize, Serialize}; use serde::{self, Deserialize, Serialize};
use std::io::prelude::*; use std::io::prelude::*;
use std::io::BufReader; use std::io::BufReader;
@ -71,10 +71,13 @@ pub fn filter_plugin(
) -> Result<OutputStream, ShellError> { ) -> Result<OutputStream, ShellError> {
trace!("filter_plugin :: {}", path); trace!("filter_plugin :: {}", path);
let args = args.evaluate_once_with_scope( let scope = &args
registry, .call_info
&Scope::it_value(UntaggedValue::string("$it").into_untagged_value()), .scope
)?; .clone()
.set_it(UntaggedValue::string("$it").into_untagged_value());
let args = args.evaluate_once_with_scope(registry, &scope)?;
let mut child = std::process::Command::new(path) let mut child = std::process::Command::new(path)
.stdin(std::process::Stdio::piped()) .stdin(std::process::Stdio::piped())
@ -95,7 +98,7 @@ pub fn filter_plugin(
trace!("filtering :: {:?}", call_info); trace!("filtering :: {:?}", call_info);
let stream = bos let stream = bos
.chain(args.input.values) .chain(args.input)
.chain(eos) .chain(eos)
.map(move |v| match v { .map(move |v| match v {
Value { Value {
@ -340,7 +343,7 @@ pub fn sink_plugin(
let call_info = args.call_info.clone(); let call_info = args.call_info.clone();
let stream = async_stream! { let stream = async_stream! {
let input: Vec<Value> = args.input.values.collect().await; let input: Vec<Value> = args.input.collect().await;
let request = JsonRpc::new("sink", (call_info.clone(), input)); let request = JsonRpc::new("sink", (call_info.clone(), input));
let request_raw = serde_json::to_string(&request); let request_raw = serde_json::to_string(&request);

View File

@ -43,5 +43,5 @@ fn prepend(
) -> Result<OutputStream, ShellError> { ) -> Result<OutputStream, ShellError> {
let prepend = futures::stream::iter(vec![row]); let prepend = futures::stream::iter(vec![row]);
Ok(OutputStream::from_input(prepend.chain(input.values))) Ok(prepend.chain(input).to_output_stream())
} }

View File

@ -50,7 +50,5 @@ fn range(
let from = *from as usize; let from = *from as usize;
let to = *to as usize; let to = *to as usize;
Ok(OutputStream::from_input( Ok(input.skip(from).take(to - from + 1).to_output_stream())
input.values.skip(from).take(to - from + 1),
))
} }

View File

@ -45,7 +45,7 @@ pub fn reduce_by(
RunnableContext { input, name, .. }: RunnableContext, RunnableContext { input, name, .. }: RunnableContext,
) -> Result<OutputStream, ShellError> { ) -> Result<OutputStream, ShellError> {
let stream = async_stream! { let stream = async_stream! {
let values: Vec<Value> = input.values.collect().await; let values: Vec<Value> = input.collect().await;
if values.is_empty() { if values.is_empty() {
yield Err(ShellError::labeled_error( yield Err(ShellError::labeled_error(

View File

@ -18,7 +18,7 @@ impl WholeStreamCommand for Reject {
} }
fn signature(&self) -> Signature { fn signature(&self) -> Signature {
Signature::build("reject").rest(SyntaxShape::Member, "the names of columns to remove") Signature::build("reject").rest(SyntaxShape::String, "the names of columns to remove")
} }
fn usage(&self) -> &str { fn usage(&self) -> &str {
@ -48,9 +48,7 @@ fn reject(
let fields: Vec<_> = fields.iter().map(|f| f.item.clone()).collect(); let fields: Vec<_> = fields.iter().map(|f| f.item.clone()).collect();
let stream = input let stream = input.map(move |item| reject_fields(&item, &fields, &item.tag));
.values
.map(move |item| reject_fields(&item, &fields, &item.tag));
Ok(stream.from_input_stream()) Ok(stream.from_input_stream())
} }

View File

@ -0,0 +1,96 @@
use crate::commands::WholeStreamCommand;
use crate::prelude::*;
use indexmap::IndexMap;
use nu_errors::ShellError;
use nu_protocol::{ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value};
use nu_source::Tagged;
pub struct Rename;
#[derive(Deserialize)]
pub struct Arguments {
column_name: Tagged<String>,
rest: Vec<Tagged<String>>,
}
impl WholeStreamCommand for Rename {
fn name(&self) -> &str {
"rename"
}
fn signature(&self) -> Signature {
Signature::build("rename")
.required(
"column_name",
SyntaxShape::String,
"the name of the column to rename for",
)
.rest(
SyntaxShape::String,
"Additional column name(s) to rename for",
)
}
fn usage(&self) -> &str {
"Creates a new table with columns renamed."
}
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
args.process(registry, rename)?.run()
}
}
pub fn rename(
Arguments { column_name, rest }: Arguments,
RunnableContext { input, name, .. }: RunnableContext,
) -> Result<OutputStream, ShellError> {
let mut new_column_names = vec![vec![column_name]];
new_column_names.push(rest);
let new_column_names = new_column_names.into_iter().flatten().collect::<Vec<_>>();
let stream = input
.map(move |item| {
let mut result = VecDeque::new();
if let Value {
value: UntaggedValue::Row(row),
tag,
} = item
{
let mut renamed_row = IndexMap::new();
for (idx, (key, value)) in row.entries.iter().enumerate() {
let key = if idx < new_column_names.len() {
&new_column_names[idx].item
} else {
key
};
renamed_row.insert(key.clone(), value.clone());
}
let out = UntaggedValue::Row(renamed_row.into()).into_value(tag);
result.push_back(ReturnSuccess::value(out));
} else {
result.push_back(ReturnSuccess::value(
UntaggedValue::Error(ShellError::labeled_error(
"no column names available",
"can't rename",
&name,
))
.into_untagged_value(),
));
}
futures::stream::iter(result)
})
.flatten();
Ok(stream.to_output_stream())
}

View File

@ -32,7 +32,7 @@ fn reverse(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream
let args = args.evaluate_once(registry)?; let args = args.evaluate_once(registry)?;
let (input, _args) = args.parts(); let (input, _args) = args.parts();
let input = input.values.collect::<Vec<_>>(); let input = input.collect::<Vec<_>>();
let output = input.map(move |mut vec| { let output = input.map(move |mut vec| {
vec.reverse(); vec.reverse();

View File

@ -10,8 +10,9 @@ pub struct Remove;
#[derive(Deserialize)] #[derive(Deserialize)]
pub struct RemoveArgs { pub struct RemoveArgs {
pub target: Tagged<PathBuf>, pub rest: Vec<Tagged<PathBuf>>,
pub recursive: Tagged<bool>, pub recursive: Tagged<bool>,
#[allow(unused)]
pub trash: Tagged<bool>, pub trash: Tagged<bool>,
} }
@ -22,17 +23,17 @@ impl PerItemCommand for Remove {
fn signature(&self) -> Signature { fn signature(&self) -> Signature {
Signature::build("rm") Signature::build("rm")
.required("path", SyntaxShape::Pattern, "the file path to remove")
.switch( .switch(
"trash", "trash",
"use the platform's recycle bin instead of permanently deleting", "use the platform's recycle bin instead of permanently deleting",
Some('t'), Some('t'),
) )
.switch("recursive", "delete subdirectories recursively", Some('r')) .switch("recursive", "delete subdirectories recursively", Some('r'))
.rest(SyntaxShape::Pattern, "the file path(s) to remove")
} }
fn usage(&self) -> &str { fn usage(&self) -> &str {
"Remove a file" "Remove file(s)"
} }
fn run( fn run(

View File

@ -0,0 +1,108 @@
use crate::commands::classified::block::run_block;
use crate::prelude::*;
use derive_new::new;
use nu_errors::ShellError;
use nu_protocol::{hir::Block, CallInfo, ReturnSuccess, Scope, Signature, SyntaxShape, Value};
#[derive(new)]
pub struct AliasCommand {
name: String,
args: Vec<String>,
block: Block,
}
impl PerItemCommand for AliasCommand {
fn name(&self) -> &str {
&self.name
}
fn signature(&self) -> Signature {
let mut alias = Signature::build(&self.name);
for arg in &self.args {
alias = alias.optional(arg, SyntaxShape::Any, "");
}
alias
}
fn usage(&self) -> &str {
""
}
fn run(
&self,
call_info: &CallInfo,
registry: &CommandRegistry,
raw_args: &RawCommandArgs,
input: Value,
) -> Result<OutputStream, ShellError> {
let tag = call_info.name_tag.clone();
let call_info = call_info.clone();
let registry = registry.clone();
let raw_args = raw_args.clone();
let block = self.block.clone();
let mut scope = Scope::it_value(input.clone());
if let Some(positional) = &call_info.args.positional {
for (pos, arg) in positional.iter().enumerate() {
scope = scope.set_var(self.args[pos].to_string(), arg.clone());
}
}
let stream = async_stream! {
let mut context = Context::from_raw(&raw_args, &registry);
let input_clone = Ok(input.clone());
let input_stream = futures::stream::once(async { input_clone }).boxed().to_input_stream();
let result = run_block(
&block,
&mut context,
input_stream,
&scope
).await;
match result {
Ok(stream) if stream.is_empty() => {
yield Err(ShellError::labeled_error(
"Expected a block",
"alias needs a block",
tag,
));
}
Ok(mut stream) => {
// We collect first to ensure errors are put into the context
while let Some(result) = stream.next().await {
yield Ok(ReturnSuccess::Value(result));
}
let errors = context.get_errors();
if let Some(x) = errors.first() {
//yield Err(error.clone());
yield Err(ShellError::labeled_error_with_secondary(
"Alias failed to run",
"alias failed to run",
tag.clone(),
x.to_string(),
tag
));
}
}
Err(e) => {
//yield Err(e);
yield Err(ShellError::labeled_error_with_secondary(
"Alias failed to run",
"alias failed to run",
tag.clone(),
e.to_string(),
tag
));
}
}
};
Ok(stream.to_output_stream())
}
}

View File

@ -0,0 +1,122 @@
use crate::commands::classified::external;
use crate::commands::WholeStreamCommand;
use crate::prelude::*;
use derive_new::new;
use parking_lot::Mutex;
use nu_errors::ShellError;
use nu_protocol::hir::{Expression, ExternalArgs, ExternalCommand, Literal, SpannedExpression};
use nu_protocol::{ReturnSuccess, Signature, SyntaxShape};
#[derive(Deserialize)]
pub struct RunExternalArgs {}
#[derive(new)]
pub struct RunExternalCommand;
fn spanned_expression_to_string(expr: SpannedExpression) -> String {
if let SpannedExpression {
expr: Expression::Literal(Literal::String(s)),
..
} = expr
{
s
} else {
"notacommand!!!".to_string()
}
}
impl WholeStreamCommand for RunExternalCommand {
fn name(&self) -> &str {
"run_external"
}
fn signature(&self) -> Signature {
Signature::build(self.name()).rest(SyntaxShape::Any, "external command arguments")
}
fn usage(&self) -> &str {
""
}
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
let positionals = args.call_info.args.positional.ok_or_else(|| {
ShellError::untagged_runtime_error("positional arguments unexpectedly empty")
})?;
let mut positionals = positionals.into_iter();
let name = positionals
.next()
.map(spanned_expression_to_string)
.ok_or_else(|| {
ShellError::untagged_runtime_error(
"run_external unexpectedly missing external name positional arg",
)
})?;
let command = ExternalCommand {
name,
name_tag: args.call_info.name_tag.clone(),
args: ExternalArgs {
list: positionals.collect(),
span: args.call_info.args.span,
},
};
let mut external_context;
#[cfg(windows)]
{
external_context = Context {
registry: registry.clone(),
host: args.host.clone(),
shell_manager: args.shell_manager.clone(),
ctrl_c: args.ctrl_c.clone(),
current_errors: Arc::new(Mutex::new(vec![])),
windows_drives_previous_cwd: Arc::new(Mutex::new(std::collections::HashMap::new())),
};
}
#[cfg(not(windows))]
{
external_context = Context {
registry: registry.clone(),
host: args.host.clone(),
shell_manager: args.shell_manager.clone(),
ctrl_c: args.ctrl_c.clone(),
current_errors: Arc::new(Mutex::new(vec![])),
};
}
let scope = args.call_info.scope.clone();
let is_last = args.call_info.args.is_last;
let input = args.input;
let stream = async_stream! {
let result = external::run_external_command(
command,
&mut external_context,
input,
&scope,
is_last,
).await;
match result {
Ok(mut stream) => {
while let Some(value) = stream.next().await {
yield Ok(ReturnSuccess::Value(value));
}
},
Err(e) => {
yield Err(e);
},
_ => {}
}
};
Ok(stream.to_output_stream())
}
}

View File

@ -1,12 +1,28 @@
use crate::commands::{UnevaluatedCallInfo, WholeStreamCommand}; use crate::commands::{UnevaluatedCallInfo, WholeStreamCommand};
use crate::prelude::*; use crate::prelude::*;
use nu_errors::ShellError; use nu_errors::ShellError;
use nu_protocol::{Primitive, ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value}; use nu_protocol::{Primitive, ReturnSuccess, Scope, Signature, SyntaxShape, UntaggedValue, Value};
use nu_source::Tagged; use nu_source::Tagged;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
pub struct Save; pub struct Save;
macro_rules! process_unknown {
($scope:tt, $input:ident, $name_tag:ident) => {{
if $input.len() > 0 {
match $input[0] {
Value {
value: UntaggedValue::Primitive(Primitive::Binary(_)),
..
} => process_binary!($scope, $input, $name_tag),
_ => process_string!($scope, $input, $name_tag),
}
} else {
process_string!($scope, $input, $name_tag)
}
}};
}
macro_rules! process_string { macro_rules! process_string {
($scope:tt, $input:ident, $name_tag:ident) => {{ ($scope:tt, $input:ident, $name_tag:ident) => {{
let mut result_string = String::new(); let mut result_string = String::new();
@ -31,6 +47,32 @@ macro_rules! process_string {
}}; }};
} }
macro_rules! process_binary {
($scope:tt, $input:ident, $name_tag:ident) => {{
let mut result_binary: Vec<u8> = Vec::new();
for res in $input {
match res {
Value {
value: UntaggedValue::Primitive(Primitive::Binary(b)),
..
} => {
for u in b.into_iter() {
result_binary.push(u);
}
}
_ => {
break $scope Err(ShellError::labeled_error(
"Save could not successfully save",
"unexpected data during binary save",
$name_tag,
));
}
}
}
Ok(result_binary)
}};
}
macro_rules! process_string_return_success { macro_rules! process_string_return_success {
($scope:tt, $result_vec:ident, $name_tag:ident) => {{ ($scope:tt, $result_vec:ident, $name_tag:ident) => {{
let mut result_string = String::new(); let mut result_string = String::new();
@ -126,7 +168,7 @@ fn save(
shell_manager, shell_manager,
host, host,
ctrl_c, ctrl_c,
commands: registry, registry,
.. ..
}: RunnableContext, }: RunnableContext,
raw_args: RawCommandArgs, raw_args: RawCommandArgs,
@ -135,7 +177,7 @@ fn save(
let name_tag = name.clone(); let name_tag = name.clone();
let stream = async_stream! { let stream = async_stream! {
let input: Vec<Value> = input.values.collect().await; let input: Vec<Value> = input.collect().await;
if path.is_none() { if path.is_none() {
// If there is no filename, check the metadata for the anchor filename // If there is no filename, check the metadata for the anchor filename
if input.len() > 0 { if input.len() > 0 {
@ -186,14 +228,15 @@ fn save(
ctrl_c, ctrl_c,
shell_manager, shell_manager,
call_info: UnevaluatedCallInfo { call_info: UnevaluatedCallInfo {
args: nu_parser::hir::Call { args: nu_protocol::hir::Call {
head: raw_args.call_info.args.head, head: raw_args.call_info.args.head,
positional: None, positional: None,
named: None, named: None,
span: Span::unknown() span: Span::unknown(),
is_last: false,
}, },
source: raw_args.call_info.source,
name_tag: raw_args.call_info.name_tag, name_tag: raw_args.call_info.name_tag,
scope: Scope::empty(), // FIXME?
} }
}; };
let mut result = converter.run(new_args.with_input(input), &registry); let mut result = converter.run(new_args.with_input(input), &registry);
@ -204,10 +247,10 @@ fn save(
process_string_return_success!('scope, result_vec, name_tag) process_string_return_success!('scope, result_vec, name_tag)
} }
} else { } else {
process_string!('scope, input, name_tag) process_unknown!('scope, input, name_tag)
} }
} else { } else {
process_string!('scope, input, name_tag) process_unknown!('scope, input, name_tag)
} }
} else { } else {
Ok(string_from(&input).into_bytes()) Ok(string_from(&input).into_bytes())

View File

@ -36,9 +36,9 @@ fn shells(args: CommandArgs, _registry: &CommandRegistry) -> Result<OutputStream
let mut dict = TaggedDictBuilder::new(&tag); let mut dict = TaggedDictBuilder::new(&tag);
if index == (*args.shell_manager.current_shell).load(Ordering::SeqCst) { if index == (*args.shell_manager.current_shell).load(Ordering::SeqCst) {
dict.insert_untagged(" ", "X".to_string()); dict.insert_untagged("active", "X".to_string());
} else { } else {
dict.insert_untagged(" ", " ".to_string()); dict.insert_untagged("active", " ".to_string());
} }
dict.insert_untagged("name", shell.name()); dict.insert_untagged("name", shell.name());
dict.insert_untagged("path", shell.path()); dict.insert_untagged("path", shell.path());

View File

@ -0,0 +1,69 @@
use crate::commands::WholeStreamCommand;
use crate::context::CommandRegistry;
use crate::prelude::*;
use nu_errors::ShellError;
use nu_protocol::{ReturnSuccess, ReturnValue, Signature, SyntaxShape, Value};
use nu_source::Tagged;
use rand::seq::SliceRandom;
use rand::thread_rng;
pub struct Shuffle;
#[derive(Deserialize)]
pub struct Arguments {
#[serde(rename = "num")]
limit: Option<Tagged<u64>>,
}
impl WholeStreamCommand for Shuffle {
fn name(&self) -> &str {
"shuffle"
}
fn signature(&self) -> Signature {
Signature::build("shuffle").named(
"num",
SyntaxShape::Int,
"Limit `num` number of rows",
Some('n'),
)
}
fn usage(&self) -> &str {
"Shuffle rows randomly."
}
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
args.process(registry, shuffle)?.run()
}
}
fn shuffle(
Arguments { limit }: Arguments,
RunnableContext { input, .. }: RunnableContext,
) -> Result<OutputStream, ShellError> {
let stream = async_stream! {
let mut values: Vec<Value> = input.collect().await;
let out = if let Some(n) = limit {
let (shuffled, _) = values.partial_shuffle(&mut thread_rng(), *n as usize);
shuffled.to_vec()
} else {
values.shuffle(&mut thread_rng());
values.clone()
};
for val in out.into_iter() {
yield ReturnSuccess::value(val);
}
};
let stream: BoxStream<'static, ReturnValue> = stream.boxed();
Ok(stream.to_output_stream())
}

View File

@ -33,7 +33,6 @@ fn size(args: CommandArgs, _registry: &CommandRegistry) -> Result<OutputStream,
let name_span = tag.span; let name_span = tag.span;
Ok(input Ok(input
.values
.map(move |v| { .map(move |v| {
if let Ok(s) = v.as_string() { if let Ok(s) = v.as_string() {
ReturnSuccess::value(count(&s, &v.tag)) ReturnSuccess::value(count(&s, &v.tag))

View File

@ -41,7 +41,5 @@ fn skip(SkipArgs { rows }: SkipArgs, context: RunnableContext) -> Result<OutputS
1 1
}; };
Ok(OutputStream::from_input( Ok(OutputStream::from_input(context.input.skip(rows_desired)))
context.input.values.skip(rows_desired),
))
} }

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