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 input = match input.try_into_stream(engine_state) {
138 Ok(input) | Err(input) => input,
139 };
140 let signals = engine_state.signals().clone();
141 let metadata = input.metadata();
142 match input {
143 PipelineData::Empty => Ok(PipelineData::empty()),
144 PipelineData::Value(v, ..) => {
145 let span = v.span();
146 match v {
147 Value::List { vals, .. } => match get_values(&vals, head, span) {
148 Ok(cols) => Ok(cols
149 .into_iter()
150 .into_pipeline_data_with_metadata(head, signals, metadata)),
151 Err(err) => Err(err),
152 },
153 Value::Custom { val, .. } => {
154 let input_as_base_value = val.to_base_value(span)?;
155 match get_values(&[input_as_base_value], head, span) {
156 Ok(cols) => Ok(cols
157 .into_iter()
158 .into_pipeline_data_with_metadata(head, signals, metadata)),
159 Err(err) => Err(err),
160 }
161 }
162 Value::Record { val, .. } => Ok(val
163 .values()
164 .cloned()
165 .collect::<Vec<_>>()
166 .into_pipeline_data_with_metadata(head, signals, metadata)),
167 Value::Error { error, .. } => Err(*error),
169 other => Err(ShellError::OnlySupportsThisInputType {
170 exp_input_type: "record or table".into(),
171 wrong_type: other.get_type().to_string(),
172 dst_span: head,
173 src_span: other.span(),
174 }),
175 }
176 }
177 PipelineData::ListStream(stream, ..) => {
178 let vals: Vec<_> = stream.into_iter().collect();
179 match get_values(&vals, head, head) {
180 Ok(cols) => Ok(cols
181 .into_iter()
182 .into_pipeline_data_with_metadata(head, signals, metadata)),
183 Err(err) => Err(err),
184 }
185 }
186 PipelineData::ByteStream(stream, ..) => Err(ShellError::OnlySupportsThisInputType {
187 exp_input_type: "record or table".into(),
188 wrong_type: stream.type_().describe().into(),
189 dst_span: head,
190 src_span: stream.span(),
191 }),
192 }
193}
194
195#[cfg(test)]
196mod test {
197 use super::*;
198
199 #[test]
200 fn test_examples() {
201 use crate::test_examples;
202
203 test_examples(Values {})
204 }
205}