2023-08-29 21:46:50 +00:00
|
|
|
use nu_cmd_base::hook::eval_hook;
|
2023-02-01 23:02:27 +00:00
|
|
|
use nu_engine::{eval_block, eval_block_with_early_return};
|
2022-04-30 18:23:05 +00:00
|
|
|
use nu_parser::{escape_quote_string, lex, parse, unescape_unquote_string, Token, TokenContents};
|
2022-02-18 18:43:34 +00:00
|
|
|
use nu_protocol::{
|
Add `command_prelude` module (#12291)
# Description
When implementing a `Command`, one must also import all the types
present in the function signatures for `Command`. This makes it so that
we often import the same set of types in each command implementation
file. E.g., something like this:
```rust
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
record, Category, Example, IntoInterruptiblePipelineData, IntoPipelineData, PipelineData,
ShellError, Signature, Span, Type, Value,
};
```
This PR adds the `nu_engine::command_prelude` module which contains the
necessary and commonly used types to implement a `Command`:
```rust
// command_prelude.rs
pub use crate::CallExt;
pub use nu_protocol::{
ast::{Call, CellPath},
engine::{Command, EngineState, Stack},
record, Category, Example, IntoInterruptiblePipelineData, IntoPipelineData, IntoSpanned,
PipelineData, Record, ShellError, Signature, Span, Spanned, SyntaxShape, Type, Value,
};
```
This should reduce the boilerplate needed to implement a command and
also gives us a place to track the breadth of the `Command` API. I tried
to be conservative with what went into the prelude modules, since it
might be hard/annoying to remove items from the prelude in the future.
Let me know if something should be included or excluded.
2024-03-26 21:17:30 +00:00
|
|
|
debugger::WithoutDebug,
|
|
|
|
engine::{EngineState, Stack, StateWorkingSet},
|
|
|
|
print_if_stream, report_error, report_error_new, PipelineData, ShellError, Span, Value,
|
2022-02-18 18:43:34 +00:00
|
|
|
};
|
2022-03-16 22:21:06 +00:00
|
|
|
#[cfg(windows)]
|
|
|
|
use nu_utils::enable_vt_processing;
|
2023-01-24 20:28:59 +00:00
|
|
|
use nu_utils::utils::perf;
|
2023-03-20 04:05:22 +00:00
|
|
|
use std::path::Path;
|
2022-02-18 18:43:34 +00:00
|
|
|
|
2022-03-16 18:17:06 +00:00
|
|
|
// This will collect environment variables from std::env and adds them to a stack.
|
|
|
|
//
|
|
|
|
// In order to ensure the values have spans, it first creates a dummy file, writes the collected
|
|
|
|
// env vars into it (in a "NAME"="value" format, quite similar to the output of the Unix 'env'
|
|
|
|
// tool), then uses the file to get the spans. The file stays in memory, no filesystem IO is done.
|
2022-06-10 18:01:08 +00:00
|
|
|
//
|
|
|
|
// The "PWD" env value will be forced to `init_cwd`.
|
|
|
|
// The reason to use `init_cwd`:
|
|
|
|
//
|
|
|
|
// While gathering parent env vars, the parent `PWD` may not be the same as `current working directory`.
|
|
|
|
// Consider to the following command as the case (assume we execute command inside `/tmp`):
|
|
|
|
//
|
|
|
|
// tmux split-window -v -c "#{pane_current_path}"
|
|
|
|
//
|
|
|
|
// Here nu execute external command `tmux`, and tmux starts a new `nushell`, with `init_cwd` value "#{pane_current_path}".
|
|
|
|
// But at the same time `PWD` still remains to be `/tmp`.
|
|
|
|
//
|
|
|
|
// In this scenario, the new `nushell`'s PWD should be "#{pane_current_path}" rather init_cwd.
|
|
|
|
pub fn gather_parent_env_vars(engine_state: &mut EngineState, init_cwd: &Path) {
|
|
|
|
gather_env_vars(std::env::vars(), engine_state, init_cwd);
|
2022-04-15 22:38:27 +00:00
|
|
|
}
|
|
|
|
|
2022-06-10 18:01:08 +00:00
|
|
|
fn gather_env_vars(
|
|
|
|
vars: impl Iterator<Item = (String, String)>,
|
|
|
|
engine_state: &mut EngineState,
|
|
|
|
init_cwd: &Path,
|
|
|
|
) {
|
2022-03-16 18:17:06 +00:00
|
|
|
fn report_capture_error(engine_state: &EngineState, env_str: &str, msg: &str) {
|
2024-05-09 23:29:27 +00:00
|
|
|
report_error_new(
|
|
|
|
engine_state,
|
2023-12-06 23:40:03 +00:00
|
|
|
&ShellError::GenericError {
|
|
|
|
error: format!("Environment variable was not captured: {env_str}"),
|
|
|
|
msg: "".into(),
|
|
|
|
span: None,
|
|
|
|
help: Some(msg.into()),
|
|
|
|
inner: vec![],
|
|
|
|
},
|
2022-03-16 18:17:06 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2022-03-25 20:14:48 +00:00
|
|
|
fn put_env_to_fake_file(name: &str, val: &str, fake_env_file: &mut String) {
|
2022-04-30 18:23:05 +00:00
|
|
|
fake_env_file.push_str(&escape_quote_string(name));
|
2022-03-16 18:17:06 +00:00
|
|
|
fake_env_file.push('=');
|
2022-04-30 18:23:05 +00:00
|
|
|
fake_env_file.push_str(&escape_quote_string(val));
|
2022-03-16 18:17:06 +00:00
|
|
|
fake_env_file.push('\n');
|
|
|
|
}
|
|
|
|
|
|
|
|
let mut fake_env_file = String::new();
|
2022-04-15 22:38:27 +00:00
|
|
|
// Write all the env vars into a fake file
|
|
|
|
for (name, val) in vars {
|
|
|
|
put_env_to_fake_file(&name, &val, &mut fake_env_file);
|
|
|
|
}
|
|
|
|
|
2022-06-10 18:01:08 +00:00
|
|
|
match init_cwd.to_str() {
|
|
|
|
Some(cwd) => {
|
|
|
|
put_env_to_fake_file("PWD", cwd, &mut fake_env_file);
|
|
|
|
}
|
|
|
|
None => {
|
|
|
|
// Could not capture current working directory
|
2024-05-09 23:29:27 +00:00
|
|
|
report_error_new(
|
|
|
|
engine_state,
|
2023-12-06 23:40:03 +00:00
|
|
|
&ShellError::GenericError {
|
|
|
|
error: "Current directory is not a valid utf-8 path".into(),
|
|
|
|
msg: "".into(),
|
|
|
|
span: None,
|
|
|
|
help: Some(format!(
|
2023-01-30 01:37:54 +00:00
|
|
|
"Retrieving current directory failed: {init_cwd:?} not a valid utf-8 path"
|
2022-06-10 18:01:08 +00:00
|
|
|
)),
|
2023-12-06 23:40:03 +00:00
|
|
|
inner: vec![],
|
|
|
|
},
|
2022-06-10 18:01:08 +00:00
|
|
|
);
|
2022-03-16 18:17:06 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Lex the fake file, assign spans to all environment variables and add them
|
|
|
|
// to stack
|
|
|
|
let span_offset = engine_state.next_span_start();
|
|
|
|
|
|
|
|
engine_state.add_file(
|
2024-03-20 18:43:50 +00:00
|
|
|
"Host Environment Variables".into(),
|
|
|
|
fake_env_file.as_bytes().into(),
|
2022-03-16 18:17:06 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
let (tokens, _) = lex(fake_env_file.as_bytes(), span_offset, &[], &[], true);
|
|
|
|
|
|
|
|
for token in tokens {
|
|
|
|
if let Token {
|
|
|
|
contents: TokenContents::Item,
|
|
|
|
span: full_span,
|
|
|
|
} = token
|
|
|
|
{
|
2023-07-31 19:47:46 +00:00
|
|
|
let contents = engine_state.get_span_contents(full_span);
|
2022-03-16 18:17:06 +00:00
|
|
|
let (parts, _) = lex(contents, full_span.start, &[], &[b'='], true);
|
|
|
|
|
|
|
|
let name = if let Some(Token {
|
|
|
|
contents: TokenContents::Item,
|
|
|
|
span,
|
2023-11-17 15:15:55 +00:00
|
|
|
}) = parts.first()
|
2022-03-16 18:17:06 +00:00
|
|
|
{
|
2023-04-07 00:35:45 +00:00
|
|
|
let mut working_set = StateWorkingSet::new(engine_state);
|
|
|
|
let bytes = working_set.get_span_contents(*span);
|
2022-03-16 18:17:06 +00:00
|
|
|
|
|
|
|
if bytes.len() < 2 {
|
|
|
|
report_capture_error(
|
|
|
|
engine_state,
|
|
|
|
&String::from_utf8_lossy(contents),
|
|
|
|
"Got empty name.",
|
|
|
|
);
|
|
|
|
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2023-04-07 00:35:45 +00:00
|
|
|
let (bytes, err) = unescape_unquote_string(bytes, *span);
|
|
|
|
if let Some(err) = err {
|
|
|
|
working_set.error(err);
|
|
|
|
}
|
2022-04-15 22:38:27 +00:00
|
|
|
|
2023-04-07 00:35:45 +00:00
|
|
|
if working_set.parse_errors.first().is_some() {
|
2022-04-15 22:38:27 +00:00
|
|
|
report_capture_error(
|
|
|
|
engine_state,
|
|
|
|
&String::from_utf8_lossy(contents),
|
|
|
|
"Got unparsable name.",
|
|
|
|
);
|
|
|
|
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
bytes
|
2022-03-16 18:17:06 +00:00
|
|
|
} else {
|
|
|
|
report_capture_error(
|
|
|
|
engine_state,
|
|
|
|
&String::from_utf8_lossy(contents),
|
|
|
|
"Got empty name.",
|
|
|
|
);
|
|
|
|
|
|
|
|
continue;
|
|
|
|
};
|
|
|
|
|
|
|
|
let value = if let Some(Token {
|
|
|
|
contents: TokenContents::Item,
|
|
|
|
span,
|
|
|
|
}) = parts.get(2)
|
|
|
|
{
|
2023-04-07 00:35:45 +00:00
|
|
|
let mut working_set = StateWorkingSet::new(engine_state);
|
|
|
|
let bytes = working_set.get_span_contents(*span);
|
2022-03-16 18:17:06 +00:00
|
|
|
|
|
|
|
if bytes.len() < 2 {
|
|
|
|
report_capture_error(
|
|
|
|
engine_state,
|
|
|
|
&String::from_utf8_lossy(contents),
|
|
|
|
"Got empty value.",
|
|
|
|
);
|
|
|
|
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2023-04-07 00:35:45 +00:00
|
|
|
let (bytes, err) = unescape_unquote_string(bytes, *span);
|
|
|
|
if let Some(err) = err {
|
|
|
|
working_set.error(err);
|
|
|
|
}
|
2022-04-15 22:38:27 +00:00
|
|
|
|
2023-04-07 00:35:45 +00:00
|
|
|
if working_set.parse_errors.first().is_some() {
|
2022-04-15 22:38:27 +00:00
|
|
|
report_capture_error(
|
|
|
|
engine_state,
|
|
|
|
&String::from_utf8_lossy(contents),
|
|
|
|
"Got unparsable value.",
|
|
|
|
);
|
|
|
|
|
|
|
|
continue;
|
|
|
|
}
|
2022-03-16 18:17:06 +00:00
|
|
|
|
2023-09-03 14:27:29 +00:00
|
|
|
Value::string(bytes, *span)
|
2022-03-16 18:17:06 +00:00
|
|
|
} else {
|
|
|
|
report_capture_error(
|
|
|
|
engine_state,
|
|
|
|
&String::from_utf8_lossy(contents),
|
|
|
|
"Got empty value.",
|
|
|
|
);
|
|
|
|
|
|
|
|
continue;
|
|
|
|
};
|
|
|
|
|
|
|
|
// stack.add_env_var(name, value);
|
2022-05-07 19:39:22 +00:00
|
|
|
engine_state.add_env_var(name, value);
|
2022-03-16 18:17:06 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn eval_source(
|
|
|
|
engine_state: &mut EngineState,
|
|
|
|
stack: &mut Stack,
|
|
|
|
source: &[u8],
|
|
|
|
fname: &str,
|
|
|
|
input: PipelineData,
|
2023-02-01 23:02:27 +00:00
|
|
|
allow_return: bool,
|
2022-03-16 18:17:06 +00:00
|
|
|
) -> bool {
|
2023-01-24 20:28:59 +00:00
|
|
|
let start_time = std::time::Instant::now();
|
|
|
|
|
2022-03-16 18:17:06 +00:00
|
|
|
let (block, delta) = {
|
|
|
|
let mut working_set = StateWorkingSet::new(engine_state);
|
2023-04-07 00:35:45 +00:00
|
|
|
let output = parse(
|
2022-03-16 18:17:06 +00:00
|
|
|
&mut working_set,
|
|
|
|
Some(fname), // format!("entry #{}", entry_num)
|
|
|
|
source,
|
|
|
|
false,
|
|
|
|
);
|
Deprecate `--flag: bool` in custom command (#11365)
# Description
While #11057 is merged, it's hard to tell the difference between
`--flag: bool` and `--flag`, and it makes user hard to read custom
commands' signature, and hard to use them correctly.
After discussion, I think we can deprecate `--flag: bool` usage, and
encourage using `--flag` instead.
# User-Facing Changes
The following code will raise warning message, but don't stop from
running.
```nushell
❯ def florb [--dry-run: bool, --another-flag] { "aaa" }; florb
Error: × Deprecated: --flag: bool
╭─[entry #7:1:1]
1 │ def florb [--dry-run: bool, --another-flag] { "aaa" }; florb
· ──┬─
· ╰── `--flag: bool` is deprecated. Please use `--flag` instead, more info: https://www.nushell.sh/book/custom_commands.html
╰────
aaa
```
cc @kubouch
# Tests + Formatting
Done
# After Submitting
- [ ] Add more information under
https://www.nushell.sh/book/custom_commands.html to indicate `--dry-run:
bool` is not allowed,
- [ ] remove `: bool` from custom commands between 0.89 and 0.90
---------
Co-authored-by: Antoine Stevan <44101798+amtoine@users.noreply.github.com>
2023-12-21 09:07:08 +00:00
|
|
|
if let Some(warning) = working_set.parse_warnings.first() {
|
|
|
|
report_error(&working_set, warning);
|
|
|
|
}
|
|
|
|
|
2023-04-07 00:35:45 +00:00
|
|
|
if let Some(err) = working_set.parse_errors.first() {
|
2022-04-04 11:11:27 +00:00
|
|
|
set_last_exit_code(stack, 1);
|
2023-04-07 00:35:45 +00:00
|
|
|
report_error(&working_set, err);
|
2022-03-16 18:17:06 +00:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
(output, working_set.render())
|
|
|
|
};
|
|
|
|
|
2022-07-14 14:09:27 +00:00
|
|
|
if let Err(err) = engine_state.merge_delta(delta) {
|
|
|
|
set_last_exit_code(stack, 1);
|
|
|
|
report_error_new(engine_state, &err);
|
|
|
|
return false;
|
|
|
|
}
|
2022-03-16 18:17:06 +00:00
|
|
|
|
2023-02-01 23:02:27 +00:00
|
|
|
let b = if allow_return {
|
IO and redirection overhaul (#11934)
# Description
The PR overhauls how IO redirection is handled, allowing more explicit
and fine-grain control over `stdout` and `stderr` output as well as more
efficient IO and piping.
To summarize the changes in this PR:
- Added a new `IoStream` type to indicate the intended destination for a
pipeline element's `stdout` and `stderr`.
- The `stdout` and `stderr` `IoStream`s are stored in the `Stack` and to
avoid adding 6 additional arguments to every eval function and
`Command::run`. The `stdout` and `stderr` streams can be temporarily
overwritten through functions on `Stack` and these functions will return
a guard that restores the original `stdout` and `stderr` when dropped.
- In the AST, redirections are now directly part of a `PipelineElement`
as a `Option<Redirection>` field instead of having multiple different
`PipelineElement` enum variants for each kind of redirection. This
required changes to the parser, mainly in `lite_parser.rs`.
- `Command`s can also set a `IoStream` override/redirection which will
apply to the previous command in the pipeline. This is used, for
example, in `ignore` to allow the previous external command to have its
stdout redirected to `Stdio::null()` at spawn time. In contrast, the
current implementation has to create an os pipe and manually consume the
output on nushell's side. File and pipe redirections (`o>`, `e>`, `e>|`,
etc.) have precedence over overrides from commands.
This PR improves piping and IO speed, partially addressing #10763. Using
the `throughput` command from that issue, this PR gives the following
speedup on my setup for the commands below:
| Command | Before (MB/s) | After (MB/s) | Bash (MB/s) |
| --------------------------- | -------------:| ------------:|
-----------:|
| `throughput o> /dev/null` | 1169 | 52938 | 54305 |
| `throughput \| ignore` | 840 | 55438 | N/A |
| `throughput \| null` | Error | 53617 | N/A |
| `throughput \| rg 'x'` | 1165 | 3049 | 3736 |
| `(throughput) \| rg 'x'` | 810 | 3085 | 3815 |
(Numbers above are the median samples for throughput)
This PR also paves the way to refactor our `ExternalStream` handling in
the various commands. For example, this PR already fixes the following
code:
```nushell
^sh -c 'echo -n "hello "; sleep 0; echo "world"' | find "hello world"
```
This returns an empty list on 0.90.1 and returns a highlighted "hello
world" on this PR.
Since the `stdout` and `stderr` `IoStream`s are available to commands
when they are run, then this unlocks the potential for more convenient
behavior. E.g., the `find` command can disable its ansi highlighting if
it detects that the output `IoStream` is not the terminal. Knowing the
output streams will also allow background job output to be redirected
more easily and efficiently.
# User-Facing Changes
- External commands returned from closures will be collected (in most
cases):
```nushell
1..2 | each {|_| nu -c "print a" }
```
This gives `["a", "a"]` on this PR, whereas this used to print "a\na\n"
and then return an empty list.
```nushell
1..2 | each {|_| nu -c "print -e a" }
```
This gives `["", ""]` and prints "a\na\n" to stderr, whereas this used
to return an empty list and print "a\na\n" to stderr.
- Trailing new lines are always trimmed for external commands when
piping into internal commands or collecting it as a value. (Failure to
decode the output as utf-8 will keep the trailing newline for the last
binary value.) In the current nushell version, the following three code
snippets differ only in parenthesis placement, but they all also have
different outputs:
1. `1..2 | each { ^echo a }`
```
a
a
╭────────────╮
│ empty list │
╰────────────╯
```
2. `1..2 | each { (^echo a) }`
```
╭───┬───╮
│ 0 │ a │
│ 1 │ a │
╰───┴───╯
```
3. `1..2 | (each { ^echo a })`
```
╭───┬───╮
│ 0 │ a │
│ │ │
│ 1 │ a │
│ │ │
╰───┴───╯
```
But in this PR, the above snippets will all have the same output:
```
╭───┬───╮
│ 0 │ a │
│ 1 │ a │
╰───┴───╯
```
- All existing flags on `run-external` are now deprecated.
- File redirections now apply to all commands inside a code block:
```nushell
(nu -c "print -e a"; nu -c "print -e b") e> test.out
```
This gives "a\nb\n" in `test.out` and prints nothing. The same result
would happen when printing to stdout and using a `o>` file redirection.
- External command output will (almost) never be ignored, and ignoring
output must be explicit now:
```nushell
(^echo a; ^echo b)
```
This prints "a\nb\n", whereas this used to print only "b\n". This only
applies to external commands; values and internal commands not in return
position will not print anything (e.g., `(echo a; echo b)` still only
prints "b").
- `complete` now always captures stderr (`do` is not necessary).
# After Submitting
The language guide and other documentation will need to be updated.
2024-03-14 20:51:55 +00:00
|
|
|
eval_block_with_early_return::<WithoutDebug>(engine_state, stack, &block, input)
|
2023-02-01 23:02:27 +00:00
|
|
|
} else {
|
IO and redirection overhaul (#11934)
# Description
The PR overhauls how IO redirection is handled, allowing more explicit
and fine-grain control over `stdout` and `stderr` output as well as more
efficient IO and piping.
To summarize the changes in this PR:
- Added a new `IoStream` type to indicate the intended destination for a
pipeline element's `stdout` and `stderr`.
- The `stdout` and `stderr` `IoStream`s are stored in the `Stack` and to
avoid adding 6 additional arguments to every eval function and
`Command::run`. The `stdout` and `stderr` streams can be temporarily
overwritten through functions on `Stack` and these functions will return
a guard that restores the original `stdout` and `stderr` when dropped.
- In the AST, redirections are now directly part of a `PipelineElement`
as a `Option<Redirection>` field instead of having multiple different
`PipelineElement` enum variants for each kind of redirection. This
required changes to the parser, mainly in `lite_parser.rs`.
- `Command`s can also set a `IoStream` override/redirection which will
apply to the previous command in the pipeline. This is used, for
example, in `ignore` to allow the previous external command to have its
stdout redirected to `Stdio::null()` at spawn time. In contrast, the
current implementation has to create an os pipe and manually consume the
output on nushell's side. File and pipe redirections (`o>`, `e>`, `e>|`,
etc.) have precedence over overrides from commands.
This PR improves piping and IO speed, partially addressing #10763. Using
the `throughput` command from that issue, this PR gives the following
speedup on my setup for the commands below:
| Command | Before (MB/s) | After (MB/s) | Bash (MB/s) |
| --------------------------- | -------------:| ------------:|
-----------:|
| `throughput o> /dev/null` | 1169 | 52938 | 54305 |
| `throughput \| ignore` | 840 | 55438 | N/A |
| `throughput \| null` | Error | 53617 | N/A |
| `throughput \| rg 'x'` | 1165 | 3049 | 3736 |
| `(throughput) \| rg 'x'` | 810 | 3085 | 3815 |
(Numbers above are the median samples for throughput)
This PR also paves the way to refactor our `ExternalStream` handling in
the various commands. For example, this PR already fixes the following
code:
```nushell
^sh -c 'echo -n "hello "; sleep 0; echo "world"' | find "hello world"
```
This returns an empty list on 0.90.1 and returns a highlighted "hello
world" on this PR.
Since the `stdout` and `stderr` `IoStream`s are available to commands
when they are run, then this unlocks the potential for more convenient
behavior. E.g., the `find` command can disable its ansi highlighting if
it detects that the output `IoStream` is not the terminal. Knowing the
output streams will also allow background job output to be redirected
more easily and efficiently.
# User-Facing Changes
- External commands returned from closures will be collected (in most
cases):
```nushell
1..2 | each {|_| nu -c "print a" }
```
This gives `["a", "a"]` on this PR, whereas this used to print "a\na\n"
and then return an empty list.
```nushell
1..2 | each {|_| nu -c "print -e a" }
```
This gives `["", ""]` and prints "a\na\n" to stderr, whereas this used
to return an empty list and print "a\na\n" to stderr.
- Trailing new lines are always trimmed for external commands when
piping into internal commands or collecting it as a value. (Failure to
decode the output as utf-8 will keep the trailing newline for the last
binary value.) In the current nushell version, the following three code
snippets differ only in parenthesis placement, but they all also have
different outputs:
1. `1..2 | each { ^echo a }`
```
a
a
╭────────────╮
│ empty list │
╰────────────╯
```
2. `1..2 | each { (^echo a) }`
```
╭───┬───╮
│ 0 │ a │
│ 1 │ a │
╰───┴───╯
```
3. `1..2 | (each { ^echo a })`
```
╭───┬───╮
│ 0 │ a │
│ │ │
│ 1 │ a │
│ │ │
╰───┴───╯
```
But in this PR, the above snippets will all have the same output:
```
╭───┬───╮
│ 0 │ a │
│ 1 │ a │
╰───┴───╯
```
- All existing flags on `run-external` are now deprecated.
- File redirections now apply to all commands inside a code block:
```nushell
(nu -c "print -e a"; nu -c "print -e b") e> test.out
```
This gives "a\nb\n" in `test.out` and prints nothing. The same result
would happen when printing to stdout and using a `o>` file redirection.
- External command output will (almost) never be ignored, and ignoring
output must be explicit now:
```nushell
(^echo a; ^echo b)
```
This prints "a\nb\n", whereas this used to print only "b\n". This only
applies to external commands; values and internal commands not in return
position will not print anything (e.g., `(echo a; echo b)` still only
prints "b").
- `complete` now always captures stderr (`do` is not necessary).
# After Submitting
The language guide and other documentation will need to be updated.
2024-03-14 20:51:55 +00:00
|
|
|
eval_block::<WithoutDebug>(engine_state, stack, &block, input)
|
2023-02-01 23:02:27 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
match b {
|
2022-10-10 12:32:55 +00:00
|
|
|
Ok(pipeline_data) => {
|
2022-11-06 00:46:40 +00:00
|
|
|
let config = engine_state.get_config();
|
|
|
|
let result;
|
|
|
|
if let PipelineData::ExternalStream {
|
|
|
|
stdout: stream,
|
|
|
|
stderr: stderr_stream,
|
|
|
|
exit_code,
|
|
|
|
..
|
|
|
|
} = pipeline_data
|
|
|
|
{
|
|
|
|
result = print_if_stream(stream, stderr_stream, false, exit_code);
|
|
|
|
} else if let Some(hook) = config.hooks.display_output.clone() {
|
2023-08-27 11:55:20 +00:00
|
|
|
match eval_hook(
|
|
|
|
engine_state,
|
|
|
|
stack,
|
|
|
|
Some(pipeline_data),
|
|
|
|
vec![],
|
|
|
|
&hook,
|
|
|
|
"display_output",
|
|
|
|
) {
|
2022-11-06 00:46:40 +00:00
|
|
|
Err(err) => {
|
|
|
|
result = Err(err);
|
|
|
|
}
|
|
|
|
Ok(val) => {
|
|
|
|
result = val.print(engine_state, stack, false, false);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
2022-12-14 03:45:37 +00:00
|
|
|
result = pipeline_data.print(engine_state, stack, true, false);
|
2022-11-06 00:46:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
match result {
|
2022-10-10 12:32:55 +00:00
|
|
|
Err(err) => {
|
2024-05-09 23:29:27 +00:00
|
|
|
report_error_new(engine_state, &err);
|
2022-10-10 12:32:55 +00:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
Ok(exit_code) => {
|
|
|
|
set_last_exit_code(stack, exit_code);
|
|
|
|
}
|
2022-03-16 18:17:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// reset vt processing, aka ansi because illbehaved externals can break it
|
|
|
|
#[cfg(windows)]
|
|
|
|
{
|
|
|
|
let _ = enable_vt_processing();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Err(err) => {
|
2022-04-04 11:11:27 +00:00
|
|
|
set_last_exit_code(stack, 1);
|
2024-05-09 23:29:27 +00:00
|
|
|
report_error_new(engine_state, &err);
|
2022-03-16 18:17:06 +00:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
2023-01-24 20:28:59 +00:00
|
|
|
perf(
|
|
|
|
&format!("eval_source {}", &fname),
|
|
|
|
start_time,
|
|
|
|
file!(),
|
|
|
|
line!(),
|
|
|
|
column!(),
|
2023-02-01 23:03:05 +00:00
|
|
|
engine_state.get_config().use_ansi_coloring,
|
2023-01-24 20:28:59 +00:00
|
|
|
);
|
2022-03-16 18:17:06 +00:00
|
|
|
|
|
|
|
true
|
|
|
|
}
|
|
|
|
|
2022-04-04 11:11:27 +00:00
|
|
|
fn set_last_exit_code(stack: &mut Stack, exit_code: i64) {
|
|
|
|
stack.add_env_var(
|
|
|
|
"LAST_EXIT_CODE".to_string(),
|
Reduced LOC by replacing several instances of `Value::Int {}`, `Value::Float{}`, `Value::Bool {}`, and `Value::String {}` with `Value::int()`, `Value::float()`, `Value::boolean()` and `Value::string()` (#7412)
# Description
While perusing Value.rs, I noticed the `Value::int()`, `Value::float()`,
`Value::boolean()` and `Value::string()` constructors, which seem
designed to make it easier to construct various Values, but which aren't
used often at all in the codebase. So, using a few find-replaces
regexes, I increased their usage. This reduces overall LOC because
structures like this:
```
Value::Int {
val: a,
span: head
}
```
are changed into
```
Value::int(a, head)
```
and are respected as such by the project's formatter.
There are little readability concerns because the second argument to all
of these is `span`, and it's almost always extremely obvious which is
the span at every callsite.
# User-Facing Changes
None.
# Tests + Formatting
Don't forget to add tests that cover your changes.
Make sure you've run and fixed any issues with these commands:
- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
# After Submitting
If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
2022-12-09 16:37:51 +00:00
|
|
|
Value::int(exit_code, Span::unknown()),
|
2022-04-04 11:11:27 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2022-04-15 22:38:27 +00:00
|
|
|
#[cfg(test)]
|
|
|
|
mod test {
|
|
|
|
use super::*;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_gather_env_vars() {
|
|
|
|
let mut engine_state = EngineState::new();
|
|
|
|
let symbols = r##" !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"##;
|
|
|
|
|
|
|
|
gather_env_vars(
|
|
|
|
[
|
|
|
|
("FOO".into(), "foo".into()),
|
|
|
|
("SYMBOLS".into(), symbols.into()),
|
|
|
|
(symbols.into(), "symbols".into()),
|
|
|
|
]
|
|
|
|
.into_iter(),
|
|
|
|
&mut engine_state,
|
2022-06-10 18:01:08 +00:00
|
|
|
Path::new("t"),
|
2022-04-15 22:38:27 +00:00
|
|
|
);
|
|
|
|
|
2022-05-07 19:39:22 +00:00
|
|
|
let env = engine_state.render_env_vars();
|
2022-04-15 22:38:27 +00:00
|
|
|
|
2022-05-07 19:39:22 +00:00
|
|
|
assert!(
|
|
|
|
matches!(env.get(&"FOO".to_string()), Some(&Value::String { val, .. }) if val == "foo")
|
|
|
|
);
|
|
|
|
assert!(
|
|
|
|
matches!(env.get(&"SYMBOLS".to_string()), Some(&Value::String { val, .. }) if val == symbols)
|
|
|
|
);
|
|
|
|
assert!(
|
|
|
|
matches!(env.get(&symbols.to_string()), Some(&Value::String { val, .. }) if val == "symbols")
|
|
|
|
);
|
|
|
|
assert!(env.get(&"PWD".to_string()).is_some());
|
2022-04-15 22:38:27 +00:00
|
|
|
assert_eq!(env.len(), 4);
|
|
|
|
}
|
|
|
|
}
|