version_sync/
contains_substring.rs

1use crate::helpers::{read_file, Result};
2
3/// Check that `path` contain the substring given by `template`.
4///
5/// The placeholders `{name}` and `{version}` will be replaced with
6/// `pkg_name` and `pkg_version`, if they are present in `template`.
7/// It is okay if `template` do not contain these placeholders.
8///
9/// See [`check_contains_regex`](crate::check_contains_regex) if you
10/// want to match with a regular expression instead.
11///
12/// # Errors
13///
14/// If the template cannot be found, an `Err` is returned with a
15/// succinct error message. Status information has then already been
16/// printed on `stdout`.
17pub fn check_contains_substring(
18    path: &str,
19    template: &str,
20    pkg_name: &str,
21    pkg_version: &str,
22) -> Result<()> {
23    // Expand the optional {name} and {version} placeholders in the
24    // template. This is almost like
25    //
26    //   format!(template, name = pkg_name, version = pkg_version)
27    //
28    // but allows the user to leave out unnecessary placeholders.
29    let pattern = template
30        .replace("{name}", pkg_name)
31        .replace("{version}", pkg_version);
32
33    let text = read_file(path).map_err(|err| format!("could not read {}: {}", path, err))?;
34
35    println!("Searching for \"{pattern}\" in {path}...");
36    match text.find(&pattern) {
37        Some(idx) => {
38            let line_no = text[..idx].lines().count();
39            println!("{} (line {}) ... ok", path, line_no + 1);
40            Ok(())
41        }
42        None => Err(format!("could not find \"{pattern}\" in {path}")),
43    }
44}
45
46#[cfg(test)]
47mod tests {
48    use super::*;
49
50    #[test]
51    fn pattern_not_found() {
52        assert_eq!(
53            check_contains_substring("README.md", "should not be found", "foobar", "1.2.3"),
54            Err(String::from(
55                "could not find \"should not be found\" in README.md"
56            ))
57        )
58    }
59
60    #[test]
61    fn pattern_found() {
62        assert_eq!(
63            check_contains_substring("README.md", "{name}", "version-sync", "1.2.3"),
64            Ok(())
65        )
66    }
67}