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
|
|
|
use nu_engine::{command_prelude::*, eval_block};
|
|
|
|
use nu_protocol::{debugger::WithoutDebug, engine::Closure};
|
revert: move to ahash (#9464)
This PR reverts https://github.com/nushell/nushell/pull/9391
We try not to revert PRs like this, though after discussion with the
Nushell team, we decided to revert this one.
The main reason is that Nushell, as a codebase, isn't ready for these
kinds of optimisations. It's in the part of the development cycle where
our main focus should be on improving the algorithms inside of Nushell
itself. Once we have matured our algorithms, then we can look for
opportunities to switch out technologies we're using for alternate
forms.
Much of Nushell still has lots of opportunities for tuning the codebase,
paying down technical debt, and making the codebase generally cleaner
and more robust. This should be the focus. Performance improvements
should flow out of that work.
Said another, optimisation that isn't part of tuning the codebase is
premature at this stage. We need to focus on doing the hard work of
making the engine, parser, etc better.
# User-Facing Changes
Reverts the HashMap -> ahash change.
cc @FilipAndersson245
2023-06-18 03:27:57 +00:00
|
|
|
use std::collections::HashMap;
|
2021-11-04 02:32:35 +00:00
|
|
|
|
|
|
|
#[derive(Clone)]
|
|
|
|
pub struct WithEnv;
|
|
|
|
|
|
|
|
impl Command for WithEnv {
|
|
|
|
fn name(&self) -> &str {
|
|
|
|
"with-env"
|
|
|
|
}
|
|
|
|
|
|
|
|
fn signature(&self) -> Signature {
|
|
|
|
Signature::build("with-env")
|
2022-11-09 21:55:05 +00:00
|
|
|
.input_output_types(vec![(Type::Any, Type::Any)])
|
2021-11-04 02:32:35 +00:00
|
|
|
.required(
|
|
|
|
"variable",
|
|
|
|
SyntaxShape::Any,
|
2023-12-15 06:32:37 +00:00
|
|
|
"The environment variable to temporarily set.",
|
2021-11-04 02:32:35 +00:00
|
|
|
)
|
|
|
|
.required(
|
|
|
|
"block",
|
2022-11-10 08:21:49 +00:00
|
|
|
SyntaxShape::Closure(None),
|
2023-12-15 06:32:37 +00:00
|
|
|
"The block to run once the variable is set.",
|
2021-11-04 02:32:35 +00:00
|
|
|
)
|
2021-11-17 04:22:37 +00:00
|
|
|
.category(Category::Env)
|
2021-11-04 02:32:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn usage(&self) -> &str {
|
|
|
|
"Runs a block with an environment variable set."
|
|
|
|
}
|
|
|
|
|
|
|
|
fn run(
|
|
|
|
&self,
|
|
|
|
engine_state: &EngineState,
|
|
|
|
stack: &mut Stack,
|
|
|
|
call: &Call,
|
|
|
|
input: PipelineData,
|
2023-02-05 21:17:46 +00:00
|
|
|
) -> Result<PipelineData, ShellError> {
|
2021-11-04 02:32:35 +00:00
|
|
|
with_env(engine_state, stack, call, input)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn examples(&self) -> Vec<Example> {
|
2024-04-16 11:08:58 +00:00
|
|
|
vec![Example {
|
|
|
|
description: "Set by key-value record",
|
|
|
|
example: r#"with-env {X: "Y", W: "Z"} { [$env.X $env.W] }"#,
|
|
|
|
result: Some(Value::list(
|
|
|
|
vec![Value::test_string("Y"), Value::test_string("Z")],
|
|
|
|
Span::test_data(),
|
|
|
|
)),
|
|
|
|
}]
|
2021-11-04 02:32:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn with_env(
|
|
|
|
engine_state: &EngineState,
|
|
|
|
stack: &mut Stack,
|
|
|
|
call: &Call,
|
|
|
|
input: PipelineData,
|
|
|
|
) -> Result<PipelineData, ShellError> {
|
|
|
|
let variable: Value = call.req(engine_state, stack, 0)?;
|
|
|
|
|
2022-11-10 08:21:49 +00:00
|
|
|
let capture_block: Closure = call.req(engine_state, stack, 1)?;
|
2022-01-12 04:06:56 +00:00
|
|
|
let block = engine_state.get_block(capture_block.block_id);
|
2024-04-09 16:48:32 +00:00
|
|
|
let mut stack = stack.captures_to_stack_preserve_out_dest(capture_block.captures);
|
2021-11-04 02:32:35 +00:00
|
|
|
|
2021-12-17 01:04:54 +00:00
|
|
|
let mut env: HashMap<String, Value> = HashMap::new();
|
2021-11-04 02:32:35 +00:00
|
|
|
|
|
|
|
match &variable {
|
|
|
|
Value::List { vals: table, .. } => {
|
2024-04-16 11:08:58 +00:00
|
|
|
nu_protocol::report_error_new(
|
|
|
|
engine_state,
|
|
|
|
&ShellError::GenericError {
|
|
|
|
error: "Deprecated argument type".into(),
|
|
|
|
msg: "providing the variables to `with-env` as a list or single row table has been deprecated".into(),
|
|
|
|
span: Some(variable.span()),
|
|
|
|
help: Some("use the record form instead".into()),
|
|
|
|
inner: vec![],
|
|
|
|
},
|
|
|
|
);
|
2021-11-04 02:32:35 +00:00
|
|
|
if table.len() == 1 {
|
|
|
|
// single row([[X W]; [Y Z]])
|
|
|
|
match &table[0] {
|
Create `Record` type (#10103)
# Description
This PR creates a new `Record` type to reduce duplicate code and
possibly bugs as well. (This is an edited version of #9648.)
- `Record` implements `FromIterator` and `IntoIterator` and so can be
iterated over or collected into. For example, this helps with
conversions to and from (hash)maps. (Also, no more
`cols.iter().zip(vals)`!)
- `Record` has a `push(col, val)` function to help insure that the
number of columns is equal to the number of values. I caught a few
potential bugs thanks to this (e.g. in the `ls` command).
- Finally, this PR also adds a `record!` macro that helps simplify
record creation. It is used like so:
```rust
record! {
"key1" => some_value,
"key2" => Value::string("text", span),
"key3" => Value::int(optional_int.unwrap_or(0), span),
"key4" => Value::bool(config.setting, span),
}
```
Since macros hinder formatting, etc., the right hand side values should
be relatively short and sweet like the examples above.
Where possible, prefer `record!` or `.collect()` on an iterator instead
of multiple `Record::push`s, since the first two automatically set the
record capacity and do less work overall.
# User-Facing Changes
Besides the changes in `nu-protocol` the only other breaking changes are
to `nu-table::{ExpandedTable::build_map, JustTable::kv_table}`.
2023-08-24 19:50:29 +00:00
|
|
|
Value::Record { val, .. } => {
|
2024-03-26 15:17:44 +00:00
|
|
|
for (k, v) in &**val {
|
2021-12-17 01:04:54 +00:00
|
|
|
env.insert(k.to_string(), v.clone());
|
2021-11-04 02:32:35 +00:00
|
|
|
}
|
|
|
|
}
|
2021-11-06 05:50:33 +00:00
|
|
|
x => {
|
2023-03-06 17:33:09 +00:00
|
|
|
return Err(ShellError::CantConvert {
|
2024-04-16 11:08:58 +00:00
|
|
|
to_type: "record".into(),
|
2023-03-06 17:33:09 +00:00
|
|
|
from_type: x.get_type().to_string(),
|
|
|
|
span: call
|
|
|
|
.positional_nth(1)
|
2022-04-09 02:55:02 +00:00
|
|
|
.expect("already checked through .req")
|
|
|
|
.span,
|
2023-03-06 17:33:09 +00:00
|
|
|
help: None,
|
|
|
|
});
|
2021-11-04 02:32:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// primitive values([X Y W Z])
|
|
|
|
for row in table.chunks(2) {
|
|
|
|
if row.len() == 2 {
|
2024-02-17 18:14:16 +00:00
|
|
|
env.insert(row[0].coerce_string()?, row[1].clone());
|
2021-11-04 02:32:35 +00:00
|
|
|
}
|
2024-04-16 11:08:58 +00:00
|
|
|
if row.len() == 1 {
|
|
|
|
return Err(ShellError::IncorrectValue {
|
|
|
|
msg: format!("Missing value for $env.{}", row[0].coerce_string()?),
|
|
|
|
val_span: row[0].span(),
|
|
|
|
call_span: call.head,
|
|
|
|
});
|
|
|
|
}
|
2021-11-04 02:32:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// when get object by `open x.json` or `from json`
|
Create `Record` type (#10103)
# Description
This PR creates a new `Record` type to reduce duplicate code and
possibly bugs as well. (This is an edited version of #9648.)
- `Record` implements `FromIterator` and `IntoIterator` and so can be
iterated over or collected into. For example, this helps with
conversions to and from (hash)maps. (Also, no more
`cols.iter().zip(vals)`!)
- `Record` has a `push(col, val)` function to help insure that the
number of columns is equal to the number of values. I caught a few
potential bugs thanks to this (e.g. in the `ls` command).
- Finally, this PR also adds a `record!` macro that helps simplify
record creation. It is used like so:
```rust
record! {
"key1" => some_value,
"key2" => Value::string("text", span),
"key3" => Value::int(optional_int.unwrap_or(0), span),
"key4" => Value::bool(config.setting, span),
}
```
Since macros hinder formatting, etc., the right hand side values should
be relatively short and sweet like the examples above.
Where possible, prefer `record!` or `.collect()` on an iterator instead
of multiple `Record::push`s, since the first two automatically set the
record capacity and do less work overall.
# User-Facing Changes
Besides the changes in `nu-protocol` the only other breaking changes are
to `nu-table::{ExpandedTable::build_map, JustTable::kv_table}`.
2023-08-24 19:50:29 +00:00
|
|
|
Value::Record { val, .. } => {
|
2024-03-26 15:17:44 +00:00
|
|
|
for (k, v) in &**val {
|
2021-12-17 01:04:54 +00:00
|
|
|
env.insert(k.clone(), v.clone());
|
2021-11-04 02:32:35 +00:00
|
|
|
}
|
|
|
|
}
|
2021-11-06 05:50:33 +00:00
|
|
|
x => {
|
2023-03-06 17:33:09 +00:00
|
|
|
return Err(ShellError::CantConvert {
|
2024-04-16 11:08:58 +00:00
|
|
|
to_type: "record".into(),
|
2023-03-06 17:33:09 +00:00
|
|
|
from_type: x.get_type().to_string(),
|
|
|
|
span: call
|
|
|
|
.positional_nth(1)
|
2022-04-09 02:55:02 +00:00
|
|
|
.expect("already checked through .req")
|
|
|
|
.span,
|
2023-03-06 17:33:09 +00:00
|
|
|
help: None,
|
|
|
|
});
|
2021-11-04 02:32:35 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2024-04-16 11:08:58 +00:00
|
|
|
// TODO: factor list of prohibited env vars into common place
|
|
|
|
for prohibited in ["PWD", "FILE_PWD", "CURRENT_FILE"] {
|
|
|
|
if env.contains_key(prohibited) {
|
|
|
|
return Err(ShellError::AutomaticEnvVarSetManually {
|
|
|
|
envvar_name: prohibited.into(),
|
|
|
|
span: call.head,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-04 02:32:35 +00:00
|
|
|
for (k, v) in env {
|
2021-12-17 01:04:54 +00:00
|
|
|
stack.add_env_var(k, v);
|
2021-11-04 02:32:35 +00:00
|
|
|
}
|
|
|
|
|
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, &mut stack, block, input)
|
2021-11-04 02:32:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod test {
|
|
|
|
use super::*;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_examples() {
|
|
|
|
use crate::test_examples;
|
|
|
|
|
|
|
|
test_examples(WithEnv {})
|
|
|
|
}
|
|
|
|
}
|