Skip to content
Myr

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

6 files+108 added−45 removed

modified:doc/fd.1+5 added
378 unmodified lines
379.IP {.}380path without file extension381.IP {/.}382basename without file extension383.IP {{}384literal '{'385.RE386387If no placeholder is present, an implicit "{}" at the end is assumed.388389If you need to include the literal text of one of the placeholders, you can use "{{}" to390escape the first "{". For example "{{}}" expands to "{}", and "{{}{{}}}" expands to "{{}".391392Examples:393394 - find all *.zip files and unzip them:395
94 unmodified lines
modified:src/exec/mod.rs+28 added-43 removed
7 unmodified lines
8use std::io;9use std::iter;10use std::path::{Component, Path, PathBuf, Prefix};11use std::process::Stdio;12use std::sync::{Mutex, OnceLock};12use std::sync::Mutex;1314use anyhow::{bail, Result};15use argmax::Command;16use regex::Regex;1617use crate::exit_codes::{merge_exitcodes, ExitCode};1819use self::command::{execute_commands, handle_cmd_error};20use self::input::{basename, dirname, remove_extension};21pub use self::job::{batch, job};23use self::token::Token;22use self::token::{tokenize, Token};2324/// Execution mode of the command25#[derive(Debug, Clone, Copy, PartialEq, Eq)]26pub enum ExecutionMode {
201 unmodified lines
228 where229 I: IntoIterator<Item = S>,230 S: AsRef<str>,231 {233 static PLACEHOLDER_PATTERN: OnceLock<Regex> = OnceLock::new();234232 let mut args = Vec::new();233 let mut has_placeholder = false;234235 for arg in input {236 let arg = arg.as_ref();237241 let mut tokens = Vec::new();242 let mut start = 0;243244 let pattern =245 PLACEHOLDER_PATTERN.get_or_init(|| Regex::new(r"\{(/?\.?|//)\}").unwrap());246247 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 }252253 start = placeholder.end();254255 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 }263264 has_placeholder = true;265 }266267 // 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 }272273 if start < arg.len() {274 // Trailing text after last placeholder.275 tokens.push(Token::Text(arg[start..].to_owned()));276 }277278 args.push(ArgumentTemplate::Tokens(tokens));238 let tmpl = tokenize(arg);239 has_placeholder |= tmpl.has_tokens();240 args.push(tmpl);241 }242243 // 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 lines
382#[cfg(test)]383mod tests {384 use super::*;385386 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 }393394 #[test]395 fn tokens_with_placeholder() {396 assert_eq!(397 CommandSet::new(vec![vec![&"echo", &"${SHELL}:"]]).unwrap(),
74 unmodified lines
472 );473 }474475 #[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 }483484 #[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 }489490 #[test]491 fn tokens_multiple() {492 assert_eq!(493 CommandSet::new(vec![vec!["cp", "{}", "{/.}.ext"]]).unwrap(),494 CommandSet {
88 unmodified lines
modified:src/exec/token.rs+69 added
1use aho_corasick::AhoCorasick;2use std::fmt::{self, Display, Formatter};3use std::sync::OnceLock;45use super::ArgumentTemplate;67/// 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 lines
30 }31 Ok(())32 }33}3435static PLACEHOLDERS: OnceLock<AhoCorasick> = OnceLock::new();3637pub(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}8788fn 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 lines
806 '{}': 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 lines
837 '{}': 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 lines
modified:Cargo.lock+1 added
289 unmodified lines
290[[package]]291name = "fd-find"292version = "8.7.1"293dependencies = [294 "aho-corasick 1.0.1",295 "anyhow",296 "argmax",297 "chrono",298 "clap",
687 unmodified lines
modified:Cargo.toml+1 added