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<tansu_cat::Error>),
26 DotEnv(#[from] dotenv::Error),
27 Generate(#[from] tansu_generator::Error),
28 Regex(#[from] regex::Error),
29 Schema(Box<tansu_schema::Error>),
30 Server(Box<tansu_broker::Error>),
31 Topic(#[from] tansu_topic::Error),
32 Url(#[from] url::ParseError),
33}
34
35impl From<tansu_cat::Error> for Error {
36 fn from(value: tansu_cat::Error) -> Self {
37 Self::Cat(Box::new(value))
38 }
39}
40
41impl From<tansu_schema::Error> for Error {
42 fn from(value: tansu_schema::Error) -> Self {
43 Self::Schema(Box::new(value))
44 }
45}
46
47impl From<tansu_broker::Error> for Error {
48 fn from(value: tansu_broker::Error) -> Self {
49 Self::Server(Box::new(value))
50 }
51}
52
53impl fmt::Display for Error {
54 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55 write!(f, "{self:?}")
56 }
57}
58
59pub type Result<T, E = Error> = result::Result<T, E>;
60
61#[derive(Clone, Debug)]
62pub struct VarRep(HashMap<String, String>);
63
64impl From<HashMap<String, String>> for VarRep {
65 fn from(value: HashMap<String, String>) -> Self {
66 Self(value)
67 }
68}
69
70impl VarRep {
71 fn replace(&self, haystack: &str) -> Result<String> {
72 Regex::new(r"\$\{(?<var>[^\}]+)\}")
73 .map(|re| re.replace(haystack, self).into_owned())
74 .map_err(Into::into)
75 }
76}
77
78impl Replacer for &VarRep {
79 fn replace_append(&mut self, caps: ®ex::Captures<'_>, dst: &mut String) {
80 if let Some(variable) = caps.name("var") {
81 if let Some(value) = self.0.get(variable.as_str()) {
82 dst.push_str(value);
83 }
84 }
85 }
86}
87
88#[derive(Clone, Debug)]
89pub struct EnvVarExp<T>(T);
90
91impl<T> EnvVarExp<T> {
92 pub fn into_inner(self) -> T {
93 self.0
94 }
95}
96
97impl<T> FromStr for EnvVarExp<T>
98where
99 T: FromStr,
100 Error: From<<T as FromStr>::Err>,
101{
102 type Err = Error;
103
104 fn from_str(s: &str) -> Result<Self, Self::Err> {
105 VarRep::from(vars().collect::<HashMap<_, _>>())
106 .replace(s)
107 .and_then(|s| T::from_str(&s).map_err(Into::into))
108 .map(|t| Self(t))
109 }
110}