nu_command/debug/
metadata_access.rs1use nu_engine::{ClosureEvalOnce, command_prelude::*};
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 metadata_record = Value::record(build_metadata_record(&input, call.head), call.head);
41
42 ClosureEvalOnce::new_env_preserve_out_dest(engine_state, caller_stack, closure)
43 .add_arg(metadata_record)?
44 .run_with_input(input)
45 }
46
47 fn examples(&self) -> Vec<Example<'_>> {
48 vec![Example {
49 description: "Access metadata and data from a stream together.",
50 example: "{foo: bar} | to json --raw | metadata access {|meta| {in: $in, content: $meta.content_type}}",
51 result: Some(Value::test_record(record! {
52 "in" => Value::test_string(r#"{"foo":"bar"}"#),
53 "content" => Value::test_string("application/json")
54 })),
55 }]
56 }
57}
58
59#[cfg(test)]
60mod test {
61 use super::*;
62
63 #[test]
64 fn test_examples() -> nu_test_support::Result {
65 nu_test_support::test().examples(MetadataAccess)
66 }
67}