Skip to content
Open
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
19 changes: 19 additions & 0 deletions docs/src/extensions.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,25 @@ This is most useful when you want reproducible output: comparing two trees,
generating a manifest, or writing a test whose expected output is a fixed list
of lines.

## `UUTILS_PATH_SEPARATOR`: `/` on Windows

On Windows, `find` joins the paths it walks with `\`, so `find src -name '*.rs'`
prints `src\find\mod.rs`, and a `-path` or `-prune` pattern written with `/`
matches nothing. Setting `UUTILS_PATH_SEPARATOR=slash` makes every path `find`
produces use `/` instead: what it prints, what `-path`, `-wholename` and
`-regex` match against, the `%p`, `%h` and `%P` directives of `-printf`, and the
`{}` handed to `-exec` and `-ok`.

```console
PS> find src -path '*/matchers/*' -name path.rs
PS> $env:UUTILS_PATH_SEPARATOR = 'slash'
PS> find src -path '*/matchers/*' -name path.rs
src/find/matchers/path.rs
```

Any other value, or none, keeps `\`. Verbatim (`\\?\`) and device (`\\.\`)
paths keep their spelling. On other platforms the variable has no effect.

## Rich expression diagnostics

`find` expressions get long, and a lone error line does not say *where* in the
Expand Down
56 changes: 55 additions & 1 deletion src/find/matchers/entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,45 @@ pub struct WalkEntry {
follow: Follow,
/// Cached metadata.
meta: OnceCell<Result<Metadata, WalkError>>,
/// The path respelled for `UUTILS_PATH_SEPARATOR`, when that differs.
respelled: OnceCell<Option<PathBuf>>,
}

/// Whether `UUTILS_PATH_SEPARATOR=slash` asks for `/` between path components.
#[cfg(windows)]
fn forward_slashes() -> bool {
static FORWARD: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*FORWARD.get_or_init(|| std::env::var_os("UUTILS_PATH_SEPARATOR").is_some_and(|v| v == "slash"))
}

/// `path` with `/` for every `\`, when `UUTILS_PATH_SEPARATOR=slash` asks for
/// it and the path has a `\` to replace. Only the separators change, so a name
/// that is not valid UTF-16 keeps its spelling. Verbatim (`\\?\`) and device
/// (`\\.\`) paths are left alone, since `/` does not mean the same thing there.
#[cfg(windows)]
fn respell(path: &Path) -> Option<PathBuf> {
use std::os::windows::ffi::{OsStrExt, OsStringExt};
const BACKSLASH: u16 = b'\\' as u16;

if !forward_slashes() {
return None;
}
let mut wide: Vec<u16> = path.as_os_str().encode_wide().collect();
let prefixed = |c: u8| wide.starts_with(&[BACKSLASH, BACKSLASH, c.into(), BACKSLASH]);

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.

could you please add a windows-only test for the \\?\ case? e.g. a canonicalized start point, which comes back verbatim

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Added path_separator_slash_leaves_verbatim_paths_alone (Windows only): it canonicalizes test_data/depth/1 into a \\?\ start point, walks it with UUTILS_PATH_SEPARATOR=slash, and checks every printed path keeps \. Passes on both Windows legs. Also rebased onto main to clear the conflict.

if !wide.contains(&BACKSLASH) || prefixed(b'?') || prefixed(b'.') {
return None;
}
for c in &mut wide {
if *c == BACKSLASH {
*c = b'/'.into();
}
}
Some(std::ffi::OsString::from_wide(&wide).into())
}

#[cfg(not(windows))]
fn respell(_path: &Path) -> Option<PathBuf> {
None
}

impl WalkEntry {
Expand All @@ -212,6 +251,7 @@ impl WalkEntry {
inner: Entry::Explicit(path.into(), depth),
follow,
meta: OnceCell::new(),
respelled: OnceCell::new(),
}
}

Expand All @@ -233,6 +273,7 @@ impl WalkEntry {
inner: Entry::WalkDir(entry),
follow,
meta: OnceCell::new(),
respelled: OnceCell::new(),
}
};
Ok(ret)
Expand All @@ -245,6 +286,7 @@ impl WalkEntry {
inner: Entry::Explicit(path.into(), depth),
follow: Follow::Never,
meta: Ok(meta).into(),
respelled: OnceCell::new(),
});
}
}
Expand All @@ -257,14 +299,26 @@ impl WalkEntry {

/// Get the path to this entry.
pub fn path(&self) -> &Path {
match self.respelled.get_or_init(|| respell(self.walked_path())) {
Some(path) => path.as_path(),
None => self.walked_path(),
}
}

/// Get the path to this entry as the walk spelled it.
fn walked_path(&self) -> &Path {
match &self.inner {
Entry::Explicit(path, _) => path.as_path(),
Entry::WalkDir(ent) => ent.path(),
}
}

/// Get the path to this entry.
pub fn into_path(self) -> PathBuf {
pub fn into_path(mut self) -> PathBuf {
self.respelled.get_or_init(|| respell(self.walked_path()));
if let Some(path) = self.respelled.take().flatten() {
return path;
}
match self.inner {
Entry::Explicit(path, _) => path,
Entry::WalkDir(ent) => ent.into_path(),
Expand Down
84 changes: 83 additions & 1 deletion tests/test_find.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use std::os::unix::fs::symlink;
#[cfg(windows)]
use std::os::windows::fs::{symlink_dir, symlink_file};

use common::test_helpers::fix_up_slashes;
use common::test_helpers::{fix_up_slashes, path_to_testing_commandline};

mod common;

Expand Down Expand Up @@ -3157,3 +3157,85 @@ fn find_debug_option() {
.stdout_contains("Valid arguments for -D:\n")
.stdout_does_not_contain("bogus");
}

#[test]
fn path_separator_slash_prints_slashes() {
// A no-op where `/` is already the separator; on Windows it replaces `\`.
ucmd()
.env("UUTILS_PATH_SEPARATOR", "slash")
.args(&["test_data/depth/1", "-name", "f2"])
.succeeds()
.stdout_only("test_data/depth/1/2/f2\n");
}

#[test]
fn path_separator_slash_matches_slash_patterns() {
ucmd()
.env("UUTILS_PATH_SEPARATOR", "slash")
.args(&[
"test_data/depth",
"-sorted",
"-path",
"*/2/*",
"-prune",
"-o",
"-type",
"f",
"-print",
])
.succeeds()
.stdout_only("test_data/depth/1/f1\ntest_data/depth/f0\n");
}

#[test]
fn path_separator_slash_reaches_printf() {
ucmd()
.env("UUTILS_PATH_SEPARATOR", "slash")
.args(&["test_data/depth", "-name", "f2", "-printf", "%p %h %P\n"])
.succeeds()
.stdout_only("test_data/depth/1/2/f2 test_data/depth/1/2 1/2/f2\n");
}

#[test]
fn path_separator_slash_reaches_exec() {
ucmd()
.env("UUTILS_PATH_SEPARATOR", "slash")
.args(&[
"test_data/depth/1",
"-name",
"f2",
"-exec",
&path_to_testing_commandline(),
"-",
"--no_print_cwd",
"{}",
";",
])
.succeeds()
.stdout_only("args=\n--no_print_cwd\ntest_data/depth/1/2/f2\n");
}

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.

the docs mention -exec and %P, please add a test for them too

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Added path_separator_slash_reaches_exec, which checks the argument {} hands over, and %P in the printf test.


#[test]
fn path_separator_other_values_keep_the_native_separator() {
let root = fix_up_slashes("test_data/depth/1");
ucmd()
.env("UUTILS_PATH_SEPARATOR", "/")
.args(&[root.as_str(), "-name", "f2"])
.succeeds()
.stdout_only(fix_up_slashes("test_data/depth/1/2/f2\n"));
}

#[test]
#[cfg(windows)]
fn path_separator_slash_leaves_verbatim_paths_alone() {
// A canonicalized start point comes back as `\\?\C:\...`, where `/` is
// not a separator, so the walk keeps `\` throughout.
let root = fs::canonicalize("test_data/depth/1").unwrap();
let root = root.to_str().unwrap();
assert!(root.starts_with(r"\\?\"));
ucmd()
.env("UUTILS_PATH_SEPARATOR", "slash")
.args(&[root, "-name", "f2"])
.succeeds()
.stdout_only(format!("{root}\\2\\f2\n"));
}
Loading