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
use crate::prelude::*;
use indexmap::indexmap;
use nu_engine::WholeStreamCommand;
use nu_errors::ShellError;
use nu_protocol::{ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value};
use nu_source::Tagged;

pub struct Rename;

impl WholeStreamCommand for Rename {
    fn name(&self) -> &str {
        "rename"
    }

    fn signature(&self) -> Signature {
        Signature::build("rename")
            .required(
                "column_name",
                SyntaxShape::String,
                "the new name for the first column",
            )
            .rest(
                "rest",
                SyntaxShape::String,
                "the new name for additional columns",
            )
    }

    fn usage(&self) -> &str {
        "Creates a new table with columns renamed."
    }

    fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> {
        rename(args)
    }

    fn examples(&self) -> Vec<Example> {
        vec![
            Example {
                description: "Rename a column",
                example: "echo [[a, b]; [1, 2]] | rename my_column",
                result: Some(vec![UntaggedValue::row(indexmap! {
                        "my_column".to_string() => UntaggedValue::int(1).into(),
                        "b".to_string() => UntaggedValue::int(2).into(),
                })
                .into()]),
            },
            Example {
                description: "Rename many columns",
                example: "echo [[a, b, c]; [1, 2, 3]] | rename eggs ham bacon",
                result: Some(vec![UntaggedValue::row(indexmap! {
                        "eggs".to_string() => UntaggedValue::int(1).into(),
                        "ham".to_string() => UntaggedValue::int(2).into(),
                        "bacon".to_string() => UntaggedValue::int(3).into(),
                })
                .into()]),
            },
        ]
    }
}

pub fn rename(args: CommandArgs) -> Result<ActionStream, ShellError> {
    let name = args.call_info.name_tag.clone();
    let column_name: Tagged<String> = args.req(0)?;
    let rest: Vec<Tagged<String>> = args.rest(1)?;
    let input = args.input;

    let mut new_column_names = vec![vec![column_name]];
    new_column_names.push(rest);

    let new_column_names = new_column_names.into_iter().flatten().collect::<Vec<_>>();

    Ok(input
        .map(move |item| {
            if let Value {
                value: UntaggedValue::Row(row),
                tag,
            } = item
            {
                let mut renamed_row = IndexMap::new();

                for (idx, (key, value)) in row.entries.iter().enumerate() {
                    let key = if idx < new_column_names.len() {
                        &new_column_names[idx].item
                    } else {
                        key
                    };

                    renamed_row.insert(key.clone(), value.clone());
                }

                let out = UntaggedValue::Row(renamed_row.into()).into_value(tag);

                ReturnSuccess::value(out)
            } else {
                ReturnSuccess::value(
                    UntaggedValue::Error(ShellError::labeled_error(
                        "no column names available",
                        "can't rename",
                        &name,
                    ))
                    .into_untagged_value(),
                )
            }
        })
        .into_action_stream())
}

#[cfg(test)]
mod tests {
    use super::Rename;
    use super::ShellError;

    #[test]
    fn examples_work_as_expected() -> Result<(), ShellError> {
        use crate::examples::test as test_examples;

        test_examples(Rename {})
    }
}