1use indexmap::IndexMap;
2use nu_engine::command_prelude::*;
3
4#[derive(Clone)]
5pub struct Values;
6
7impl Command for Values {
8 fn name(&self) -> &str {
9 "values"
10 }
11
12 fn signature(&self) -> Signature {
13 Signature::build(self.name())
14 .input_output_types(vec![
15 (Type::record(), Type::List(Box::new(Type::Any))),
16 (Type::table(), Type::List(Box::new(Type::Any))),
17 ])
18 .category(Category::Filters)
19 }
20
21 fn description(&self) -> &str {
22 "Given a record or table, produce a list of its columns' values."
23 }
24
25 fn extra_description(&self) -> &str {
26 "This is a counterpart to `columns`, which produces a list of columns' names."
27 }
28
29 fn examples(&self) -> Vec<Example> {
30 vec![
31 Example {
32 example: "{ mode:normal userid:31415 } | values",
33 description: "Get the values from the record (produce a list)",
34 result: Some(Value::list(
35 vec![Value::test_string("normal"), Value::test_int(31415)],
36 Span::test_data(),
37 )),
38 },
39 Example {
40 example: "{ f:250 g:191 c:128 d:1024 e:2000 a:16 b:32 } | values",
41 description: "Values are ordered by the column order of the record",
42 result: Some(Value::list(
43 vec![
44 Value::test_int(250),
45 Value::test_int(191),
46 Value::test_int(128),
47 Value::test_int(1024),
48 Value::test_int(2000),
49 Value::test_int(16),
50 Value::test_int(32),
51 ],
52 Span::test_data(),
53 )),
54 },
55 Example {
56 example: "[[name meaning]; [ls list] [mv move] [cd 'change directory']] | values",
57 description: "Get the values from the table (produce a list of lists)",
58 result: Some(Value::list(
59 vec![
60 Value::list(
61 vec![
62 Value::test_string("ls"),
63 Value::test_string("mv"),
64 Value::test_string("cd"),
65 ],
66 Span::test_data(),
67 ),
68 Value::list(
69 vec![
70 Value::test_string("list"),
71 Value::test_string("move"),
72 Value::test_string("change directory"),
73 ],
74 Span::test_data(),
75 ),
76 ],
77 Span::test_data(),
78 )),
79 },
80 ]
81 }
82
83 fn run(
84 &self,
85 engine_state: &EngineState,
86 _stack: &mut Stack,
87 call: &Call,
88 input: PipelineData,
89 ) -> Result<PipelineData, ShellError> {
90 let span = call.head;
91 values(engine_state, span, input)
92 }
93}
94
95pub fn get_values<'a>(
100 input: impl IntoIterator<Item = &'a Value>,
101 head: Span,
102 input_span: Span,
103) -> Result<Vec<Value>, ShellError> {
104 let mut output: IndexMap<String, Vec<Value>> = IndexMap::new();
105
106 for item in input {
107 match item {
108 Value::Record { val, .. } => {
109 for (k, v) in &**val {
110 if let Some(vec) = output.get_mut(k) {
111 vec.push(v.clone());
112 } else {
113 output.insert(k.clone(), vec![v.clone()]);
114 }
115 }
116 }
117 Value::Error { error, .. } => return Err(*error.clone()),
118 _ => {
119 return Err(ShellError::OnlySupportsThisInputType {
120 exp_input_type: "record or table".into(),
121 wrong_type: item.get_type().to_string(),
122 dst_span: head,
123 src_span: input_span,
124 });
125 }
126 }
127 }
128
129 Ok(output.into_values().map(|v| Value::list(v, head)).collect())
130}
131
132fn values(
133 engine_state: &EngineState,
134 head: Span,
135 input: PipelineData,
136) -> Result<PipelineData, ShellError> {
137 let signals = engine_state.signals().clone();
138 let metadata = input.metadata();
139 match input {
140 PipelineData::Empty => Ok(PipelineData::empty()),
141 PipelineData::Value(v, ..) => {
142 let span = v.span();
143 match v {
144 Value::List { vals, .. } => match get_values(&vals, head, span) {
145 Ok(cols) => Ok(cols
146 .into_iter()
147 .into_pipeline_data_with_metadata(head, signals, metadata)),
148 Err(err) => Err(err),
149 },
150 Value::Custom { val, .. } => {
151 let input_as_base_value = val.to_base_value(span)?;
152 match get_values(&[input_as_base_value], head, span) {
153 Ok(cols) => Ok(cols
154 .into_iter()
155 .into_pipeline_data_with_metadata(head, signals, metadata)),
156 Err(err) => Err(err),
157 }
158 }
159 Value::Record { val, .. } => Ok(val
160 .values()
161 .cloned()
162 .collect::<Vec<_>>()
163 .into_pipeline_data_with_metadata(head, signals, metadata)),
164 Value::Error { error, .. } => Err(*error),
166 other => Err(ShellError::OnlySupportsThisInputType {
167 exp_input_type: "record or table".into(),
168 wrong_type: other.get_type().to_string(),
169 dst_span: head,
170 src_span: other.span(),
171 }),
172 }
173 }
174 PipelineData::ListStream(stream, ..) => {
175 let vals: Vec<_> = stream.into_iter().collect();
176 match get_values(&vals, head, head) {
177 Ok(cols) => Ok(cols
178 .into_iter()
179 .into_pipeline_data_with_metadata(head, signals, metadata)),
180 Err(err) => Err(err),
181 }
182 }
183 PipelineData::ByteStream(stream, ..) => Err(ShellError::OnlySupportsThisInputType {
184 exp_input_type: "record or table".into(),
185 wrong_type: stream.type_().describe().into(),
186 dst_span: head,
187 src_span: stream.span(),
188 }),
189 }
190}
191
192#[cfg(test)]
193mod test {
194 use super::*;
195
196 #[test]
197 fn test_examples() {
198 use crate::test_examples;
199
200 test_examples(Values {})
201 }
202}