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
use super::{handle_value, operate_column_paths, PathSubcommandArguments};
use crate::prelude::*;
use nu_engine::WholeStreamCommand;
use nu_errors::ShellError;
use nu_protocol::{ColumnPath, Signature, SyntaxShape, UntaggedValue, Value};
use std::path::Path;

pub struct PathSplit;

struct PathSplitArguments {
    rest: Vec<ColumnPath>,
}

impl PathSubcommandArguments for PathSplitArguments {
    fn get_column_paths(&self) -> &Vec<ColumnPath> {
        &self.rest
    }
}

impl WholeStreamCommand for PathSplit {
    fn name(&self) -> &str {
        "path split"
    }

    fn signature(&self) -> Signature {
        Signature::build("path split")
            .rest(SyntaxShape::ColumnPath, "Optionally operate by column path")
    }

    fn usage(&self) -> &str {
        "Split a path into parts by a separator."
    }

    fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
        let tag = args.call_info.name_tag.clone();
        let cmd_args = Arc::new(PathSplitArguments {
            rest: args.rest(0)?,
        });

        Ok(operate_split(args.input, &action, tag.span, cmd_args))
    }

    #[cfg(windows)]
    fn examples(&self) -> Vec<Example> {
        vec![
            Example {
                description: "Split a path into parts",
                example: r"echo 'C:\Users\viking\spam.txt' | path split",
                result: Some(vec![
                    Value::from(UntaggedValue::string("C:")),
                    Value::from(UntaggedValue::string(r"\")),
                    Value::from(UntaggedValue::string("Users")),
                    Value::from(UntaggedValue::string("viking")),
                    Value::from(UntaggedValue::string("spam.txt")),
                ]),
            },
            Example {
                description: "Split all paths under the 'name' column",
                example: r"ls | path split name",
                result: None,
            },
        ]
    }

    #[cfg(not(windows))]
    fn examples(&self) -> Vec<Example> {
        vec![
            Example {
                description: "Split a path into parts",
                example: r"echo '/home/viking/spam.txt' | path split",
                result: Some(vec![
                    Value::from(UntaggedValue::string("/")),
                    Value::from(UntaggedValue::string("home")),
                    Value::from(UntaggedValue::string("viking")),
                    Value::from(UntaggedValue::string("spam.txt")),
                ]),
            },
            Example {
                description: "Split all paths under the 'name' column",
                example: r"ls | path split name",
                result: None,
            },
        ]
    }
}

fn operate_split<F, T>(
    input: crate::InputStream,
    action: &'static F,
    span: Span,
    args: Arc<T>,
) -> OutputStream
where
    T: PathSubcommandArguments + Send + Sync + 'static,
    F: Fn(&Path, Tag, &T) -> Value + Send + Sync + 'static,
{
    if args.get_column_paths().is_empty() {
        // Do not wrap result into a table
        input
            .flat_map(move |v| {
                let split_result = handle_value(&action, &v, span, Arc::clone(&args));

                match split_result {
                    Ok(Value {
                        value: UntaggedValue::Table(parts),
                        ..
                    }) => parts.into_iter().into_output_stream(),
                    Err(e) => OutputStream::one(Value::error(e)),
                    _ => OutputStream::one(Value::error(ShellError::labeled_error(
                        "Internal Error",
                        "unexpected result from the split function",
                        span,
                    ))),
                }
            })
            .into_output_stream()
    } else {
        operate_column_paths(input, action, span, args)
    }
}

fn action(path: &Path, tag: Tag, _args: &PathSplitArguments) -> Value {
    let parts: Vec<Value> = path
        .components()
        .map(|comp| {
            let s = comp.as_os_str().to_string_lossy();
            UntaggedValue::string(s).into_value(&tag)
        })
        .collect();

    UntaggedValue::table(&parts).into_value(tag)
}

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

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

        test_examples(PathSplit {})
    }
}