Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

watch command #6

Closed
wants to merge 1 commit into from
Closed

watch command #6

wants to merge 1 commit into from

Conversation

rgwood
Copy link
Owner

@rgwood rgwood commented Apr 26, 2022

This PR creates an experimental watch command:

〉help watch
Watch for file changes and execute Nu code when they happen.

Search terms: watcher, reload, filesystem

Usage:
  > watch {flags} <path> <block> 

Flags:
  -h, --help
      Display this help message
  -d, --debounce-ms <Int>
      Debounce changes for this many milliseconds (default: 100). Adjust if you find that single writes are reported as multiple events
  -g, --glob <String>
      Only report changes for files that match this glob pattern (default: all files)
  -r, --recursive <Boolean>
      Watch all directories under <path> recursively. Will be ignored if <path> is a file (default: true)
  -v, --verbose
      Operate in verbose mode (default: false)

Parameters:
  path: the path to watch. Can be a file or directory
  block: A Nu block of code to run whenever a file changes. The block will be passed `operation`, `path`, and `new_path` (for renames only) arguments in that order

Examples:
  Run `cargo test` whenever a Rust file changes
  > watch . --glob=**/*.rs { cargo test }

  Watch all changes in the current directory
  > watch . { |op, path, new_path| $"($op) ($path) ($new_path)"}

  Log all changes in a directory
  > watch /foo/bar { |op, path| $"($op) - ($path)(char nl)" | save --append changes_in_bar.log }

image

It uses the popular notify crate to watch for file changes., and it runs in the foreground until the user presses ctrl+c.

Motivation

I find myself using little file watcher tools to automate tasks quite often; for example I'll want to run tests when my code changes, watch what a program is doing inside a directory, etc.

It's currently possible to use a tool like watchexec to launch a new instance of Nu in response to file changes. But I think it might be more powerful and ergonomic to be able to respond to events without leaving Nu.

Future work

  • Currently this just queues up changes and runs the block serially for each one. Might need to revisit that (maybe we'll want to batch changes if many arrive in a short period of time?)
  • I wasn't able to find a good way to display errors from the block with nice Miette formatting. I will look into that later.

Build measurements

Before PR: 493 crates, 35.37s, 15.8 MiB
After PR: 502 crates, 36.42s, 16.0MiB

(cargo build --release on Linux w/ 12900K CPU, mold linker)

Tests

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

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

@rgwood rgwood closed this Apr 26, 2022
rgwood pushed a commit that referenced this pull request Nov 23, 2022
# Description
BEFORE:
```
〉ls | size
Error: nu::shell::pipeline_mismatch (link)

  × Pipeline mismatch.
   ╭─[entry #22:1:1]
 1 │ ls | size
   ·      ──┬─
   ·        │╰── value originates from here
   ·        ╰── expected: string
   ╰────

〉ls | sort-by SIZE
Error: nu:🐚:column_not_found (link)

  × Cannot find column
   ╭─[entry #17:1:1]
 1 │ ls | sort-by SIZE
   ·      ───┬───
   ·         │╰── value originates here
   ·         ╰── cannot find column
   ╰────

〉[4kb] | path join 'b'
Error: nu:🐚:pipeline_mismatch (link)

  × Pipeline mismatch.
   ╭─[entry #6:1:1]
 1 │ [4kb] | path join 'b'
   · ──┬──
   ·   │╰── value originates from here
   ·   ╰── expected: string or record
   ╰────
```
AFTER:
```
〉ls | size
Error: nu:🐚:pipeline_mismatch (link)

  × Pipeline mismatch.
   ╭─[entry #1:1:1]
 1 │ ls | size
   · ─┬   ──┬─
   ·  │     ╰── expected: string
   ·  ╰── value originates from here
   ╰────

〉ls | get 0 | sort-by SIZE
Error: nu:🐚:column_not_found (link)

  × Cannot find column
   ╭─[entry #2:1:1]
 1 │ ls | get 0 | sort-by SIZE
   · ─┬           ───┬───
   ·  │              ╰── cannot find column 'SIZE'
   ·  ╰── value originates here
   ╰────

〉[4kb] | path join 'b'
Error: nu:🐚:pipeline_mismatch (link)

  × Pipeline mismatch.
   ╭─[entry #1:1:1]
 1 │ [4kb] | path join 'b'
   · ──┬──   ────┬────
   ·   │         ╰── expected: string or record
   ·   ╰── value originates from here
   ╰────

```

(Hey, anyone noticed that there's TWO wordings of "value originates from
here" in this codebase………?)

# User-Facing Changes

See above.

# Tests + Formatting

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

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

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

# After Submitting

If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
rgwood pushed a commit that referenced this pull request Dec 14, 2022
BEFORE:
```
〉du *.***
Error:
  × wildcards are either regular `*` or recursive `**`
   ╭─[entry #6:1:1]
 1 │ du *.***
   · ─┬
   ·  ╰── glob error
   ╰────
```
AFTER:
```
〉du *.***
Error:
  × glob error
   ╭─[entry #8:1:1]
 1 │ du *.***
   ·    ──┬──
   ·      ╰── wildcards are either regular `*` or recursive `**`
   ╰────

```
rgwood pushed a commit that referenced this pull request Feb 14, 2023
# Description

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

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

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

```bash

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

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

# User-Facing Changes

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

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

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

# Tests + Formatting

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

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

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

# After Submitting

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

---------

Co-authored-by: Stefan Holderbach <[email protected]>
rgwood pushed a commit that referenced this pull request Aug 7, 2023
# Description

This PR updates the `char` command to allow `Table` output due to the
`--list` parameter.

### Before
```nushell
char --list | transpose
Error: nu::parser::input_type_mismatch

  × Command does not support string input.
   ╭─[entry #6:1:1]
 1 │ char --list | transpose
   ·               ────┬────
   ·                   ╰── command doesn't support string input
   ╰────
```

### After
```nushell
❯ char --list | transpose
╭───┬───────────┬─────────┬─────────┬─────────┬───────────┬─────────┬─────────────┬─────────┬─────────┬─────────┬──────────┬──────────┬──────────┬────────────┬──────────┬─────────────┬──────────┬────────────┬──────────┬──────────┬─────╮
│ # │  column0  │ column1 │ column2 │ column3 │  column4  │ column5 │   column6   │ column7 │ column8 │ column9 │ column10 │ column11 │ column12 │  column13  │ column14 │  column15   │ column16 │  column17  │ column18 │ column19 │ ... │
├───┼───────────┼─────────┼─────────┼─────────┼───────────┼─────────┼─────────────┼─────────┼─────────┼─────────┼──────────┼──────────┼──────────┼────────────┼──────────┼─────────────┼──────────┼────────────┼──────────┼──────────┼─────┤
│ 0 │ name      │ newline │ enter   │ nl      │ line_feed │ lf      │ carriage_re │ cr      │ crlf    │ tab     │ sp       │ space    │ pipe     │ left_brace │ lbrace   │ right_brace │ rbrace   │ left_paren │ lp       │ lparen   │ ... │
│   │           │         │         │         │           │         │ turn        │         │         │         │          │          │          │            │          │             │          │            │          │          │     │
│ 1 │ character │         │         │         │           │         │             │         │         │         │          │          │ |        │ {          │ {        │ }           │ }        │ (          │ (        │ (        │ ... │
│   │           │         │         │         │           │         │             │         │         │         │          │          │          │            │          │             │          │            │          │          │     │
│ 2 │ unicode   │ a       │ a       │ a       │ a         │ a       │ d           │ d       │ d a     │ 9       │ 20       │ 20       │ 7c       │ 7b         │ 7b       │ 7d          │ 7d       │ 28         │ 28       │ 28       │ ... │
╰───┴───────────┴─────────┴─────────┴─────────┴───────────┴─────────┴─────────────┴─────────┴─────────┴─────────┴──────────┴──────────┴──────────┴────────────┴──────────┴─────────────┴──────────┴────────────┴──────────┴──────────┴─────╯
```

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

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

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

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A
clippy::needless_collect -A clippy::result_large_err` to check that
you're using the standard code style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- -c "use std testing; testing run-tests --path
crates/nu-std"` to run the tests for the standard library

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

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
rgwood pushed a commit that referenced this pull request Oct 1, 2023
should close nushell#10549 

# Description
this PR is twofold
- uses `to nuon --raw` in the error messages to make sure nushell#10549 is
solved and makes a difference between `"1"` and `1`
- tries to introduce slightly better errors, i.e. by putting left /
right on new lines => this should hopefully help when the values become
a bit big 😋

# User-Facing Changes
the original issue:
```nushell
> assert equal {one:1 two:2} {one:"1" two:"2"}
Error:   × Assertion failed.
   ╭─[entry #3:1:1]
 1 │ assert equal {one:1 two:2} {one:"1" two:"2"}
   ·              ───────────────┬───────────────
   ·                             ╰── These are not equal.
        Left  : '{one: 1, two: 2}'
        Right : '{one: "1", two: "2"}'
   ╰────
```

a sample for all the assertions and their new messages
```nushell
> assert equal {one:1 two:2} {one:"1" two:"2"}
Error:   × Assertion failed.
   ╭─[entry #3:1:1]
 1 │ assert equal {one:1 two:2} {one:"1" two:"2"}
   ·              ───────────────┬───────────────
   ·                             ╰── These are not equal.
        Left  : '{one: 1, two: 2}'
        Right : '{one: "1", two: "2"}'
   ╰────
```
```nushell
> assert equal 1 2
Error:   × Assertion failed.
   ╭─[entry #4:1:1]
 1 │ assert equal 1 2
   ·              ─┬─
   ·               ╰── These are not equal.
        Left  : '1'
        Right : '2'
   ╰────
```
```nushell
> assert less 3 1
Error:   × Assertion failed.
   ╭─[entry #6:1:1]
 1 │ assert less 3 1
   ·             ─┬─
   ·              ╰── The condition *left < right* is not satisfied.
        Left  : '3'
        Right : '1'
   ╰────
```
```nushell
> assert less or equal 3 1
Error:   × Assertion failed.
   ╭─[entry #7:1:1]
 1 │ assert less or equal 3 1
   ·                      ─┬─
   ·                       ╰── The condition *left <= right* is not satisfied.
        Left  : '3'
        Right : '1'
   ╰────
```
```nushell
> assert greater 1 3
Error:   × Assertion failed.
   ╭─[entry #8:1:1]
 1 │ assert greater 1 3
   ·                ─┬─
   ·                 ╰── The condition *left > right* is not satisfied.
        Left  : '1'
        Right : '3'
   ╰────
```
```nushell
> assert greater or equal 1 3
Error:   × Assertion failed.
   ╭─[entry #9:1:1]
 1 │ assert greater or equal 1 3
   ·                         ─┬─
   ·                          ╰── The condition *left < right* is not satisfied.
        Left  : '1'
        Right : '3'
   ╰────
```
```nushell
> assert length [1 2 3] 2
Error:   × Assertion failed.
   ╭─[entry #10:1:1]
 1 │ assert length [1 2 3] 2
   ·               ────┬────
   ·                   ╰── This does not have the correct length:
        value    : [1, 2, 3]
        length   : 3
        expected : 2
   ╰────
```
```nushell
> assert length [1 "2" 3] 2
Error:   × Assertion failed.
   ╭─[entry #11:1:1]
 1 │ assert length [1 "2" 3] 2
   ·               ─────┬─────
   ·                    ╰── This does not have the correct length:
        value    : [1, "2", 3]
        length   : 3
        expected : 2
   ╰────
```
```nushell
> assert str contains "foo" "bar"
Error:   × Assertion failed.
   ╭─[entry #13:1:1]
 1 │ assert str contains "foo" "bar"
   ·                     ─────┬─────
   ·                          ╰── This does not contain '($right)'.
        value: "foo"
   ╰────
```

# Tests + Formatting

# After Submitting
rgwood pushed a commit that referenced this pull request Feb 11, 2024
…ushell#11569)

# Description
Fixes: nushell#11455

### For arguments which is annotated with `:path/:directory/:glob`
To fix the issue, we need to have a way to know if a path is originally
quoted during runtime. So the information needed to be added at several
levels:
* parse time (from user input to expression)
We need to add quoted information into `Expr::Filepath`,
`Expr::Directory`, `Expr::GlobPattern`
* eval time
When convert from `Expr::Filepath`, `Expr::Directory`,
`Expr::GlobPattern` to `Value::String` during runtime, we won't auto
expanded the path if it's quoted

### For `ls`
It's really special, because it accepts a `String` as a pattern, and it
generates `glob` expression inside the command itself.

So the idea behind the change is introducing a special SyntaxShape to
ls: `SyntaxShape::LsGlobPattern`. So we can track if the pattern is
originally quoted easier, and we don't auto expand the path either.

Then when constructing a glob pattern inside ls, we check if input
pattern is quoted, if so: we escape the input pattern, so we can run `ls
a[123]b`, because it's already escaped.
Finally, to accomplish the checking process, we also need to introduce a
new value type called `Value::QuotedString` to differ from
`Value::String`, it's used to generate an enum called `NuPath`, which is
finally used in `ls` function. `ls` learned from `NuPath` to know if
user input is quoted.

# User-Facing Changes
Actually it contains several changes
### For arguments which is annotated with `:path/:directory/:glob`
#### Before
```nushell
> def foo [p: path] { echo $p }; print (foo "~/a"); print (foo '~/a')
/home/windsoilder/a
/home/windsoilder/a
> def foo [p: directory] { echo $p }; print (foo "~/a"); print (foo '~/a')
/home/windsoilder/a
/home/windsoilder/a
> def foo [p: glob] { echo $p }; print (foo "~/a"); print (foo '~/a')
/home/windsoilder/a
/home/windsoilder/a
```
#### After
```nushell
> def foo [p: path] { echo $p }; print (foo "~/a"); print (foo '~/a')
~/a
~/a
> def foo [p: directory] { echo $p }; print (foo "~/a"); print (foo '~/a')
~/a
~/a
> def foo [p: glob] { echo $p }; print (foo "~/a"); print (foo '~/a')
~/a
~/a
```
### For ls command
`touch '[uwu]'`
#### Before
```
❯ ls -D "[uwu]"
Error:   × No matches found for [uwu]
   ╭─[entry #6:1:1]
 1 │ ls -D "[uwu]"
   ·       ───┬───
   ·          ╰── Pattern, file or folder not found
   ╰────
  help: no matches found
```

#### After
```
❯ ls -D "[uwu]"
╭───┬───────┬──────┬──────┬──────────╮
│ # │ name  │ type │ size │ modified │
├───┼───────┼──────┼──────┼──────────┤
│ 0 │ [uwu] │ file │  0 B │ now      │
╰───┴───────┴──────┴──────┴──────────╯
```

# Tests + Formatting
Done

# After Submitting
NaN
rgwood pushed a commit that referenced this pull request Jun 13, 2024
# Description
Fix wrong casting which is related to
nushell#12974 (comment)

# User-Facing Changes
AS-IS (before fixing)
```
$ "-10000PiB" | into filesize
6.2 EiB                                                         <--- Wrong casted value
$ "10000PiB" | into filesize 
-6.2 EiB                                                        <--- Wrong casted value
```

TO-BE (after fixing)
```
$ "-10000PiB" | into filesize
Error: nu::shell::cant_convert

  × Can't convert to filesize.
   ╭─[entry #6:1:1]
 1 │ "-10000PiB" | into filesize
   · ─────┬─────
   ·      ╰── can't convert string to filesize
   ╰────

$ "10000PiB" | into filesize
Error: nu:🐚:cant_convert

  × Can't convert to filesize.
   ╭─[entry #7:1:1]
 1 │ "10000PiB" | into filesize
   · ─────┬────
   ·      ╰── can't convert string to filesize
   ╰────
```
rgwood pushed a commit that referenced this pull request Aug 9, 2024
# Description
From the feedbacks from @amtoine , it's good to make nushell shows error
for `o>|` syntax.

# User-Facing Changes
## Before
```nushell
'foo' o>| print                                                                                                                                                                                                                     07/09/2024 06:44:23 AM
Error: nu::parser::parse_mismatch

  × Parse mismatch during operation.
   ╭─[entry #6:1:9]
 1 │ 'foo' o>| print
   ·         ┬
   ·         ╰── expected redirection target
```

## After
```nushell
'foo' o>| print                                                                                                                                                                                                                     07/09/2024 06:47:26 AM
Error: nu::parser::parse_mismatch

  × Parse mismatch during operation.
   ╭─[entry #1:1:7]
 1 │ 'foo' o>| print
   ·       ─┬─
   ·        ╰── expected `|`.  Redirection stdout to pipe is the same as piping directly.
   ╰────
```

# Tests + Formatting
Added one test

---------

Co-authored-by: Darren Schroeder <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant