diff --git a/src/searcher.rs b/src/searcher.rs index 64c4c40..1f3aae7 100644 --- a/src/searcher.rs +++ b/src/searcher.rs @@ -156,6 +156,7 @@ impl<'a> Searcher<'a> { start: &Path, strip_root: bool, ) -> ControlFlow<()> { + let start = Self::trim_trailing_slashes(start); let mut walker = WalkDir::new(start) .follow_links(self.config.follow_symlinks) .into_iter(); @@ -723,6 +724,22 @@ impl<'a> Searcher<'a> { Path::new(unsafe { OsStr::from_encoded_bytes_unchecked(bytes) }) } + /// Reduce a run of trailing slashes on a directory operand to a single + /// slash, as GNU grep does, so `tree//` walks as `tree/sub/...` rather + /// than `tree//sub/...`. Slashes inside the operand are left alone, and + /// so is an operand made only of slashes. + fn trim_trailing_slashes(path: &Path) -> &Path { + let bytes = path.as_os_str().as_encoded_bytes(); + let keep = match bytes.iter().rposition(|&b| b != b'/') { + // Keep the last non-slash byte plus at most one slash after it. + Some(last) => bytes.len().min(last + 2), + None => bytes.len(), + }; + + // SAFETY: We only sliced off ASCII slashes from the end of `path`. + Path::new(unsafe { OsStr::from_encoded_bytes_unchecked(&bytes[..keep]) }) + } + fn is_special_file(path: &Path) -> bool { match std::fs::metadata(path) { Ok(m) => { diff --git a/tests/test_grep.rs b/tests/test_grep.rs index 75961f7..bc5656d 100644 --- a/tests/test_grep.rs +++ b/tests/test_grep.rs @@ -1555,6 +1555,31 @@ fn recursive_no_file_defaults_to_cwd_not_stdin() { .stdout_contains("a.txt"); } +#[test] +fn recursive_collapses_repeated_trailing_slashes() { + // GNU grep reduces the trailing slashes of a directory operand to one, + // but keeps the slashes inside it. + let (scene, _) = ucmd(); + build_tree(&scene); + for (operand, expected) in [ + ("tree//sub//", "tree//sub/c.txt:grep me\n"), + ("tree/sub///", "tree/sub/c.txt:grep me\n"), + ("tree/sub/", "tree/sub/c.txt:grep me\n"), + ] { + scene + .cmd(env!("CARGO_BIN_EXE_grep")) + .args(&["-r", "grep", operand]) + .succeeds() + .stdout_only(expected); + } + scene + .cmd(env!("CARGO_BIN_EXE_grep")) + .current_dir(scene.fixtures.plus("tree/sub")) + .args(&["-r", "grep", ".//"]) + .succeeds() + .stdout_only("./c.txt:grep me\n"); +} + #[test] fn recursive_implicit_cwd_strips_dot_prefix() { // `-r` with no path argument searches the implicit ".", so reported paths