refactor: cache cwd at startup instead of per-entry resolution
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Instead of calling current_dir() for every entry when --full-path is set, cache it once in Config at startup. This eliminates the need for FatalError handling and makes path resolution infallible during the walk. If the cwd can't be retrieved, fd now fails early with a clear error message.
authored by Rizky Mirzaviandy Priambodo · committed by Rizky Mirzaviandy Priambodo · parent 24f7f2b · Browse files · 5 files·+74 added−81 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+74 added−81 removed
- other:+74 added−81 removed
Provenance
- Commit
26756f2- Tree
016184c- Author
Rizky Mirzaviandy Priambodo <142987522+Xavrir@users.noreply.github.com>- Committer
Rizky Mirzaviandy Priambodo <142987522+Xavrir@users.noreply.github.com>- Parent
24f7f2b
5 files changed+74 added−81 removed
modified:src/exec/job.rs+7 added-24 removed
26 unmodified lines27 print_error(err.to_string());28 }29 continue;30 }31- WorkerResult::FatalError(err) => {32- if config.show_filesystem_errors {33- print_error(err.to_string());34- }35- return ExitCode::GeneralError;36- }31 };32 33 // Generate a command, execute it and store its exit code.34 let code = cmd.execute(12 unmodified lines47 results: impl IntoIterator<Item = WorkerResult>,48 cmd: &CommandSet,49 config: &Config,50 ) -> ExitCode {57- let mut paths = Vec::new();58-59- for worker_result in results {60- match worker_result {61- WorkerResult::Entry(dir_entry) => paths.push(dir_entry.into_stripped_path(config)),51+ let paths = results52+ .into_iter()53+ .filter_map(|worker_result| match worker_result {54+ WorkerResult::Entry(dir_entry) => Some(dir_entry.into_stripped_path(config)),55 WorkerResult::Error(err) => {56 if config.show_filesystem_errors {57 print_error(err.to_string());58 }59+ None60 }67- WorkerResult::FatalError(err) => {68- if config.show_filesystem_errors {69- print_error(err.to_string());70- }71- return ExitCode::GeneralError;72- }73- }74- }61+ });62 76- cmd.execute_batch(77- paths.into_iter(),78- config.batch_size,79- config.path_separator.as_deref(),80- )63+ cmd.execute_batch(paths, config.batch_size, config.path_separator.as_deref())64 }modified:src/config.rs+3 added-3 removed
13 unmodified lines14 pub struct Config {15 /// Whether the search is case-sensitive or case-insensitive.16 pub case_sensitive: bool,17 18- /// Whether to search within the full file path or just the base name (filename or directory19- /// name).20- pub search_full_path: bool,18+ /// Cached current working directory for absolute path construction.19+ /// Populated when `--full-path` is set; `None` means search by filename only.20+ pub cwd: Option<PathBuf>,21 22 /// Whether to ignore hidden files and directories (or not).23 pub ignore_hidden: bool,24 119 unmodified linesmodified:src/filesystem.rs+47 added
18 unmodified lines19 let path = path.strip_prefix(".").unwrap_or(path);20 env::current_dir().map(|path_buf| path_buf.join(path))21 }22 23+/// Construct an absolute path from a potentially relative path and a24+/// pre-resolved working directory. Unlike `path_absolute_form`, this25+/// does not call `env::current_dir()` and cannot fail.26+pub fn make_absolute(path: &Path, cwd: &Path) -> PathBuf {27+ if path.is_absolute() {28+ return path.to_path_buf();29+ }30+ let path = path.strip_prefix(".").unwrap_or(path);31+ cwd.join(path)32+}33+34 pub fn absolute_path(path: &Path) -> io::Result<PathBuf> {35 let path_buf = path_absolute_form(path)?;36 37 #[cfg(windows)]125 unmodified lines163 strip_current_dir(Path::new("foo/bar/baz")),164 Path::new("foo/bar/baz")165 );166 }167+168+ #[test]169+ fn make_absolute_with_relative_path() {170+ use super::make_absolute;171+ use std::path::PathBuf;172+173+ let cwd = Path::new("/home/user");174+ assert_eq!(175+ make_absolute(Path::new("foo/bar"), cwd),176+ PathBuf::from("/home/user/foo/bar")177+ );178+ }179+180+ #[test]181+ fn make_absolute_strips_dot_prefix() {182+ use super::make_absolute;183+ use std::path::PathBuf;184+185+ let cwd = Path::new("/home/user");186+ assert_eq!(187+ make_absolute(Path::new("./foo/bar"), cwd),188+ PathBuf::from("/home/user/foo/bar")189+ );190+ }191+192+ #[test]193+ fn make_absolute_with_absolute_path() {194+ use super::make_absolute;195+ use std::path::PathBuf;196+197+ let cwd = Path::new("/home/user");198+ assert_eq!(199+ make_absolute(Path::new("/absolute/path"), cwd),200+ PathBuf::from("/absolute/path")201+ );202+ }203 }modified:src/main.rs+10 added-1 removed
243 unmodified lines244 };245 let command = extract_command(&mut opts, colored_output)?;246 let has_command = command.is_some();247 248+ let cwd = if opts.full_path {249+ Some(env::current_dir().context(250+ "Could not determine current directory. \251+ This is required for --full-path.",252+ )?)253+ } else {254+ None255+ };256+257 Ok(Config {258 case_sensitive,250- search_full_path: opts.full_path,259+ cwd,260 ignore_hidden: !(opts.hidden || opts.rg_alias_ignore()),261 read_fdignore: !(opts.no_ignore || opts.rg_alias_ignore()),262 read_vcsignore: !(opts.no_ignore || opts.rg_alias_ignore() || opts.no_ignore_vcs),263 require_git_to_read_vcsignore: !opts.no_require_git,238 unmodified linesmodified:src/walk.rs+7 added-53 removed
40 unmodified lines41 // Errors should be rare, so it's probably better to allow large_enum_variant than42 // to box the Entry variant43 Entry(DirEntry),44 Error(ignore::Error),45- FatalError(ignore::Error),45 }46 47 /// A batch of WorkerResults to send over a channel.48 #[derive(Clone)]179 unmodified lines228 if self.config.show_filesystem_errors {229 print_error(err.to_string());230 }231 }233- WorkerResult::FatalError(err) => {234- if self.config.show_filesystem_errors {235- print_error(err.to_string());236- }237- return Err(ExitCode::GeneralError);238- }232 }233 }234 235 // If we don't have another batch ready, flush before waiting287 unmodified lines523 524 // Check the name first, since it doesn't require metadata525 let entry_path = entry.path();526 534- let search_str = match search_str_for_entry(entry_path, config.search_full_path) {535- Ok(search_str) => search_str,536- Err(err) => {537- let error = ignore::Error::WithPath {538- path: entry_path.to_path_buf(),539- err: Box::new(ignore::Error::Io(err)),540- };527+ let search_str = search_str_for_entry(entry_path, config.cwd.as_deref());528 542- return match tx.send(WorkerResult::FatalError(error)) {543- Ok(_) => WalkState::Quit,544- Err(_) => WalkState::Quit,545- };546- }547- };548-529 if !patterns530 .iter()531 .all(|pat| pat.is_match(&filesystem::osstr_to_bytes(search_str.as_ref())))532 {131 unmodified lines664 }665 666 fn search_str_for_entry<'a>(667 entry_path: &'a std::path::Path,688- search_full_path: bool,689-) -> io::Result<Cow<'a, OsStr>> {690- if search_full_path {691- let path_abs_buf = filesystem::path_absolute_form(entry_path)?;692- Ok(Cow::Owned(path_abs_buf.as_os_str().to_os_string()))668+ cwd: Option<&std::path::Path>,669+) -> Cow<'a, OsStr> {670+ if let Some(cwd) = cwd {671+ let abs_path = filesystem::make_absolute(entry_path, cwd);672+ Cow::Owned(abs_path.as_os_str().to_os_string())673 } else {674 match entry_path.file_name() {695- Some(filename) => Ok(Cow::Borrowed(filename)),675+ Some(filename) => Cow::Borrowed(filename),676 None => unreachable!(677 "Encountered file system entry without a file name. This should only \678 happen for paths like 'foo/bar/..' or '/' which are not supposed to \679 appear in a file system traversal."9 unmodified lines689 /// path will simply be written to standard output.690 pub fn scan(paths: &[PathBuf], patterns: Vec<Regex>, config: Config) -> Result<ExitCode> {691 WorkerState::new(patterns, config).scan(paths)692 }713-714-#[cfg(test)]715-mod tests {716- use super::search_str_for_entry;717- use std::env;718- use std::fs;719- use std::path::Path;720-721- #[test]722- #[cfg(all(not(windows), not(target_os = "illumos")))]723- fn full_path_search_returns_error_for_invalid_cwd() {724- let original_dir = env::current_dir().unwrap();725- let temp_dir = tempfile::tempdir().unwrap();726- let cwd = temp_dir.path().join("cwd");727-728- fs::create_dir(&cwd).unwrap();729- env::set_current_dir(&cwd).unwrap();730- fs::remove_dir(&cwd).unwrap();731-732- let result = search_str_for_entry(Path::new("relative/path"), true);733-734- env::set_current_dir(original_dir).unwrap();735-736- assert!(result.is_err());737- }738-}