Skip to main content

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, DeprecationEntry, DeprecationType, ReportMode, 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                "(DEPRECATED) 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                "path-columns",
38                SyntaxShape::List(Box::new(SyntaxShape::String)),
39                "A list of columns in the input for which path metadata will be assigned.",
40                Some('p'),
41            )
42            .named(
43                "content-type",
44                SyntaxShape::String,
45                "Assign content type metadata to the input.",
46                Some('c'),
47            )
48            .named(
49                "merge",
50                SyntaxShape::Record(vec![]),
51                "(DEPRECATED) Merge arbitrary metadata fields.",
52                Some('m'),
53            )
54            .allow_variants_without_examples(true)
55            .category(Category::Debug)
56    }
57
58    fn deprecation_info(&self) -> Vec<DeprecationEntry> {
59        vec![
60            DeprecationEntry {
61                ty: DeprecationType::Flag("merge".into()),
62                report_mode: ReportMode::FirstUse,
63                since: Some("0.111.0".into()),
64                expected_removal: Some("0.112.0".into()),
65                help: Some(
66                    "Use the closure parameter instead: `metadata set {|| merge {key: value}}`"
67                        .into(),
68                ),
69            },
70            DeprecationEntry {
71                ty: DeprecationType::Flag("datasource-ls".into()),
72                report_mode: ReportMode::FirstUse,
73                since: Some("0.111.0".into()),
74                expected_removal: Some("0.113.0".into()),
75                help: Some(
76                    "Use the path-columns flag instead: `metadata set --path-columns [name]`"
77                        .into(),
78                ),
79            },
80        ]
81    }
82
83    fn run(
84        &self,
85        engine_state: &EngineState,
86        stack: &mut Stack,
87        call: &Call,
88        mut input: PipelineData,
89    ) -> Result<PipelineData, ShellError> {
90        let head = call.head;
91        let closure: Option<Closure> = call.opt(engine_state, stack, 0)?;
92        let ds_fp: Option<String> = call.get_flag(engine_state, stack, "datasource-filepath")?;
93        let ds_ls = call.has_flag(engine_state, stack, "datasource-ls")?;
94        let path_columns: Option<Vec<String>> =
95            call.get_flag(engine_state, stack, "path-columns")?;
96        let content_type: Option<String> = call.get_flag(engine_state, stack, "content-type")?;
97        let merge: Option<Value> = call.get_flag(engine_state, stack, "merge")?;
98
99        let mut metadata = match &mut input {
100            PipelineData::Value(_, metadata)
101            | PipelineData::ListStream(_, metadata)
102            | PipelineData::ByteStream(_, metadata) => metadata.take().unwrap_or_default(),
103            PipelineData::Empty => return Err(ShellError::PipelineEmpty { dst_span: head }),
104        };
105
106        // Handle closure parameter - mutually exclusive with flags
107        if let Some(closure) = closure {
108            if ds_fp.is_some()
109                || ds_ls
110                || path_columns.is_some()
111                || content_type.is_some()
112                || merge.is_some()
113            {
114                return Err(ShellError::GenericError {
115                    error: "Incompatible parameters".into(),
116                    msg: "cannot use closure with other flags".into(),
117                    span: Some(head),
118                    help: Some("Use either the closure parameter or flags, not both".into()),
119                    inner: vec![],
120                });
121            }
122
123            let record = extend_record_with_metadata(Record::new(), Some(&metadata), head);
124            let metadata_value = record.into_value(head);
125
126            let result = ClosureEvalOnce::new(engine_state, stack, closure)
127                .run_with_value(metadata_value)?
128                .into_value(head)?;
129
130            let result_record = result.as_record().map_err(|err| ShellError::GenericError {
131                error: "Closure must return a record".into(),
132                msg: format!("got {}", result.get_type()),
133                span: Some(head),
134                help: Some("The closure should return a record with metadata fields".into()),
135                inner: vec![err],
136            })?;
137
138            metadata = parse_metadata_from_record(result_record);
139            return Ok(input.set_metadata(Some(metadata)));
140        }
141
142        if let Some(path_columns) = path_columns {
143            metadata.path_columns = path_columns;
144        }
145
146        // Flag-based metadata modification
147        if let Some(content_type) = content_type {
148            metadata.content_type = Some(content_type);
149        }
150
151        if let Some(merge) = merge {
152            let custom_record = merge.as_record()?;
153            for (key, value) in custom_record {
154                metadata.custom.insert(key.clone(), value.clone());
155            }
156        }
157
158        match (ds_fp, ds_ls) {
159            (Some(path), false) => metadata.data_source = DataSource::FilePath(path.into()),
160            #[allow(deprecated)]
161            (None, true) => {
162                metadata.data_source = DataSource::Ls;
163                metadata.path_columns.push("name".to_string());
164            }
165            (Some(_), true) => {
166                return Err(ShellError::IncompatibleParameters {
167                    left_message: "cannot use `--datasource-filepath`".into(),
168                    left_span: call
169                        .get_flag_span(stack, "datasource-filepath")
170                        .expect("has flag"),
171                    right_message: "with `--datasource-ls`".into(),
172                    right_span: call
173                        .get_flag_span(stack, "datasource-ls")
174                        .expect("has flag"),
175                });
176            }
177            (None, false) => (),
178        }
179
180        Ok(input.set_metadata(Some(metadata)))
181    }
182
183    fn examples(&self) -> Vec<Example<'_>> {
184        vec![
185            Example {
186                description: "Set the metadata of a table literal so the `name` column is treated as a path.",
187                example: "[[name color]; [Cargo.lock '#ff0000'] [Cargo.toml '#00ff00'] [README.md '#0000ff']] | metadata set --path-columns [name]",
188                result: None,
189            },
190            Example {
191                description: "Set the metadata of a file path.",
192                example: "'crates' | metadata set --datasource-filepath $'(pwd)/crates'",
193                result: None,
194            },
195            Example {
196                description: "Set the content type metadata.",
197                example: "'crates' | metadata set --content-type text/plain | metadata | get content_type",
198                result: Some(Value::test_string("text/plain")),
199            },
200            Example {
201                description: "Merge custom metadata.",
202                example: r#""data" | metadata set {|| merge {custom_key: "value"}} | metadata | get custom_key"#,
203                result: None,
204            },
205            Example {
206                description: "Set metadata using a closure.",
207                example: r#""data" | metadata set --content-type "text/csv" | metadata set {|m| $m | update content_type {$in + "-processed"}} | metadata | get content_type"#,
208                result: Some(Value::test_string("text/csv-processed")),
209            },
210        ]
211    }
212}
213
214#[cfg(test)]
215mod test {
216    use crate::{Metadata, test_examples_with_commands};
217
218    use super::*;
219
220    #[test]
221    fn test_examples() {
222        test_examples_with_commands(MetadataSet {}, &[&Metadata {}])
223    }
224}