summaryrefslogtreecommitdiffhomepage
path: root/mullvad-cli/src/location.rs
blob: 20853893b8c7cf0c698cf03d9afc890b3730688c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
use mullvad_types::relay_constraints::{Constraint, LocationConstraint};

pub fn get_subcommand() -> clap::App<'static, 'static> {
    clap::SubCommand::with_name("location")
        .arg(
            clap::Arg::with_name("country")
                .help("The two letter country code, or 'any' for no preference.")
                .required(true)
                .index(1)
                .validator(country_code_validator),
        )
        .arg(
            clap::Arg::with_name("city")
                .help("The three letter city code")
                .index(2)
                .validator(city_code_validator),
        )
        .arg(
            clap::Arg::with_name("hostname")
                .help("The hostname")
                .index(3),
        )
}

pub fn get_constraint(matches: &clap::ArgMatches<'_>) -> Constraint<LocationConstraint> {
    let country_original = matches.value_of("country").unwrap();
    let country = country_original.to_lowercase();
    let city = matches.value_of("city").map(str::to_lowercase);
    let hostname = matches.value_of("hostname").map(str::to_lowercase);

    match (country_original, city, hostname) {
        ("any", None, None) => Constraint::Any,
        ("any", ..) => clap::Error::with_description(
            "City can't be given when selecting 'any' country",
            clap::ErrorKind::InvalidValue,
        )
        .exit(),
        (_, None, None) => Constraint::Only(LocationConstraint::Country(country)),
        (_, Some(city), None) => Constraint::Only(LocationConstraint::City(country, city)),
        (_, Some(city), Some(hostname)) => {
            Constraint::Only(LocationConstraint::Hostname(country, city, hostname))
        }
        (..) => clap::Error::with_description(
            "Invalid country, city and hostname combination given",
            clap::ErrorKind::InvalidValue,
        )
        .exit(),
    }
}

fn country_code_validator(code: String) -> std::result::Result<(), String> {
    if code.len() == 2 || code == "any" {
        Ok(())
    } else {
        Err(String::from("Country codes must be two letters, or 'any'."))
    }
}

fn city_code_validator(code: String) -> std::result::Result<(), String> {
    if code.len() == 3 {
        Ok(())
    } else {
        Err(String::from("City codes must be three letters"))
    }
}