1use std::{collections::HashMap, env::vars, fmt, result, str::FromStr};
16
17mod cli;
18
19pub use cli::Cli;
20use regex::{Regex, Replacer};
21
22#[derive(thiserror::Error, Debug)]
23pub enum Error {
24 Box(#[from] Box<dyn std::error::Error + Send + Sync>),
25 Cat(Box<nisshi_cat::Error>),
26 Client(Box<nisshi_client::Error>),
27 DotEnv(#[from] dotenv::Error),
28 Generate(#[from] nisshi_generator::Error),
29 InvalidLength(#[from] sha2::digest::InvalidLength),
30 Perf(#[from] nisshi_perf::Error),
31 Proxy(#[from] nisshi_proxy::Error),
32 Regex(#[from] regex::Error),
33 SansIo(#[from] nisshi_sans_io::Error),
34 Schema(Box<nisshi_schema::Error>),
35 Server(Box<nisshi_broker::Error>),
36 Tls(#[from] rustls::Error),
37 TlsPkiPem(#[from] rustls::pki_types::pem::Error),
38 Topic(#[from] nisshi_topic::Error),
39 Url(#[from] url::ParseError),
40}
41
42impl From<nisshi_cat::Error> for Error {
43 fn from(value: nisshi_cat::Error) -> Self {
44 Self::Cat(Box::new(value))
45 }
46}
47
48impl From<nisshi_client::Error> for Error {
49 fn from(value: nisshi_client::Error) -> Self {
50 Self::Client(Box::new(value))
51 }
52}
53
54impl From<nisshi_schema::Error> for Error {
55 fn from(value: nisshi_schema::Error) -> Self {
56 Self::Schema(Box::new(value))
57 }
58}
59
60impl From<nisshi_broker::Error> for Error {
61 fn from(value: nisshi_broker::Error) -> Self {
62 Self::Server(Box::new(value))
63 }
64}
65
66impl fmt::Display for Error {
67 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68 write!(f, "{self:?}")
69 }
70}
71
72pub type Result<T, E = Error> = result::Result<T, E>;
73
74#[derive(Clone, Debug)]
75pub struct VarRep(HashMap<String, String>);
76
77impl From<HashMap<String, String>> for VarRep {
78 fn from(value: HashMap<String, String>) -> Self {
79 Self(value)
80 }
81}
82
83impl VarRep {
84 fn replace(&self, haystack: &str) -> Result<String> {
85 Regex::new(r"\$\{(?<var>[^\}]+)\}")
86 .map(|re| re.replace(haystack, self).into_owned())
87 .map_err(Into::into)
88 }
89}
90
91impl Replacer for &VarRep {
92 fn replace_append(&mut self, caps: ®ex::Captures<'_>, dst: &mut String) {
93 if let Some(variable) = caps.name("var")
94 && let Some(value) = self.0.get(variable.as_str())
95 {
96 dst.push_str(value);
97 }
98 }
99}
100
101#[derive(Clone, Debug)]
102pub struct EnvVarExp<T>(T);
103
104impl<T> EnvVarExp<T> {
105 pub fn into_inner(self) -> T {
106 self.0
107 }
108}
109
110impl<T> FromStr for EnvVarExp<T>
111where
112 T: FromStr,
113 Error: From<<T as FromStr>::Err>,
114{
115 type Err = Error;
116
117 fn from_str(s: &str) -> Result<Self, Self::Err> {
118 VarRep::from(vars().collect::<HashMap<_, _>>())
119 .replace(s)
120 .and_then(|s| T::from_str(&s).map_err(Into::into))
121 .map(|t| Self(t))
122 }
123}