Skip to content

Commit 8b12686

Browse files
ls: On Windows don't display files hidden by NTFS (#1662)
This little check, allows us to hide the files that shouldn't be shown on the listing on Windows operating systems. Just like the "dot" in UNIX based operating systems Windows uses its own file attributes to determine if a file is hidden or not. The lack of support for this option is normally an annoyance for many users, this commit adds full support for this feature
1 parent 469abf2 commit 8b12686

2 files changed

Lines changed: 39 additions & 1 deletion

File tree

‎src/uu/ls/src/ls.rs‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,18 @@ fn sort_entries(entries: &mut Vec<PathBuf>, options: &getopts::Matches) {
255255
}
256256
}
257257

258+
#[cfg(windows)]
259+
fn is_hidden(file_path: &DirEntry) -> std::io::Result<bool> {
260+
let metadata = fs::metadata(file_path.path())?;
261+
let attr = metadata.file_attributes();
262+
Ok(((attr & 0x2) > 0) || file_path.file_name().to_string_lossy().starts_with('.'))
263+
}
264+
265+
#[cfg(unix)]
266+
fn is_hidden(file_path: &DirEntry) -> std::io::Result<bool> {
267+
Ok(file_path.file_name().to_string_lossy().starts_with('.'))
268+
}
269+
258270
#[cfg(windows)]
259271
fn sort_entries(entries: &mut Vec<PathBuf>, options: &getopts::Matches) {
260272
let mut reverse = options.opt_present("r");
@@ -286,7 +298,7 @@ fn sort_entries(entries: &mut Vec<PathBuf>, options: &getopts::Matches) {
286298
fn should_display(entry: &DirEntry, options: &getopts::Matches) -> bool {
287299
let ffi_name = entry.file_name();
288300
let name = ffi_name.to_string_lossy();
289-
if !options.opt_present("a") && !options.opt_present("A") && name.starts_with('.') {
301+
if !options.opt_present("a") && !options.opt_present("A") && is_hidden(entry).unwrap() {
290302
return false;
291303
}
292304
if options.opt_present("B") && name.ends_with('~') {

‎tests/by-util/test_ls.rs‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,3 +310,29 @@ fn test_ls_human() {
310310
assert!(result.success);
311311
assert!(result.stdout.contains("1.02M"));
312312
}
313+
314+
#[cfg(windows)]
315+
#[test]
316+
fn test_ls_hidden_windows() {
317+
let scene = TestScenario::new(util_name!());
318+
let at = &scene.fixtures;
319+
let file = "hiddenWindowsFileNoDot";
320+
at.touch(file);
321+
// hide the file
322+
scene
323+
.cmd("attrib")
324+
.arg("+h")
325+
.arg("+S")
326+
.arg("+r")
327+
.arg(file)
328+
.run();
329+
let result = scene.ucmd().run();
330+
println!("stderr = {:?}", result.stderr);
331+
println!("stdout = {:?}", result.stdout);
332+
assert!(result.success);
333+
let result = scene.ucmd().arg("-a").run();
334+
println!("stderr = {:?}", result.stderr);
335+
println!("stdout = {:?}", result.stdout);
336+
assert!(result.success);
337+
assert!(result.stdout.contains(file));
338+
}

0 commit comments

Comments
 (0)