1use std::{env, fmt};
2
3use reqwest::{Client as RwClient, Url};
4
5use crate::{Client, Config};
6
7#[must_use]
9pub struct Builder {
10 api_key: Option<String>,
11 base_url: Option<Url>,
12 user_agent: Option<String>,
13 http_client: Option<RwClient>,
14}
15
16impl Builder {
17 pub const fn new() -> Self {
21 Self {
22 api_key: None,
23 base_url: None,
24 user_agent: None,
25 http_client: None,
26 }
27 }
28
29 pub fn with_api_key(mut self, api_key: &str) -> Self {
31 self.api_key = Some(api_key.to_owned());
32 self
33 }
34
35 pub fn with_base_url(mut self, base_url: Url) -> Self {
39 self.base_url = Some(base_url);
40 self
41 }
42
43 pub fn with_user_agent(mut self, user_agent: &str) -> Self {
47 self.user_agent = Some(user_agent.to_owned());
48 self
49 }
50
51 pub fn with_http_client(mut self, client: RwClient) -> Self {
55 self.http_client = Some(client);
56 self
57 }
58
59 pub fn build(self) -> Client {
67 let config = Config {
68 api_key: self.api_key.or_else(default_api_key),
69 user_agent: self.user_agent.unwrap_or_else(default_user_agent),
70 base_url: self.base_url.unwrap_or_else(default_base_url),
71 client: self.http_client.unwrap_or_default(),
72 };
73
74 config.into_client()
75 }
76}
77
78impl Default for Builder {
79 #[inline]
80 fn default() -> Self {
81 Self::new()
82 }
83}
84
85impl fmt::Debug for Builder {
86 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87 f.debug_struct("Builder")
88 .field("user_agent", &self.user_agent.is_some())
89 .field("base_url", &self.base_url.is_some())
90 .field("http_client", &self.http_client.is_some())
91 .finish_non_exhaustive()
92 }
93}
94
95fn default_api_key() -> Option<String> {
96 match env::var("GLIDE_API_KEY") {
97 Ok(var) => Some(var),
98 Err(env::VarError::NotPresent) => None,
99 Err(env::VarError::NotUnicode(_)) => {
100 panic!("env variable `GLIDE_BASE_URL` should be a valid `String`")
101 }
102 }
103}
104
105fn default_base_url() -> Url {
106 env::var("GLIDE_BASE_URL")
107 .map_or_else(|_| Url::parse("http://127.0.0.1:9099/"), |x| Url::parse(&x))
108 .expect("env variable `GLIDE_BASE_URL` should be a valid `URL`")
109}
110
111fn default_user_agent() -> String {
112 if let Ok(x) = env::var("GLIDE_USER_AGENT") {
113 return x;
114 };
115
116 format!(
117 "Glide/{} (Rust; Ver {})",
118 env!("CARGO_PKG_VERSION"),
119 env!("CARGO_PKG_RUST_VERSION")
120 )
121}