Skip to main content

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