Skip to content
Myr

input.rs

This file

Path

src/exec/input.rs

258 lines · 6.9 KiB · Rust

Last changed by

Relicense under MIT/Apache-2.0Antti Keränenbefore adoption701b8f2

History of this file

Take it

1// Copyright (c) 2017 fd developers2// Licensed under the Apache License, Version 2.03// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0>4// or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>,5// at your option. All files in the project carrying such6// notice may not be copied, modified, or distributed except7// according to those terms.89use std::path::MAIN_SEPARATOR;10use std::borrow::Cow;1112#[cfg(windows)]13const ESCAPE: char = '^';1415#[cfg(not(windows))]16const ESCAPE: char = '\\';1718/// A builder for efficiently generating input strings.19///20/// After choosing your required specs, the `get()` method will escape special characters found21/// in the input. Allocations will only occur if special characters are found that need to be22/// escaped.23pub struct Input<'a> {24    data: &'a str,25}2627impl<'a> Input<'a> {28    /// Creates a new `Input` structure, which provides access to command-building29    /// primitives, such as `basename()` and `dirname()`.30    pub fn new(data: &'a str) -> Input<'a> {31        Input { data }32    }3334    /// Removes the parent component of the path35    pub fn basename(&'a mut self) -> &'a mut Self {36        let mut index = 0;37        for (id, character) in self.data.char_indices() {38            if character == MAIN_SEPARATOR {39                index = id;40            }41        }4243        if index != 0 {44            self.data = &self.data[index + 1..]45        }4647        self48    }4950    /// Removes the extension from the path51    pub fn remove_extension(&'a mut self) -> &'a mut Self {52        let mut dir_index = 0;53        let mut ext_index = 0;5455        for (id, character) in self.data.char_indices() {56            if character == MAIN_SEPARATOR {57                dir_index = id;58            }59            if character == '.' {60                ext_index = id;61            }62        }6364        // Account for hidden files and directories65        if ext_index != 0 && dir_index + 2 <= ext_index {66            self.data = &self.data[0..ext_index];67        }6869        self70    }7172    /// Removes the basename from the path.73    pub fn dirname(&'a mut self) -> &'a mut Self {74        let mut index = 0;75        for (id, character) in self.data.char_indices() {76            if character == MAIN_SEPARATOR {77                index = id;78            }79        }8081        self.data = if index == 0 {82            "."83        } else {84            &self.data[0..index]85        };8687        self88    }8990    pub fn get(&'a self) -> Cow<'a, str> {91        fn char_is_quotable(x: char) -> bool {92            [93                ' ',94                '(',95                ')',96                '[',97                ']',98                '&',99                '$',100                '@',101                '{',102                '}',103                '<',104                '>',105                '|',106                ';',107                '"',108                '\'',109                '#',110                '*',111                '%',112                '?',113                '`',114            ].contains(&x)115        };116117        // If a quotable character is found, we will use that position for allocating.118        let pos = match self.data.find(char_is_quotable) {119            Some(pos) => pos,120            // Otherwise, we will return the contents of `data` without allocating.121            None => return Cow::Borrowed(self.data),122        };123124        // When building the input string, we will start by adding the characters that125        // we've already verified to be free of special characters.126        let mut owned = String::with_capacity(self.data.len());127        owned.push_str(&self.data[..pos]);128        owned.push(ESCAPE);129130        // This slice contains the data that is left to be scanned for special characters.131        // If multiple characters are found, this slice will be sliced and updated multiple times.132        let mut slice = &self.data[pos..];133134        // Repeatedly search for special characters until all special characters have been found,135        // appending and inserting the escape character each time, as well as updating our136        // starting position.137        while let Some(pos) = slice[1..].find(char_is_quotable) {138            owned.push_str(&slice[..pos + 1]);139            owned.push(ESCAPE);140            slice = &slice[pos + 1..];141        }142143        // Finally, we return our newly-allocated input string.144        owned.push_str(slice);145        Cow::Owned(owned)146    }147}148149#[cfg(test)]150mod tests {151    use super::{MAIN_SEPARATOR, Input};152153    fn correct(input: &str) -> String {154        let mut sep = String::new();155        sep.push(MAIN_SEPARATOR);156        input.replace('/', &sep)157    }158159    #[test]160    fn path_remove_ext_simple() {161        assert_eq!(&Input::new("foo.txt").remove_extension().get(), "foo");162    }163164    #[test]165    fn path_remove_ext_dir() {166        assert_eq!(167            &Input::new(&correct("dir/foo.txt")).remove_extension().get(),168            &correct("dir/foo")169        );170    }171172    #[test]173    fn path_hidden() {174        assert_eq!(&Input::new(".foo").remove_extension().get(), ".foo")175    }176177    #[test]178    fn path_remove_ext_utf8() {179        assert_eq!(&Input::new("💖.txt").remove_extension().get(), "💖");180    }181182    #[test]183    fn path_remove_ext_empty() {184        assert_eq!(&Input::new("").remove_extension().get(), "");185    }186187    #[test]188    fn path_basename_simple() {189        assert_eq!(&Input::new("foo.txt").basename().get(), "foo.txt");190    }191192    #[test]193    fn path_basename_dir() {194        assert_eq!(195            &Input::new(&correct("dir/foo.txt")).basename().get(),196            "foo.txt"197        );198    }199200    #[test]201    fn path_basename_empty() {202        assert_eq!(&Input::new("").basename().get(), "");203    }204205    #[test]206    fn path_basename_utf8() {207        assert_eq!(208            &Input::new(&correct("💖/foo.txt")).basename().get(),209            "foo.txt"210        );211        assert_eq!(212            &Input::new(&correct("dir/💖.txt")).basename().get(),213            "💖.txt"214        );215    }216217    #[test]218    fn path_dirname_simple() {219        assert_eq!(&Input::new("foo.txt").dirname().get(), ".");220    }221222    #[test]223    fn path_dirname_dir() {224        assert_eq!(&Input::new(&correct("dir/foo.txt")).dirname().get(), "dir");225    }226227    #[test]228    fn path_dirname_utf8() {229        assert_eq!(230            &Input::new(&correct("💖/foo.txt")).dirname().get(),231            "💖"232        );233        assert_eq!(&Input::new(&correct("dir/💖.txt")).dirname().get(), "dir");234    }235236    #[test]237    fn path_dirname_empty() {238        assert_eq!(&Input::new("").dirname().get(), ".");239    }240241    #[cfg(windows)]242    #[test]243    fn path_special_chars() {244        assert_eq!(245            &Input::new("A Directory\\And A File").get(),246            "A^ Directory\\And^ A^ File"247        );248    }249250    #[cfg(not(windows))]251    #[test]252    fn path_special_chars() {253        assert_eq!(254            &Input::new("A Directory/And A File").get(),255            "A\\ Directory/And\\ A\\ File"256        );257    }258}