2022-11-06 00:46:40 +00:00
|
|
|
use crate::repl::eval_hook;
|
2022-03-16 18:17:06 +00:00
|
|
|
use nu_engine::eval_block;
|
2022-04-30 18:23:05 +00:00
|
|
|
use nu_parser::{escape_quote_string, lex, parse, unescape_unquote_string, Token, TokenContents};
|
2022-03-16 18:17:06 +00:00
|
|
|
use nu_protocol::engine::StateWorkingSet;
|
2022-05-01 07:33:41 +00:00
|
|
|
use nu_protocol::CliError;
|
2022-02-18 18:43:34 +00:00
|
|
|
use nu_protocol::{
|
|
|
|
engine::{EngineState, Stack},
|
2022-11-06 00:46:40 +00:00
|
|
|
print_if_stream, 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;
|
2022-06-10 18:01:08 +00:00
|
|
|
use std::path::{Path, PathBuf};
|
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) {
|
|
|
|
let working_set = StateWorkingSet::new(engine_state);
|
|
|
|
report_error(
|
|
|
|
&working_set,
|
2022-04-18 12:34:10 +00:00
|
|
|
&ShellError::GenericError(
|
2023-01-30 01:37:54 +00:00
|
|
|
format!("Environment variable was not captured: {env_str}"),
|
2022-04-18 12:34:10 +00:00
|
|
|
"".to_string(),
|
|
|
|
None,
|
|
|
|
Some(msg.into()),
|
|
|
|
Vec::new(),
|
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
|
|
|
|
let working_set = StateWorkingSet::new(engine_state);
|
|
|
|
report_error(
|
|
|
|
&working_set,
|
|
|
|
&ShellError::GenericError(
|
|
|
|
"Current directory is not a valid utf-8 path".to_string(),
|
|
|
|
"".to_string(),
|
|
|
|
None,
|
|
|
|
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
|
|
|
)),
|
|
|
|
Vec::new(),
|
|
|
|
),
|
|
|
|
);
|
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(
|
|
|
|
"Host Environment Variables".to_string(),
|
|
|
|
fake_env_file.as_bytes().to_vec(),
|
|
|
|
);
|
|
|
|
|
|
|
|
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
|
|
|
|
{
|
|
|
|
let contents = engine_state.get_span_contents(&full_span);
|
|
|
|
let (parts, _) = lex(contents, full_span.start, &[], &[b'='], true);
|
|
|
|
|
|
|
|
let name = if let Some(Token {
|
|
|
|
contents: TokenContents::Item,
|
|
|
|
span,
|
|
|
|
}) = parts.get(0)
|
|
|
|
{
|
|
|
|
let bytes = engine_state.get_span_contents(span);
|
|
|
|
|
|
|
|
if bytes.len() < 2 {
|
|
|
|
report_capture_error(
|
|
|
|
engine_state,
|
|
|
|
&String::from_utf8_lossy(contents),
|
|
|
|
"Got empty name.",
|
|
|
|
);
|
|
|
|
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2022-04-15 22:38:27 +00:00
|
|
|
let (bytes, parse_error) = unescape_unquote_string(bytes, *span);
|
|
|
|
|
|
|
|
if parse_error.is_some() {
|
|
|
|
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)
|
|
|
|
{
|
|
|
|
let bytes = engine_state.get_span_contents(span);
|
|
|
|
|
|
|
|
if bytes.len() < 2 {
|
|
|
|
report_capture_error(
|
|
|
|
engine_state,
|
|
|
|
&String::from_utf8_lossy(contents),
|
|
|
|
"Got empty value.",
|
|
|
|
);
|
|
|
|
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2022-04-15 22:38:27 +00:00
|
|
|
let (bytes, parse_error) = unescape_unquote_string(bytes, *span);
|
|
|
|
|
|
|
|
if parse_error.is_some() {
|
|
|
|
report_capture_error(
|
|
|
|
engine_state,
|
|
|
|
&String::from_utf8_lossy(contents),
|
|
|
|
"Got unparsable value.",
|
|
|
|
);
|
|
|
|
|
|
|
|
continue;
|
|
|
|
}
|
2022-03-16 18:17:06 +00:00
|
|
|
|
|
|
|
Value::String {
|
2022-04-15 22:38:27 +00:00
|
|
|
val: bytes,
|
2022-03-16 18:17:06 +00:00
|
|
|
span: *span,
|
|
|
|
}
|
|
|
|
} 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,
|
|
|
|
) -> 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);
|
|
|
|
let (output, err) = parse(
|
|
|
|
&mut working_set,
|
|
|
|
Some(fname), // format!("entry #{}", entry_num)
|
|
|
|
source,
|
|
|
|
false,
|
2022-03-18 19:03:57 +00:00
|
|
|
&[],
|
2022-03-16 18:17:06 +00:00
|
|
|
);
|
|
|
|
if let Some(err) = err {
|
2022-04-04 11:11:27 +00:00
|
|
|
set_last_exit_code(stack, 1);
|
2022-03-16 18:17:06 +00:00
|
|
|
report_error(&working_set, &err);
|
|
|
|
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
|
|
|
|
|
|
|
match eval_block(engine_state, stack, &block, input, false, false) {
|
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() {
|
|
|
|
match eval_hook(engine_state, stack, Some(pipeline_data), vec![], &hook) {
|
|
|
|
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) => {
|
|
|
|
let working_set = StateWorkingSet::new(engine_state);
|
2022-03-16 18:17:06 +00:00
|
|
|
|
2022-10-10 12:32:55 +00:00
|
|
|
report_error(&working_set, &err);
|
2022-03-16 18:17:06 +00:00
|
|
|
|
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);
|
2022-03-16 18:17:06 +00:00
|
|
|
|
|
|
|
let working_set = StateWorkingSet::new(engine_state);
|
|
|
|
|
|
|
|
report_error(&working_set, &err);
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
2023-01-24 20:28:59 +00:00
|
|
|
perf(
|
|
|
|
&format!("eval_source {}", &fname),
|
|
|
|
start_time,
|
|
|
|
file!(),
|
|
|
|
line!(),
|
|
|
|
column!(),
|
|
|
|
);
|
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-03-16 18:17:06 +00:00
|
|
|
pub fn report_error(
|
|
|
|
working_set: &StateWorkingSet,
|
|
|
|
error: &(dyn miette::Diagnostic + Send + Sync + 'static),
|
|
|
|
) {
|
|
|
|
eprintln!("Error: {:?}", CliError(error, working_set));
|
|
|
|
// reset vt processing, aka ansi because illbehaved externals can break it
|
|
|
|
#[cfg(windows)]
|
|
|
|
{
|
2022-03-16 22:21:06 +00:00
|
|
|
let _ = nu_utils::enable_vt_processing();
|
2022-03-16 18:17:06 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-07-10 10:45:46 +00:00
|
|
|
pub fn report_error_new(
|
|
|
|
engine_state: &EngineState,
|
|
|
|
error: &(dyn miette::Diagnostic + Send + Sync + 'static),
|
|
|
|
) {
|
|
|
|
let working_set = StateWorkingSet::new(engine_state);
|
|
|
|
|
|
|
|
report_error(&working_set, error);
|
|
|
|
}
|
|
|
|
|
2022-03-16 18:17:06 +00:00
|
|
|
pub fn get_init_cwd() -> PathBuf {
|
2023-01-24 11:23:42 +00:00
|
|
|
std::env::current_dir().unwrap_or_else(|_| {
|
|
|
|
std::env::var("PWD")
|
|
|
|
.map(Into::into)
|
|
|
|
.unwrap_or_else(|_| nu_path::home_dir().unwrap_or_default())
|
|
|
|
})
|
2022-03-16 18:17:06 +00:00
|
|
|
}
|
2022-04-15 22:38:27 +00:00
|
|
|
|
2022-07-14 14:09:27 +00:00
|
|
|
pub fn get_guaranteed_cwd(engine_state: &EngineState, stack: &Stack) -> PathBuf {
|
2023-01-24 11:23:42 +00:00
|
|
|
nu_engine::env::current_dir(engine_state, stack).unwrap_or_else(|e| {
|
|
|
|
let working_set = StateWorkingSet::new(engine_state);
|
|
|
|
report_error(&working_set, &e);
|
|
|
|
get_init_cwd()
|
|
|
|
})
|
2022-07-14 14:09: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);
|
|
|
|
}
|
|
|
|
}
|