Skip to main content

devbook_tui/
config.rs

1pub const PRESET_HOST_LOCAL: &str = "http://localhost:3000";
2pub const PRESET_HOST_DOCKER: &str = "http://localhost:3008";
3
4pub fn get_preset_hosts() -> Vec<String> {
5    let mut hosts = Vec::new();
6    if let Ok(remote) = std::env::var("DEVBOOK_REMOTE_URL").or_else(|_| std::env::var("DEVBOOK_URL")) {
7        let norm = normalize_url(&remote);
8        if !norm.is_empty() {
9            hosts.push(norm);
10        }
11    }
12
13    for preset in [PRESET_HOST_LOCAL, PRESET_HOST_DOCKER] {
14        let p = preset.to_string();
15        if !hosts.contains(&p) {
16            hosts.push(p);
17        }
18    }
19
20    hosts
21}
22
23#[derive(Debug, Clone)]
24pub struct Config {
25    pub base_url: String,
26    pub api_token: Option<String>,
27    pub allow_host_switcher: bool,
28}
29
30pub fn normalize_url(raw: &str) -> String {
31    let mut s = raw.trim().to_string();
32    if s.is_empty() {
33        return PRESET_HOST_LOCAL.to_string();
34    }
35    if !s.starts_with("http://") && !s.starts_with("https://") {
36        s = format!("http://{}", s);
37    }
38    // Trim trailing slashes
39    while s.ends_with('/') {
40        s.pop();
41    }
42    // Strip trailing /api/v1 if provided
43    if s.ends_with("/api/v1") {
44        s.truncate(s.len() - 7);
45    }
46    while s.ends_with('/') {
47        s.pop();
48    }
49    s
50}
51
52impl Config {
53    pub fn new(base_url: &str) -> Self {
54        Self {
55            base_url: normalize_url(base_url),
56            api_token: std::env::var("DEVBOOK_API_KEY")
57                .or_else(|_| std::env::var("DEVBOOK_API_TOKEN"))
58                .ok(),
59            allow_host_switcher: std::env::var("DEVBOOK_REMOTE_URL").is_err(),
60        }
61    }
62
63    pub fn from_env_and_args() -> Self {
64        let args: Vec<String> = std::env::args().collect();
65        let env_remote = std::env::var("DEVBOOK_REMOTE_URL")
66            .or_else(|_| std::env::var("DEVBOOK_URL"))
67            .ok();
68        Self::parse_from_args_and_env(&args, env_remote.as_deref())
69    }
70
71    pub fn parse_from_args_and_env(args: &[String], env_remote: Option<&str>) -> Self {
72        let mut chosen_url: Option<String> = None;
73        let mut has_allow_switch = false;
74
75        let mut i = 1;
76        while i < args.len() {
77            match args[i].as_str() {
78                "--url" | "--host" | "-u" => {
79                    if i + 1 < args.len() {
80                        chosen_url = Some(args[i + 1].clone());
81                        i += 1;
82                    }
83                }
84                arg if arg.starts_with("--url=") => {
85                    chosen_url = Some(arg.trim_start_matches("--url=").to_string());
86                }
87                arg if arg.starts_with("--host=") => {
88                    chosen_url = Some(arg.trim_start_matches("--host=").to_string());
89                }
90                "--local" => {
91                    chosen_url = Some(PRESET_HOST_LOCAL.to_string());
92                }
93                "--remote" => {
94                    if let Some(remote) = env_remote {
95                        chosen_url = Some(remote.to_string());
96                    }
97                }
98                "--allow-switch" => {
99                    has_allow_switch = true;
100                }
101                _ => {}
102            }
103            i += 1;
104        }
105
106        let base_url = chosen_url
107            .or_else(|| env_remote.map(|s| s.to_string()))
108            .unwrap_or_else(|| PRESET_HOST_LOCAL.to_string());
109
110        let allow_host_switcher = env_remote.is_none() || has_allow_switch;
111
112        Self {
113            base_url: normalize_url(&base_url),
114            api_token: std::env::var("DEVBOOK_API_KEY")
115                .or_else(|_| std::env::var("DEVBOOK_API_TOKEN"))
116                .ok(),
117            allow_host_switcher,
118        }
119    }
120
121    pub fn set_url(&mut self, new_url: &str) {
122        self.base_url = normalize_url(new_url);
123    }
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129
130    #[test]
131    fn test_normalize_url() {
132        assert_eq!(normalize_url("http://localhost:3000/"), "http://localhost:3000");
133        assert_eq!(normalize_url("http://remote-server:3008/"), "http://remote-server:3008");
134        assert_eq!(normalize_url("localhost:3008"), "http://localhost:3008");
135        assert_eq!(normalize_url("http://localhost:3008/api/v1"), "http://localhost:3008");
136        assert_eq!(normalize_url("http://localhost:3008/api/v1/"), "http://localhost:3008");
137    }
138
139    #[test]
140    fn test_default_without_env_or_flags() {
141        let args = vec!["devbook-tui".to_string()];
142        let cfg = Config::parse_from_args_and_env(&args, None);
143        assert_eq!(cfg.base_url, "http://localhost:3000");
144        assert!(cfg.allow_host_switcher);
145    }
146
147    #[test]
148    fn test_default_with_devbook_remote_url() {
149        let args = vec!["devbook-tui".to_string()];
150        let cfg = Config::parse_from_args_and_env(&args, Some("http://remote-server:3008"));
151        assert_eq!(cfg.base_url, "http://remote-server:3008");
152        // Locked by default when DEVBOOK_REMOTE_URL is set
153        assert!(!cfg.allow_host_switcher);
154    }
155
156    #[test]
157    fn test_allow_switch_override_with_remote_url() {
158        let args = vec!["devbook-tui".to_string(), "--allow-switch".to_string()];
159        let cfg = Config::parse_from_args_and_env(&args, Some("http://remote-server:3008"));
160        assert_eq!(cfg.base_url, "http://remote-server:3008");
161        assert!(cfg.allow_host_switcher);
162    }
163
164    #[test]
165    fn test_local_flag_overrides_remote_env() {
166        let args = vec!["devbook-tui".to_string(), "--local".to_string()];
167        let cfg = Config::parse_from_args_and_env(&args, Some("http://remote-server:3008"));
168        assert_eq!(cfg.base_url, "http://localhost:3000");
169    }
170
171    #[test]
172    fn test_custom_url_flag_overrides_remote_env() {
173        let args = vec![
174            "devbook-tui".to_string(),
175            "--url".to_string(),
176            "http://custom:8080".to_string(),
177        ];
178        let cfg = Config::parse_from_args_and_env(&args, Some("http://remote-server:3008"));
179        assert_eq!(cfg.base_url, "http://custom:8080");
180    }
181}