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::OneOf(vec![SyntaxShape::String, SyntaxShape::Nothing]),
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<Option<String>> =
81 call.get_flag(engine_state, stack, "content-type")?;
82
83 let mut metadata = match &mut input {
84 PipelineData::Value(_, metadata)
85 | PipelineData::ListStream(_, metadata)
86 | PipelineData::ByteStream(_, metadata) => metadata.take().unwrap_or_default(),
87 PipelineData::Empty => return Err(ShellError::PipelineEmpty { dst_span: head }),
88 };
89
90 if let Some(closure) = closure {
92 if ds_fp.is_some() || ds_ls || path_columns.is_some() || content_type.is_some() {
93 return Err(ShellError::Generic(
94 GenericError::new(
95 "Incompatible parameters",
96 "cannot use closure with other flags",
97 head,
98 )
99 .with_help("Use either the closure parameter or flags, not both"),
100 ));
101 }
102
103 let record = extend_record_with_metadata(Record::new(), Some(&metadata), head);
104 let metadata_value = record.into_value(head);
105
106 let result = ClosureEvalOnce::new(engine_state, stack, closure)
107 .run_with_value(metadata_value)?
108 .into_value(head)?;
109
110 let result_record = result.as_record().map_err(|err| {
111 ShellError::Generic(
112 GenericError::new(
113 "Closure must return a record",
114 format!("got {}", result.get_type()),
115 head,
116 )
117 .with_help("The closure should return a record with metadata fields")
118 .with_inner([err]),
119 )
120 })?;
121
122 metadata = parse_metadata_from_record(result_record);
123 return Ok(input.set_metadata(Some(metadata)));
124 }
125
126 if let Some(path_columns) = path_columns {
127 metadata.path_columns = path_columns;
128 }
129
130 if let Some(content_type) = content_type {
132 metadata.content_type = content_type;
133 }
134
135 match (ds_fp, ds_ls) {
136 (Some(path), false) => metadata.data_source = DataSource::FilePath(path.into()),
137 #[allow(deprecated)]
138 (None, true) => {
139 metadata.data_source = DataSource::Ls;
140 metadata.path_columns.push("name".to_string());
141 }
142 (Some(_), true) => {
143 return Err(ShellError::IncompatibleParameters {
144 left_message: "cannot use `--datasource-filepath`".into(),
145 left_span: call
146 .get_flag_span(stack, "datasource-filepath")
147 .expect("has flag"),
148 right_message: "with `--datasource-ls`".into(),
149 right_span: call
150 .get_flag_span(stack, "datasource-ls")
151 .expect("has flag"),
152 });
153 }
154 (None, false) => (),
155 }
156
157 Ok(input.set_metadata(Some(metadata)))
158 }
159
160 fn examples(&self) -> Vec<Example<'_>> {
161 vec![
162 Example {
163 description: "Set the metadata of a table literal so the `name` column is treated as a path.",
164 example: "[[name color]; [Cargo.lock '#ff0000'] [Cargo.toml '#00ff00'] [README.md '#0000ff']] | metadata set --path-columns [name]",
165 result: None,
166 },
167 Example {
168 description: "Set the metadata of a file path.",
169 example: "'crates' | metadata set --datasource-filepath $'(pwd)/crates'",
170 result: None,
171 },
172 Example {
173 description: "Set the content type metadata.",
174 example: "'crates' | metadata set --content-type text/plain | metadata | get content_type",
175 result: Some(Value::test_string("text/plain")),
176 },
177 Example {
178 description: "Merge custom metadata.",
179 example: r#""data" | metadata set {|| merge {custom_key: "value"}} | metadata | get custom_key"#,
180 result: None,
181 },
182 Example {
183 description: "Set metadata using a closure.",
184 example: r#""data" | metadata set --content-type "text/csv" | metadata set {|m| $m | update content_type {$in + "-processed"}} | metadata | get content_type"#,
185 result: Some(Value::test_string("text/csv-processed")),
186 },
187 ]
188 }
189}
190
191#[cfg(test)]
192mod test {
193 use super::*;
194
195 #[test]
196 fn test_examples() -> nu_test_support::Result {
197 nu_test_support::test().examples(MetadataSet)
198 }
199}