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
66
67
//
// Copyright 2023 Zesty Tech Ltd. All rights reserved.
// Use is subject to license terms.
//

use std::fmt;
use std::str::FromStr;

use serde_with::{DeserializeFromStr, SerializeDisplay};
use thiserror::Error;

pub use aws::AwsRegion;
pub use azure::AzureRegion;
pub use gcp::GcpRegion;

mod aws;
mod azure;
mod gcp;
mod impls;

#[derive(Debug, Error)]
#[error("Invalid region specified: {0}")]
pub struct InvalidRegion(String);

impl InvalidRegion {
    fn new(text: impl Into<String>) -> Self {
        Self(text.into())
    }
}

#[derive(Clone, Copy, Debug, SerializeDisplay, DeserializeFromStr)]
#[non_exhaustive]
pub enum Location {
    Aws(AwsRegion),
    Azure(AzureRegion),
    Gcp(GcpRegion),
}

trait CloudLocation {
    const CLOUD_VENDOR: &'static str;
    const CLOUD_VENDOR_PREFIX: &'static str;
    fn as_str(&self) -> &'static str;
    fn normal_region(text: &str) -> String {
        text.strip_prefix(Self::CLOUD_VENDOR_PREFIX)
            .unwrap_or(text)
            .to_lowercase()
    }
}

#[derive(Debug, Error)]
pub enum ParseError {
    #[error("Ambiguous region, use either {0}")]
    AmbiguousLocation(String),
    #[error("Unknown region: {0}")]
    UnknownLocation(String),
}

impl ParseError {
    fn ambiguous(candidates: &[&str]) -> Self {
        let text = candidates.join(" or ");
        Self::AmbiguousLocation(text)
    }

    fn unknown(text: &str) -> Self {
        Self::UnknownLocation(text.to_string())
    }
}