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
use indexmap::IndexMap;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
    Category, Example, IntoInterruptiblePipelineData, PipelineData, ShellError, Signature, Span,
    Type, Value,
};

#[derive(Clone)]
pub struct Values;

impl Command for Values {
    fn name(&self) -> &str {
        "values"
    }

    fn signature(&self) -> Signature {
        Signature::build(self.name())
            .input_output_types(vec![
                (Type::Record(vec![]), Type::List(Box::new(Type::Any))),
                (Type::Table(vec![]), Type::List(Box::new(Type::Any))),
            ])
            .category(Category::Filters)
    }

    fn usage(&self) -> &str {
        "Given a record or table, produce a list of its columns' values."
    }

    fn extra_usage(&self) -> &str {
        "This is a counterpart to `columns`, which produces a list of columns' names."
    }

    fn examples(&self) -> Vec<Example> {
        vec![
            Example {
                example: "{ mode:normal userid:31415 } | values",
                description: "Get the values from the record (produce a list)",
                result: Some(Value::list(
                    vec![Value::test_string("normal"), Value::test_int(31415)],
                    Span::test_data(),
                )),
            },
            Example {
                example: "{ f:250 g:191 c:128 d:1024 e:2000 a:16 b:32 } | values",
                description: "Values are ordered by the column order of the record",
                result: Some(Value::list(
                    vec![
                        Value::test_int(250),
                        Value::test_int(191),
                        Value::test_int(128),
                        Value::test_int(1024),
                        Value::test_int(2000),
                        Value::test_int(16),
                        Value::test_int(32),
                    ],
                    Span::test_data(),
                )),
            },
            Example {
                example: "[[name meaning]; [ls list] [mv move] [cd 'change directory']] | values",
                description: "Get the values from the table (produce a list of lists)",
                result: Some(Value::list(
                    vec![
                        Value::list(
                            vec![
                                Value::test_string("ls"),
                                Value::test_string("mv"),
                                Value::test_string("cd"),
                            ],
                            Span::test_data(),
                        ),
                        Value::list(
                            vec![
                                Value::test_string("list"),
                                Value::test_string("move"),
                                Value::test_string("change directory"),
                            ],
                            Span::test_data(),
                        ),
                    ],
                    Span::test_data(),
                )),
            },
        ]
    }

    fn run(
        &self,
        engine_state: &EngineState,
        _stack: &mut Stack,
        call: &Call,
        input: PipelineData,
    ) -> Result<PipelineData, ShellError> {
        let span = call.head;
        values(engine_state, span, input)
    }
}

// The semantics of `values` are as follows:
// For each column, get the values for that column, in row order.
// Holes are not preserved, i.e. position in the resulting list
// does not necessarily equal row number.
pub fn get_values<'a>(
    input: impl IntoIterator<Item = &'a Value>,
    head: Span,
    input_span: Span,
) -> Result<Vec<Value>, ShellError> {
    let mut output: IndexMap<String, Vec<Value>> = IndexMap::new();

    for item in input {
        match item {
            Value::Record { val, .. } => {
                for (k, v) in val {
                    if let Some(vec) = output.get_mut(k) {
                        vec.push(v.clone());
                    } else {
                        output.insert(k.clone(), vec![v.clone()]);
                    }
                }
            }
            Value::Error { error, .. } => return Err(*error.clone()),
            _ => {
                return Err(ShellError::OnlySupportsThisInputType {
                    exp_input_type: "record or table".into(),
                    wrong_type: item.get_type().to_string(),
                    dst_span: head,
                    src_span: input_span,
                })
            }
        }
    }

    Ok(output.into_values().map(|v| Value::list(v, head)).collect())
}

fn values(
    engine_state: &EngineState,
    head: Span,
    input: PipelineData,
) -> Result<PipelineData, ShellError> {
    let ctrlc = engine_state.ctrlc.clone();
    let metadata = input.metadata();
    match input {
        PipelineData::Empty => Ok(PipelineData::Empty),
        PipelineData::Value(v, ..) => {
            let span = v.span();
            match v {
                Value::List { vals, .. } => match get_values(&vals, head, span) {
                    Ok(cols) => Ok(cols
                        .into_iter()
                        .into_pipeline_data_with_metadata(metadata, ctrlc)),
                    Err(err) => Err(err),
                },
                Value::CustomValue { val, .. } => {
                    let input_as_base_value = val.to_base_value(span)?;
                    match get_values(&[input_as_base_value], head, span) {
                        Ok(cols) => Ok(cols
                            .into_iter()
                            .into_pipeline_data_with_metadata(metadata, ctrlc)),
                        Err(err) => Err(err),
                    }
                }
                Value::Record { val, .. } => Ok(val
                    .into_values()
                    .into_pipeline_data_with_metadata(metadata, ctrlc)),
                Value::LazyRecord { val, .. } => {
                    let record = match val.collect()? {
                        Value::Record { val, .. } => val,
                        _ => Err(ShellError::NushellFailedSpanned {
                            msg: "`LazyRecord::collect()` promises `Value::Record`".into(),
                            label: "Violating lazy record found here".into(),
                            span,
                        })?,
                    };
                    Ok(record
                        .into_values()
                        .into_pipeline_data_with_metadata(metadata, ctrlc))
                }
                // Propagate errors
                Value::Error { error, .. } => Err(*error),
                other => Err(ShellError::OnlySupportsThisInputType {
                    exp_input_type: "record or table".into(),
                    wrong_type: other.get_type().to_string(),
                    dst_span: head,
                    src_span: other.span(),
                }),
            }
        }
        PipelineData::ListStream(stream, ..) => {
            let vals: Vec<_> = stream.into_iter().collect();
            match get_values(&vals, head, head) {
                Ok(cols) => Ok(cols
                    .into_iter()
                    .into_pipeline_data_with_metadata(metadata, ctrlc)),
                Err(err) => Err(err),
            }
        }
        PipelineData::ExternalStream { .. } => Err(ShellError::OnlySupportsThisInputType {
            exp_input_type: "record or table".into(),
            wrong_type: "raw data".into(),
            dst_span: head,
            src_span: input
                .span()
                .expect("PipelineData::ExternalStream had no span"),
        }),
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_examples() {
        use crate::test_examples;

        test_examples(Values {})
    }
}