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
use nu_engine::CallExt;
use nu_protocol::ast::{Call, CellPath};
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
    Category, Example, FromValue, IntoInterruptiblePipelineData, IntoPipelineData, PipelineData,
    ShellError, Signature, Span, SyntaxShape, Value,
};

#[derive(Clone)]
pub struct DropColumn;

impl Command for DropColumn {
    fn name(&self) -> &str {
        "drop column"
    }

    fn signature(&self) -> Signature {
        Signature::build(self.name())
            .optional(
                "columns",
                SyntaxShape::Int,
                "starting from the end, the number of columns to remove",
            )
            .category(Category::Filters)
    }

    fn usage(&self) -> &str {
        "Remove the last number of columns. If you want to remove columns by name, try 'reject'."
    }

    fn search_terms(&self) -> Vec<&str> {
        vec!["delete"]
    }

    fn run(
        &self,
        engine_state: &EngineState,
        stack: &mut Stack,
        call: &Call,
        input: PipelineData,
    ) -> Result<PipelineData, ShellError> {
        // the number of columns to drop
        let columns: Option<i64> = call.opt(engine_state, stack, 0)?;
        let span = call.head;

        let columns_to_drop = if let Some(quantity) = columns {
            quantity
        } else {
            1
        };

        dropcol(engine_state, span, input, columns_to_drop)
    }

    fn examples(&self) -> Vec<Example> {
        vec![Example {
            description: "Remove the last column of a table",
            example: "echo [[lib, extension]; [nu-lib, rs] [nu-core, rb]] | drop column",
            result: Some(Value::List {
                vals: vec![
                    Value::Record {
                        cols: vec!["lib".into()],
                        vals: vec![Value::test_string("nu-lib")],
                        span: Span::test_data(),
                    },
                    Value::Record {
                        cols: vec!["lib".into()],
                        vals: vec![Value::test_string("nu-core")],
                        span: Span::test_data(),
                    },
                ],
                span: Span::test_data(),
            }),
        }]
    }
}

fn dropcol(
    engine_state: &EngineState,
    span: Span,
    input: PipelineData,
    columns: i64, // the number of columns to drop
) -> Result<PipelineData, ShellError> {
    let mut keep_columns = vec![];

    match input {
        PipelineData::Value(
            Value::List {
                vals: input_vals,
                span,
            },
            ..,
        ) => {
            let mut output = vec![];
            let input_cols = get_input_cols(input_vals.clone());
            let kc = get_keep_columns(input_cols, columns);
            keep_columns = get_cellpath_columns(kc, span);

            for input_val in input_vals {
                let mut cols = vec![];
                let mut vals = vec![];

                for path in &keep_columns {
                    let fetcher = input_val.clone().follow_cell_path(&path.members, false)?;
                    cols.push(path.into_string());
                    vals.push(fetcher);
                }
                output.push(Value::Record { cols, vals, span })
            }

            Ok(output
                .into_iter()
                .into_pipeline_data(engine_state.ctrlc.clone()))
        }
        PipelineData::ListStream(stream, ..) => {
            let mut output = vec![];

            let v: Vec<_> = stream.into_iter().collect();
            let input_cols = get_input_cols(v.clone());
            let kc = get_keep_columns(input_cols, columns);
            keep_columns = get_cellpath_columns(kc, span);

            for input_val in v {
                let mut cols = vec![];
                let mut vals = vec![];

                for path in &keep_columns {
                    let fetcher = input_val.clone().follow_cell_path(&path.members, false)?;
                    cols.push(path.into_string());
                    vals.push(fetcher);
                }
                output.push(Value::Record { cols, vals, span })
            }

            Ok(output
                .into_iter()
                .into_pipeline_data(engine_state.ctrlc.clone()))
        }
        PipelineData::Value(v, ..) => {
            let mut cols = vec![];
            let mut vals = vec![];

            for cell_path in &keep_columns {
                let result = v.clone().follow_cell_path(&cell_path.members, false)?;

                cols.push(cell_path.into_string());
                vals.push(result);
            }

            Ok(Value::Record { cols, vals, span }.into_pipeline_data())
        }
        x => Ok(x),
    }
}

fn get_input_cols(input: Vec<Value>) -> Vec<String> {
    let rec = input.first();
    match rec {
        Some(Value::Record { cols, vals: _, .. }) => cols.to_vec(),
        _ => vec!["".to_string()],
    }
}

fn get_cellpath_columns(keep_cols: Vec<String>, span: Span) -> Vec<CellPath> {
    let mut output = vec![];
    for keep_col in keep_cols {
        let val = Value::String {
            val: keep_col,
            span,
        };
        let cell_path = match CellPath::from_value(&val) {
            Ok(v) => v,
            Err(_) => return vec![],
        };
        output.push(cell_path);
    }
    output
}

fn get_keep_columns(input: Vec<String>, mut num_of_columns_to_drop: i64) -> Vec<String> {
    let vlen: i64 = input.len() as i64;

    if num_of_columns_to_drop > vlen {
        num_of_columns_to_drop = vlen;
    }

    let num_of_columns_to_keep = (vlen - num_of_columns_to_drop) as usize;
    input[0..num_of_columns_to_keep].to_vec()
}

#[cfg(test)]
mod test {
    #[test]
    fn test_examples() {
        use super::DropColumn;
        use crate::test_examples;
        test_examples(DropColumn {})
    }
}