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

#[derive(Clone)]
pub struct Headers;

impl Command for Headers {
    fn name(&self) -> &str {
        "headers"
    }

    fn signature(&self) -> Signature {
        Signature::build(self.name()).category(Category::Filters)
    }

    fn usage(&self) -> &str {
        "Use the first row of the table as column names."
    }

    fn examples(&self) -> Vec<Example> {
        let columns = vec!["a".to_string(), "b".to_string(), "c".to_string()];
        vec![
            Example {
                description: "Returns headers from table",
                example: r#""a b c|1 2 3" | split row "|" | split column " " | headers"#,
                result: Some(Value::List {
                    vals: vec![Value::Record {
                        cols: columns.clone(),
                        vals: vec![
                            Value::test_string("1"),
                            Value::test_string("2"),
                            Value::test_string("3"),
                        ],
                        span: Span::test_data(),
                    }],
                    span: Span::test_data(),
                }),
            },
            Example {
                description: "Don't panic on rows with different headers",
                example: r#""a b c|1 2 3|1 2 3 4" | split row "|" | split column " " | headers"#,
                result: Some(Value::List {
                    vals: vec![
                        Value::Record {
                            cols: columns.clone(),
                            vals: vec![
                                Value::test_string("1"),
                                Value::test_string("2"),
                                Value::test_string("3"),
                            ],
                            span: Span::test_data(),
                        },
                        Value::Record {
                            cols: columns,
                            vals: vec![
                                Value::test_string("1"),
                                Value::test_string("2"),
                                Value::test_string("3"),
                            ],
                            span: Span::test_data(),
                        },
                    ],
                    span: Span::test_data(),
                }),
            },
        ]
    }

    fn run(
        &self,
        engine_state: &EngineState,
        _stack: &mut Stack,
        call: &Call,
        input: PipelineData,
    ) -> Result<nu_protocol::PipelineData, ShellError> {
        let config = engine_state.get_config();
        let metadata = input.metadata();
        let value = input.into_value(call.head);
        let headers = extract_headers(&value, config)?;
        let new_headers = replace_headers(value, &headers)?;

        Ok(new_headers.into_pipeline_data().set_metadata(metadata))
    }
}

fn replace_headers(value: Value, headers: &[String]) -> Result<Value, ShellError> {
    match value {
        Value::Record { vals, span, .. } => {
            let vals = vals.into_iter().take(headers.len()).collect();
            Ok(Value::Record {
                cols: headers.to_owned(),
                vals,
                span,
            })
        }
        Value::List { vals, span } => {
            let vals = vals
                .into_iter()
                .skip(1)
                .map(|value| replace_headers(value, headers))
                .collect::<Result<Vec<Value>, ShellError>>()?;

            Ok(Value::List { vals, span })
        }
        _ => Err(ShellError::TypeMismatch(
            "record".to_string(),
            value.span()?,
        )),
    }
}

fn extract_headers(value: &Value, config: &Config) -> Result<Vec<String>, ShellError> {
    match value {
        Value::Record { vals, .. } => Ok(vals
            .iter()
            .enumerate()
            .map(|(idx, value)| {
                let col = value.into_string("", config);
                if col.is_empty() {
                    format!("column{}", idx)
                } else {
                    col
                }
            })
            .collect::<Vec<String>>()),
        Value::List { vals, span } => vals
            .iter()
            .map(|value| extract_headers(value, config))
            .next()
            .ok_or_else(|| {
                ShellError::GenericError(
                    "Found empty list".to_string(),
                    "unable to extract headers".to_string(),
                    Some(*span),
                    None,
                    Vec::new(),
                )
            })?,
        _ => Err(ShellError::TypeMismatch(
            "record".to_string(),
            value.span()?,
        )),
    }
}

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

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

        test_examples(Headers {})
    }
}