Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/searcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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) => {
Expand Down
25 changes: 25 additions & 0 deletions tests/test_grep.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 [

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please also add the .// case from the issue

("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
Expand Down
Loading