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

pub struct PathFilestem;

#[derive(Deserialize)]
struct PathFilestemArguments {
    prefix: Option<Tagged<String>>,
    suffix: Option<Tagged<String>>,
    replace: Option<Tagged<String>>,
    rest: Vec<ColumnPath>,
}

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

#[async_trait]
impl WholeStreamCommand for PathFilestem {
    fn name(&self) -> &str {
        "path filestem"
    }

    fn signature(&self) -> Signature {
        Signature::build("path filestem")
            .named(
                "replace",
                SyntaxShape::String,
                "Return original path with filestem replaced by this string",
                Some('r'),
            )
            .named(
                "prefix",
                SyntaxShape::String,
                "Strip this string from from the beginning of a file name",
                Some('p'),
            )
            .named(
                "suffix",
                SyntaxShape::String,
                "Strip this string from from the end of a file name",
                Some('s'),
            )
            .rest(SyntaxShape::ColumnPath, "Optionally operate by column path")
    }

    fn usage(&self) -> &str {
        "Gets the file stem of a path"
    }

    async fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
        let tag = args.call_info.name_tag.clone();
        let (
            PathFilestemArguments {
                prefix,
                suffix,
                replace,
                rest,
            },
            input,
        ) = args.process().await?;
        let args = Arc::new(PathFilestemArguments {
            prefix,
            suffix,
            replace,
            rest,
        });
        operate(input, &action, tag.span, args).await
    }

    #[cfg(windows)]
    fn examples(&self) -> Vec<Example> {
        vec![
            Example {
                description: "Get filestem of a path",
                example: "echo 'C:\\Users\\joe\\bacon_lettuce.egg' | path filestem",
                result: Some(vec![Value::from("bacon_lettuce")]),
            },
            Example {
                description: "Get filestem of a path, stripped of prefix and suffix",
                example: "echo 'C:\\Users\\joe\\bacon_lettuce.egg.gz' | path filestem -p bacon_ -s .egg.gz",
                result: Some(vec![Value::from("lettuce")]),
            },
            Example {
                description: "Replace the filestem that would be returned",
                example: "echo 'C:\\Users\\joe\\bacon_lettuce.egg.gz' | path filestem -p bacon_ -s .egg.gz -r spam",
                result: Some(vec![Value::from(UntaggedValue::filepath("C:\\Users\\joe\\bacon_spam.egg.gz"))]),
            },
        ]
    }

    #[cfg(not(windows))]
    fn examples(&self) -> Vec<Example> {
        vec![
            Example {
                description: "Get filestem of a path",
                example: "echo '/home/joe/bacon_lettuce.egg' | path filestem",
                result: Some(vec![Value::from("bacon_lettuce")]),
            },
            Example {
                description: "Get filestem of a path, stripped of prefix and suffix",
                example: "echo '/home/joe/bacon_lettuce.egg.gz' | path filestem -p bacon_ -s .egg.gz",
                result: Some(vec![Value::from("lettuce")]),
            },
            Example {
                description: "Replace the filestem that would be returned",
                example: "echo '/home/joe/bacon_lettuce.egg.gz' | path filestem -p bacon_ -s .egg.gz -r spam",
                result: Some(vec![Value::from(UntaggedValue::filepath("/home/joe/bacon_spam.egg.gz"))]),
            },
        ]
    }
}

fn action(path: &Path, args: &PathFilestemArguments) -> UntaggedValue {
    let basename = match path.file_name() {
        Some(name) => name.to_string_lossy().to_string(),
        None => "".to_string(),
    };

    let suffix = match args.suffix {
        Some(ref suf) => match basename.rmatch_indices(&suf.item).next() {
            Some((i, _)) => basename.split_at(i).1.to_string(),
            None => "".to_string(),
        },
        None => match path.extension() {
            // Prepend '.' since the extension returned comes without it
            Some(ext) => ".".to_string() + &ext.to_string_lossy().to_string(),
            None => "".to_string(),
        },
    };

    let prefix = match args.prefix {
        Some(ref pre) => match basename.matches(&pre.item).next() {
            Some(m) => basename.split_at(m.len()).0.to_string(),
            None => "".to_string(),
        },
        None => "".to_string(),
    };

    let basename_without_prefix = match basename.matches(&prefix).next() {
        Some(m) => basename.split_at(m.len()).1.to_string(),
        None => basename,
    };

    let stem = match basename_without_prefix.rmatch_indices(&suffix).next() {
        Some((i, _)) => basename_without_prefix.split_at(i).0.to_string(),
        None => basename_without_prefix,
    };

    match args.replace {
        Some(ref replace) => {
            let new_name = prefix + &replace.item + &suffix;
            UntaggedValue::filepath(path.with_file_name(&new_name))
        }
        None => UntaggedValue::string(stem),
    }
}

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

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

        test_examples(PathFilestem {})
    }
}