fix: handle invalid working directories gracefully with --full-path (#1900)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- Add FatalError variant to WorkerResult for unrecoverable errors - Extract search_str_for_entry() helper to propagate IO errors from path_absolute_form - Propagate fatal errors through job and batch execution paths - Add regression test for invalid cwd scenario - Update CHANGELOG for #1900
authored by Rizky Mirzaviandy Priambodo · committed by Rizky Mirzaviandy Priambodo · parent 7027d45 · Browse files · 3 files·+89 added−19 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+89 added−19 removed
- other:+89 added−19 removed
Provenance
- Commit
d3a500a- Tree
d994b27- Author
Rizky Mirzaviandy Priambodo <142987522+Xavrir@users.noreply.github.com>- Committer
Rizky Mirzaviandy Priambodo <142987522+Xavrir@users.noreply.github.com>- Parent
7027d45
3 files changed+89 added−19 removed
modified:src/exec/job.rs+24 added-7 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+ }37 };38 39 // Generate a command, execute it and store its exit code.40 let code = cmd.execute(12 unmodified lines53 results: impl IntoIterator<Item = WorkerResult>,54 cmd: &CommandSet,55 config: &Config,56 ) -> ExitCode {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)),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)),62 WorkerResult::Error(err) => {63 if config.show_filesystem_errors {64 print_error(err.to_string());65 }59- None66 }61- });67+ WorkerResult::FatalError(err) => {68+ if config.show_filesystem_errors {69+ print_error(err.to_string());70+ }71+ return ExitCode::GeneralError;72+ }73+ }74+ }75 63- cmd.execute_batch(paths, config.batch_size, config.path_separator.as_deref())76+ cmd.execute_batch(77+ paths.into_iter(),78+ config.batch_size,79+ config.path_separator.as_deref(),80+ )81 }modified:src/walk.rs+64 added-12 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),46 }47 48 /// A batch of WorkerResults to send over a channel.49 #[derive(Clone)]179 unmodified lines229 if self.config.show_filesystem_errors {230 print_error(err.to_string());231 }232 }233+ WorkerResult::FatalError(err) => {234+ if self.config.show_filesystem_errors {235+ print_error(err.to_string());236+ }237+ return Err(ExitCode::GeneralError);238+ }239 }240 }241 242 // If we don't have another batch ready, flush before waiting287 unmodified lines530 531 // Check the name first, since it doesn't require metadata532 let entry_path = entry.path();533 527- let search_str: Cow<OsStr> = if config.search_full_path {528- let path_abs_buf = filesystem::path_absolute_form(entry_path)529- .expect("Retrieving absolute path succeeds");530- Cow::Owned(path_abs_buf.as_os_str().to_os_string())531- } else {532- match entry_path.file_name() {533- Some(filename) => Cow::Borrowed(filename),534- None => unreachable!(535- "Encountered file system entry without a file name. This should only \536- happen for paths like 'foo/bar/..' or '/' which are not supposed to \537- appear in a file system traversal."538- ),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+ };541+542+ return match tx.send(WorkerResult::FatalError(error)) {543+ Ok(_) => WalkState::Quit,544+ Err(_) => WalkState::Quit,545+ };546 }547 };548 549 if !patterns132 unmodified lines682 }683 }684 }685 686+fn search_str_for_entry<'a>(687+ 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()))693+ } else {694+ match entry_path.file_name() {695+ Some(filename) => Ok(Cow::Borrowed(filename)),696+ None => unreachable!(697+ "Encountered file system entry without a file name. This should only \698+ happen for paths like 'foo/bar/..' or '/' which are not supposed to \699+ appear in a file system traversal."700+ ),701+ }702+ }703+}704+705 /// Recursively scan the given search path for files / pathnames matching the patterns.706 ///707 /// If the `--exec` argument was supplied, this will create a thread pool for executing708 /// jobs in parallel from a given command line and the discovered paths. Otherwise, each709 /// path will simply be written to standard output.710 pub fn scan(paths: &[PathBuf], patterns: Vec<Regex>, config: Config) -> Result<ExitCode> {711 WorkerState::new(patterns, config).scan(paths)712 }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+}modified:CHANGELOG.md+1 added
1 # 10.4.22 3 ## Bugfixes4 - Fixed performance regression due to `--ignore-contain`; see #1913 and #19145+- Handle invalid working directories gracefully when using `--full-path`, see #1900 (@Xavrir).6 7 # 10.4.18 9 This is just a re-release of 10.4.0 due to an issue with the 10.4.0 release.841 unmodified lines