Skip to content
Myr

Merge pull request #1139 from Uthar/master

Before adoption: this commit came in with the history the project adopted, so no landing records it.

add support for matching multiple patterns

authored by David Peter · committed by GitHub · parents 8dda499, 36e6022 · Browse files · 5 files+258 added−22 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+258 added−22 removed

  • tests:+197 added−0 removed
  • other:+61 added−22 removed

5 files+258 added−22 removed

modified:src/cli.rs+12 added
142 unmodified lines
143 exact filename, consider using '--glob'."144 )]145 pub fixed_strings: bool,146147 /// Additional search patterns that need to be matched148 #[arg(149 long = "and",150 value_name = "pattern",151 long_help = "Add additional required search patterns, all of which must be matched. Multiple \152 additional patterns can be specified. The patterns are regular expressions, \153 unless '--glob' or '--fixed-strings' is used.",154 hide_short_help = true,155 allow_hyphen_values = true156 )]157 pub exprs: Option<Vec<String>>,158159 /// Show absolute instead of relative paths160 #[arg(161 long,162 short = 'a',
640 unmodified lines
modified:src/main.rs+38 added-16 removed
19 unmodified lines
20use atty::Stream;21use clap::{CommandFactory, Parser};22use globset::GlobBuilder;23use lscolors::LsColors;24use regex::bytes::{RegexBuilder, RegexSetBuilder};24use regex::bytes::{Regex, RegexBuilder, RegexSetBuilder};2526use crate::cli::{ColorWhen, Opts};27use crate::config::Config;28use crate::exec::CommandSet;
51 unmodified lines
80 bail!("No valid search paths given.");81 }8283 ensure_search_pattern_is_not_a_path(&opts)?;84 let pattern_regex = build_pattern_regex(&opts)?;84 let pattern = &opts.pattern;85 let exprs = &opts.exprs;86 let empty = Vec::new();8786 let config = construct_config(opts, &pattern_regex)?;87 ensure_use_hidden_option_for_leading_dot_pattern(&config, &pattern_regex)?;88 let re = build_regex(pattern_regex, &config)?;89 walk::scan(&search_paths, Arc::new(re), Arc::new(config))88 let pattern_regexps = exprs89 .as_ref()90 .unwrap_or(&empty)91 .iter()92 .chain([pattern])93 .map(|pat| build_pattern_regex(pat, &opts))94 .collect::<Result<Vec<String>>>()?;9596 let config = construct_config(opts, &pattern_regexps)?;9798 ensure_use_hidden_option_for_leading_dot_pattern(&config, &pattern_regexps)?;99100 let regexps = pattern_regexps101 .into_iter()102 .map(|pat| build_regex(pat, &config))103 .collect::<Result<Vec<Regex>>>()?;104105 walk::scan(&search_paths, Arc::new(regexps), Arc::new(config))106}107108#[cfg(feature = "completions")]109#[cold]
50 unmodified lines
160 Ok(())161 }162}163148fn build_pattern_regex(opts: &Opts) -> Result<String> {149 let pattern = &opts.pattern;164fn build_pattern_regex(pattern: &str, opts: &Opts) -> Result<String> {165 Ok(if opts.glob && !pattern.is_empty() {166 let glob = GlobBuilder::new(pattern).literal_separator(true).build()?;167 glob.regex().to_owned()168 } else if opts.fixed_strings {
17 unmodified lines
186 _ => Ok(()),187 }188}189175fn construct_config(mut opts: Opts, pattern_regex: &str) -> Result<Config> {190fn construct_config(mut opts: Opts, pattern_regexps: &[String]) -> Result<Config> {191 // The search will be case-sensitive if the command line flag is set or177 // if the pattern has an uppercase character (smart case).178 let case_sensitive =179 !opts.ignore_case && (opts.case_sensitive || pattern_has_uppercase_char(pattern_regex));192 // if any of the patterns has an uppercase character (smart case).193 let case_sensitive = !opts.ignore_case194 && (opts.case_sensitive195 || pattern_regexps196 .iter()197 .any(|pat| pattern_has_uppercase_char(pat)));198199 let path_separator = opts200 .path_separator201 .take()
230 unmodified lines
432}433434fn ensure_use_hidden_option_for_leading_dot_pattern(435 config: &Config,418 pattern_regex: &str,436 pattern_regexps: &[String],437) -> Result<()> {420 if cfg!(unix) && config.ignore_hidden && pattern_matches_strings_with_leading_dot(pattern_regex)438 if cfg!(unix)439 && config.ignore_hidden440 && pattern_regexps441 .iter()442 .any(|pat| pattern_matches_strings_with_leading_dot(pat))443 {444 Err(anyhow!(423 "The pattern seems to only match files with a leading dot, but hidden files are \445 "The pattern(s) seems to only match files with a leading dot, but hidden files are \446 filtered by default. Consider adding -H/--hidden to search hidden files as well \425 or adjust your search pattern."447 or adjust your search pattern(s)."448 ))449 } else {450 Ok(())451 }
16 unmodified lines
modified:src/walk.rs+9 added-6 removed
45 unmodified lines
46pub const MAX_BUFFER_LENGTH: usize = 1000;47/// Default duration until output buffering switches to streaming.48pub const DEFAULT_MAX_BUFFER_TIME: Duration = Duration::from_millis(100);4950/// Recursively scan the given search path for files / pathnames matching the pattern.50/// Recursively scan the given search path for files / pathnames matching the patterns.51///52/// If the `--exec` argument was supplied, this will create a thread pool for executing53/// jobs in parallel from a given command line and the discovered paths. Otherwise, each54/// path will simply be written to standard output.55pub fn scan(paths: &[PathBuf], pattern: Arc<Regex>, config: Arc<Config>) -> Result<ExitCode> {55pub fn scan(paths: &[PathBuf], patterns: Arc<Vec<Regex>>, config: Arc<Config>) -> Result<ExitCode> {56 let first_path = &paths[0];5758 // Channel capacity was chosen empircally to perform similarly to an unbounded channel59 let (tx, rx) = bounded(0x4000 * config.threads);
92 unmodified lines
152 // Spawn the thread that receives all results through the channel.153 let receiver_thread = spawn_receiver(&config, &quit_flag, &interrupt_flag, rx);154155 // Spawn the sender threads.156 spawn_senders(&config, &quit_flag, pattern, parallel_walker, tx);156 spawn_senders(&config, &quit_flag, patterns, parallel_walker, tx);157158 // Wait for the receiver thread to print out all results.159 let exit_code = receiver_thread.join().unwrap();160
221 unmodified lines
382383fn spawn_senders(384 config: &Arc<Config>,385 quit_flag: &Arc<AtomicBool>,386 pattern: Arc<Regex>,386 patterns: Arc<Vec<Regex>>,387 parallel_walker: ignore::WalkParallel,388 tx: Sender<WorkerResult>,389) {390 parallel_walker.run(|| {391 let config = Arc::clone(config);392 let pattern = Arc::clone(&pattern);392 let patterns = Arc::clone(&patterns);393 let tx_thread = tx.clone();394 let quit_flag = Arc::clone(quit_flag);395396 Box::new(move |entry_o| {
61 unmodified lines
458 ),459 }460 };461462 if !pattern.is_match(&filesystem::osstr_to_bytes(search_str.as_ref())) {462 if !patterns463 .iter()464 .all(|pat| pat.is_match(&filesystem::osstr_to_bytes(search_str.as_ref())))465 {466 return ignore::WalkState::Continue;467 }468469 // Filter out unwanted extensions.
88 unmodified lines
modified:tests/tests.rs+197 added
74 unmodified lines
75 one/two/three/directory_foo/",76 );77}7879static AND_EXTRA_FILES: &[&str] = &[80 "a.foo",81 "one/b.foo",82 "one/two/c.foo",83 "one/two/C.Foo2",84 "one/two/three/baz-quux",85 "one/two/three/Baz-Quux2",86 "one/two/three/d.foo",87 "fdignored.foo",88 "gitignored.foo",89 ".hidden.foo",90 "A-B.jpg",91 "A-C.png",92 "B-A.png",93 "B-C.png",94 "C-A.jpg",95 "C-B.png",96 "e1 e2",97];9899/// AND test100#[test]101fn test_and_basic() {102 let te = TestEnv::new(DEFAULT_DIRS, AND_EXTRA_FILES);103104 te.assert_output(105 &["foo", "--and", "c"],106 "one/two/C.Foo2107 one/two/c.foo108 one/two/three/directory_foo/",109 );110111 te.assert_output(112 &["f", "--and", "[ad]", "--and", "[_]"],113 "one/two/three/directory_foo/",114 );115116 te.assert_output(117 &["f", "--and", "[ad]", "--and", "[.]"],118 "a.foo119 one/two/three/d.foo",120 );121122 te.assert_output(&["Foo", "--and", "C"], "one/two/C.Foo2");123124 te.assert_output(&["foo", "--and", "asdasdasdsadasd"], "");125}126127#[test]128fn test_and_empty_pattern() {129 let te = TestEnv::new(DEFAULT_DIRS, AND_EXTRA_FILES);130 te.assert_output(&["Foo", "--and", "2", "--and", ""], "one/two/C.Foo2");131}132133#[test]134fn test_and_bad_pattern() {135 let te = TestEnv::new(DEFAULT_DIRS, AND_EXTRA_FILES);136137 te.assert_failure(&["Foo", "--and", "2", "--and", "[", "--and", "C"]);138 te.assert_failure(&["Foo", "--and", "[", "--and", "2", "--and", "C"]);139 te.assert_failure(&["Foo", "--and", "2", "--and", "C", "--and", "["]);140 te.assert_failure(&["[", "--and", "2", "--and", "C", "--and", "Foo"]);141}142143#[test]144fn test_and_pattern_starts_with_dash() {145 let te = TestEnv::new(DEFAULT_DIRS, AND_EXTRA_FILES);146147 te.assert_output(148 &["baz", "--and", "quux"],149 "one/two/three/Baz-Quux2150 one/two/three/baz-quux",151 );152 te.assert_output(153 &["baz", "--and", "-"],154 "one/two/three/Baz-Quux2155 one/two/three/baz-quux",156 );157 te.assert_output(158 &["Quu", "--and", "x", "--and", "-"],159 "one/two/three/Baz-Quux2",160 );161}162163#[test]164fn test_and_plus_extension() {165 let te = TestEnv::new(DEFAULT_DIRS, AND_EXTRA_FILES);166167 te.assert_output(168 &[169 "A",170 "--and",171 "B",172 "--extension",173 "jpg",174 "--extension",175 "png",176 ],177 "A-B.jpg178 B-A.png",179 );180181 te.assert_output(182 &[183 "A",184 "--extension",185 "jpg",186 "--and",187 "B",188 "--extension",189 "png",190 ],191 "A-B.jpg192 B-A.png",193 );194}195196#[test]197fn test_and_plus_type() {198 let te = TestEnv::new(DEFAULT_DIRS, AND_EXTRA_FILES);199200 te.assert_output(201 &["c", "--type", "d", "--and", "foo"],202 "one/two/three/directory_foo/",203 );204205 te.assert_output(206 &["c", "--type", "f", "--and", "foo"],207 "one/two/C.Foo2208 one/two/c.foo",209 );210}211212#[test]213fn test_and_plus_glob() {214 let te = TestEnv::new(DEFAULT_DIRS, AND_EXTRA_FILES);215216 te.assert_output(&["*foo", "--glob", "--and", "c*"], "one/two/c.foo");217}218219#[test]220fn test_and_plus_fixed_strings() {221 let te = TestEnv::new(DEFAULT_DIRS, AND_EXTRA_FILES);222223 te.assert_output(224 &["foo", "--fixed-strings", "--and", "c", "--and", "."],225 "one/two/c.foo226 one/two/C.Foo2",227 );228229 te.assert_output(230 &["foo", "--fixed-strings", "--and", "[c]", "--and", "."],231 "",232 );233234 te.assert_output(235 &["Foo", "--fixed-strings", "--and", "C", "--and", "."],236 "one/two/C.Foo2",237 );238}239240#[test]241fn test_and_plus_ignore_case() {242 let te = TestEnv::new(DEFAULT_DIRS, AND_EXTRA_FILES);243244 te.assert_output(245 &["Foo", "--ignore-case", "--and", "C", "--and", "[.]"],246 "one/two/C.Foo2247 one/two/c.foo",248 );249}250251#[test]252fn test_and_plus_case_sensitive() {253 let te = TestEnv::new(DEFAULT_DIRS, AND_EXTRA_FILES);254255 te.assert_output(256 &["foo", "--case-sensitive", "--and", "c", "--and", "[.]"],257 "one/two/c.foo",258 );259}260261#[test]262fn test_and_plus_full_path() {263 let te = TestEnv::new(DEFAULT_DIRS, AND_EXTRA_FILES);264265 te.assert_output(266 &["three", "--full-path", "--and", "foo", "--and", "dir"],267 "one/two/three/directory_foo/",268 );269270 te.assert_output(271 &["three", "--full-path", "--and", "two", "--and", "dir"],272 "one/two/three/directory_foo/",273 );274}275276/// Test each pattern type with an empty pattern.277#[test]278fn test_empty_pattern() {279 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);
2138 unmodified lines
modified:CHANGELOG.md+2 added
1# Upcoming release23## Features45- New `--and <pattern>` option to add additional patterns that must also be matched. See #3156 and #1139 (@Uthar)7- Added `--changed-after` as alias for `--changed-within`, to have a name consistent with `--changed-before`.8910## Changes
660 unmodified lines