github_heatmap/utils/
parsers.rs

1use regex::Regex;
2
3fn validate_regex(value: &str, reg_exp: &Regex) -> Result<String, String> {
4    match reg_exp.is_match(value) {
5        true => Ok(value.to_string()),
6        false => Err(String::from("Failed to validate regex")),
7    }
8}
9
10/// Attempts to parse a Github profile slug, based on a regular expression
11/// typically used while restricting profile names. Assures that only
12/// valid profile slugs are being provided as an argument to Clap.
13///
14/// # Errors
15/// Returns an error if provided slug argument does not match regular
16/// expression.
17///
18pub fn parse_slug(value: &str) -> Result<String, String> {
19    let github_slug_regex = Regex::new(r"^[a-zA-Z0-9-]{0,38}$").unwrap();
20
21    let result = validate_regex(value, &github_slug_regex).map_err(|_| 
22        "slug must only contain alphanumeric characters and/or hyphens"
23    )?;
24
25    Ok(result)
26}
27
28/// Attempts to parse a provided Year argument, based on simple regular
29/// expression. Assures that only valid calendar years are being provided
30/// as an argument to clap.
31///
32/// # Errors
33/// Returns an error if provided year argument does not match regular
34/// expression.
35///
36pub fn parse_year(value: &str) -> Result<String, String> {
37    let year_regex = Regex::new(r"^[\d]{4}$").unwrap();
38
39    let result = validate_regex(value, &year_regex).map_err(|_|
40        "year must be a valid calendar year, e.g. 2022"
41    )?;
42    
43    Ok(result)
44}