forked from extern/nushell
74dcd91cc3
* Use only $nu.env.PWD for getting current directory Because setting and reading to/from std::env changes the global state shich is problematic if we call `cd` from multiple threads (e.g., in a `par-each` block). With this change, when engine-q starts, it will either inherit existing PWD env var, or create a new one from `std::env::current_dir()`. Otherwise, everything that needs the current directory will get it from `$nu.env.PWD`. Each spawned external command will get its current directory per-process which should be thread-safe. One thing left to do is to patch nu-path for this as well since it uses `std::env::current_dir()` in its expansions. * Rename nu-path functions *_with is not *_relative which should be more descriptive and frees "with" for use in a followup commit. * Clone stack every each iter; Fix some commands Cloning the stack each iteration of `each` makes sure we're not reusing PWD between iterations. Some fixes in commands to make them use the new PWD. * Post-rebase cleanup, fmt, clippy * Change back _relative to _with in nu-path funcs Didn't use the idea I had for the new "_with". * Remove leftover current_dir from rebase * Add cwd sync at merge_delta() This makes sure the parser and completer always have up-to-date cwd. * Always pass absolute path to glob in ls * Do not allow PWD a relative path; Allow recovery Makes it possible to recover PWD by proceeding with the REPL cycle. * Clone stack in each also for byte/string stream * (WIP) Start moving env variables to engine state * (WIP) Move env vars to engine state (ugly) Quick and dirty code. * (WIP) Remove unused mut and args; Fmt * (WIP) Fix dataframe tests * (WIP) Fix missing args after rebase * (WIP) Clone only env vars, not the whole stack * (WIP) Add env var clone to `for` loop as well * Minor edits * Refactor merge_delta() to include stack merging. Less error-prone than doing it manually. * Clone env for each `update` command iteration * Mark env var hidden only when found in eng. state * Fix clippt warnings * Add TODO about env var reading * Do not clone empty environment in loops * Remove extra cwd collection * Split current_dir() into str and path; Fix autocd * Make completions respect PWD env var
209 lines
6.9 KiB
Rust
209 lines
6.9 KiB
Rust
use nu_engine::{eval_block, eval_expression};
|
|
use nu_protocol::ast::Call;
|
|
use nu_protocol::engine::{Command, EngineState, Stack};
|
|
use nu_protocol::{
|
|
Category, Example, IntoInterruptiblePipelineData, PipelineData, Signature, Span, SyntaxShape,
|
|
Value,
|
|
};
|
|
|
|
#[derive(Clone)]
|
|
pub struct For;
|
|
|
|
impl Command for For {
|
|
fn name(&self) -> &str {
|
|
"for"
|
|
}
|
|
|
|
fn usage(&self) -> &str {
|
|
"Loop over a range"
|
|
}
|
|
|
|
fn signature(&self) -> nu_protocol::Signature {
|
|
Signature::build("for")
|
|
.required(
|
|
"var_name",
|
|
SyntaxShape::VarWithOptType,
|
|
"name of the looping variable",
|
|
)
|
|
.required(
|
|
"range",
|
|
SyntaxShape::Keyword(b"in".to_vec(), Box::new(SyntaxShape::Any)),
|
|
"range of the loop",
|
|
)
|
|
.required(
|
|
"block",
|
|
SyntaxShape::Block(Some(vec![])),
|
|
"the block to run",
|
|
)
|
|
.switch(
|
|
"numbered",
|
|
"returned a numbered item ($it.index and $it.item)",
|
|
Some('n'),
|
|
)
|
|
.creates_scope()
|
|
.category(Category::Core)
|
|
}
|
|
|
|
fn run(
|
|
&self,
|
|
engine_state: &EngineState,
|
|
stack: &mut Stack,
|
|
call: &Call,
|
|
_input: PipelineData,
|
|
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
|
|
let head = call.head;
|
|
let var_id = call.positional[0]
|
|
.as_var()
|
|
.expect("internal error: missing variable");
|
|
|
|
let keyword_expr = call.positional[1]
|
|
.as_keyword()
|
|
.expect("internal error: missing keyword");
|
|
let values = eval_expression(engine_state, stack, keyword_expr)?;
|
|
|
|
let block_id = call.positional[2]
|
|
.as_block()
|
|
.expect("internal error: expected block");
|
|
|
|
let numbered = call.has_flag("numbered");
|
|
|
|
let ctrlc = engine_state.ctrlc.clone();
|
|
let engine_state = engine_state.clone();
|
|
let block = engine_state.get_block(block_id).clone();
|
|
let mut stack = stack.collect_captures(&block.captures);
|
|
let orig_env_vars = stack.env_vars.clone();
|
|
let orig_env_hidden = stack.env_hidden.clone();
|
|
|
|
match values {
|
|
Value::List { vals, .. } => Ok(vals
|
|
.into_iter()
|
|
.enumerate()
|
|
.map(move |(idx, x)| {
|
|
stack.with_env(&orig_env_vars, &orig_env_hidden);
|
|
|
|
stack.add_var(
|
|
var_id,
|
|
if numbered {
|
|
Value::Record {
|
|
cols: vec!["index".into(), "item".into()],
|
|
vals: vec![
|
|
Value::Int {
|
|
val: idx as i64,
|
|
span: head,
|
|
},
|
|
x,
|
|
],
|
|
span: head,
|
|
}
|
|
} else {
|
|
x
|
|
},
|
|
);
|
|
|
|
//let block = engine_state.get_block(block_id);
|
|
match eval_block(&engine_state, &mut stack, &block, PipelineData::new(head)) {
|
|
Ok(pipeline_data) => pipeline_data.into_value(head),
|
|
Err(error) => Value::Error { error },
|
|
}
|
|
})
|
|
.into_pipeline_data(ctrlc)),
|
|
Value::Range { val, .. } => Ok(val
|
|
.into_range_iter()?
|
|
.enumerate()
|
|
.map(move |(idx, x)| {
|
|
stack.with_env(&orig_env_vars, &orig_env_hidden);
|
|
|
|
stack.add_var(
|
|
var_id,
|
|
if numbered {
|
|
Value::Record {
|
|
cols: vec!["index".into(), "item".into()],
|
|
vals: vec![
|
|
Value::Int {
|
|
val: idx as i64,
|
|
span: head,
|
|
},
|
|
x,
|
|
],
|
|
span: head,
|
|
}
|
|
} else {
|
|
x
|
|
},
|
|
);
|
|
|
|
//let block = engine_state.get_block(block_id);
|
|
match eval_block(&engine_state, &mut stack, &block, PipelineData::new(head)) {
|
|
Ok(pipeline_data) => pipeline_data.into_value(head),
|
|
Err(error) => Value::Error { error },
|
|
}
|
|
})
|
|
.into_pipeline_data(ctrlc)),
|
|
x => {
|
|
stack.add_var(var_id, x);
|
|
|
|
eval_block(&engine_state, &mut stack, &block, PipelineData::new(head))
|
|
}
|
|
}
|
|
}
|
|
|
|
fn examples(&self) -> Vec<Example> {
|
|
let span = Span::test_data();
|
|
vec![
|
|
Example {
|
|
description: "Echo the square of each integer",
|
|
example: "for x in [1 2 3] { $x * $x }",
|
|
result: Some(Value::List {
|
|
vals: vec![
|
|
Value::Int { val: 1, span },
|
|
Value::Int { val: 4, span },
|
|
Value::Int { val: 9, span },
|
|
],
|
|
span,
|
|
}),
|
|
},
|
|
Example {
|
|
description: "Work with elements of a range",
|
|
example: "for $x in 1..3 { $x }",
|
|
result: Some(Value::List {
|
|
vals: vec![
|
|
Value::Int { val: 1, span },
|
|
Value::Int { val: 2, span },
|
|
Value::Int { val: 3, span },
|
|
],
|
|
span,
|
|
}),
|
|
},
|
|
Example {
|
|
description: "Number each item and echo a message",
|
|
example: "for $it in ['bob' 'fred'] --numbered { $\"($it.index) is ($it.item)\" }",
|
|
result: Some(Value::List {
|
|
vals: vec![
|
|
Value::String {
|
|
val: "0 is bob".into(),
|
|
span,
|
|
},
|
|
Value::String {
|
|
val: "1 is fred".into(),
|
|
span,
|
|
},
|
|
],
|
|
span,
|
|
}),
|
|
},
|
|
]
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod test {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn test_examples() {
|
|
use crate::test_examples;
|
|
|
|
test_examples(For {})
|
|
}
|
|
}
|