Skip to content
Myr

input.rs

This file

Path

src/exec/input.rs

234 lines · 5.9 KiB · Rust

Last changed by

Add TODOs and FIXMEs about WindowsJ.Wbefore adoption614f576

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;1112use shell_escape::escape;1314/// A builder for efficiently generating input strings.15///16/// After choosing your required specs, the `get()` method will escape special characters found17/// in the input. Allocations will only occur if special characters are found that need to be18/// escaped.19pub struct Input<'a> {20    data: &'a str,21}2223impl<'a> Input<'a> {24    /// Creates a new `Input` structure, which provides access to command-building25    /// primitives, such as `basename()` and `dirname()`.26    pub fn new(data: &'a str) -> Input<'a> {27        Input { data }28    }2930    /// Removes the parent component of the path31    pub fn basename(&'a mut self) -> &'a mut Self {32        let mut index = 0;33        for (id, character) in self.data.char_indices() {34            if character == MAIN_SEPARATOR {35                index = id;36            }37        }3839        // FIXME: On Windows, should return what for C:file.txt D:file.txt and \\server\share ?40        if index != 0 {41            self.data = &self.data[index + 1..]42        }4344        self45    }4647    /// Removes the extension from the path48    pub fn remove_extension(&'a mut self) -> &'a mut Self {49        let mut has_dir = false;50        let mut dir_index = 0;51        let mut ext_index = 0;5253        for (id, character) in self.data.char_indices() {54            if character == MAIN_SEPARATOR {55                has_dir = true;56                dir_index = id;57            }58            if character == '.' {59                ext_index = id;60            }61        }6263        // Account for hidden files and directories64        if ext_index != 0 && (!has_dir || dir_index + 2 <= ext_index) {65            self.data = &self.data[0..ext_index];66        }6768        self69    }7071    /// Removes the basename from the path.72    pub fn dirname(&'a mut self) -> &'a mut Self {73        let mut has_dir = false;74        let mut index = 0;75        for (id, character) in self.data.char_indices() {76            if character == MAIN_SEPARATOR {77                has_dir = true;78                index = id;79            }80        }8182        // FIXME: On Windows, return what for C:file.txt D:file.txt and \\server\share ?83        self.data = if !has_dir {84            "."85        } else if index == 0 {86            &self.data[..1]87        } else {88            &self.data[0..index]89        };9091        self92    }9394    pub fn get(&'a self) -> Cow<'a, str> {95        escape(Cow::Borrowed(self.data))96    }9798    #[cfg(test)]99    fn get_private(&'a self) -> Cow<'a, str> {100        Cow::Borrowed(self.data)101    }102}103104#[cfg(test)]105mod tests {106    use super::{MAIN_SEPARATOR, Input};107108    fn correct(input: &str) -> String {109        let mut sep = String::new();110        sep.push(MAIN_SEPARATOR);111        input.replace('/', &sep)112    }113114    #[test]115    fn path_remove_ext_simple() {116        assert_eq!(117            &Input::new("foo.txt").remove_extension().get_private(),118            "foo"119        );120    }121122    #[test]123    fn path_remove_ext_dir() {124        assert_eq!(125            &Input::new(&correct("dir/foo.txt"))126                .remove_extension()127                .get_private(),128            &correct("dir/foo")129        );130    }131132    #[test]133    fn path_hidden() {134        assert_eq!(&Input::new(".foo").remove_extension().get_private(), ".foo")135    }136137    #[test]138    fn path_remove_ext_utf8() {139        assert_eq!(140            &Input::new("💖.txt").remove_extension().get_private(),141            "💖"142        );143    }144145    #[test]146    fn path_remove_ext_empty() {147        assert_eq!(&Input::new("").remove_extension().get_private(), "");148    }149150    #[test]151    fn path_basename_simple() {152        assert_eq!(&Input::new("foo.txt").basename().get_private(), "foo.txt");153    }154155    #[test]156    fn path_basename_no_ext() {157        assert_eq!(158            &Input::new("foo.txt")159                .basename()160                .remove_extension()161                .get_private(),162            "foo"163        );164    }165166    #[test]167    fn path_basename_dir() {168        assert_eq!(169            &Input::new(&correct("dir/foo.txt")).basename().get_private(),170            "foo.txt"171        );172    }173174    #[test]175    fn path_basename_empty() {176        assert_eq!(&Input::new("").basename().get_private(), "");177    }178179    #[test]180    fn path_basename_utf8() {181        assert_eq!(182            &Input::new(&correct("💖/foo.txt"))183                .basename()184                .get_private(),185            "foo.txt"186        );187        assert_eq!(188            &Input::new(&correct("dir/💖.txt"))189                .basename()190                .get_private(),191            "💖.txt"192        );193    }194195    #[test]196    fn path_dirname_simple() {197        assert_eq!(&Input::new("foo.txt").dirname().get_private(), ".");198    }199200    #[test]201    fn path_dirname_dir() {202        assert_eq!(203            &Input::new(&correct("dir/foo.txt")).dirname().get_private(),204            "dir"205        );206    }207208    #[test]209    fn path_dirname_utf8() {210        assert_eq!(211            &Input::new(&correct("💖/foo.txt")).dirname().get_private(),212            "💖"213        );214        assert_eq!(215            &Input::new(&correct("dir/💖.txt")).dirname().get_private(),216            "dir"217        );218    }219220    #[test]221    fn path_dirname_empty() {222        assert_eq!(&Input::new("").dirname().get_private(), ".");223    }224225    #[test]226    fn path_dirname_root() {227        #[cfg(windows)]228        assert_eq!(&Input::new("C:\\").dirname().get_private(), "C:");229        #[cfg(windows)]230        assert_eq!(&Input::new("\\").dirname().get_private(), "\\");231        #[cfg(not(windows))]232        assert_eq!(&Input::new("/").dirname().get_private(), "/");233    }234}