nu_command/debug/
metadata_access.rs1use 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 let mut callee_stack = caller_stack.captures_to_stack_preserve_out_dest(closure.captures);
45 let metadata_record = Value::record(build_metadata_record(&input, call.head), call.head);
46
47 if let Some(var_id) = block.signature.get_positional(0).and_then(|var| var.var_id) {
48 callee_stack.add_var(var_id, metadata_record)
49 }
50
51 let eval = get_eval_block_with_early_return(engine_state);
52 eval(engine_state, &mut callee_stack, block, input).map(|p| p.body)
53 }
54
55 fn examples(&self) -> Vec<Example<'_>> {
56 vec![Example {
57 description: "Access metadata and data from a stream together",
58 example: r#"{foo: bar} | to json --raw | metadata access {|meta| {in: $in, content: $meta.content_type}}"#,
59 result: Some(Value::test_record(record! {
60 "in" => Value::test_string(r#"{"foo":"bar"}"#),
61 "content" => Value::test_string(r#"application/json"#)
62 })),
63 }]
64 }
65}
66
67#[cfg(test)]
68mod test {
69 use crate::ToJson;
70
71 use super::*;
72
73 #[test]
74 fn test_examples() {
75 use crate::test_examples_with_commands;
76
77 test_examples_with_commands(MetadataAccess {}, &[&ToJson])
78 }
79}