Skip to main content

nu_command/filters/
headers.rs

1use nu_engine::command_prelude::*;
2use nu_protocol::{Config, shell_error::generic::GenericError};
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 mut input = input.into_stream_or_original(engine_state);
60        let config = &stack.get_config(engine_state);
61        let metadata = input.take_metadata();
62        let span = input.span().unwrap_or(call.head);
63        let value = input.into_value(span)?;
64        let Value::List { vals: table, .. } = value else {
65            return Err(ShellError::TypeMismatch {
66                err_message: "not a table".to_string(),
67                span,
68            });
69        };
70
71        let (old_headers, new_headers) = extract_headers(&table, span, config)?;
72        let value = replace_headers(table, span, &old_headers, &new_headers)?;
73
74        Ok(value.into_pipeline_data_with_metadata(metadata))
75    }
76}
77
78fn extract_headers(
79    table: &[Value],
80    span: Span,
81    config: &Config,
82) -> Result<(Vec<String>, Vec<String>), ShellError> {
83    table
84        .first()
85        .ok_or_else(|| {
86            ShellError::Generic(GenericError::new(
87                "Found empty list",
88                "unable to extract headers",
89                span,
90            ))
91        })
92        .and_then(Value::as_record)
93        .and_then(|record| {
94            for v in record.values() {
95                if !is_valid_header(v) {
96                    return Err(ShellError::TypeMismatch {
97                        err_message: "needs compatible type: Null, String, Bool, Float, Int"
98                            .to_string(),
99                        span: v.span(),
100                    });
101                }
102            }
103
104            let old_headers = record.columns().cloned().collect();
105            let new_headers = record
106                .values()
107                .enumerate()
108                .map(|(idx, value)| {
109                    let col = value.to_expanded_string("", config);
110                    if col.is_empty() {
111                        format!("column{idx}")
112                    } else {
113                        col
114                    }
115                })
116                .collect();
117
118            Ok((old_headers, new_headers))
119        })
120}
121
122fn is_valid_header(value: &Value) -> bool {
123    matches!(
124        value,
125        Value::Nothing { .. }
126            | Value::String { val: _, .. }
127            | Value::Bool { val: _, .. }
128            | Value::Float { val: _, .. }
129            | Value::Int { val: _, .. }
130    )
131}
132
133fn replace_headers(
134    rows: Vec<Value>,
135    span: Span,
136    old_headers: &[String],
137    new_headers: &[String],
138) -> Result<Value, ShellError> {
139    rows.into_iter()
140        .skip(1)
141        .map(|value| {
142            let span = value.span();
143            if let Value::Record { val: record, .. } = value {
144                Ok(Value::record(
145                    record
146                        .into_owned()
147                        .into_iter()
148                        .filter_map(|(col, val)| {
149                            old_headers
150                                .iter()
151                                .position(|c| c == &col)
152                                .map(|i| (new_headers[i].clone(), val))
153                        })
154                        .collect(),
155                    span,
156                ))
157            } else {
158                Err(ShellError::CantConvert {
159                    to_type: "record".into(),
160                    from_type: value.get_type().to_string(),
161                    span,
162                    help: None,
163                })
164            }
165        })
166        .collect::<Result<_, _>>()
167        .map(|rows| Value::list(rows, span))
168}
169
170#[cfg(test)]
171mod test {
172    use super::*;
173
174    #[test]
175    fn test_examples() -> nu_test_support::Result {
176        nu_test_support::test().examples(Headers)
177    }
178}