1use nu_engine::{ClosureEval, ClosureEvalOnce, command_prelude::*};
2use nu_protocol::ast::PathMember;
3
4#[derive(Clone)]
5pub struct Update;
6
7impl Command for Update {
8 fn name(&self) -> &str {
9 "update"
10 }
11
12 fn signature(&self) -> Signature {
13 Signature::build("update")
14 .input_output_types(vec![
15 (Type::record(), Type::record()),
16 (Type::table(), Type::table()),
17 (
18 Type::List(Box::new(Type::Any)),
19 Type::List(Box::new(Type::Any)),
20 ),
21 ])
22 .required(
23 "field",
24 SyntaxShape::CellPath,
25 "The name of the column to update.",
26 )
27 .required(
28 "replacement value",
29 SyntaxShape::Any,
30 "The new value to give the cell(s), or a closure to create the value.",
31 )
32 .allow_variants_without_examples(true)
33 .category(Category::Filters)
34 }
35
36 fn description(&self) -> &str {
37 "Update an existing column to have a new value."
38 }
39
40 fn extra_description(&self) -> &str {
41 "When updating a column, the closure will be run for each row, and the current row will be passed as the first argument. \
42Referencing `$in` inside the closure will provide the value at the column for the current row.
43
44When updating a specific index, the closure will instead be run once. The first argument to the closure and the `$in` value will both be the current value at the index."
45 }
46
47 fn run(
48 &self,
49 engine_state: &EngineState,
50 stack: &mut Stack,
51 call: &Call,
52 input: PipelineData,
53 ) -> Result<PipelineData, ShellError> {
54 update(engine_state, stack, call, input)
55 }
56
57 fn examples(&self) -> Vec<Example<'_>> {
58 vec![
59 Example {
60 description: "Update a column value.",
61 example: "{'name': 'nu', 'stars': 5} | update name 'Nushell'",
62 result: Some(Value::test_record(record! {
63 "name" => Value::test_string("Nushell"),
64 "stars" => Value::test_int(5),
65 })),
66 },
67 Example {
68 description: "Use a closure to alter each value in the 'authors' column to a single string.",
69 example: "[[project, authors]; ['nu', ['Andrés', 'JT', 'Yehuda']]] | update authors {|row| $row.authors | str join ',' }",
70 result: Some(Value::test_list(vec![Value::test_record(record! {
71 "project" => Value::test_string("nu"),
72 "authors" => Value::test_string("Andrés,JT,Yehuda"),
73 })])),
74 },
75 Example {
76 description: "Implicitly use the `$in` value in a closure to update 'authors'.",
77 example: "[[project, authors]; ['nu', ['Andrés', 'JT', 'Yehuda']]] | update authors { str join ',' }",
78 result: Some(Value::test_list(vec![Value::test_record(record! {
79 "project" => Value::test_string("nu"),
80 "authors" => Value::test_string("Andrés,JT,Yehuda"),
81 })])),
82 },
83 Example {
84 description: "Update a value at an index in a list.",
85 example: "[1 2 3] | update 1 4",
86 result: Some(Value::test_list(vec![
87 Value::test_int(1),
88 Value::test_int(4),
89 Value::test_int(3),
90 ])),
91 },
92 Example {
93 description: "Use a closure to compute a new value at an index.",
94 example: "[1 2 3] | update 1 {|i| $i + 2 }",
95 result: Some(Value::test_list(vec![
96 Value::test_int(1),
97 Value::test_int(4),
98 Value::test_int(3),
99 ])),
100 },
101 ]
102 }
103}
104
105fn update(
106 engine_state: &EngineState,
107 stack: &mut Stack,
108 call: &Call,
109 input: PipelineData,
110) -> Result<PipelineData, ShellError> {
111 let head = call.head;
112 let cell_path: CellPath = call.req(engine_state, stack, 0)?;
113 let replacement: Value = call.req(engine_state, stack, 1)?;
114 let input = match input.try_into_stream(engine_state) {
115 Ok(input) | Err(input) => input,
116 };
117
118 match input {
119 PipelineData::Value(mut value, metadata) => {
120 if let Value::Closure { val, .. } = replacement {
121 match (cell_path.members.first(), &mut value) {
122 (Some(PathMember::String { .. }), Value::List { vals, .. }) => {
123 let mut closure = ClosureEval::new(engine_state, stack, *val);
124 for val in vals {
125 update_value_by_closure(
126 val,
127 &mut closure,
128 head,
129 &cell_path.members,
130 false,
131 )?;
132 }
133 }
134 (first, _) => {
135 update_single_value_by_closure(
136 &mut value,
137 ClosureEvalOnce::new(engine_state, stack, *val),
138 head,
139 &cell_path.members,
140 matches!(first, Some(PathMember::Int { .. })),
141 )?;
142 }
143 }
144 } else {
145 value.update_data_at_cell_path(&cell_path.members, replacement)?;
146 }
147 Ok(value.into_pipeline_data_with_metadata(metadata))
148 }
149 PipelineData::ListStream(stream, metadata) => {
150 if let Some((
151 &PathMember::Int {
152 val,
153 span: path_span,
154 optional,
155 },
156 path,
157 )) = cell_path.members.split_first()
158 {
159 let mut stream = stream.into_iter();
160 let mut pre_elems = vec![];
161
162 for idx in 0..=val {
163 if let Some(v) = stream.next() {
164 pre_elems.push(v);
165 } else if optional {
166 return Ok(pre_elems
167 .into_iter()
168 .chain(stream)
169 .into_pipeline_data_with_metadata(
170 head,
171 engine_state.signals().clone(),
172 metadata,
173 ));
174 } else if idx == 0 {
175 return Err(ShellError::AccessEmptyContent { span: path_span });
176 } else {
177 return Err(ShellError::AccessBeyondEnd {
178 max_idx: idx - 1,
179 span: path_span,
180 });
181 }
182 }
183
184 let value = pre_elems.last_mut().expect("one element");
186
187 if let Value::Closure { val, .. } = replacement {
188 update_single_value_by_closure(
189 value,
190 ClosureEvalOnce::new(engine_state, stack, *val),
191 head,
192 path,
193 true,
194 )?;
195 } else {
196 value.update_data_at_cell_path(path, replacement)?;
197 }
198
199 Ok(pre_elems
200 .into_iter()
201 .chain(stream)
202 .into_pipeline_data_with_metadata(
203 head,
204 engine_state.signals().clone(),
205 metadata,
206 ))
207 } else if let Value::Closure { val, .. } = replacement {
208 let mut closure = ClosureEval::new(engine_state, stack, *val);
209 let stream = stream.map(move |mut value| {
210 let err = update_value_by_closure(
211 &mut value,
212 &mut closure,
213 head,
214 &cell_path.members,
215 false,
216 );
217
218 if let Err(e) = err {
219 Value::error(e, head)
220 } else {
221 value
222 }
223 });
224
225 Ok(PipelineData::list_stream(stream, metadata))
226 } else {
227 let stream = stream.map(move |mut value| {
228 if let Err(e) =
229 value.update_data_at_cell_path(&cell_path.members, replacement.clone())
230 {
231 Value::error(e, head)
232 } else {
233 value
234 }
235 });
236
237 Ok(PipelineData::list_stream(stream, metadata))
238 }
239 }
240 PipelineData::Empty => Err(ShellError::IncompatiblePathAccess {
241 type_name: "empty pipeline".to_string(),
242 span: head,
243 }),
244 PipelineData::ByteStream(stream, ..) => Err(ShellError::IncompatiblePathAccess {
245 type_name: stream.type_().describe().into(),
246 span: head,
247 }),
248 }
249}
250
251fn update_value_by_closure(
252 value: &mut Value,
253 closure: &mut ClosureEval,
254 span: Span,
255 cell_path: &[PathMember],
256 first_path_member_int: bool,
257) -> Result<(), ShellError> {
258 let value_at_path = value.follow_cell_path(cell_path)?;
259
260 let is_optional = cell_path.iter().any(|member| match member {
262 PathMember::String { optional, .. } => *optional,
263 PathMember::Int { optional, .. } => *optional,
264 });
265 if is_optional && matches!(value_at_path.as_ref(), Value::Nothing { .. }) {
266 return Ok(());
267 }
268
269 let arg = if first_path_member_int {
270 value_at_path.as_ref()
271 } else {
272 &*value
273 };
274
275 let new_value = closure
276 .add_arg(arg.clone())
277 .run_with_input(value_at_path.into_owned().into_pipeline_data())?
278 .into_value(span)?;
279
280 value.update_data_at_cell_path(cell_path, new_value)
281}
282
283fn update_single_value_by_closure(
284 value: &mut Value,
285 closure: ClosureEvalOnce,
286 span: Span,
287 cell_path: &[PathMember],
288 first_path_member_int: bool,
289) -> Result<(), ShellError> {
290 let value_at_path = value.follow_cell_path(cell_path)?;
291
292 let is_optional = cell_path.iter().any(|member| match member {
294 PathMember::String { optional, .. } => *optional,
295 PathMember::Int { optional, .. } => *optional,
296 });
297 if is_optional && matches!(value_at_path.as_ref(), Value::Nothing { .. }) {
298 return Ok(());
299 }
300
301 let arg = if first_path_member_int {
302 value_at_path.as_ref()
303 } else {
304 &*value
305 };
306
307 let new_value = closure
308 .add_arg(arg.clone())
309 .run_with_input(value_at_path.into_owned().into_pipeline_data())?
310 .into_value(span)?;
311
312 value.update_data_at_cell_path(cell_path, new_value)
313}
314
315#[cfg(test)]
316mod test {
317 use super::*;
318
319 #[test]
320 fn test_examples() {
321 use crate::test_examples;
322
323 test_examples(Update {})
324 }
325}