+
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
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ regex = "1.10"
once_cell = "1.19"
onig = { version = "6.4", default-features = false }
uucore = { version = "0.0.27", features = ["entries", "fs", "fsext", "mode"] }
nix = { version = "0.29", features = ["user"] }
nix = { version = "0.29", features = ["fs", "user"] }

[dev-dependencies]
assert_cmd = "2"
Expand Down
128 changes: 128 additions & 0 deletions src/find/matchers/fs.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
// This file is part of the uutils findutils package.
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.

use std::path::Path;
use std::{
error::Error,
io::{stderr, Write},
};

use super::Matcher;

/// Get the filesystem type of a file.
/// 1. get the metadata of the file
/// 2. get the device ID of the metadata
/// 3. search the filesystem list
///
/// Returns an empty string when no file system list matches.
///
/// # Errors
/// Returns an error if the metadata could not be read.
/// Returns an error if the filesystem list could not be read.
///
/// This is only supported on Unix.
#[cfg(unix)]
pub fn get_file_system_type(path: &Path) -> Result<String, Box<dyn Error>> {
use std::os::unix::fs::MetadataExt;

let metadata = match path.metadata() {
Ok(metadata) => metadata,
Err(err) => Err(err)?,
};
let dev_id = metadata.dev().to_string();
let fs_list = match uucore::fsext::read_fs_list() {
Ok(fs_list) => fs_list,
Err(err) => Err(err)?,
};
let result = fs_list
.into_iter()
.find(|fs| fs.dev_id == dev_id)
.map_or_else(String::new, |fs| fs.fs_type);

Ok(result)
}

/// This matcher handles the -fstype argument.
/// It matches the filesystem type of the file.
///
/// This is only supported on Unix.
pub struct FileSystemMatcher {
fs_text: String,
}

impl FileSystemMatcher {
pub fn new(fs_text: String) -> Self {
Self { fs_text }
}
}

impl Matcher for FileSystemMatcher {
fn matches(&self, file_info: &walkdir::DirEntry, _: &mut super::MatcherIO) -> bool {
#[cfg(not(unix))]
{
false
}
#[cfg(unix)]
{
match get_file_system_type(file_info.path()) {
Ok(result) => result == self.fs_text,
Err(_) => {
writeln!(
&mut stderr(),
"Error getting filesystem type for {}",
file_info.path().to_string_lossy()
)
.unwrap();

false
}
}
}
}
}

#[cfg(test)]
mod tests {
#[test]
#[cfg(unix)]
fn test_fs_matcher() {
use crate::find::{
matchers::{fs::get_file_system_type, tests::get_dir_entry_for, Matcher},
tests::FakeDependencies,
};
use std::fs::File;
use tempfile::Builder;

let deps = FakeDependencies::new();
let mut matcher_io = deps.new_matcher_io();

// create temp file and get its fs type
// We pass this file and the corresponding file system type into the Matcher for comparison.
let temp_dir = Builder::new().prefix("fs_matcher").tempdir().unwrap();
let foo_path = temp_dir.path().join("foo");
let _ = File::create(foo_path).expect("create temp file");
let file_info = get_dir_entry_for(&temp_dir.path().to_string_lossy(), "foo");

let target_fs_type = get_file_system_type(file_info.path()).unwrap();

// should match fs type
let matcher = super::FileSystemMatcher::new(target_fs_type.clone());
assert!(
matcher.matches(&file_info, &mut matcher_io),
"{} should match {}",
file_info.path().to_string_lossy(),
target_fs_type
);

// should not match fs type
let matcher = super::FileSystemMatcher::new(target_fs_type.clone() + "foo");
assert!(
!matcher.matches(&file_info, &mut matcher_io),
"{} should not match {}",
file_info.path().to_string_lossy(),
target_fs_type
);
}
}
9 changes: 9 additions & 0 deletions src/find/matchers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ mod access;
mod delete;
mod empty;
pub mod exec;
pub mod fs;
mod glob;
mod group;
mod lname;
Expand All @@ -30,6 +31,7 @@ mod user;

use ::regex::Regex;
use chrono::{DateTime, Datelike, NaiveDateTime, Utc};
use fs::FileSystemMatcher;
use std::path::Path;
use std::time::SystemTime;
use std::{error::Error, str::FromStr};
Expand Down Expand Up @@ -421,6 +423,13 @@ fn build_matcher_tree(
i += 1;
Some(TypeMatcher::new(args[i])?.into_box())
}
"-fstype" => {
if i >= args.len() - 1 {
return Err(From::from(format!("missing argument to {}", args[i])));
}
i += 1;
Some(FileSystemMatcher::new(args[i].to_string()).into_box())
}
"-delete" => {
// -delete implicitly requires -depth
config.depth_first = true;
Expand Down
25 changes: 25 additions & 0 deletions src/find/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1194,4 +1194,29 @@ mod tests {
assert_eq!(rc, 0);
assert_eq!(deps.get_output_as_string(), "");
}

#[test]
#[cfg(unix)]
fn test_fs_matcher() {
use crate::find::tests::FakeDependencies;
use matchers::fs::get_file_system_type;
use std::path::Path;

let path = Path::new("./test_data/simple/subdir");
let target_fs_type = get_file_system_type(path).unwrap();

// should match fs type
let deps = FakeDependencies::new();
let rc = find_main(
&[
"find",
"./test_data/simple/subdir",
"-fstype",
&target_fs_type,
],
&deps,
);

assert_eq!(rc, 0);
}
}
50 changes: 50 additions & 0 deletions tests/find_cmd_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -780,6 +780,56 @@ fn find_age_range() {
}
}

#[test]
#[cfg(unix)]
#[serial(working_dir)]
fn find_fs() {
use findutils::find::matchers::fs::get_file_system_type;
use std::path::Path;

let path = Path::new("./test_data/simple/subdir");
let target_fs_type = get_file_system_type(path).unwrap();

// match fs type
Command::cargo_bin("find")
.expect("found binary")
.args(["./test_data/simple/subdir", "-fstype", &target_fs_type])
.assert()
.success()
.stdout(predicate::str::contains("./test_data/simple/subdir"))
.stderr(predicate::str::is_empty());

// not match fs type
Command::cargo_bin("find")
.expect("found binary")
.args([
"./test_data/simple/subdir",
"-fstype",
format!("{} foo", target_fs_type).as_str(),
])
.assert()
.success()
.stdout(predicate::str::is_empty())
.stderr(predicate::str::is_empty());

// not contain fstype text.
Command::cargo_bin("find")
.expect("found binary")
.args(["./test_data/simple/subdir", "-fstype"])
.assert()
.failure()
.stdout(predicate::str::is_empty());

// void fstype
Command::cargo_bin("find")
.expect("found binary")
.args(["./test_data/simple/subdir", "-fstype", " "])
.assert()
.success()
.stdout(predicate::str::is_empty())
.stderr(predicate::str::is_empty());
}

#[test]
#[serial(working_dir)]
fn find_samefile() {
Expand Down
点击 这是indexloc提供的php浏览器服务,不要输入任何密码和下载