nu_command/debug/
metadata_set.rs

1use super::util::{extend_record_with_metadata, parse_metadata_from_record};
2use nu_engine::{ClosureEvalOnce, command_prelude::*};
3use nu_protocol::{DataSource, engine::Closure};
4
5#[derive(Clone)]
6pub struct MetadataSet;
7
8impl Command for MetadataSet {
9    fn name(&self) -> &str {
10        "metadata set"
11    }
12
13    fn description(&self) -> &str {
14        "Set the metadata for items in the stream."
15    }
16
17    fn signature(&self) -> nu_protocol::Signature {
18        Signature::build("metadata set")
19            .input_output_types(vec![(Type::Any, Type::Any)])
20            .optional(
21                "closure",
22                SyntaxShape::Closure(Some(vec![SyntaxShape::Record(vec![])])),
23                "A closure that receives the current metadata and returns a new metadata record. Cannot be used with other flags.",
24            )
25            .switch(
26                "datasource-ls",
27                "Assign the DataSource::Ls metadata to the input",
28                Some('l'),
29            )
30            .named(
31                "datasource-filepath",
32                SyntaxShape::Filepath,
33                "Assign the DataSource::FilePath metadata to the input",
34                Some('f'),
35            )
36            .named(
37                "content-type",
38                SyntaxShape::String,
39                "Assign content type metadata to the input",
40                Some('c'),
41            )
42            .named(
43                "merge",
44                SyntaxShape::Record(vec![]),
45                "Merge arbitrary metadata fields",
46                Some('m'),
47            )
48            .allow_variants_without_examples(true)
49            .category(Category::Debug)
50    }
51
52    fn run(
53        &self,
54        engine_state: &EngineState,
55        stack: &mut Stack,
56        call: &Call,
57        mut input: PipelineData,
58    ) -> Result<PipelineData, ShellError> {
59        let head = call.head;
60        let closure: Option<Closure> = call.opt(engine_state, stack, 0)?;
61        let ds_fp: Option<String> = call.get_flag(engine_state, stack, "datasource-filepath")?;
62        let ds_ls = call.has_flag(engine_state, stack, "datasource-ls")?;
63        let content_type: Option<String> = call.get_flag(engine_state, stack, "content-type")?;
64        let merge: Option<Value> = call.get_flag(engine_state, stack, "merge")?;
65
66        let mut metadata = match &mut input {
67            PipelineData::Value(_, metadata)
68            | PipelineData::ListStream(_, metadata)
69            | PipelineData::ByteStream(_, metadata) => metadata.take().unwrap_or_default(),
70            PipelineData::Empty => return Err(ShellError::PipelineEmpty { dst_span: head }),
71        };
72
73        // Handle closure parameter - mutually exclusive with flags
74        if let Some(closure) = closure {
75            if ds_fp.is_some() || ds_ls || content_type.is_some() || merge.is_some() {
76                return Err(ShellError::GenericError {
77                    error: "Incompatible parameters".into(),
78                    msg: "cannot use closure with other flags".into(),
79                    span: Some(head),
80                    help: Some("Use either the closure parameter or flags, not both".into()),
81                    inner: vec![],
82                });
83            }
84
85            let record = extend_record_with_metadata(Record::new(), Some(&metadata), head);
86            let metadata_value = record.into_value(head);
87
88            let result = ClosureEvalOnce::new(engine_state, stack, closure)
89                .run_with_value(metadata_value)?
90                .into_value(head)?;
91
92            let result_record = result.as_record().map_err(|err| ShellError::GenericError {
93                error: "Closure must return a record".into(),
94                msg: format!("got {}", result.get_type()),
95                span: Some(head),
96                help: Some("The closure should return a record with metadata fields".into()),
97                inner: vec![err],
98            })?;
99
100            metadata = parse_metadata_from_record(result_record);
101            return Ok(input.set_metadata(Some(metadata)));
102        }
103
104        // Flag-based metadata modification
105        if let Some(content_type) = content_type {
106            metadata.content_type = Some(content_type);
107        }
108
109        if let Some(merge) = merge {
110            let custom_record = merge.as_record()?;
111            for (key, value) in custom_record {
112                metadata.custom.insert(key.clone(), value.clone());
113            }
114        }
115
116        match (ds_fp, ds_ls) {
117            (Some(path), false) => metadata.data_source = DataSource::FilePath(path.into()),
118            (None, true) => metadata.data_source = DataSource::Ls,
119            (Some(_), true) => {
120                return Err(ShellError::IncompatibleParameters {
121                    left_message: "cannot use `--datasource-filepath`".into(),
122                    left_span: call
123                        .get_flag_span(stack, "datasource-filepath")
124                        .expect("has flag"),
125                    right_message: "with `--datasource-ls`".into(),
126                    right_span: call
127                        .get_flag_span(stack, "datasource-ls")
128                        .expect("has flag"),
129                });
130            }
131            (None, false) => (),
132        }
133
134        Ok(input.set_metadata(Some(metadata)))
135    }
136
137    fn examples(&self) -> Vec<Example<'_>> {
138        vec![
139            Example {
140                description: "Set the metadata of a table literal",
141                example: "[[name color]; [Cargo.lock '#ff0000'] [Cargo.toml '#00ff00'] [README.md '#0000ff']] | metadata set --datasource-ls",
142                result: None,
143            },
144            Example {
145                description: "Set the metadata of a file path",
146                example: "'crates' | metadata set --datasource-filepath $'(pwd)/crates'",
147                result: None,
148            },
149            Example {
150                description: "Set the content type metadata",
151                example: "'crates' | metadata set --content-type text/plain | metadata | get content_type",
152                result: Some(Value::test_string("text/plain")),
153            },
154            Example {
155                description: "Set custom metadata",
156                example: r#""data" | metadata set --merge {custom_key: "value"} | metadata | get custom_key"#,
157                result: Some(Value::test_string("value")),
158            },
159            Example {
160                description: "Set metadata using a closure",
161                example: r#""data" | metadata set --content-type "text/csv" | metadata set {|m| $m | update content_type {$in + "-processed"}} | metadata | get content_type"#,
162                result: Some(Value::test_string("text/csv-processed")),
163            },
164        ]
165    }
166}
167
168#[cfg(test)]
169mod test {
170    use crate::{Metadata, test_examples_with_commands};
171
172    use super::*;
173
174    #[test]
175    fn test_examples() {
176        test_examples_with_commands(MetadataSet {}, &[&Metadata {}])
177    }
178}