feat: Add a way to escape { and }in exec templates.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
fixes #1303
authored by Thayne McCombs · committed by David Peter · parent a11f842 · Browse files · 6 files·+108 added−45 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+108 added−45 removed
- other:+108 added−45 removed
Provenance
- Commit
d9b69c8- Tree
600c0c8- Author
Thayne McCombs <astrothayne@gmail.com>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
a11f842
6 files changed+108 added−45 removed
modified:doc/fd.1+5 added
378 unmodified lines379 .IP {.}380 path without file extension381 .IP {/.}382 basename without file extension383+.IP {{}384+literal '{'385 .RE386 387 If no placeholder is present, an implicit "{}" at the end is assumed.388 389+If you need to include the literal text of one of the placeholders, you can use "{{}" to390+escape the first "{". For example "{{}}" expands to "{}", and "{{}{{}}}" expands to "{{}".391+392 Examples:393 394 - find all *.zip files and unzip them:395 94 unmodified linesmodified:src/exec/mod.rs+28 added-43 removed
7 unmodified lines8 use std::io;9 use std::iter;10 use std::path::{Component, Path, PathBuf, Prefix};11 use std::process::Stdio;12-use std::sync::{Mutex, OnceLock};12+use std::sync::Mutex;13 14 use anyhow::{bail, Result};15 use argmax::Command;16-use regex::Regex;16 17 use crate::exit_codes::{merge_exitcodes, ExitCode};18 19 use self::command::{execute_commands, handle_cmd_error};20 use self::input::{basename, dirname, remove_extension};21 pub use self::job::{batch, job};23-use self::token::Token;22+use self::token::{tokenize, Token};23 24 /// Execution mode of the command25 #[derive(Debug, Clone, Copy, PartialEq, Eq)]26 pub enum ExecutionMode {201 unmodified lines228 where229 I: IntoIterator<Item = S>,230 S: AsRef<str>,231 {233- static PLACEHOLDER_PATTERN: OnceLock<Regex> = OnceLock::new();234-232 let mut args = Vec::new();233 let mut has_placeholder = false;234 235 for arg in input {236 let arg = arg.as_ref();237 241- let mut tokens = Vec::new();242- let mut start = 0;243-244- let pattern =245- PLACEHOLDER_PATTERN.get_or_init(|| Regex::new(r"\{(/?\.?|//)\}").unwrap());246-247- for placeholder in pattern.find_iter(arg) {248- // Leading text before the placeholder.249- if placeholder.start() > start {250- tokens.push(Token::Text(arg[start..placeholder.start()].to_owned()));251- }252-253- start = placeholder.end();254-255- match placeholder.as_str() {256- "{}" => tokens.push(Token::Placeholder),257- "{.}" => tokens.push(Token::NoExt),258- "{/}" => tokens.push(Token::Basename),259- "{//}" => tokens.push(Token::Parent),260- "{/.}" => tokens.push(Token::BasenameNoExt),261- _ => unreachable!("Unhandled placeholder"),262- }263-264- has_placeholder = true;265- }266-267- // Without a placeholder, the argument is just fixed text.268- if tokens.is_empty() {269- args.push(ArgumentTemplate::Text(arg.to_owned()));270- continue;271- }272-273- if start < arg.len() {274- // Trailing text after last placeholder.275- tokens.push(Token::Text(arg[start..].to_owned()));276- }277-278- args.push(ArgumentTemplate::Tokens(tokens));238+ let tmpl = tokenize(arg);239+ has_placeholder |= tmpl.has_tokens();240+ args.push(tmpl);241 }242 243 // We need to check that we have at least one argument, because if not244 // it will try to execute each file and directory it finds.137 unmodified lines382 #[cfg(test)]383 mod tests {384 use super::*;385 386+ fn generate_str(template: &CommandTemplate, input: &str) -> Vec<String> {387+ template388+ .args389+ .iter()390+ .map(|arg| arg.generate(input, None).into_string().unwrap())391+ .collect()392+ }393+394 #[test]395 fn tokens_with_placeholder() {396 assert_eq!(397 CommandSet::new(vec![vec![&"echo", &"${SHELL}:"]]).unwrap(),74 unmodified lines472 );473 }474 475 #[test]476+ fn tokens_with_literal_braces() {477+ let template = CommandTemplate::new(vec!["{{}}", "{{", "{.}}"]).unwrap();478+ assert_eq!(479+ generate_str(&template, "foo"),480+ vec!["{}", "{", "{.}", "foo"]481+ );482+ }483+484+ #[test]485+ fn tokens_with_literal_braces_and_placeholder() {486+ let template = CommandTemplate::new(vec!["{{{},end}"]).unwrap();487+ assert_eq!(generate_str(&template, "foo"), vec!["{foo,end}"]);488+ }489+490+ #[test]491 fn tokens_multiple() {492 assert_eq!(493 CommandSet::new(vec![vec!["cp", "{}", "{/.}.ext"]]).unwrap(),494 CommandSet {88 unmodified linesmodified:src/exec/token.rs+69 added
1+use aho_corasick::AhoCorasick;2 use std::fmt::{self, Display, Formatter};3+use std::sync::OnceLock;4 5+use super::ArgumentTemplate;6+7 /// Designates what should be written to a buffer8 ///9 /// Each `Token` contains either text, or a placeholder variant, which will be used to generate10 /// commands after all tokens for a given command template have been collected.19 unmodified lines30 }31 Ok(())32 }33 }34+35+static PLACEHOLDERS: OnceLock<AhoCorasick> = OnceLock::new();36+37+pub(super) fn tokenize(input: &str) -> ArgumentTemplate {38+ // NOTE: we assume that { and } have the same length39+ const BRACE_LEN: usize = '{'.len_utf8();40+ let mut tokens = Vec::new();41+ let mut remaining = input;42+ let mut buf = String::new();43+ let placeholders = PLACEHOLDERS.get_or_init(|| {44+ AhoCorasick::new(&["{{", "}}", "{}", "{/}", "{//}", "{.}", "{/.}"]).unwrap()45+ });46+ while let Some(m) = placeholders.find(remaining) {47+ match m.pattern().as_u32() {48+ 0 | 1 => {49+ // we found an escaped {{ or }}, so add50+ // everything up to the first char to the buffer51+ // then skipp the second one.52+ buf += &remaining[..m.start() + BRACE_LEN];53+ remaining = &remaining[m.end()..];54+ }55+ id if !remaining[m.end()..].starts_with('}') => {56+ buf += &remaining[..m.start()];57+ if !buf.is_empty() {58+ tokens.push(Token::Text(std::mem::take(&mut buf)));59+ }60+ tokens.push(token_from_pattern_id(id));61+ remaining = &remaining[m.end()..];62+ }63+ _ => {64+ // We got a normal pattern, but the final "}"65+ // is escaped, so add up to that to the buffer, then66+ // skip the final }67+ buf += &remaining[..m.end()];68+ remaining = &remaining[m.end() + BRACE_LEN..];69+ }70+ }71+ }72+ // Add the rest of the string to the buffer, and add the final buffer to the tokens73+ if !remaining.is_empty() {74+ buf += remaining;75+ }76+ if tokens.is_empty() {77+ // No placeholders were found, so just return the text78+ return ArgumentTemplate::Text(buf);79+ }80+ // Add final text segment81+ if !buf.is_empty() {82+ tokens.push(Token::Text(buf));83+ }84+ debug_assert!(!tokens.is_empty());85+ ArgumentTemplate::Tokens(tokens)86+}87+88+fn token_from_pattern_id(id: u32) -> Token {89+ use Token::*;90+ match id {91+ 2 => Placeholder,92+ 3 => Basename,93+ 4 => Parent,94+ 5 => NoExt,95+ 6 => BasenameNoExt,96+ _ => unreachable!(),97+ }98+}modified:src/cli.rs+4 added-2 removed
805 unmodified lines806 '{}': path (of the current search result)\n \807 '{/}': basename\n \808 '{//}': parent directory\n \809 '{.}': path without file extension\n \810- '{/.}': basename without file extension\n\n\810+ '{/.}': basename without file extension\n \811+ '{{}': literal '{' (for escaping)\n\n\812 If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\813 Examples:\n\n \814 - find all *.zip files and unzip them:\n\n \815 fd -e zip -x unzip\n\n \21 unmodified lines837 '{}': path (of all search results)\n \838 '{/}': basename\n \839 '{//}': parent directory\n \840 '{.}': path without file extension\n \840- '{/.}': basename without file extension\n\n\841+ '{/.}': basename without file extension\n \842+ '{{}': literal '{' (for escaping)\n\n\843 If no placeholder is present, an implicit \"{}\" at the end is assumed.\n\n\844 Examples:\n\n \845 - Find all test_*.py files and open them in your favorite editor:\n\n \846 fd -g 'test_*.py' -X vim\n\n \25 unmodified linesmodified:Cargo.lock+1 added
289 unmodified lines290 [[package]]291 name = "fd-find"292 version = "8.7.1"293 dependencies = [294+ "aho-corasick 1.0.1",295 "anyhow",296 "argmax",297 "chrono",298 "clap",687 unmodified linesmodified:Cargo.toml+1 added
32 unmodified lines33343536373839404155 unmodified lines32 unmodified lines[build-dependencies]version_check = "0.9"
[dependencies]aho-corasick = "1.0"nu-ansi-term = "0.49"argmax = "0.3.1"ignore = "0.4.20"num_cpus = "1.16"55 unmodified lines