ignore: fix global gitignore bug that arises with absolute paths
Before adoption: this commit came in with the history the project adopted, so no landing records it.
The `ignore` crate currently handles two different kinds of "global" gitignore files: gitignores from `~/.gitconfig`'s `core.excludesFile` and gitignores passed in via `WalkBuilder::add_ignore` (corresponding to ripgrep's `--ignore-file` flag). In contrast to any other kind of gitignore file, these gitignore files should have their patterns interpreted relative to the current working directory. (Arguably there are other choices we could make here, e.g., based on the paths given. But the `ignore` infrastructure can't handle that, and it's not clearly correct to me.) Normally, a gitignore file has its patterns interpreted relative to where the gitignore file is. This relative interpretation matters for patterns like `/foo`, which are anchored to _some_ directory. Previously, we would generally get the global gitignores correct because it's most common to use ripgrep without providing a path. Thus, it searches the current working directory. In this case, no stripping of the paths is needed in order for the gitignore patterns to be applied directly. But if one provides an absolute path (or something else) to ripgrep to search, the paths aren't stripped correctly. Indeed, in the core, I had just given up and not provided a "root" path to these global gitignores. So it had no hope of getting this correct. We fix this assigning the CWD to the `Gitignore` values created from global gitignore files. This was a painful thing to do because we'd ideally: 1. Call `std::env::current_dir()` at most once for each traversal. 2. Provide a way to avoid the library calling `std::env::current_dir()` at all. (Since this is global process state and folks might want to set it to different values for $reasons.) The `ignore` crate's internals are a total mess. But I think I've addressed the above 2 points in a semver compatible manner. Fixes #3179
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+213 added−11 removed
- tests:+50 added−0 removed
- other:+163 added−11 removed
Provenance
- Commit
b610d1c- Tree
2b9c74f- Author
Andrew Gallant <jamslam@gmail.com>- Committer
Andrew Gallant <jamslam@gmail.com>- Parent
9ec0852
6 files changed+213 added−11 removed
modified:crates/core/flags/hiargs.rs+7 added-2 removed
43 unmodified lines44 column: bool,45 context: ContextMode,46 context_separator: ContextSeparator,47 crlf: bool,48+ cwd: PathBuf,49 dfa_size_limit: Option<usize>,50 encoding: EncodingMode,51 engine: EngineChoice,52 field_context_separator: FieldContextSeparator,209 unmodified lines262 column,263 context: low.context,264 context_separator: low.context_separator,265 crlf: low.crlf,266+ cwd: state.cwd,267 dfa_size_limit: low.dfa_size_limit,268 encoding: low.encoding,269 engine: low.engine,270 field_context_separator: low.field_context_separator,627 unmodified lines898 .git_global(!self.no_ignore_vcs && !self.no_ignore_global)899 .git_ignore(!self.no_ignore_vcs)900 .git_exclude(!self.no_ignore_vcs && !self.no_ignore_exclude)901 .require_git(!self.no_require_git)900- .ignore_case_insensitive(self.ignore_file_case_insensitive);902+ .ignore_case_insensitive(self.ignore_file_case_insensitive)903+ .current_dir(&self.cwd);904 if !self.no_ignore_dot {905 builder.add_custom_ignore_filename(".rgignore");906 }907 // When we want to sort paths lexicographically in ascending order,41 unmodified lines949 /// argument parsing.950 fn new() -> anyhow::Result<State> {951 use std::io::IsTerminal;952 953+ let cwd = current_dir()?;954+ log::debug!("read CWD from environment: {}", cwd.display());955 Ok(State {956 is_terminal_stdout: std::io::stdout().is_terminal(),957 stdin_consumed: false,953- cwd: current_dir()?,958+ cwd,959 })960 }961 }962 518 unmodified linesmodified:crates/ignore/src/dir.rs+57 added-4 removed
116 unmodified lines117 is_absolute_parent: bool,118 /// The absolute base path of this matcher. Populated only if parent119 /// directories are added.120 absolute_base: Option<Arc<PathBuf>>,121+ /// The directory that gitignores should be interpreted relative to.122+ ///123+ /// Usually this is the directory containing the gitignore file. But in124+ /// some cases, like for global gitignores or for gitignores specified125+ /// explicitly, this should generally be set to the current working126+ /// directory. This is only used for global gitignores or "explicit"127+ /// gitignores.128+ ///129+ /// When `None`, this means the CWD could not be determined or is unknown.130+ /// In this case, global gitignore files are ignored because they otherwise131+ /// cannot be matched correctly.132+ global_gitignores_relative_to: Option<PathBuf>,133 /// Explicit global ignore matchers specified by the caller.134 explicit_ignores: Arc<Vec<Gitignore>>,135 /// Ignore files used in addition to `.ignore`136 custom_ignore_filenames: Arc<Vec<OsString>>,193 unmodified lines330 types: self.0.types.clone(),331 parent: Some(self.clone()),332 is_absolute_parent: false,333 absolute_base: self.0.absolute_base.clone(),334+ global_gitignores_relative_to: self335+ .0336+ .global_gitignores_relative_to337+ .clone(),338 explicit_ignores: self.0.explicit_ignores.clone(),339 custom_ignore_filenames: self.0.custom_ignore_filenames.clone(),340 custom_ignore_matcher: custom_ig_matcher,341 ignore_matcher: ig_matcher,255 unmodified lines597 /// Explicit global ignore matchers.598 explicit_ignores: Vec<Gitignore>,599 /// Ignore files in addition to .ignore.600 custom_ignore_filenames: Vec<OsString>,601+ /// The directory that gitignores should be interpreted relative to.602+ ///603+ /// Usually this is the directory containing the gitignore file. But in604+ /// some cases, like for global gitignores or for gitignores specified605+ /// explicitly, this should generally be set to the current working606+ /// directory. This is only used for global gitignores or "explicit"607+ /// gitignores.608+ ///609+ /// When `None`, global gitignores are ignored.610+ global_gitignores_relative_to: Option<PathBuf>,611 /// Ignore config.612 opts: IgnoreOptions,613 }614 615 impl IgnoreBuilder {616 /// Create a new builder for an `Ignore` matcher.617 ///592- /// All relative file paths are resolved with respect to the current593- /// working directory.618+ /// It is likely a bug to use this without also calling `current_dir()`619+ /// outside of tests. This isn't made mandatory because this is an internal620+ /// abstraction and it's annoying to update tests.621 pub(crate) fn new() -> IgnoreBuilder {622 IgnoreBuilder {623 dir: Path::new("").to_path_buf(),624 overrides: Arc::new(Override::empty()),625 types: Arc::new(Types::empty()),626 explicit_ignores: vec![],627 custom_ignore_filenames: vec![],628+ global_gitignores_relative_to: None,629 opts: IgnoreOptions {630 hidden: true,631 ignore: true,632 parents: true,10 unmodified lines643 ///644 /// The matcher returned won't match anything until ignore rules from645 /// directories are added to it.646 pub(crate) fn build(&self) -> Ignore {647+ self.build_with_cwd(None)648+ }649+650+ /// Builds a new `Ignore` matcher using the given CWD directory.651+ ///652+ /// The matcher returned won't match anything until ignore rules from653+ /// directories are added to it.654+ pub(crate) fn build_with_cwd(&self, cwd: Option<PathBuf>) -> Ignore {655+ let global_gitignores_relative_to =656+ cwd.or_else(|| self.global_gitignores_relative_to.clone());657 let git_global_matcher = if !self.opts.git_global {658 Gitignore::empty()621- } else {622- let mut builder = GitignoreBuilder::new("");659+ } else if let Some(ref cwd) = global_gitignores_relative_to {660+ let mut builder = GitignoreBuilder::new(cwd);661 builder662 .case_insensitive(self.opts.ignore_case_insensitive)663 .unwrap();664 let (gi, err) = builder.build_global();665 if let Some(err) = err {666 log::debug!("{}", err);667 }668 gi669+ } else {670+ log::debug!(671+ "ignoring global gitignore file because CWD is not known"672+ );673+ Gitignore::empty()674 };675 676 Ignore(Arc::new(IgnoreInner {677 compiled: Arc::new(RwLock::new(HashMap::new())),2 unmodified lines680 types: self.types.clone(),681 parent: None,682 is_absolute_parent: true,683 absolute_base: None,684+ global_gitignores_relative_to,685 explicit_ignores: Arc::new(self.explicit_ignores.clone()),686 custom_ignore_filenames: Arc::new(687 self.custom_ignore_filenames.clone(),688 ),6 unmodified lines695 opts: self.opts,696 }))697 }698 699+ /// Set the current directory used for matching global gitignores.700+ pub(crate) fn current_dir(701+ &mut self,702+ cwd: impl Into<PathBuf>,703+ ) -> &mut IgnoreBuilder {704+ self.global_gitignores_relative_to = Some(cwd.into());705+ self706+ }707+708 /// Add an override matcher.709 ///710 /// By default, no override matcher is used.711 ///593 unmodified linesmodified:crates/ignore/src/gitignore.rs+4 added-1 removed
126 unmodified lines127 /// does not exist or does not specify `core.excludesFile`, then128 /// `$XDG_CONFIG_HOME/git/ignore` is read. If `$XDG_CONFIG_HOME` is not129 /// set or is empty, then `$HOME/.config/git/ignore` is used instead.130 pub fn global() -> (Gitignore, Option<Error>) {131- GitignoreBuilder::new("").build_global()131+ match std::env::current_dir() {132+ Ok(cwd) => GitignoreBuilder::new(cwd).build_global(),133+ Err(err) => (Gitignore::empty(), Some(err.into())),134+ }135 }136 137 /// Creates a new empty gitignore matcher that never matches anything.138 ///711 unmodified linesmodified:crates/ignore/src/walk.rs+93 added-4 removed
2 unmodified lines3 ffi::OsStr,4 fs::{self, FileType, Metadata},5 io,6 path::{Path, PathBuf},7- sync::Arc,7 sync::atomic::{AtomicBool, AtomicUsize, Ordering as AtomicOrdering},8+ sync::{Arc, OnceLock},9 };10 11 use {12 crossbeam_deque::{Stealer, Worker as Deque},478 unmodified lines491 sorter: Option<Sorter>,492 threads: usize,493 skip: Option<Arc<Handle>>,494 filter: Option<Filter>,495+ /// The directory that gitignores should be interpreted relative to.496+ ///497+ /// Usually this is the directory containing the gitignore file. But in498+ /// some cases, like for global gitignores or for gitignores specified499+ /// explicitly, this should generally be set to the current working500+ /// directory. This is only used for global gitignores or "explicit"501+ /// gitignores.502+ ///503+ /// When `None`, the CWD is fetched from `std::env::current_dir()`. If504+ /// that fails, then global gitignores are ignored (an error is logged).505+ global_gitignores_relative_to:506+ OnceLock<Result<PathBuf, Arc<std::io::Error>>>,507 }508 509 #[derive(Clone)]510 enum Sorter {12 unmodified lines523 .field("max_depth", &self.max_depth)524 .field("min_depth", &self.min_depth)525 .field("max_filesize", &self.max_filesize)526 .field("follow_links", &self.follow_links)527+ .field("same_file_system", &self.same_file_system)528+ .field("sorter", &"<...>")529 .field("threads", &self.threads)530 .field("skip", &self.skip)531+ .field("filter", &"<...>")532+ .field(533+ "global_gitignores_relative_to",534+ &self.global_gitignores_relative_to,535+ )536 .finish()537 }538 }539 16 unmodified lines556 sorter: None,557 threads: 0,558 skip: None,559 filter: None,560+ global_gitignores_relative_to: OnceLock::new(),561 }562 }563 564 /// Build a new `Walk` iterator.36 unmodified lines601 }602 })603 .collect::<Vec<_>>()604 .into_iter();585- let ig_root = self.ig_builder.build();605+ let ig_root = self606+ .get_or_set_current_dir()607+ .map(|cwd| self.ig_builder.build_with_cwd(Some(cwd.to_path_buf())))608+ .unwrap_or_else(|| self.ig_builder.build());609 Walk {610 its,611 it: None,612 ig_root: ig_root.clone(),9 unmodified lines622 /// Note that this *doesn't* return something that implements `Iterator`.623 /// Instead, the returned value must be run with a closure. e.g.,624 /// `builder.build_parallel().run(|| |path| { println!("{path:?}"); WalkState::Continue })`.625 pub fn build_parallel(&self) -> WalkParallel {626+ let ig_root = self627+ .get_or_set_current_dir()628+ .map(|cwd| self.ig_builder.build_with_cwd(Some(cwd.to_path_buf())))629+ .unwrap_or_else(|| self.ig_builder.build());630 WalkParallel {631 paths: self.paths.clone().into_iter(),605- ig_root: self.ig_builder.build(),632+ ig_root,633 max_depth: self.max_depth,634 min_depth: self.min_depth,635 max_filesize: self.max_filesize,636 follow_links: self.follow_links,68 unmodified lines705 /// Add a global ignore file to the matcher.706 ///707 /// This has lower precedence than all other sources of ignore rules.708 ///709+ /// # Errors710+ ///711 /// If there was a problem adding the ignore file, then an error is712 /// returned. Note that the error may indicate *partial* failure. For713 /// example, if an ignore file contains an invalid glob, all other globs714 /// are still applied.715+ ///716+ /// An error will also occur if this walker could not get the current717+ /// working directory (and `WalkBuilder::current_dir` isn't set).718 pub fn add_ignore<P: AsRef<Path>>(&mut self, path: P) -> Option<Error> {719+ let path = path.as_ref();720+ let Some(cwd) = self.get_or_set_current_dir() else {721+ let err = std::io::Error::other(format!(722+ "CWD is not known, ignoring global gitignore {}",723+ path.display()724+ ));725+ return Some(err.into());726+ };687- let mut builder = GitignoreBuilder::new("");727+ let mut builder = GitignoreBuilder::new(cwd);728 let mut errs = PartialErrorBuilder::default();729 errs.maybe_push(builder.add(path));730 match builder.build() {731 Ok(gi) => {244 unmodified lines976 {977 self.filter = Some(Filter(Arc::new(filter)));978 self979 }980+981+ /// Set the current working directory used for matching global gitignores.982+ ///983+ /// If this is not set, then this walker will attempt to discover the984+ /// correct path from the environment's current working directory. If985+ /// that fails, then global gitignore files will be ignored.986+ ///987+ /// Global gitignore files come from things like a user's git configuration988+ /// or from gitignore files added via [`WalkBuilder::add_ignore`].989+ pub fn current_dir(990+ &mut self,991+ cwd: impl Into<PathBuf>,992+ ) -> &mut WalkBuilder {993+ let cwd = cwd.into();994+ self.ig_builder.current_dir(cwd.clone());995+ if let Err(cwd) = self.global_gitignores_relative_to.set(Ok(cwd)) {996+ // OK because `Err` from `set` implies a value exists.997+ *self.global_gitignores_relative_to.get_mut().unwrap() = cwd;998+ }999+ self1000+ }1001+1002+ /// Gets the currently configured CWD on this walk builder.1003+ ///1004+ /// This is "lazy." That is, we only ask for the CWD from the environment1005+ /// if `WalkBuilder::current_dir` hasn't been called yet. And we ensure1006+ /// that we only do it once.1007+ fn get_or_set_current_dir(&self) -> Option<&Path> {1008+ let result = self.global_gitignores_relative_to.get_or_init(|| {1009+ let result = std::env::current_dir().map_err(Arc::new);1010+ match result {1011+ Ok(ref path) => {1012+ log::trace!(1013+ "automatically discovered CWD: {}",1014+ path.display()1015+ );1016+ }1017+ Err(ref err) => {1018+ log::debug!(1019+ "failed to find CWD \1020+ (global gitignores will be ignored): \1021+ {err}"1022+ );1023+ }1024+ }1025+ result1026+ });1027+ result.as_ref().ok().map(|path| &**path)1028+ }1029 }1030 1031 /// Walk is a recursive directory iterator over file paths in one or more1032 /// directories.1462 unmodified linesmodified:tests/regression.rs+50 added
1653 unmodified lines1654 eqnice!(cmd().args(&["--files", "."]).stdout(), "./.foo.txt\n");1655 eqnice!(cmd().args(&["--files", "./"]).stdout(), "./.foo.txt\n");1656 });1657 1658+// See: https://github.com/BurntSushi/ripgrep/issues/31791659+rgtest!(r3179_global_gitignore_cwd, |dir: Dir, mut cmd: TestCommand| {1660+ dir.create_dir("a/b/c");1661+ dir.create("a/b/c/haystack", "");1662+ dir.create(".test.gitignore", "/haystack");1663+1664+ // I'm not sure in which cases this can fail. If it1665+ // does and it's unavoidable, feel free to submit a1666+ // patch that skips this test when this canonicalization1667+ // fails.1668+ //1669+ // The reason we canonicalize here is strange, and it is1670+ // perhaps papering over a bug in ripgrep. But on macOS,1671+ // `TMPDIR` is set to `/var/blah/blah`. However, `/var`1672+ // is symlinked to `/private/var`. So the CWD detected by1673+ // the process is `/private/var`. So it turns out that the1674+ // CWD is not a proper prefix of `dir.path()` here. So we1675+ // cheat around this by forcing our path to be canonicalized1676+ // so it's `/private/var` everywhere.1677+ //1678+ // Arguably, ripgrep should still work here without1679+ // canonicalization. But it's not actually quite clear1680+ // to me how to do it. I *believe* the solution here is1681+ // that gitignore matching should be relative to the directory1682+ // path given to `WalkBuider::{add,new}`, and *not* to the1683+ // CWD. But this is a very big change to how `ignore` works1684+ // I think. At least conceptually. So that will need to be1685+ // something we do when we rewrite `ignore`. Sigh.1686+ //1687+ // ... but, on Windows, path canonicalization seems to1688+ // totally fuck things up, so skip it there. HEAVY sigh.1689+ let dir_path = if cfg!(windows) {1690+ dir.path().to_path_buf()1691+ } else {1692+ dir.path().canonicalize().unwrap()1693+ };1694+ let ignore_file_path = dir_path.join(".test.gitignore");1695+ cmd.current_dir("a/b/c")1696+ .arg("--files")1697+ .arg("--ignore-file")1698+ .arg(ignore_file_path.display().to_string())1699+ // This is a key part of the reproduction. When just providing `.`1700+ // to ignore's walker (as ripgrep does when a path to search isn't1701+ // provided), then everything works as one expects. Because there's1702+ // nothing to strip off of the paths being searched. But when one1703+ // provides an absolute path, the stripping didn't work.1704+ .arg(&dir_path)1705+ .assert_err();1706+});1707+1708 // See: https://github.com/BurntSushi/ripgrep/issues/31801709 rgtest!(r3180_look_around_panic, |dir: Dir, mut cmd: TestCommand| {1710 dir.create("haystack", " b b b b b b b b\nc\n");1711 8 unmodified linesmodified:CHANGELOG.md+2 added
48 unmodified lines49 * [BUG #3155](https://github.com/BurntSushi/ripgrep/issues/3155):50 Statically compile PCRE2 into macOS release artifacts on `aarch64`.51 * [BUG #3173](https://github.com/BurntSushi/ripgrep/issues/3173):52 Fix ancestor ignore filter bug when searching whitelisted hidden files.53+* [BUG #3179](https://github.com/BurntSushi/ripgrep/issues/3179):54+ Fix gitignore bug when searching absolute paths with global gitignores.55 * [BUG #3180](https://github.com/BurntSushi/ripgrep/issues/3180):56 Fix a panicking bug when using `-U/--multiline` and `-r/--replace`.57 58 Feature enhancements:1737 unmodified lines