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
58 changes: 42 additions & 16 deletions src/locate/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ impl UError for Error {
}

pub struct Statistics {
/// Whether some entries may have been left out, which changes how the total is labelled.
filtered: bool,
matches: usize,
total_length: usize,
whitespace: usize,
Expand All @@ -95,8 +97,9 @@ pub struct Statistics {
}

impl Statistics {
fn new() -> Self {
fn new(filtered: bool) -> Self {
Self {
filtered,
matches: 0,
total_length: 0,
whitespace: 0,
Expand Down Expand Up @@ -137,7 +140,12 @@ impl Statistics {
}
writeln!(out, "Locate database size: {} bytes", metadata.len())?;
}
writeln!(out, "Matching Filenames: {}", self.matches)?;
let label = if self.filtered {
"Matching Filenames"
} else {
"All Filenames"
};
writeln!(out, "{label}: {}", self.matches)?;
writeln!(
out,
"File names have a cumulative length of {} bytes",
Expand Down Expand Up @@ -192,6 +200,14 @@ impl Patterns {
}
}

/// Whether no pattern was given, which `--statistics` allows: no search is performed then.
fn is_empty(&self) -> bool {
match self {
Self::String { patterns, .. } => patterns.is_empty(),
Self::Regex(v) => v.is_empty(),
}
}

fn all_match(&self, entry: &str) -> bool {
match self {
Self::String {
Expand Down Expand Up @@ -282,7 +298,7 @@ impl TryFrom<ArgMatches> for ParsedInfo {
null_bytes: value.get_flag("null"),
print: value.get_flag("print"),
};
// `patterns` is a required argument, so this is normally non-empty
// `patterns` is required unless --statistics is given
let patterns: Vec<String> = value
.get_many::<String>("patterns")
.map(|v| v.cloned().collect())
Expand Down Expand Up @@ -453,7 +469,7 @@ fn uu_app() -> Command {
.num_args(1..)
.action(ArgAction::Append)
.value_parser(value_parser!(String))
.required(true),
.required_unless_present("statistics"),
)
}

Expand Down Expand Up @@ -565,6 +581,17 @@ fn match_entry(entry: &CStr, config: &Config, patterns: &Patterns) -> bool {
const GLOB_METACHARS: &str = r"*?[]\";

let buf = crate::bytes_to_path(entry.to_bytes());
// existence is always checked against the full path, even in `--basename` mode
let existence_matches = || match config.existing {
ExistenceMode::Any => true,
ExistenceMode::Present => path_exists(&buf, config.follow_symlinks),
ExistenceMode::NotPresent => !path_exists(&buf, config.follow_symlinks),
};
// no search is performed without a pattern, so every entry counts
if patterns.is_empty() {
return existence_matches();
}

let name = if config.basename {
let Some(path) = buf.file_name() else {
return false;
Expand Down Expand Up @@ -603,14 +630,7 @@ fn match_entry(entry: &CStr, config: &Config, patterns: &Patterns) -> bool {
patterns.any_match(entry.as_ref())
};

// existence is always checked against the full path, even in `--basename` mode
let existence_matches = match config.existing {
ExistenceMode::Any => true,
ExistenceMode::Present => path_exists(&buf, config.follow_symlinks),
ExistenceMode::NotPresent => !path_exists(&buf, config.follow_symlinks),
};

patterns_match && existence_matches
patterns_match && existence_matches()
}

/// Whether a database of the given `age` is older than `max_age` days.
Expand Down Expand Up @@ -640,7 +660,11 @@ fn do_locate(args: &[&str]) -> LocateResult<()> {
}
Ok(matches) => {
let ParsedInfo { patterns, config } = ParsedInfo::try_from(matches)?;
let mut stats = Statistics::new();
let no_search = patterns.is_empty();
let mut stats =
Statistics::new(!no_search || !matches!(config.existing, ExistenceMode::Any));

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 -e/-E without pattern case (back to "Matching Filenames") isn't tested, could you please add a case?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added in cb0b5c1: test_locate_statistics_without_pattern_existence now covers --existing and --non-existing with no pattern and checks for Matching Filenames: 1.

// without a search the statistics cover the whole database
let limit = config.limit.filter(|_| !no_search);
let stdout = io::stdout();
let mut out = stdout.lock();

Expand All @@ -652,7 +676,7 @@ fn do_locate(args: &[&str]) -> LocateResult<()> {
.filter_map(|p| DbReader::new(p.as_path()).ok())
{
// --limit applies to the whole output, not to each database
let remaining = config.limit.map_or(usize::MAX, |l| l.saturating_sub(count));
let remaining = limit.map_or(usize::MAX, |l| l.saturating_sub(count));
if remaining == 0 && config.mode != Mode::Statistics {
break;
}
Expand Down Expand Up @@ -687,7 +711,9 @@ fn do_locate(args: &[&str]) -> LocateResult<()> {
iter.filter(|s| match_entry(s.as_c_str(), &config, &patterns))
.take(remaining)
.inspect(|s| {
if (config.mode == Mode::Normal || config.print) && write_result.is_ok()
if (config.mode == Mode::Normal || config.print)
&& !no_search
&& write_result.is_ok()
{
write_result = if config.null_bytes {
write!(out, "{}\0", s.to_string_lossy())
Expand Down Expand Up @@ -771,7 +797,7 @@ mod tests {
std::fs::write(&db, b"\0LOCATE02\0\0/foo\0").unwrap();
let dbreader = DbReader::new(&db).unwrap();

let stats = Statistics::new();
let stats = Statistics::new(false);
// A failing writer must surface an error rather than panicking, so a
// full disk or closed pipe exits with a diagnostic instead of exit 101.
assert!(stats.print_header(&mut FailWriter, &dbreader).is_err());
Expand Down
96 changes: 91 additions & 5 deletions tests/db_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,13 +67,99 @@ fn test_locate_non_existing() {
.failure();
}

#[rstest]
#[case::plain(&[])]
#[case::regex(&["--regex"])]
#[case::limit_is_ignored(&["--limit=1"])]
fn test_locate_statistics_without_pattern(#[case] extra: &[&str]) {
let mut args = vec!["--statistics", DB_FLAG];
args.extend(extra);
let output = Command::cargo_bin("locate")
.expect("couldn't find locate binary")
.args(args)
.output()
.unwrap();
assert!(output.status.success());
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(stdout.contains("All Filenames: "), "{stdout}");
assert!(!stdout.contains("Matching Filenames"), "{stdout}");
let count: usize = stdout
.lines()
.find_map(|l| l.strip_prefix("All Filenames: "))
.unwrap()
.parse()
.unwrap();
assert!(count > 1, "{stdout}");
}

#[rstest]
#[case::existing("--existing")]
#[case::non_existing("--non-existing")]
fn test_locate_statistics_without_pattern_existence(#[case] flag: &str) {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("db");
let present = dir.path().display().to_string();
let missing = dir.path().join("missing").display().to_string();
let mut contents = b"\0LOCATE02\0\0".to_vec();
for path in [&present, &missing] {
contents.extend_from_slice(path.as_bytes());
contents.extend_from_slice(b"\0\0");
}
contents.pop();
std::fs::write(&db, contents).unwrap();
let output = Command::cargo_bin("locate")
.expect("couldn't find locate binary")
.args([
"--statistics",
flag,
&format!("--database={}", db.display()),
])
.output()
.unwrap();
assert!(output.status.success());
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(stdout.contains("Matching Filenames: 1\n"), "{stdout}");
assert!(!stdout.contains("All Filenames"), "{stdout}");
}

#[test]
fn test_locate_statistics() {
Command::cargo_bin("locate")
fn test_locate_statistics_with_pattern_reports_matches() {
let output = Command::cargo_bin("locate")
.expect("couldn't find locate binary")
.args(["", "--statistics", DB_FLAG])
.assert()
.success();
.args(["abbbc", "--statistics", DB_FLAG])
.output()
.unwrap();
assert!(output.status.success());
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(stdout.contains("Matching Filenames: "), "{stdout}");
assert!(!stdout.contains("All Filenames"), "{stdout}");
}

#[test]
fn test_locate_statistics_without_pattern_prints_no_entries() {
let output = Command::cargo_bin("locate")
.expect("couldn't find locate binary")
.args(["--statistics", "--print", DB_FLAG])
.output()
.unwrap();
assert!(output.status.success());
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(!stdout.contains("abbbc"), "{stdout}");
}

#[test]
fn test_locate_statistics_without_pattern_counts_glob_metachars() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("db");
std::fs::write(&db, b"\0LOCATE02\0\0/a*b\0\0/foo\0").unwrap();
let output = Command::cargo_bin("locate")
.expect("couldn't find locate binary")
.args(["--statistics", &format!("--database={}", db.display())])
.output()
.unwrap();
assert!(output.status.success());
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(stdout.contains("All Filenames: 2\n"), "{stdout}");
}

#[rstest]
Expand Down
Loading