nu_command/filters/
headers.rs

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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
use nu_engine::command_prelude::*;
use nu_protocol::Config;

#[derive(Clone)]
pub struct Headers;

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

    fn signature(&self) -> Signature {
        Signature::build(self.name())
            .input_output_types(vec![
                (Type::table(), Type::table()),
                (
                    // Tables with missing values are List<Any>
                    Type::List(Box::new(Type::Any)),
                    Type::table(),
                ),
            ])
            .category(Category::Filters)
    }

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

    fn examples(&self) -> Vec<Example> {
        vec![
            Example {
                description: "Sets the column names for a table created by `split column`",
                example: r#""a b c|1 2 3" | split row "|" | split column " " | headers"#,
                result: Some(Value::test_list(vec![Value::test_record(record! {
                    "a" => Value::test_string("1"),
                    "b" => Value::test_string("2"),
                    "c" => Value::test_string("3"),
                })])),
            },
            Example {
                description: "Columns which don't have data in their first row are removed",
                example: r#""a b c|1 2 3|1 2 3 4" | split row "|" | split column " " | headers"#,
                result: Some(Value::test_list(vec![
                    Value::test_record(record! {
                        "a" => Value::test_string("1"),
                        "b" => Value::test_string("2"),
                        "c" => Value::test_string("3"),
                    }),
                    Value::test_record(record! {
                        "a" => Value::test_string("1"),
                        "b" => Value::test_string("2"),
                        "c" => Value::test_string("3"),
                    }),
                ])),
            },
        ]
    }

    fn run(
        &self,
        engine_state: &EngineState,
        _stack: &mut Stack,
        call: &Call,
        input: PipelineData,
    ) -> Result<PipelineData, ShellError> {
        let config = engine_state.get_config();
        let metadata = input.metadata();
        let span = input.span().unwrap_or(call.head);
        let value = input.into_value(span)?;
        let Value::List { vals: table, .. } = value else {
            return Err(ShellError::TypeMismatch {
                err_message: "not a table".to_string(),
                span,
            });
        };

        let (old_headers, new_headers) = extract_headers(&table, span, config)?;
        let value = replace_headers(table, span, &old_headers, &new_headers)?;

        Ok(value.into_pipeline_data_with_metadata(metadata))
    }
}

fn extract_headers(
    table: &[Value],
    span: Span,
    config: &Config,
) -> Result<(Vec<String>, Vec<String>), ShellError> {
    table
        .first()
        .ok_or_else(|| ShellError::GenericError {
            error: "Found empty list".into(),
            msg: "unable to extract headers".into(),
            span: Some(span),
            help: None,
            inner: vec![],
        })
        .and_then(Value::as_record)
        .and_then(|record| {
            for v in record.values() {
                if !is_valid_header(v) {
                    return Err(ShellError::TypeMismatch {
                        err_message: "needs compatible type: Null, String, Bool, Float, Int"
                            .to_string(),
                        span: v.span(),
                    });
                }
            }

            let old_headers = record.columns().cloned().collect();
            let new_headers = record
                .values()
                .enumerate()
                .map(|(idx, value)| {
                    let col = value.to_expanded_string("", config);
                    if col.is_empty() {
                        format!("column{idx}")
                    } else {
                        col
                    }
                })
                .collect();

            Ok((old_headers, new_headers))
        })
}

fn is_valid_header(value: &Value) -> bool {
    matches!(
        value,
        Value::Nothing { .. }
            | Value::String { val: _, .. }
            | Value::Bool { val: _, .. }
            | Value::Float { val: _, .. }
            | Value::Int { val: _, .. }
    )
}

fn replace_headers(
    rows: Vec<Value>,
    span: Span,
    old_headers: &[String],
    new_headers: &[String],
) -> Result<Value, ShellError> {
    rows.into_iter()
        .skip(1)
        .map(|value| {
            let span = value.span();
            if let Value::Record { val: record, .. } = value {
                Ok(Value::record(
                    record
                        .into_owned()
                        .into_iter()
                        .filter_map(|(col, val)| {
                            old_headers
                                .iter()
                                .position(|c| c == &col)
                                .map(|i| (new_headers[i].clone(), val))
                        })
                        .collect(),
                    span,
                ))
            } else {
                Err(ShellError::CantConvert {
                    to_type: "record".into(),
                    from_type: value.get_type().to_string(),
                    span,
                    help: None,
                })
            }
        })
        .collect::<Result<_, _>>()
        .map(|rows| Value::list(rows, span))
}

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

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

        test_examples(Headers {})
    }
}