forked from nushell/nushell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
move_.rs
293 lines (271 loc) · 10.6 KB
/
move_.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
use nu_engine::CallExt;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
record, Category, Example, IntoInterruptiblePipelineData, IntoPipelineData, PipelineData,
Record, ShellError, Signature, Span, Spanned, SyntaxShape, Type, Value,
};
#[derive(Clone, Debug)]
enum BeforeOrAfter {
Before(String),
After(String),
}
#[derive(Clone)]
pub struct Move;
impl Command for Move {
fn name(&self) -> &str {
"move"
}
fn usage(&self) -> &str {
"Move columns before or after other columns."
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build("move")
.input_output_types(vec![
(Type::Record(vec![]), Type::Record(vec![])),
(Type::Table(vec![]), Type::Table(vec![])),
])
.rest("columns", SyntaxShape::String, "The columns to move.")
.named(
"after",
SyntaxShape::String,
"the column that will precede the columns moved",
None,
)
.named(
"before",
SyntaxShape::String,
"the column that will be the next after the columns moved",
None,
)
.category(Category::Filters)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
example: "[[name value index]; [foo a 1] [bar b 2] [baz c 3]] | move index --before name",
description: "Move a column before the first column",
result:
Some(Value::test_list(
vec![
Value::test_record(record! {
"index" => Value::test_int(1),
"name" => Value::test_string("foo"),
"value" => Value::test_string("a"),
}),
Value::test_record(record! {
"index" => Value::test_int(2),
"name" => Value::test_string("bar"),
"value" => Value::test_string("b"),
}),
Value::test_record(record! {
"index" => Value::test_int(3),
"name" => Value::test_string("baz"),
"value" => Value::test_string("c"),
}),
],
))
},
Example {
example: "[[name value index]; [foo a 1] [bar b 2] [baz c 3]] | move value name --after index",
description: "Move multiple columns after the last column and reorder them",
result:
Some(Value::test_list(
vec![
Value::test_record(record! {
"index" => Value::test_int(1),
"value" => Value::test_string("a"),
"name" => Value::test_string("foo"),
}),
Value::test_record(record! {
"index" => Value::test_int(2),
"value" => Value::test_string("b"),
"name" => Value::test_string("bar"),
}),
Value::test_record(record! {
"index" => Value::test_int(3),
"value" => Value::test_string("c"),
"name" => Value::test_string("baz"),
}),
],
))
},
Example {
example: "{ name: foo, value: a, index: 1 } | move name --before index",
description: "Move columns of a record",
result: Some(Value::test_record(record! {
"value" => Value::test_string("a"),
"name" => Value::test_string("foo"),
"index" => Value::test_int(1),
}))
},
]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let columns: Vec<Value> = call.rest(engine_state, stack, 0)?;
let after: Option<Value> = call.get_flag(engine_state, stack, "after")?;
let before: Option<Value> = call.get_flag(engine_state, stack, "before")?;
let before_or_after = match (after, before) {
(Some(v), None) => Spanned {
span: v.span(),
item: BeforeOrAfter::After(v.coerce_into_string()?),
},
(None, Some(v)) => Spanned {
span: v.span(),
item: BeforeOrAfter::Before(v.coerce_into_string()?),
},
(Some(_), Some(_)) => {
return Err(ShellError::GenericError {
error: "Cannot move columns".into(),
msg: "Use either --after, or --before, not both".into(),
span: Some(call.head),
help: None,
inner: vec![],
})
}
(None, None) => {
return Err(ShellError::GenericError {
error: "Cannot move columns".into(),
msg: "Missing --after or --before flag".into(),
span: Some(call.head),
help: None,
inner: vec![],
})
}
};
let metadata = input.metadata();
let ctrlc = engine_state.ctrlc.clone();
let call = call.clone();
match input {
PipelineData::Value(Value::List { .. }, ..) | PipelineData::ListStream { .. } => {
let res = input.into_iter().map(move |x| match x.as_record() {
Ok(record) => {
match move_record_columns(record, &columns, &before_or_after, call.head) {
Ok(val) => val,
Err(error) => Value::error(error, call.head),
}
}
Err(error) => Value::error(error, call.head),
});
if let Some(md) = metadata {
Ok(res.into_pipeline_data_with_metadata(md, ctrlc))
} else {
Ok(res.into_pipeline_data(ctrlc))
}
}
PipelineData::Value(Value::Record { val, .. }, ..) => {
Ok(
move_record_columns(&val, &columns, &before_or_after, call.head)?
.into_pipeline_data(),
)
}
_ => Err(ShellError::PipelineMismatch {
exp_input_type: "record or table".to_string(),
dst_span: call.head,
src_span: Span::new(call.head.start, call.head.start),
}),
}
}
}
// Move columns within a record
fn move_record_columns(
record: &Record,
columns: &[Value],
before_or_after: &Spanned<BeforeOrAfter>,
span: Span,
) -> Result<Value, ShellError> {
let mut column_idx: Vec<usize> = Vec::with_capacity(columns.len());
// Check if before/after column exist
match &before_or_after.item {
BeforeOrAfter::After(after) => {
if !record.contains(after) {
return Err(ShellError::GenericError {
error: "Cannot move columns".into(),
msg: "column does not exist".into(),
span: Some(before_or_after.span),
help: None,
inner: vec![],
});
}
}
BeforeOrAfter::Before(before) => {
if !record.contains(before) {
return Err(ShellError::GenericError {
error: "Cannot move columns".into(),
msg: "column does not exist".into(),
span: Some(before_or_after.span),
help: None,
inner: vec![],
});
}
}
}
// Find indices of columns to be moved
for column in columns.iter() {
if let Some(idx) = record.index_of(&column.coerce_str()?) {
column_idx.push(idx);
} else {
return Err(ShellError::GenericError {
error: "Cannot move columns".into(),
msg: "column does not exist".into(),
span: Some(column.span()),
help: None,
inner: vec![],
});
}
}
let mut out = Record::with_capacity(record.len());
for (i, (inp_col, inp_val)) in record.iter().enumerate() {
match &before_or_after.item {
BeforeOrAfter::After(after) if after == inp_col => {
out.push(inp_col.clone(), inp_val.clone());
for idx in column_idx.iter() {
if let Some((col, val)) = record.get_index(*idx) {
out.push(col.clone(), val.clone());
} else {
return Err(ShellError::NushellFailedSpanned {
msg: "Error indexing input columns".to_string(),
label: "originates from here".to_string(),
span,
});
}
}
}
BeforeOrAfter::Before(before) if before == inp_col => {
for idx in column_idx.iter() {
if let Some((col, val)) = record.get_index(*idx) {
out.push(col.clone(), val.clone());
} else {
return Err(ShellError::NushellFailedSpanned {
msg: "Error indexing input columns".to_string(),
label: "originates from here".to_string(),
span,
});
}
}
out.push(inp_col.clone(), inp_val.clone());
}
_ => {
if !column_idx.contains(&i) {
out.push(inp_col.clone(), inp_val.clone());
}
}
}
}
Ok(Value::record(out, span))
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(Move {})
}
}