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, engine::Closure, shell_error::generic::GenericError};
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            .named(
26                "datasource-filepath",
27                SyntaxShape::Filepath,
28                "Assign the DataSource::FilePath metadata to the input.",
29                Some('f'),
30            )
31            .named(
32                "path-columns",
33                SyntaxShape::List(Box::new(SyntaxShape::String)),
34                "A list of columns in the input for which path metadata will be assigned.",
35                Some('p'),
36            )
37            .named(
38                "content-type",
39                SyntaxShape::OneOf(vec![SyntaxShape::String, SyntaxShape::Nothing]),
40                "Assign content type metadata to the input.",
41                Some('c'),
42            )
43            .allow_variants_without_examples(true)
44            .category(Category::Debug)
45    }
46
47    fn run(
48        &self,
49        engine_state: &EngineState,
50        stack: &mut Stack,
51        call: &Call,
52        mut input: PipelineData,
53    ) -> Result<PipelineData, ShellError> {
54        let head = call.head;
55        let closure: Option<Closure> = call.opt(engine_state, stack, 0)?;
56        let ds_fp: Option<String> = call.get_flag(engine_state, stack, "datasource-filepath")?;
57        let path_columns: Option<Vec<String>> =
58            call.get_flag(engine_state, stack, "path-columns")?;
59        let content_type: Option<Option<String>> =
60            call.get_flag(engine_state, stack, "content-type")?;
61
62        let mut metadata = match &mut input {
63            PipelineData::Value(_, metadata)
64            | PipelineData::ListStream(_, metadata)
65            | PipelineData::ByteStream(_, metadata) => metadata.take().unwrap_or_default(),
66            PipelineData::Empty => return Err(ShellError::PipelineEmpty { dst_span: head }),
67        };
68
69        // Handle closure parameter - mutually exclusive with flags
70        if let Some(closure) = closure {
71            if ds_fp.is_some() || path_columns.is_some() || content_type.is_some() {
72                return Err(ShellError::Generic(
73                    GenericError::new(
74                        "Incompatible parameters",
75                        "cannot use closure with other flags",
76                        head,
77                    )
78                    .with_help("Use either the closure parameter or flags, not both"),
79                ));
80            }
81
82            let record = extend_record_with_metadata(Record::new(), Some(&metadata), head);
83            let metadata_value = record.into_value(head);
84
85            let result = ClosureEvalOnce::new(engine_state, stack, closure)
86                .run_with_value(metadata_value)?
87                .into_value(head)?;
88
89            let result_record = result.as_record().map_err(|err| {
90                ShellError::Generic(
91                    GenericError::new(
92                        "Closure must return a record",
93                        format!("got {}", result.get_type()),
94                        head,
95                    )
96                    .with_help("The closure should return a record with metadata fields")
97                    .with_inner([err]),
98                )
99            })?;
100
101            metadata = parse_metadata_from_record(result_record);
102            return Ok(input.set_metadata(Some(metadata)));
103        }
104
105        if let Some(path_columns) = path_columns {
106            metadata.path_columns = path_columns;
107        }
108
109        // Flag-based metadata modification
110        if let Some(content_type) = content_type {
111            metadata.content_type = content_type;
112        }
113
114        if let Some(path) = ds_fp {
115            metadata.data_source = DataSource::FilePath(path.into());
116        }
117
118        Ok(input.set_metadata(Some(metadata)))
119    }
120
121    fn examples(&self) -> Vec<Example<'_>> {
122        vec![
123            Example {
124                description: "Set the metadata of a table literal so the `name` column is treated as a path.",
125                example: "[[name color]; [Cargo.lock '#ff0000'] [Cargo.toml '#00ff00'] [README.md '#0000ff']] | metadata set --path-columns [name]",
126                result: None,
127            },
128            Example {
129                description: "Set the metadata of a file path.",
130                example: "'crates' | metadata set --datasource-filepath $'(pwd)/crates'",
131                result: None,
132            },
133            Example {
134                description: "Set the content type metadata.",
135                example: "'crates' | metadata set --content-type text/plain | metadata | get content_type",
136                result: Some(Value::test_string("text/plain")),
137            },
138            Example {
139                description: "Merge custom metadata.",
140                example: r#""data" | metadata set {|| merge {custom_key: "value"}} | metadata | get custom_key"#,
141                result: None,
142            },
143            Example {
144                description: "Set metadata using a closure.",
145                example: r#""data" | metadata set --content-type "text/csv" | metadata set {|m| $m | update content_type {$in + "-processed"}} | metadata | get content_type"#,
146                result: Some(Value::test_string("text/csv-processed")),
147            },
148        ]
149    }
150}
151
152#[cfg(test)]
153mod test {
154    use super::*;
155
156    #[test]
157    fn test_examples() -> nu_test_support::Result {
158        nu_test_support::test().examples(MetadataSet)
159    }
160}