nu_command/debug/
metadata_access.rs

1use nu_engine::{command_prelude::*, get_eval_block_with_early_return};
2use nu_protocol::{
3    PipelineData, ShellError, Signature, SyntaxShape, Type, Value,
4    engine::{Call, Closure, Command, EngineState, Stack},
5};
6
7use super::util::build_metadata_record;
8
9#[derive(Clone)]
10pub struct MetadataAccess;
11
12impl Command for MetadataAccess {
13    fn name(&self) -> &str {
14        "metadata access"
15    }
16
17    fn description(&self) -> &str {
18        "Access the metadata for the input stream within a closure."
19    }
20
21    fn signature(&self) -> Signature {
22        Signature::build("metadata access")
23            .required(
24                "closure",
25                SyntaxShape::Closure(Some(vec![SyntaxShape::Record(vec![])])),
26                "The closure to run with metadata access.",
27            )
28            .input_output_types(vec![(Type::Any, Type::Any)])
29            .category(Category::Debug)
30    }
31
32    fn run(
33        &self,
34        engine_state: &EngineState,
35        caller_stack: &mut Stack,
36        call: &Call,
37        input: PipelineData,
38    ) -> Result<PipelineData, ShellError> {
39        let closure: Closure = call.req(engine_state, caller_stack, 0)?;
40        let block = engine_state.get_block(closure.block_id);
41
42        // `ClosureEvalOnce` is not used as it uses `Stack::captures_to_stack` rather than
43        // `Stack::captures_to_stack_preserve_out_dest`. This command shouldn't collect streams
44        let mut callee_stack = caller_stack.captures_to_stack_preserve_out_dest(closure.captures);
45        let metadata_record = Value::record(
46            build_metadata_record(input.metadata().as_ref(), call.head),
47            call.head,
48        );
49
50        if let Some(var_id) = block.signature.get_positional(0).and_then(|var| var.var_id) {
51            callee_stack.add_var(var_id, metadata_record)
52        }
53
54        let eval = get_eval_block_with_early_return(engine_state);
55        eval(engine_state, &mut callee_stack, block, input)
56    }
57
58    fn examples(&self) -> Vec<Example> {
59        vec![Example {
60            description: "Access metadata and data from a stream together",
61            example: r#"{foo: bar} | to json --raw | metadata access {|meta| {in: $in, meta: $meta}}"#,
62            result: Some(Value::test_record(record! {
63                "in" => Value::test_string(r#"{"foo":"bar"}"#),
64                "meta" => Value::test_record(record! {
65                    "content_type" => Value::test_string(r#"application/json"#)
66                })
67            })),
68        }]
69    }
70}
71
72#[cfg(test)]
73mod test {
74    use crate::ToJson;
75
76    use super::*;
77
78    #[test]
79    fn test_examples() {
80        use crate::test_examples_with_commands;
81
82        test_examples_with_commands(MetadataAccess {}, &[&ToJson])
83    }
84}