2022-05-10 22:17:07 +02:00
|
|
|
use nu_engine::eval_block;
|
|
|
|
use nu_parser::parse;
|
|
|
|
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 22:17:30 +01:00
|
|
|
debugger::WithoutDebug,
|
2022-07-14 16:09:27 +02:00
|
|
|
engine::{EngineState, Stack, StateWorkingSet},
|
2024-05-10 01:29:27 +02:00
|
|
|
PipelineData, ShellError, Span, Value,
|
2022-05-10 22:17:07 +02:00
|
|
|
};
|
|
|
|
use nu_test_support::fs;
|
|
|
|
use reedline::Suggestion;
|
Migrate to a new PWD API (#12603)
This is the first PR towards migrating to a new `$env.PWD` API that
returns potentially un-canonicalized paths. Refer to PR #12515 for
motivations.
## New API: `EngineState::cwd()`
The goal of the new API is to cover both parse-time and runtime use
case, and avoid unintentional misuse. It takes an `Option<Stack>` as
argument, which if supplied, will search for `$env.PWD` on the stack in
additional to the engine state. I think with this design, there's less
confusion over parse-time and runtime environments. If you have access
to a stack, just supply it; otherwise supply `None`.
## Deprecation of other PWD-related APIs
Other APIs are re-implemented using `EngineState::cwd()` and properly
documented. They're marked deprecated, but their behavior is unchanged.
Unused APIs are deleted, and code that accesses `$env.PWD` directly
without using an API is rewritten.
Deprecated APIs:
* `EngineState::current_work_dir()`
* `StateWorkingSet::get_cwd()`
* `env::current_dir()`
* `env::current_dir_str()`
* `env::current_dir_const()`
* `env::current_dir_str_const()`
Other changes:
* `EngineState::get_cwd()` (deleted)
* `StateWorkingSet::list_env()` (deleted)
* `repl::do_run_cmd()` (rewritten with `env::current_dir_str()`)
## `cd` and `pwd` now use logical paths by default
This pulls the changes from PR #12515. It's currently somewhat broken
because using non-canonicalized paths exposed a bug in our path
normalization logic (Issue #12602). Once that is fixed, this should
work.
## Future plans
This PR needs some tests. Which test helpers should I use, and where
should I put those tests?
I noticed that unquoted paths are expanded within `eval_filepath()` and
`eval_directory()` before they even reach the `cd` command. This means
every paths is expanded twice. Is this intended?
Once this PR lands, the plan is to review all usages of the deprecated
APIs and migrate them to `EngineState::cwd()`. In the meantime, these
usages are annotated with `#[allow(deprecated)]` to avoid breaking CI.
---------
Co-authored-by: Jakub Žádník <kubouch@gmail.com>
2024-05-03 13:33:09 +02:00
|
|
|
use std::path::{PathBuf, MAIN_SEPARATOR};
|
2022-05-10 22:17:07 +02:00
|
|
|
|
2023-06-14 23:12:55 +02:00
|
|
|
fn create_default_context() -> EngineState {
|
|
|
|
nu_command::add_shell_command_context(nu_cmd_lang::create_default_context())
|
|
|
|
}
|
|
|
|
|
2022-05-10 22:17:07 +02:00
|
|
|
// creates a new engine with the current path into the completions fixtures folder
|
|
|
|
pub fn new_engine() -> (PathBuf, String, EngineState, Stack) {
|
|
|
|
// Target folder inside assets
|
|
|
|
let dir = fs::fixtures().join("completions");
|
Migrate to a new PWD API (#12603)
This is the first PR towards migrating to a new `$env.PWD` API that
returns potentially un-canonicalized paths. Refer to PR #12515 for
motivations.
## New API: `EngineState::cwd()`
The goal of the new API is to cover both parse-time and runtime use
case, and avoid unintentional misuse. It takes an `Option<Stack>` as
argument, which if supplied, will search for `$env.PWD` on the stack in
additional to the engine state. I think with this design, there's less
confusion over parse-time and runtime environments. If you have access
to a stack, just supply it; otherwise supply `None`.
## Deprecation of other PWD-related APIs
Other APIs are re-implemented using `EngineState::cwd()` and properly
documented. They're marked deprecated, but their behavior is unchanged.
Unused APIs are deleted, and code that accesses `$env.PWD` directly
without using an API is rewritten.
Deprecated APIs:
* `EngineState::current_work_dir()`
* `StateWorkingSet::get_cwd()`
* `env::current_dir()`
* `env::current_dir_str()`
* `env::current_dir_const()`
* `env::current_dir_str_const()`
Other changes:
* `EngineState::get_cwd()` (deleted)
* `StateWorkingSet::list_env()` (deleted)
* `repl::do_run_cmd()` (rewritten with `env::current_dir_str()`)
## `cd` and `pwd` now use logical paths by default
This pulls the changes from PR #12515. It's currently somewhat broken
because using non-canonicalized paths exposed a bug in our path
normalization logic (Issue #12602). Once that is fixed, this should
work.
## Future plans
This PR needs some tests. Which test helpers should I use, and where
should I put those tests?
I noticed that unquoted paths are expanded within `eval_filepath()` and
`eval_directory()` before they even reach the `cd` command. This means
every paths is expanded twice. Is this intended?
Once this PR lands, the plan is to review all usages of the deprecated
APIs and migrate them to `EngineState::cwd()`. In the meantime, these
usages are annotated with `#[allow(deprecated)]` to avoid breaking CI.
---------
Co-authored-by: Jakub Žádník <kubouch@gmail.com>
2024-05-03 13:33:09 +02:00
|
|
|
let dir_str = dir
|
2022-05-10 22:17:07 +02:00
|
|
|
.clone()
|
|
|
|
.into_os_string()
|
|
|
|
.into_string()
|
|
|
|
.unwrap_or_default();
|
|
|
|
|
|
|
|
// Create a new engine with default context
|
2022-07-14 16:09:27 +02:00
|
|
|
let mut engine_state = create_default_context();
|
2022-05-10 22:17:07 +02:00
|
|
|
|
2023-09-01 08:18:55 +02:00
|
|
|
// Add $nu
|
2024-05-10 01:29:27 +02:00
|
|
|
engine_state.generate_nu_constant();
|
2023-09-01 08:18:55 +02:00
|
|
|
|
2022-05-10 22:17:07 +02:00
|
|
|
// New stack
|
|
|
|
let mut stack = Stack::new();
|
|
|
|
|
2022-12-08 21:37:10 +01:00
|
|
|
// Add pwd as env var
|
|
|
|
stack.add_env_var(
|
|
|
|
"PWD".to_string(),
|
2023-09-03 16:27:29 +02:00
|
|
|
Value::string(dir_str.clone(), nu_protocol::Span::new(0, dir_str.len())),
|
2022-12-08 21:37:10 +01:00
|
|
|
);
|
|
|
|
stack.add_env_var(
|
|
|
|
"TEST".to_string(),
|
2023-09-03 16:27:29 +02:00
|
|
|
Value::string(
|
|
|
|
"NUSHELL".to_string(),
|
|
|
|
nu_protocol::Span::new(0, dir_str.len()),
|
|
|
|
),
|
2023-02-09 03:53:46 +01:00
|
|
|
);
|
|
|
|
#[cfg(windows)]
|
|
|
|
stack.add_env_var(
|
|
|
|
"Path".to_string(),
|
2023-09-03 16:27:29 +02:00
|
|
|
Value::string(
|
|
|
|
"c:\\some\\path;c:\\some\\other\\path".to_string(),
|
|
|
|
nu_protocol::Span::new(0, dir_str.len()),
|
|
|
|
),
|
2023-02-09 03:53:46 +01:00
|
|
|
);
|
|
|
|
#[cfg(not(windows))]
|
|
|
|
stack.add_env_var(
|
|
|
|
"PATH".to_string(),
|
2023-09-03 16:27:29 +02:00
|
|
|
Value::string(
|
|
|
|
"/some/path:/some/other/path".to_string(),
|
|
|
|
nu_protocol::Span::new(0, dir_str.len()),
|
|
|
|
),
|
2022-12-08 21:37:10 +01:00
|
|
|
);
|
|
|
|
|
|
|
|
// Merge environment into the permanent state
|
2024-05-24 18:09:59 +02:00
|
|
|
let merge_result = engine_state.merge_env(&mut stack, &dir);
|
2023-06-04 21:04:28 +02:00
|
|
|
assert!(merge_result.is_ok());
|
2022-12-08 21:37:10 +01:00
|
|
|
|
|
|
|
(dir, dir_str, engine_state, stack)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn new_quote_engine() -> (PathBuf, String, EngineState, Stack) {
|
|
|
|
// Target folder inside assets
|
|
|
|
let dir = fs::fixtures().join("quoted_completions");
|
Migrate to a new PWD API (#12603)
This is the first PR towards migrating to a new `$env.PWD` API that
returns potentially un-canonicalized paths. Refer to PR #12515 for
motivations.
## New API: `EngineState::cwd()`
The goal of the new API is to cover both parse-time and runtime use
case, and avoid unintentional misuse. It takes an `Option<Stack>` as
argument, which if supplied, will search for `$env.PWD` on the stack in
additional to the engine state. I think with this design, there's less
confusion over parse-time and runtime environments. If you have access
to a stack, just supply it; otherwise supply `None`.
## Deprecation of other PWD-related APIs
Other APIs are re-implemented using `EngineState::cwd()` and properly
documented. They're marked deprecated, but their behavior is unchanged.
Unused APIs are deleted, and code that accesses `$env.PWD` directly
without using an API is rewritten.
Deprecated APIs:
* `EngineState::current_work_dir()`
* `StateWorkingSet::get_cwd()`
* `env::current_dir()`
* `env::current_dir_str()`
* `env::current_dir_const()`
* `env::current_dir_str_const()`
Other changes:
* `EngineState::get_cwd()` (deleted)
* `StateWorkingSet::list_env()` (deleted)
* `repl::do_run_cmd()` (rewritten with `env::current_dir_str()`)
## `cd` and `pwd` now use logical paths by default
This pulls the changes from PR #12515. It's currently somewhat broken
because using non-canonicalized paths exposed a bug in our path
normalization logic (Issue #12602). Once that is fixed, this should
work.
## Future plans
This PR needs some tests. Which test helpers should I use, and where
should I put those tests?
I noticed that unquoted paths are expanded within `eval_filepath()` and
`eval_directory()` before they even reach the `cd` command. This means
every paths is expanded twice. Is this intended?
Once this PR lands, the plan is to review all usages of the deprecated
APIs and migrate them to `EngineState::cwd()`. In the meantime, these
usages are annotated with `#[allow(deprecated)]` to avoid breaking CI.
---------
Co-authored-by: Jakub Žádník <kubouch@gmail.com>
2024-05-03 13:33:09 +02:00
|
|
|
let dir_str = dir
|
2022-12-08 21:37:10 +01:00
|
|
|
.clone()
|
|
|
|
.into_os_string()
|
|
|
|
.into_string()
|
|
|
|
.unwrap_or_default();
|
|
|
|
|
|
|
|
// Create a new engine with default context
|
|
|
|
let mut engine_state = create_default_context();
|
|
|
|
|
|
|
|
// New stack
|
|
|
|
let mut stack = Stack::new();
|
|
|
|
|
2022-05-10 22:17:07 +02:00
|
|
|
// Add pwd as env var
|
|
|
|
stack.add_env_var(
|
|
|
|
"PWD".to_string(),
|
2023-09-03 16:27:29 +02:00
|
|
|
Value::string(dir_str.clone(), nu_protocol::Span::new(0, dir_str.len())),
|
2022-05-10 22:17:07 +02:00
|
|
|
);
|
2022-05-26 23:38:03 +02:00
|
|
|
stack.add_env_var(
|
2023-10-02 19:44:51 +02:00
|
|
|
"TEST".to_string(),
|
|
|
|
Value::string(
|
|
|
|
"NUSHELL".to_string(),
|
|
|
|
nu_protocol::Span::new(0, dir_str.len()),
|
|
|
|
),
|
|
|
|
);
|
|
|
|
|
|
|
|
// Merge environment into the permanent state
|
2024-05-24 18:09:59 +02:00
|
|
|
let merge_result = engine_state.merge_env(&mut stack, &dir);
|
2023-10-02 19:44:51 +02:00
|
|
|
assert!(merge_result.is_ok());
|
|
|
|
|
|
|
|
(dir, dir_str, engine_state, stack)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn new_partial_engine() -> (PathBuf, String, EngineState, Stack) {
|
|
|
|
// Target folder inside assets
|
|
|
|
let dir = fs::fixtures().join("partial_completions");
|
Migrate to a new PWD API (#12603)
This is the first PR towards migrating to a new `$env.PWD` API that
returns potentially un-canonicalized paths. Refer to PR #12515 for
motivations.
## New API: `EngineState::cwd()`
The goal of the new API is to cover both parse-time and runtime use
case, and avoid unintentional misuse. It takes an `Option<Stack>` as
argument, which if supplied, will search for `$env.PWD` on the stack in
additional to the engine state. I think with this design, there's less
confusion over parse-time and runtime environments. If you have access
to a stack, just supply it; otherwise supply `None`.
## Deprecation of other PWD-related APIs
Other APIs are re-implemented using `EngineState::cwd()` and properly
documented. They're marked deprecated, but their behavior is unchanged.
Unused APIs are deleted, and code that accesses `$env.PWD` directly
without using an API is rewritten.
Deprecated APIs:
* `EngineState::current_work_dir()`
* `StateWorkingSet::get_cwd()`
* `env::current_dir()`
* `env::current_dir_str()`
* `env::current_dir_const()`
* `env::current_dir_str_const()`
Other changes:
* `EngineState::get_cwd()` (deleted)
* `StateWorkingSet::list_env()` (deleted)
* `repl::do_run_cmd()` (rewritten with `env::current_dir_str()`)
## `cd` and `pwd` now use logical paths by default
This pulls the changes from PR #12515. It's currently somewhat broken
because using non-canonicalized paths exposed a bug in our path
normalization logic (Issue #12602). Once that is fixed, this should
work.
## Future plans
This PR needs some tests. Which test helpers should I use, and where
should I put those tests?
I noticed that unquoted paths are expanded within `eval_filepath()` and
`eval_directory()` before they even reach the `cd` command. This means
every paths is expanded twice. Is this intended?
Once this PR lands, the plan is to review all usages of the deprecated
APIs and migrate them to `EngineState::cwd()`. In the meantime, these
usages are annotated with `#[allow(deprecated)]` to avoid breaking CI.
---------
Co-authored-by: Jakub Žádník <kubouch@gmail.com>
2024-05-03 13:33:09 +02:00
|
|
|
let dir_str = dir
|
2023-10-02 19:44:51 +02:00
|
|
|
.clone()
|
|
|
|
.into_os_string()
|
|
|
|
.into_string()
|
|
|
|
.unwrap_or_default();
|
|
|
|
|
|
|
|
// Create a new engine with default context
|
|
|
|
let mut engine_state = create_default_context();
|
|
|
|
|
|
|
|
// New stack
|
|
|
|
let mut stack = Stack::new();
|
|
|
|
|
|
|
|
// Add pwd as env var
|
|
|
|
stack.add_env_var(
|
|
|
|
"PWD".to_string(),
|
|
|
|
Value::string(dir_str.clone(), nu_protocol::Span::new(0, dir_str.len())),
|
|
|
|
);
|
|
|
|
stack.add_env_var(
|
2022-05-26 23:38:03 +02:00
|
|
|
"TEST".to_string(),
|
2023-09-03 16:27:29 +02:00
|
|
|
Value::string(
|
|
|
|
"NUSHELL".to_string(),
|
|
|
|
nu_protocol::Span::new(0, dir_str.len()),
|
|
|
|
),
|
2022-05-26 23:38:03 +02:00
|
|
|
);
|
2022-05-10 22:17:07 +02:00
|
|
|
|
2022-07-14 16:09:27 +02:00
|
|
|
// Merge environment into the permanent state
|
2024-05-24 18:09:59 +02:00
|
|
|
let merge_result = engine_state.merge_env(&mut stack, &dir);
|
2023-06-04 21:04:28 +02:00
|
|
|
assert!(merge_result.is_ok());
|
2022-05-10 22:17:07 +02:00
|
|
|
|
2022-05-14 22:09:41 +02:00
|
|
|
(dir, dir_str, engine_state, stack)
|
|
|
|
}
|
|
|
|
|
|
|
|
// match a list of suggestions with the expected values
|
|
|
|
pub fn match_suggestions(expected: Vec<String>, suggestions: Vec<Suggestion>) {
|
2022-07-17 14:46:40 +02:00
|
|
|
let expected_len = expected.len();
|
|
|
|
let suggestions_len = suggestions.len();
|
|
|
|
if expected_len != suggestions_len {
|
|
|
|
panic!(
|
|
|
|
"\nexpected {expected_len} suggestions but got {suggestions_len}: \n\
|
|
|
|
Suggestions: {suggestions:#?} \n\
|
|
|
|
Expected: {expected:#?}\n"
|
|
|
|
)
|
|
|
|
}
|
2022-05-14 22:09:41 +02:00
|
|
|
expected.iter().zip(suggestions).for_each(|it| {
|
|
|
|
assert_eq!(it.0, &it.1.value);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
// append the separator to the converted path
|
|
|
|
pub fn folder(path: PathBuf) -> String {
|
|
|
|
let mut converted_path = file(path);
|
Migrate to a new PWD API (#12603)
This is the first PR towards migrating to a new `$env.PWD` API that
returns potentially un-canonicalized paths. Refer to PR #12515 for
motivations.
## New API: `EngineState::cwd()`
The goal of the new API is to cover both parse-time and runtime use
case, and avoid unintentional misuse. It takes an `Option<Stack>` as
argument, which if supplied, will search for `$env.PWD` on the stack in
additional to the engine state. I think with this design, there's less
confusion over parse-time and runtime environments. If you have access
to a stack, just supply it; otherwise supply `None`.
## Deprecation of other PWD-related APIs
Other APIs are re-implemented using `EngineState::cwd()` and properly
documented. They're marked deprecated, but their behavior is unchanged.
Unused APIs are deleted, and code that accesses `$env.PWD` directly
without using an API is rewritten.
Deprecated APIs:
* `EngineState::current_work_dir()`
* `StateWorkingSet::get_cwd()`
* `env::current_dir()`
* `env::current_dir_str()`
* `env::current_dir_const()`
* `env::current_dir_str_const()`
Other changes:
* `EngineState::get_cwd()` (deleted)
* `StateWorkingSet::list_env()` (deleted)
* `repl::do_run_cmd()` (rewritten with `env::current_dir_str()`)
## `cd` and `pwd` now use logical paths by default
This pulls the changes from PR #12515. It's currently somewhat broken
because using non-canonicalized paths exposed a bug in our path
normalization logic (Issue #12602). Once that is fixed, this should
work.
## Future plans
This PR needs some tests. Which test helpers should I use, and where
should I put those tests?
I noticed that unquoted paths are expanded within `eval_filepath()` and
`eval_directory()` before they even reach the `cd` command. This means
every paths is expanded twice. Is this intended?
Once this PR lands, the plan is to review all usages of the deprecated
APIs and migrate them to `EngineState::cwd()`. In the meantime, these
usages are annotated with `#[allow(deprecated)]` to avoid breaking CI.
---------
Co-authored-by: Jakub Žádník <kubouch@gmail.com>
2024-05-03 13:33:09 +02:00
|
|
|
converted_path.push(MAIN_SEPARATOR);
|
2022-05-14 22:09:41 +02:00
|
|
|
|
|
|
|
converted_path
|
|
|
|
}
|
|
|
|
|
|
|
|
// convert a given path to string
|
|
|
|
pub fn file(path: PathBuf) -> String {
|
|
|
|
path.into_os_string().into_string().unwrap_or_default()
|
|
|
|
}
|
|
|
|
|
|
|
|
// merge_input executes the given input into the engine
|
|
|
|
// and merges the state
|
|
|
|
pub fn merge_input(
|
|
|
|
input: &[u8],
|
|
|
|
engine_state: &mut EngineState,
|
|
|
|
stack: &mut Stack,
|
2024-05-24 18:09:59 +02:00
|
|
|
dir: PathBuf,
|
2022-05-14 22:09:41 +02:00
|
|
|
) -> Result<(), ShellError> {
|
2022-05-10 22:17:07 +02:00
|
|
|
let (block, delta) = {
|
2022-06-04 08:47:36 +02:00
|
|
|
let mut working_set = StateWorkingSet::new(engine_state);
|
2022-05-10 22:17:07 +02:00
|
|
|
|
2023-04-07 20:09:38 +02:00
|
|
|
let block = parse(&mut working_set, None, input, false);
|
2022-05-10 22:17:07 +02:00
|
|
|
|
2023-04-07 02:35:45 +02:00
|
|
|
assert!(working_set.parse_errors.is_empty());
|
2022-05-10 22:17:07 +02:00
|
|
|
|
|
|
|
(block, working_set.render())
|
|
|
|
};
|
2022-07-14 16:09:27 +02:00
|
|
|
|
2022-09-26 19:29:25 +02:00
|
|
|
engine_state.merge_delta(delta)?;
|
2022-07-14 16:09:27 +02:00
|
|
|
|
Debugger experiments (#11441)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx
you can also mention related issues, PRs or discussions!
-->
# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.
Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->
This PR adds a new evaluator path with callbacks to a mutable trait
object implementing a Debugger trait. The trait object can do anything,
e.g., profiling, code coverage, step debugging. Currently,
entering/leaving a block and a pipeline element is marked with
callbacks, but more callbacks can be added as necessary. Not all
callbacks need to be used by all debuggers; unused ones are simply empty
calls. A simple profiler is implemented as a proof of concept.
The debugging support is implementing by making `eval_xxx()` functions
generic depending on whether we're debugging or not. This has zero
computational overhead, but makes the binary slightly larger (see
benchmarks below). `eval_xxx()` variants called from commands (like
`eval_block_with_early_return()` in `each`) are chosen with a dynamic
dispatch for two reasons: to not grow the binary size due to duplicating
the code of many commands, and for the fact that it isn't possible
because it would make Command trait objects object-unsafe.
In the future, I hope it will be possible to allow plugin callbacks such
that users would be able to implement their profiler plugins instead of
having to recompile Nushell.
[DAP](https://microsoft.github.io/debug-adapter-protocol/) would also be
interesting to explore.
Try `help debug profile`.
## Screenshots
Basic output:
![profiler_new](https://github.com/nushell/nushell/assets/25571562/418b9df0-b659-4dcb-b023-2d5fcef2c865)
To profile with more granularity, increase the profiler depth (you'll
see that repeated `is-windows` calls take a large chunk of total time,
making it a good candidate for optimizing):
![profiler_new_m3](https://github.com/nushell/nushell/assets/25571562/636d756d-5d56-460c-a372-14716f65f37f)
## Benchmarks
### Binary size
Binary size increase vs. main: **+40360 bytes**. _(Both built with
`--release --features=extra,dataframe`.)_
### Time
```nushell
# bench_debug.nu
use std bench
let test = {
1..100
| each {
ls | each {|row| $row.name | str length }
}
| flatten
| math avg
}
print 'debug:'
let res2 = bench { debug profile $test } --pretty
print $res2
```
```nushell
# bench_nodebug.nu
use std bench
let test = {
1..100
| each {
ls | each {|row| $row.name | str length }
}
| flatten
| math avg
}
print 'no debug:'
let res1 = bench { do $test } --pretty
print $res1
```
`cargo run --release -- bench_debug.nu` is consistently 1--2 ms slower
than `cargo run --release -- bench_nodebug.nu` due to the collection
overhead + gathering the report. This is expected. When gathering more
stuff, the overhead is obviously higher.
`cargo run --release -- bench_nodebug.nu` vs. `nu bench_nodebug.nu` I
didn't measure any difference. Both benchmarks report times between 97
and 103 ms randomly, without one being consistently higher than the
other. This suggests that at least in this particular case, when not
running any debugger, there is no runtime overhead.
## API changes
This PR adds a generic parameter to all `eval_xxx` functions that forces
you to specify whether you use the debugger. You can resolve it in two
ways:
* Use a provided helper that will figure it out for you. If you wanted
to use `eval_block(&engine_state, ...)`, call `let eval_block =
get_eval_block(&engine_state); eval_block(&engine_state, ...)`
* If you know you're in an evaluation path that doesn't need debugger
support, call `eval_block::<WithoutDebug>(&engine_state, ...)` (this is
the case of hooks, for example).
I tried to add more explanation in the docstring of `debugger_trait.rs`.
## TODO
- [x] Better profiler output to reduce spam of iterative commands like
`each`
- [x] Resolve `TODO: DEBUG` comments
- [x] Resolve unwraps
- [x] Add doc comments
- [x] Add usage and extra usage for `debug profile`, explaining all
columns
# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->
Hopefully 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` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `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.
-->
2024-03-08 19:21:35 +01:00
|
|
|
assert!(eval_block::<WithoutDebug>(
|
2022-06-04 08:47:36 +02:00
|
|
|
engine_state,
|
2022-05-14 22:09:41 +02:00
|
|
|
stack,
|
2022-05-10 22:17:07 +02:00
|
|
|
&block,
|
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 21:51:55 +01:00
|
|
|
PipelineData::Value(Value::nothing(Span::unknown()), None),
|
2022-05-10 22:17:07 +02:00
|
|
|
)
|
|
|
|
.is_ok());
|
|
|
|
|
2022-07-14 16:09:27 +02:00
|
|
|
// Merge environment into the permanent state
|
2024-05-24 18:09:59 +02:00
|
|
|
engine_state.merge_env(stack, &dir)
|
2022-05-10 22:17:07 +02:00
|
|
|
}
|