Skip to content
Myr

mod.rs

This file

Path

src/fmt/mod.rs

281 lines · 9.9 KiB · Rust

Last changed by

Merge pull request #1813 from tmccombs/rust-versionThayne McCombsbefore adoptiond23ac06

History of this file

Take it

1mod input;23use std::borrow::Cow;4use std::ffi::{OsStr, OsString};5use std::fmt::{self, Display, Formatter};6use std::path::{Component, Path, Prefix};7use std::sync::OnceLock;89use aho_corasick::AhoCorasick;1011use self::input::{basename, dirname, remove_extension};1213/// Designates what should be written to a buffer14///15/// Each `Token` contains either text, or a placeholder variant, which will be used to generate16/// commands after all tokens for a given command template have been collected.17#[derive(Clone, Debug, PartialEq, Eq)]18pub enum Token {19    Placeholder,20    Basename,21    Parent,22    NoExt,23    BasenameNoExt,24    Text(String),25}2627impl Display for Token {28    fn fmt(&self, f: &mut Formatter) -> fmt::Result {29        match *self {30            Token::Placeholder => f.write_str("{}")?,31            Token::Basename => f.write_str("{/}")?,32            Token::Parent => f.write_str("{//}")?,33            Token::NoExt => f.write_str("{.}")?,34            Token::BasenameNoExt => f.write_str("{/.}")?,35            Token::Text(ref string) => f.write_str(string)?,36        }37        Ok(())38    }39}4041/// A parsed format string42///43/// This is either a collection of `Token`s including at least one placeholder variant,44/// or a fixed text.45#[derive(Clone, Debug, PartialEq)]46pub enum FormatTemplate {47    Tokens(Vec<Token>),48    Text(String),49}5051static PLACEHOLDERS: OnceLock<AhoCorasick> = OnceLock::new();5253impl FormatTemplate {54    pub fn has_tokens(&self) -> bool {55        matches!(self, FormatTemplate::Tokens(_))56    }5758    pub fn parse(fmt: &str) -> Self {59        // NOTE: we assume that { and } have the same length60        const BRACE_LEN: usize = '{'.len_utf8();61        let mut tokens = Vec::new();62        let mut remaining = fmt;63        let mut buf = String::new();64        let placeholders = PLACEHOLDERS.get_or_init(|| {65            AhoCorasick::new(["{{", "}}", "{}", "{/}", "{//}", "{.}", "{/.}"]).unwrap()66        });67        while let Some(m) = placeholders.find(remaining) {68            match m.pattern().as_u32() {69                0 | 1 => {70                    // we found an escaped {{ or }}, so add71                    // everything up to the first char to the buffer72                    // then skip the second one.73                    buf += &remaining[..m.start() + BRACE_LEN];74                    remaining = &remaining[m.end()..];75                }76                id if !remaining[m.end()..].starts_with('}') => {77                    buf += &remaining[..m.start()];78                    if !buf.is_empty() {79                        tokens.push(Token::Text(std::mem::take(&mut buf)));80                    }81                    tokens.push(token_from_pattern_id(id));82                    remaining = &remaining[m.end()..];83                }84                _ => {85                    // We got a normal pattern, but the final "}"86                    // is escaped, so add up to that to the buffer, then87                    // skip the final }88                    buf += &remaining[..m.end()];89                    remaining = &remaining[m.end() + BRACE_LEN..];90                }91            }92        }93        // Add the rest of the string to the buffer, and add the final buffer to the tokens94        if !remaining.is_empty() {95            buf += remaining;96        }97        if tokens.is_empty() {98            // No placeholders were found, so just return the text99            return FormatTemplate::Text(buf);100        }101        // Add final text segment102        if !buf.is_empty() {103            tokens.push(Token::Text(buf));104        }105        debug_assert!(!tokens.is_empty());106        FormatTemplate::Tokens(tokens)107    }108109    /// Generate a result string from this template. If path_separator is Some, then it will replace110    /// the path separator in all placeholder tokens. Fixed text and tokens are not affected by111    /// path separator substitution.112    pub fn generate(&self, path: impl AsRef<Path>, path_separator: Option<&str>) -> OsString {113        use Token::*;114        let path = path.as_ref();115116        match *self {117            Self::Tokens(ref tokens) => {118                let mut s = OsString::new();119                for token in tokens {120                    match token {121                        Basename => s.push(Self::replace_separator(basename(path), path_separator)),122                        BasenameNoExt => s.push(Self::replace_separator(123                            &remove_extension(basename(path).as_ref()),124                            path_separator,125                        )),126                        NoExt => s.push(Self::replace_separator(127                            &remove_extension(path),128                            path_separator,129                        )),130                        Parent => s.push(Self::replace_separator(&dirname(path), path_separator)),131                        Placeholder => {132                            s.push(Self::replace_separator(path.as_ref(), path_separator))133                        }134                        Text(string) => s.push(string),135                    }136                }137                s138            }139            Self::Text(ref text) => OsString::from(text),140        }141    }142143    /// Replace the path separator in the input with the custom separator string. If path_separator144    /// is None, simply return a borrowed Cow<OsStr> of the input. Otherwise, the input is145    /// interpreted as a Path and its components are iterated through and re-joined into a new146    /// OsString.147    fn replace_separator<'a>(path: &'a OsStr, path_separator: Option<&str>) -> Cow<'a, OsStr> {148        // fast-path - no replacement necessary149        if path_separator.is_none() {150            return Cow::Borrowed(path);151        }152153        let path_separator = path_separator.unwrap();154        let mut out = OsString::with_capacity(path.len());155        let mut components = Path::new(path).components().peekable();156157        while let Some(comp) = components.next() {158            match comp {159                // Absolute paths on Windows are tricky.  A Prefix component is usually a drive160                // letter or UNC path, and is usually followed by RootDir. There are also161                // "verbatim" prefixes beginning with "\\?\" that skip normalization. We choose to162                // ignore verbatim path prefixes here because they're very rare, might be163                // impossible to reach here, and there's no good way to deal with them. If users164                // are doing something advanced involving verbatim windows paths, they can do their165                // own output filtering with a tool like sed.166                Component::Prefix(prefix) => {167                    if let Prefix::UNC(server, share) = prefix.kind() {168                        // Prefix::UNC is a parsed version of '\\server\share'169                        out.push(path_separator);170                        out.push(path_separator);171                        out.push(server);172                        out.push(path_separator);173                        out.push(share);174                    } else {175                        // All other Windows prefix types are rendered as-is. This results in e.g. "C:" for176                        // drive letters. DeviceNS and Verbatim* prefixes won't have backslashes converted,177                        // but they're not returned by directories fd can search anyway so we don't worry178                        // about them.179                        out.push(comp.as_os_str());180                    }181                }182183                // Root directory is always replaced with the custom separator.184                Component::RootDir => out.push(path_separator),185186                // Everything else is joined normally, with a trailing separator if we're not last187                _ => {188                    out.push(comp.as_os_str());189                    if components.peek().is_some() {190                        out.push(path_separator);191                    }192                }193            }194        }195        Cow::Owned(out)196    }197}198199// Convert the id from an aho-corasick match to the200// appropriate token201fn token_from_pattern_id(id: u32) -> Token {202    use Token::*;203    match id {204        2 => Placeholder,205        3 => Basename,206        4 => Parent,207        5 => NoExt,208        6 => BasenameNoExt,209        _ => unreachable!(),210    }211}212213#[cfg(test)]214mod fmt_tests {215    use super::*;216    use std::path::PathBuf;217218    #[test]219    fn parse_no_placeholders() {220        let templ = FormatTemplate::parse("This string has no placeholders");221        assert_eq!(222            templ,223            FormatTemplate::Text("This string has no placeholders".into())224        );225    }226227    #[test]228    fn parse_only_brace_escapes() {229        let templ = FormatTemplate::parse("This string only has escapes like {{ and }}");230        assert_eq!(231            templ,232            FormatTemplate::Text("This string only has escapes like { and }".into())233        );234    }235236    #[test]237    fn all_placeholders() {238        use Token::*;239240        let templ = FormatTemplate::parse(241            "{{path={} \242            basename={/} \243            parent={//} \244            noExt={.} \245            basenameNoExt={/.} \246            }}",247        );248        assert_eq!(249            templ,250            FormatTemplate::Tokens(vec![251                Text("{path=".into()),252                Placeholder,253                Text(" basename=".into()),254                Basename,255                Text(" parent=".into()),256                Parent,257                Text(" noExt=".into()),258                NoExt,259                Text(" basenameNoExt=".into()),260                BasenameNoExt,261                Text(" }".into()),262            ])263        );264265        let mut path = PathBuf::new();266        path.push("a");267        path.push("folder");268        path.push("file.txt");269270        let expanded = templ.generate(&path, Some("/")).into_string().unwrap();271272        assert_eq!(273            expanded,274            "{path=a/folder/file.txt \275            basename=file.txt \276            parent=a/folder \277            noExt=a/folder/file \278            basenameNoExt=file }"279        );280    }281}