run_make_support/
string.rs

1use std::path::Path;
2
3use crate::fs;
4use crate::path_helpers::{cwd, has_extension, shallow_find_files};
5
6/// Gathers all files in the current working directory that have the extension `ext`, and counts
7/// the number of lines within that contain a match with the regex pattern `re`.
8pub fn count_regex_matches_in_files_with_extension(re: &regex::Regex, ext: &str) -> usize {
9    let fetched_files = shallow_find_files(cwd(), |path| has_extension(path, ext));
10
11    let mut count = 0;
12    for file in fetched_files {
13        let content = fs::read_to_string(file);
14        count += content.lines().filter(|line| re.is_match(&line)).count();
15    }
16
17    count
18}
19
20/// Read the contents of a file that cannot simply be read by
21/// [`read_to_string`][crate::fs::read_to_string], due to invalid UTF-8 data, then assert
22/// that it contains `expected`.
23#[track_caller]
24pub fn invalid_utf8_contains<P: AsRef<Path>, S: AsRef<str>>(path: P, expected: S) {
25    let buffer = fs::read(path.as_ref());
26    let expected = expected.as_ref();
27    if !String::from_utf8_lossy(&buffer).contains(expected) {
28        eprintln!("=== FILE CONTENTS (LOSSY) ===");
29        eprintln!("{}", String::from_utf8_lossy(&buffer));
30        eprintln!("=== SPECIFIED TEXT ===");
31        eprintln!("{}", expected);
32        panic!("specified text was not found in file");
33    }
34}
35
36/// Read the contents of a file that cannot simply be read by
37/// [`read_to_string`][crate::fs::read_to_string], due to invalid UTF-8 data, then assert
38/// that it does not contain `expected`.
39#[track_caller]
40pub fn invalid_utf8_not_contains<P: AsRef<Path>, S: AsRef<str>>(path: P, expected: S) {
41    let buffer = fs::read(path.as_ref());
42    let expected = expected.as_ref();
43    if String::from_utf8_lossy(&buffer).contains(expected) {
44        eprintln!("=== FILE CONTENTS (LOSSY) ===");
45        eprintln!("{}", String::from_utf8_lossy(&buffer));
46        eprintln!("=== SPECIFIED TEXT ===");
47        eprintln!("{}", expected);
48        panic!("specified text was unexpectedly found in file");
49    }
50}