naming_conventions/conventions/
no_case.rs

1use crate::{tool, Convention};
2
3use regex::{Captures, Error, Regex};
4
5pub struct NoCase;
6
7impl Convention for NoCase {
8    fn to(&self, string: &str) -> Result<String, Error> {
9        to_no_case(string)
10    }
11
12    fn is(&self, string: &str) -> Result<bool, Error> {
13        is_no_case(string)
14    }
15}
16
17pub fn to_no_case(string: &str) -> Result<String, Error> {
18    let replacement =
19        |haystack: &str, caps: &Captures, push: &Option<bool>| -> Result<String, Error> {
20            let m = caps.get(0).unwrap();
21
22            let mut term = String::from(" ");
23            if push.unwrap() {
24                term.push_str(&haystack[m.start()..m.end()]);
25            }
26
27            Ok(term)
28        };
29
30    let re = Regex::new(r"([A-Z][a-z]+)|([A-Z][A-Z]+)").unwrap();
31    let result = tool::replace_all(&re, string, replacement, &Some(true)).unwrap();
32
33    let re = Regex::new(r"(\s|[_-])+").unwrap();
34    let result: String = tool::replace_all(&re, &result, replacement, &Some(false)).unwrap();
35
36    log::debug!(target: "convention::no_case::to_no_case", "'{}' changed to '{}' (no case).", string, result.trim());
37    Ok(result.trim().into())
38}
39
40pub fn is_no_case(string: &str) -> Result<bool, Error> {
41    let no_case = to_no_case(string)?;
42    Ok(no_case == string)
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    fn init() {
50        dotenv::dotenv().ok();
51        let _ = env_logger::try_init();
52    }
53
54    #[test]
55    fn test_to_no_case() {
56        tests::init();
57
58        let result = to_no_case("vahid_Vakili ").unwrap();
59        assert_eq!(&result, "vahid Vakili")
60    }
61
62    #[test]
63    fn test_is_no_case() {
64        tests::init();
65
66        let result = is_no_case("vahid vakili").unwrap();
67        assert_eq!(result, true);
68
69        let result = is_no_case("vahid_vakili").unwrap();
70        assert_eq!(result, false);
71    }
72}