mirror of
https://github.com/nushell/nushell.git
synced 2025-08-09 10:36:00 +02:00
Add magic $in variable (#309)
* Add magic in variable * Oops, missing file
This commit is contained in:
@ -27,6 +27,7 @@ pub fn create_default_context() -> EngineState {
|
||||
BuildString,
|
||||
CamelCase,
|
||||
Cd,
|
||||
Collect,
|
||||
Cp,
|
||||
Date,
|
||||
DateFormat,
|
||||
|
75
crates/nu-command/src/filters/collect.rs
Normal file
75
crates/nu-command/src/filters/collect.rs
Normal file
@ -0,0 +1,75 @@
|
||||
use nu_engine::eval_block;
|
||||
use nu_protocol::ast::Call;
|
||||
use nu_protocol::engine::{Command, EngineState, Stack};
|
||||
use nu_protocol::{Example, PipelineData, Signature, SyntaxShape, Value};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Collect;
|
||||
|
||||
impl Command for Collect {
|
||||
fn name(&self) -> &str {
|
||||
"collect"
|
||||
}
|
||||
|
||||
fn signature(&self) -> Signature {
|
||||
Signature::build("collect").required(
|
||||
"block",
|
||||
SyntaxShape::Block(Some(vec![SyntaxShape::Any])),
|
||||
"the block to run once the stream is collected",
|
||||
)
|
||||
}
|
||||
|
||||
fn usage(&self) -> &str {
|
||||
"Collect the stream and pass it to a block."
|
||||
}
|
||||
|
||||
fn run(
|
||||
&self,
|
||||
engine_state: &EngineState,
|
||||
stack: &mut Stack,
|
||||
call: &Call,
|
||||
input: PipelineData,
|
||||
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
|
||||
let block_id = call.positional[0]
|
||||
.as_block()
|
||||
.expect("internal error: expected block");
|
||||
|
||||
let block = engine_state.get_block(block_id).clone();
|
||||
let mut stack = stack.collect_captures(&block.captures);
|
||||
|
||||
let input: Value = input.into_value(call.head);
|
||||
|
||||
if let Some(var) = block.signature.get_positional(0) {
|
||||
if let Some(var_id) = &var.var_id {
|
||||
stack.add_var(*var_id, input);
|
||||
}
|
||||
}
|
||||
|
||||
eval_block(
|
||||
engine_state,
|
||||
&mut stack,
|
||||
&block,
|
||||
PipelineData::new(call.head),
|
||||
)
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<Example> {
|
||||
vec![Example {
|
||||
description: "Use the second value in the stream",
|
||||
example: "echo 1 2 3 | collect { |x| echo $x.1 }",
|
||||
result: Some(Value::test_int(2)),
|
||||
}]
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_examples() {
|
||||
use crate::test_examples;
|
||||
|
||||
test_examples(Collect {})
|
||||
}
|
||||
}
|
@ -1,3 +1,4 @@
|
||||
mod collect;
|
||||
mod each;
|
||||
mod first;
|
||||
mod get;
|
||||
@ -13,6 +14,7 @@ mod where_;
|
||||
mod wrap;
|
||||
mod zip;
|
||||
|
||||
pub use collect::Collect;
|
||||
pub use each::Each;
|
||||
pub use first::First;
|
||||
pub use get::Get;
|
||||
|
Reference in New Issue
Block a user