gitignore_template_generator/validator/
impls.rs

1use url::Url;
2
3use super::api::CliArgsValidator;
4use crate::constant;
5
6/// Default implementation of cli args validator.
7///
8/// Can be used directly as part of [`clap::Arg::value_parser`].
9pub struct DefaultCliArgsValidator;
10
11impl CliArgsValidator for DefaultCliArgsValidator {
12    /// Checks if given value contains commas.
13    ///
14    /// Returns [`constant::error_messages::COMMAS_NOT_ALLOWED`] if any commas
15    /// found.
16    ///
17    /// See [`CliArgsValidator::has_no_commas`] for more infos.
18    fn has_no_commas(value: &str) -> Result<String, String> {
19        if value.contains(',') {
20            Err(String::from(constant::error_messages::COMMAS_NOT_ALLOWED))
21        } else {
22            Ok(value.to_string())
23        }
24    }
25
26    /// Checks if given value contains whitespaces.
27    ///
28    /// Returns [`constant::error_messages::WHITESPACES_NOT_ALLOWED`] if any
29    /// whitespaces found.
30    ///
31    /// See [`CliArgsValidator::has_no_whitespaces`] for more infos.
32    fn has_no_whitespaces(value: &str) -> Result<String, String> {
33        if value.chars().any(|c| c.is_whitespace()) {
34            Err(String::from(
35                constant::error_messages::WHITESPACES_NOT_ALLOWED,
36            ))
37        } else {
38            Ok(value.to_string())
39        }
40    }
41
42    fn has_valid_template_name(value: &str) -> Result<String, String> {
43        match Self::has_no_commas(value) {
44            Ok(no_commas_value) => match Self::has_no_whitespaces(&no_commas_value) {
45                Ok(clean_value) => Ok(clean_value),
46                Err(whitespaces_error) => Err(whitespaces_error),
47            },
48            Err(commas_error) => match Self::has_no_whitespaces(value) {
49                Ok(_) => Err(commas_error),
50                Err(whitespaces_error) => Err(format!("{} + {}", commas_error, whitespaces_error)),
51            },
52        }
53    }
54
55    fn is_starting_with_slash(value: &str) -> Result<String, String> {
56        if value.starts_with('/') {
57            Ok(value.to_string())
58        } else {
59            Err(String::from(
60                constant::error_messages::URI_WITHOUT_STARTING_SLASH,
61            ))
62        }
63    }
64
65    fn is_valid_url(value: &str) -> Result<String, String> {
66        match Url::parse(value) {
67            Ok(valid_url) => {
68                if valid_url.scheme() == "https" || valid_url.scheme() == "http" {
69                    Ok(value.to_string())
70                } else {
71                    Err(String::from(constant::error_messages::INVALID_URL))
72                }
73            }
74            Err(_) => Err(String::from(constant::error_messages::INVALID_URL)),
75        }
76    }
77}