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()])),
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 .named(
44 "table-width-priority-columns",
45 SyntaxShape::List(Box::new(SyntaxShape::String)),
46 "A list of columns to prioritize during table width allocation.",
47 Some('w'),
48 )
49 .allow_variants_without_examples(true)
50 .category(Category::Debug)
51 }
52
53 fn run(
54 &self,
55 engine_state: &EngineState,
56 stack: &mut Stack,
57 call: &Call,
58 mut input: PipelineData,
59 ) -> Result<PipelineData, ShellError> {
60 let head = call.head;
61 let closure: Option<Closure> = call.opt(engine_state, stack, 0)?;
62 let ds_fp: Option<String> = call.get_flag(engine_state, stack, "datasource-filepath")?;
63 let path_columns: Option<Vec<String>> =
64 call.get_flag(engine_state, stack, "path-columns")?;
65 let content_type: Option<Option<String>> =
66 call.get_flag(engine_state, stack, "content-type")?;
67 let table_width_priority_columns: Option<Vec<String>> =
68 call.get_flag(engine_state, stack, "table-width-priority-columns")?;
69
70 let mut metadata = match &mut input {
71 PipelineData::Value(_, metadata)
72 | PipelineData::ListStream(_, metadata)
73 | PipelineData::ByteStream(_, metadata) => metadata.take().unwrap_or_default(),
74 PipelineData::Empty => return Err(ShellError::PipelineEmpty { dst_span: head }),
75 };
76
77 if let Some(closure) = closure {
79 if ds_fp.is_some()
80 || path_columns.is_some()
81 || content_type.is_some()
82 || table_width_priority_columns.is_some()
83 {
84 return Err(ShellError::Generic(
85 GenericError::new(
86 "Incompatible parameters",
87 "cannot use closure with other flags",
88 head,
89 )
90 .with_help("Use either the closure parameter or flags, not both"),
91 ));
92 }
93
94 let record = extend_record_with_metadata(Record::new(), Some(&metadata), head);
95 let metadata_value = record.into_value(head);
96
97 let result = ClosureEvalOnce::new(engine_state, stack, closure)
98 .run_with_value(metadata_value)?
99 .into_value(head)?;
100
101 let result_record = result.as_record().map_err(|err| {
102 ShellError::Generic(
103 GenericError::new(
104 "Closure must return a record",
105 format!("got {}", result.get_type()),
106 head,
107 )
108 .with_help("The closure should return a record with metadata fields")
109 .with_inner([err]),
110 )
111 })?;
112
113 metadata = parse_metadata_from_record(result_record);
114 return Ok(input.set_metadata(Some(metadata)));
115 }
116
117 if let Some(path_columns) = path_columns {
118 metadata.path_columns = path_columns;
119 }
120
121 if let Some(table_width_priority_columns) = table_width_priority_columns {
122 metadata.set_table_width_priority_columns(head, table_width_priority_columns);
123 }
124
125 if let Some(content_type) = content_type {
127 metadata.content_type = content_type;
128 }
129
130 if let Some(path) = ds_fp {
131 metadata.data_source = DataSource::FilePath(path.into());
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 so the `name` column is treated as a path.",
141 example: "[[name color]; [Cargo.lock '#ff0000'] [Cargo.toml '#00ff00'] [README.md '#0000ff']] | metadata set --path-columns [name]",
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: "Merge custom metadata.",
156 example: r#""data" | metadata set {|| merge {custom_key: "value"}} | metadata | get custom_key"#,
157 result: None,
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 Example {
165 description: "Set table width-priority columns metadata.",
166 example: r#""data" | metadata set --table-width-priority-columns [command virtual] | metadata | get table_width_priority_columns | str join ",""#,
167 result: Some(Value::test_string("command,virtual")),
168 },
169 ]
170 }
171}
172
173#[cfg(test)]
174mod test {
175 use super::*;
176
177 #[test]
178 fn test_examples() -> nu_test_support::Result {
179 nu_test_support::test().examples(MetadataSet)
180 }
181}