1use nu_engine::command_prelude::*;
2use nu_protocol::{ast::PathMember, casing::Casing};
3use std::{cmp::Reverse, collections::HashSet};
4
5#[derive(Clone)]
6pub struct Reject;
7
8impl Command for Reject {
9 fn name(&self) -> &str {
10 "reject"
11 }
12
13 fn signature(&self) -> Signature {
14 Signature::build("reject")
15 .input_output_types(vec![
16 (Type::record(), Type::record()),
17 (Type::table(), Type::table()),
18 (Type::list(Type::Any), Type::list(Type::Any)),
19 ])
20 .switch(
21 "ignore-errors",
22 "ignore missing data (make all cell path members optional)",
23 Some('i'),
24 )
25 .rest(
26 "rest",
27 SyntaxShape::CellPath,
28 "The names of columns to remove from the table.",
29 )
30 .category(Category::Filters)
31 }
32
33 fn description(&self) -> &str {
34 "Remove the given columns or rows from the table. Opposite of `select`."
35 }
36
37 fn extra_description(&self) -> &str {
38 "To remove a quantity of rows or columns, use `skip`, `drop`, or `drop column`."
39 }
40
41 fn search_terms(&self) -> Vec<&str> {
42 vec!["drop", "key"]
43 }
44
45 fn run(
46 &self,
47 engine_state: &EngineState,
48 stack: &mut Stack,
49 call: &Call,
50 input: PipelineData,
51 ) -> Result<PipelineData, ShellError> {
52 let columns: Vec<Value> = call.rest(engine_state, stack, 0)?;
53 let mut new_columns: Vec<CellPath> = vec![];
54 for col_val in columns {
55 let col_span = &col_val.span();
56 match col_val {
57 Value::CellPath { val, .. } => {
58 new_columns.push(val);
59 }
60 Value::String { val, .. } => {
61 let cv = CellPath {
62 members: vec![PathMember::String {
63 val: val.clone(),
64 span: *col_span,
65 optional: false,
66 casing: Casing::Sensitive,
67 }],
68 };
69 new_columns.push(cv.clone());
70 }
71 Value::Int { val, .. } => {
72 let cv = CellPath {
73 members: vec![PathMember::Int {
74 val: val as usize,
75 span: *col_span,
76 optional: false,
77 }],
78 };
79 new_columns.push(cv.clone());
80 }
81 x => {
82 return Err(ShellError::CantConvert {
83 to_type: "cell path".into(),
84 from_type: x.get_type().to_string(),
85 span: x.span(),
86 help: None,
87 });
88 }
89 }
90 }
91 let span = call.head;
92
93 let ignore_errors = call.has_flag(engine_state, stack, "ignore-errors")?;
94 if ignore_errors {
95 for cell_path in &mut new_columns {
96 cell_path.make_optional();
97 }
98 }
99
100 reject(engine_state, span, input, new_columns)
101 }
102
103 fn examples(&self) -> Vec<Example> {
104 vec![
105 Example {
106 description: "Reject a column in the `ls` table",
107 example: "ls | reject modified",
108 result: None,
109 },
110 Example {
111 description: "Reject a column in a table",
112 example: "[[a, b]; [1, 2]] | reject a",
113 result: Some(Value::test_list(vec![Value::test_record(record! {
114 "b" => Value::test_int(2),
115 })])),
116 },
117 Example {
118 description: "Reject a row in a table",
119 example: "[[a, b]; [1, 2] [3, 4]] | reject 1",
120 result: Some(Value::test_list(vec![Value::test_record(record! {
121 "a" => Value::test_int(1),
122 "b" => Value::test_int(2),
123 })])),
124 },
125 Example {
126 description: "Reject the specified field in a record",
127 example: "{a: 1, b: 2} | reject a",
128 result: Some(Value::test_record(record! {
129 "b" => Value::test_int(2),
130 })),
131 },
132 Example {
133 description: "Reject a nested field in a record",
134 example: "{a: {b: 3, c: 5}} | reject a.b",
135 result: Some(Value::test_record(record! {
136 "a" => Value::test_record(record! {
137 "c" => Value::test_int(5),
138 }),
139 })),
140 },
141 Example {
142 description: "Reject multiple rows",
143 example: "[[name type size]; [Cargo.toml toml 1kb] [Cargo.lock toml 2kb] [file.json json 3kb]] | reject 0 2",
144 result: None,
145 },
146 Example {
147 description: "Reject multiple columns",
148 example: "[[name type size]; [Cargo.toml toml 1kb] [Cargo.lock toml 2kb]] | reject type size",
149 result: Some(Value::test_list(vec![
150 Value::test_record(record! { "name" => Value::test_string("Cargo.toml") }),
151 Value::test_record(record! { "name" => Value::test_string("Cargo.lock") }),
152 ])),
153 },
154 Example {
155 description: "Reject multiple columns by spreading a list",
156 example: "let cols = [type size]; [[name type size]; [Cargo.toml toml 1kb] [Cargo.lock toml 2kb]] | reject ...$cols",
157 result: Some(Value::test_list(vec![
158 Value::test_record(record! { "name" => Value::test_string("Cargo.toml") }),
159 Value::test_record(record! { "name" => Value::test_string("Cargo.lock") }),
160 ])),
161 },
162 Example {
163 description: "Reject item in list",
164 example: "[1 2 3] | reject 1",
165 result: Some(Value::test_list(vec![
166 Value::test_int(1),
167 Value::test_int(3),
168 ])),
169 },
170 ]
171 }
172}
173
174fn reject(
175 engine_state: &EngineState,
176 span: Span,
177 input: PipelineData,
178 cell_paths: Vec<CellPath>,
179) -> Result<PipelineData, ShellError> {
180 let mut unique_rows: HashSet<usize> = HashSet::new();
181 let metadata = input.metadata();
182 let mut new_columns = vec![];
183 let mut new_rows = vec![];
184 for column in cell_paths {
185 let CellPath { ref members } = column;
186 match members.first() {
187 Some(PathMember::Int { val, span, .. }) => {
188 if members.len() > 1 {
189 return Err(ShellError::GenericError {
190 error: "Reject only allows row numbers for rows".into(),
191 msg: "extra after row number".into(),
192 span: Some(*span),
193 help: None,
194 inner: vec![],
195 });
196 }
197 if !unique_rows.contains(val) {
198 unique_rows.insert(*val);
199 new_rows.push(column);
200 }
201 }
202 _ => {
203 if !new_columns.contains(&column) {
204 new_columns.push(column)
205 }
206 }
207 };
208 }
209 new_rows.sort_unstable_by_key(|k| {
210 Reverse({
211 match k.members[0] {
212 PathMember::Int { val, .. } => val,
213 PathMember::String { .. } => usize::MIN,
214 }
215 })
216 });
217
218 new_columns.append(&mut new_rows);
219
220 let has_integer_path_member = new_columns.iter().any(|path| {
221 path.members
222 .iter()
223 .any(|member| matches!(member, PathMember::Int { .. }))
224 });
225
226 match input {
227 PipelineData::ListStream(stream, ..) if !has_integer_path_member => {
228 let result = stream
229 .into_iter()
230 .map(move |mut value| {
231 let span = value.span();
232
233 for cell_path in new_columns.iter() {
234 if let Err(error) = value.remove_data_at_cell_path(&cell_path.members) {
235 return Value::error(error, span);
236 }
237 }
238
239 value
240 })
241 .into_pipeline_data(span, engine_state.signals().clone());
242
243 Ok(result)
244 }
245
246 input => {
247 let mut val = input.into_value(span)?;
248
249 for cell_path in new_columns {
250 val.remove_data_at_cell_path(&cell_path.members)?;
251 }
252
253 Ok(val.into_pipeline_data_with_metadata(metadata))
254 }
255 }
256}
257
258#[cfg(test)]
259mod test {
260 #[test]
261 fn test_examples() {
262 use super::Reject;
263 use crate::test_examples;
264 test_examples(Reject {})
265 }
266}