nu_command/filters/
headers.rs

1use nu_engine::command_prelude::*;
2use nu_protocol::Config;
3
4#[derive(Clone)]
5pub struct Headers;
6
7impl Command for Headers {
8    fn name(&self) -> &str {
9        "headers"
10    }
11
12    fn signature(&self) -> Signature {
13        Signature::build(self.name())
14            .input_output_types(vec![(Type::table(), Type::table())])
15            .category(Category::Filters)
16    }
17
18    fn description(&self) -> &str {
19        "Use the first row of the table as column names."
20    }
21
22    fn examples(&self) -> Vec<Example> {
23        vec![
24            Example {
25                description: "Sets the column names for a table created by `split column`",
26                example: r#""a b c|1 2 3" | split row "|" | split column " " | headers"#,
27                result: Some(Value::test_list(vec![Value::test_record(record! {
28                    "a" => Value::test_string("1"),
29                    "b" => Value::test_string("2"),
30                    "c" => Value::test_string("3"),
31                })])),
32            },
33            Example {
34                description: "Columns which don't have data in their first row are removed",
35                example: r#""a b c|1 2 3|1 2 3 4" | split row "|" | split column " " | headers"#,
36                result: Some(Value::test_list(vec![
37                    Value::test_record(record! {
38                        "a" => Value::test_string("1"),
39                        "b" => Value::test_string("2"),
40                        "c" => Value::test_string("3"),
41                    }),
42                    Value::test_record(record! {
43                        "a" => Value::test_string("1"),
44                        "b" => Value::test_string("2"),
45                        "c" => Value::test_string("3"),
46                    }),
47                ])),
48            },
49        ]
50    }
51
52    fn run(
53        &self,
54        engine_state: &EngineState,
55        _stack: &mut Stack,
56        call: &Call,
57        input: PipelineData,
58    ) -> Result<PipelineData, ShellError> {
59        let config = engine_state.get_config();
60        let metadata = input.metadata();
61        let span = input.span().unwrap_or(call.head);
62        let value = input.into_value(span)?;
63        let Value::List { vals: table, .. } = value else {
64            return Err(ShellError::TypeMismatch {
65                err_message: "not a table".to_string(),
66                span,
67            });
68        };
69
70        let (old_headers, new_headers) = extract_headers(&table, span, config)?;
71        let value = replace_headers(table, span, &old_headers, &new_headers)?;
72
73        Ok(value.into_pipeline_data_with_metadata(metadata))
74    }
75}
76
77fn extract_headers(
78    table: &[Value],
79    span: Span,
80    config: &Config,
81) -> Result<(Vec<String>, Vec<String>), ShellError> {
82    table
83        .first()
84        .ok_or_else(|| ShellError::GenericError {
85            error: "Found empty list".into(),
86            msg: "unable to extract headers".into(),
87            span: Some(span),
88            help: None,
89            inner: vec![],
90        })
91        .and_then(Value::as_record)
92        .and_then(|record| {
93            for v in record.values() {
94                if !is_valid_header(v) {
95                    return Err(ShellError::TypeMismatch {
96                        err_message: "needs compatible type: Null, String, Bool, Float, Int"
97                            .to_string(),
98                        span: v.span(),
99                    });
100                }
101            }
102
103            let old_headers = record.columns().cloned().collect();
104            let new_headers = record
105                .values()
106                .enumerate()
107                .map(|(idx, value)| {
108                    let col = value.to_expanded_string("", config);
109                    if col.is_empty() {
110                        format!("column{idx}")
111                    } else {
112                        col
113                    }
114                })
115                .collect();
116
117            Ok((old_headers, new_headers))
118        })
119}
120
121fn is_valid_header(value: &Value) -> bool {
122    matches!(
123        value,
124        Value::Nothing { .. }
125            | Value::String { val: _, .. }
126            | Value::Bool { val: _, .. }
127            | Value::Float { val: _, .. }
128            | Value::Int { val: _, .. }
129    )
130}
131
132fn replace_headers(
133    rows: Vec<Value>,
134    span: Span,
135    old_headers: &[String],
136    new_headers: &[String],
137) -> Result<Value, ShellError> {
138    rows.into_iter()
139        .skip(1)
140        .map(|value| {
141            let span = value.span();
142            if let Value::Record { val: record, .. } = value {
143                Ok(Value::record(
144                    record
145                        .into_owned()
146                        .into_iter()
147                        .filter_map(|(col, val)| {
148                            old_headers
149                                .iter()
150                                .position(|c| c == &col)
151                                .map(|i| (new_headers[i].clone(), val))
152                        })
153                        .collect(),
154                    span,
155                ))
156            } else {
157                Err(ShellError::CantConvert {
158                    to_type: "record".into(),
159                    from_type: value.get_type().to_string(),
160                    span,
161                    help: None,
162                })
163            }
164        })
165        .collect::<Result<_, _>>()
166        .map(|rows| Value::list(rows, span))
167}
168
169#[cfg(test)]
170mod test {
171    use super::*;
172
173    #[test]
174    fn test_examples() {
175        use crate::test_examples;
176
177        test_examples(Headers {})
178    }
179}