BlueGit

ict rusty-teams

Files

rusty-teams / crates / browser / src / config.rs

config.rs

config.rs 14.7 KiB Download Raw
1use std::collections::HashMap;
2use std::path::{Path, PathBuf};
3use std::process::Command;
4
5use crate::error::BrowserError;
6
7pub const PROFILE_NAME: &str = "rusty-teams-chrome";
8pub const DEFAULT_PORT: u16 = 9222;
9const CHROME_RELATIVE: &str = r"Google\Chrome\Application\chrome.exe";
10const WINDOWS_VARIABLES: [&str; 4] = ["LOCALAPPDATA", "PROGRAMFILES", "PROGRAMFILES(X86)", "TEMP"];
11const LINUX_CHROME_NAMES: [&str; 5] =
12 ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "chrome"];
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum Platform {
16 Wsl,
17 Windows,
18 Linux,
19}
20
21impl Platform {
22 pub fn detect() -> Platform {
23 if cfg!(windows) {
24 return Platform::Windows;
25 }
26 let proc_version = std::fs::read_to_string("/proc/version").ok();
27 Platform::from_proc_version(proc_version.as_deref())
28 }
29
30 pub fn from_proc_version(content: Option<&str>) -> Platform {
31 match content {
32 Some(text) if text.to_ascii_lowercase().contains("microsoft") => Platform::Wsl,
33 _ => Platform::Linux,
34 }
35 }
36}
37
38#[derive(Debug, Clone)]
39pub(crate) enum ChromeSearch {
40 Files(Vec<PathBuf>),
41 Named(Vec<String>),
42}
43
44#[derive(Debug, Clone)]
45pub struct Config {
46 pub platform: Platform,
47 pub port: u16,
48 pub profile: String,
49 pub mode_file: PathBuf,
50 profile_parent: String,
51 mode_parent: PathBuf,
52 pub(crate) chrome_search: ChromeSearch,
53}
54
55pub struct ConfigInputs<'a> {
56 pub windows_variables: HashMap<String, String>,
57 pub linux_data_dir: Option<PathBuf>,
58 pub to_local: &'a dyn Fn(&str) -> String,
59}
60
61impl Config {
62 pub fn detect() -> Result<Config, BrowserError> {
63 let platform = Platform::detect();
64 let windows_variables = match platform {
65 Platform::Linux => HashMap::new(),
66 Platform::Windows => WINDOWS_VARIABLES
67 .iter()
68 .filter_map(|name| std::env::var(name).ok().map(|value| ((*name).to_owned(), value)))
69 .collect(),
70 Platform::Wsl => wsl_windows_variables()?,
71 };
72 let linux_data_dir = directories::BaseDirs::new().map(|dirs| dirs.data_dir().to_path_buf());
73 let to_local = |windows_path: &str| match platform {
74 Platform::Wsl => wslpath(windows_path).unwrap_or_else(|| windows_path_to_wsl(windows_path)),
75 _ => windows_path.to_owned(),
76 };
77 Config::resolve(
78 platform,
79 DEFAULT_PORT,
80 &ConfigInputs { windows_variables, linux_data_dir, to_local: &to_local },
81 )
82 }
83
84 pub fn resolve(platform: Platform, port: u16, inputs: &ConfigInputs) -> Result<Config, BrowserError> {
85 let to_local = inputs.to_local;
86 let missing = |name: &str| BrowserError::Environment(format!("%{name}% is not set"));
87 let config = match platform {
88 Platform::Linux => {
89 let data_dir = inputs
90 .linux_data_dir
91 .clone()
92 .ok_or_else(|| BrowserError::Environment("no XDG data directory".into()))?;
93 Config {
94 platform,
95 port,
96 // Built with the platform's '/' like with_profile_name, not the
97 // host's separator: the string is a Linux path whoever builds it.
98 profile: format!("{}/{}", path_text(&data_dir), PROFILE_NAME),
99 mode_file: data_dir.join(format!("{PROFILE_NAME}.mode")),
100 profile_parent: path_text(&data_dir),
101 mode_parent: data_dir,
102 chrome_search: ChromeSearch::Named(
103 LINUX_CHROME_NAMES.iter().map(|name| (*name).to_owned()).collect(),
104 ),
105 }
106 }
107 Platform::Windows | Platform::Wsl => {
108 let local = inputs.windows_variables.get("LOCALAPPDATA").ok_or_else(|| missing("LOCALAPPDATA"))?;
109 let candidates = ["PROGRAMFILES", "PROGRAMFILES(X86)", "LOCALAPPDATA"]
110 .iter()
111 .filter_map(|name| inputs.windows_variables.get(*name))
112 .map(|root| PathBuf::from(to_local(&format!("{root}\\{CHROME_RELATIVE}"))))
113 .collect();
114 Config {
115 platform,
116 port,
117 profile: format!("{local}\\{PROFILE_NAME}"),
118 mode_file: PathBuf::from(to_local(&format!("{local}\\{PROFILE_NAME}.mode"))),
119 profile_parent: local.clone(),
120 mode_parent: PathBuf::from(to_local(local)),
121 chrome_search: ChromeSearch::Files(candidates),
122 }
123 }
124 };
125 Ok(config)
126 }
127
128 pub fn with_port(mut self, port: u16) -> Config {
129 self.port = port;
130 self
131 }
132
133 pub fn with_profile_name(mut self, name: &str) -> Config {
134 let separator = if self.platform == Platform::Linux { "/" } else { "\\" };
135 self.profile = format!("{}{separator}{name}", self.profile_parent);
136 self.mode_file = self.mode_parent.join(format!("{name}.mode"));
137 self
138 }
139
140 pub fn chrome_executable(&self) -> Result<PathBuf, BrowserError> {
141 let path_variable = std::env::var_os("PATH").unwrap_or_default();
142 find_chrome(&self.chrome_search, &path_variable, &|path| path.is_file())
143 }
144}
145
146fn path_text(path: &Path) -> String {
147 path.to_string_lossy().into_owned()
148}
149
150pub(crate) fn find_chrome(
151 search: &ChromeSearch,
152 path_variable: &std::ffi::OsStr,
153 exists: &dyn Fn(&Path) -> bool,
154) -> Result<PathBuf, BrowserError> {
155 match search {
156 ChromeSearch::Files(candidates) => candidates
157 .iter()
158 .find(|candidate| exists(candidate))
159 .cloned()
160 .ok_or_else(|| BrowserError::ChromeNotFound("not under Program Files or LocalAppData".into())),
161 ChromeSearch::Named(names) => std::env::split_paths(path_variable)
162 .flat_map(|directory| names.iter().map(move |name| directory.join(name)))
163 .find(|candidate| exists(candidate))
164 .ok_or_else(|| BrowserError::ChromeNotFound(format!("none of {} on PATH", names.join(", ")))),
165 }
166}
167
168pub fn windows_path_to_wsl(windows_path: &str) -> String {
169 match windows_path.split_once(':') {
170 Some((drive, rest)) if drive.len() == 1 => {
171 format!("/mnt/{}{}", drive.to_ascii_lowercase(), rest.replace('\\', "/"))
172 }
173 _ => windows_path.replace('\\', "/"),
174 }
175}
176
177fn wslpath(windows_path: &str) -> Option<String> {
178 let output = Command::new("wslpath").arg("-u").arg(windows_path).output().ok()?;
179 if !output.status.success() {
180 return None;
181 }
182 let text = String::from_utf8(output.stdout).ok()?;
183 let trimmed = text.trim();
184 (!trimmed.is_empty()).then(|| trimmed.to_owned())
185}
186
187pub(crate) fn parse_windows_variables(output: &str) -> Option<HashMap<String, String>> {
188 let line = output.lines().map(str::trim).rfind(|line| !line.is_empty())?;
189 let values: Vec<&str> = line.split(';').collect();
190 if values.len() != WINDOWS_VARIABLES.len() {
191 return None;
192 }
193 let map: HashMap<String, String> = WINDOWS_VARIABLES
194 .iter()
195 .zip(values)
196 .filter(|(name, value)| *value != format!("%{name}%"))
197 .map(|(name, value)| ((*name).to_owned(), value.to_owned()))
198 .collect();
199 map.contains_key("LOCALAPPDATA").then_some(map)
200}
201
202fn wsl_windows_variables() -> Result<HashMap<String, String>, BrowserError> {
203 let echo = WINDOWS_VARIABLES.iter().map(|name| format!("%{name}%")).collect::<Vec<_>>().join(";");
204 let output = Command::new("/mnt/c/Windows/System32/cmd.exe")
205 .args(["/c", &format!("echo {echo}")])
206 .current_dir("/mnt/c")
207 .output()
208 .map_err(|error| BrowserError::Environment(format!("cmd.exe: {error}")))?;
209 parse_windows_variables(&String::from_utf8_lossy(&output.stdout))
210 .ok_or_else(|| BrowserError::Environment("cmd.exe returned no %LOCALAPPDATA%".into()))
211}
212
213#[cfg(test)]
214mod tests {
215 use super::*;
216 use std::ffi::OsString;
217
218 fn windows_inputs(to_local: &dyn Fn(&str) -> String) -> ConfigInputs<'_> {
219 let variables = [
220 ("LOCALAPPDATA", r"C:\Users\me\AppData\Local"),
221 ("PROGRAMFILES", r"C:\Program Files"),
222 ("PROGRAMFILES(X86)", r"C:\Program Files (x86)"),
223 ];
224 ConfigInputs {
225 windows_variables: variables.iter().map(|(k, v)| ((*k).into(), (*v).into())).collect(),
226 linux_data_dir: None,
227 to_local,
228 }
229 }
230
231 #[test]
232 fn detects_platform_from_proc_version() {
233 let wsl = "Linux version 6.18.33.2-microsoft-standard-WSL2 (root@x)";
234 assert_eq!(Platform::from_proc_version(Some(wsl)), Platform::Wsl);
235 assert_eq!(Platform::from_proc_version(Some("Linux version 6.8.0-generic")), Platform::Linux);
236 assert_eq!(Platform::from_proc_version(None), Platform::Linux);
237 }
238
239 #[test]
240 fn converts_windows_paths() {
241 assert_eq!(windows_path_to_wsl(r"C:\Users\me\x.mode"), "/mnt/c/Users/me/x.mode");
242 assert_eq!(windows_path_to_wsl(r"D:\a"), "/mnt/d/a");
243 }
244
245 #[test]
246 fn resolves_wsl_config() {
247 let to_local = |path: &str| windows_path_to_wsl(path);
248 let config = Config::resolve(Platform::Wsl, 9222, &windows_inputs(&to_local)).unwrap();
249 assert_eq!(config.profile, r"C:\Users\me\AppData\Local\rusty-teams-chrome");
250 assert_eq!(
251 config.mode_file,
252 PathBuf::from("/mnt/c/Users/me/AppData/Local/rusty-teams-chrome.mode")
253 );
254 let ChromeSearch::Files(files) = &config.chrome_search else { panic!("expected files") };
255 assert_eq!(files[0], PathBuf::from("/mnt/c/Program Files/Google/Chrome/Application/chrome.exe"));
256 assert_eq!(files.len(), 3);
257 }
258
259 #[test]
260 fn resolves_windows_config_without_conversion() {
261 let to_local = |path: &str| path.to_owned();
262 let config = Config::resolve(Platform::Windows, 9222, &windows_inputs(&to_local)).unwrap();
263 assert_eq!(config.mode_file, PathBuf::from(r"C:\Users\me\AppData\Local\rusty-teams-chrome.mode"));
264 }
265
266 #[test]
267 fn native_windows_uses_the_app_profile_and_chrome_install_dirs() {
268 let to_local = |path: &str| path.to_owned();
269 let config = Config::resolve(Platform::Windows, 9222, &windows_inputs(&to_local)).unwrap();
270 assert_eq!(config.profile, r"C:\Users\me\AppData\Local\rusty-teams-chrome");
271 let ChromeSearch::Files(files) = &config.chrome_search else { panic!("expected files") };
272 let expected = [
273 r"C:\Program Files\Google\Chrome\Application\chrome.exe",
274 r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
275 r"C:\Users\me\AppData\Local\Google\Chrome\Application\chrome.exe",
276 ];
277 assert_eq!(files.iter().map(|file| file.to_string_lossy().into_owned()).collect::<Vec<_>>(), expected);
278 }
279
280 #[test]
281 fn native_windows_with_only_localappdata_still_finds_a_per_user_chrome() {
282 let to_local = |path: &str| path.to_owned();
283 let inputs = ConfigInputs {
284 windows_variables: [("LOCALAPPDATA".to_owned(), r"D:\L".to_owned())].into(),
285 linux_data_dir: None,
286 to_local: &to_local,
287 };
288 let config = Config::resolve(Platform::Windows, 9222, &inputs).unwrap();
289 let ChromeSearch::Files(files) = &config.chrome_search else { panic!("expected files") };
290 assert_eq!(files, &[PathBuf::from(r"D:\L\Google\Chrome\Application\chrome.exe")]);
291 assert_eq!(config.with_profile_name("x").profile, r"D:\L\x");
292 }
293
294 #[test]
295 fn wsl_profile_stays_a_windows_path_while_files_are_mounted() {
296 let to_local = |path: &str| windows_path_to_wsl(path);
297 let config = Config::resolve(Platform::Wsl, 9222, &windows_inputs(&to_local)).unwrap();
298 assert!(config.profile.starts_with(r"C:\"));
299 assert!(config.mode_file.starts_with("/mnt/c"));
300 }
301
302 #[test]
303 fn resolves_linux_config_under_xdg_data_dir() {
304 let to_local = |path: &str| path.to_owned();
305 let inputs = ConfigInputs {
306 windows_variables: HashMap::new(),
307 linux_data_dir: Some(PathBuf::from("/home/u/.local/share")),
308 to_local: &to_local,
309 };
310 let config = Config::resolve(Platform::Linux, 9222, &inputs).unwrap();
311 assert_eq!(config.profile, "/home/u/.local/share/rusty-teams-chrome");
312 assert_eq!(config.mode_file, PathBuf::from("/home/u/.local/share/rusty-teams-chrome.mode"));
313 }
314
315 #[test]
316 fn missing_localappdata_is_an_error() {
317 let to_local = |path: &str| path.to_owned();
318 let inputs = ConfigInputs { windows_variables: HashMap::new(), linux_data_dir: None, to_local: &to_local };
319 assert!(Config::resolve(Platform::Windows, 9222, &inputs).is_err());
320 }
321
322 #[test]
323 fn overrides_port_and_profile_name() {
324 let to_local = |path: &str| windows_path_to_wsl(path);
325 let config = Config::resolve(Platform::Wsl, 9222, &windows_inputs(&to_local))
326 .unwrap()
327 .with_port(9333)
328 .with_profile_name("rusty-teams-chrome-test");
329 assert_eq!(config.port, 9333);
330 assert_eq!(config.profile, r"C:\Users\me\AppData\Local\rusty-teams-chrome-test");
331 assert!(config.mode_file.ends_with("rusty-teams-chrome-test.mode"));
332 }
333
334 #[test]
335 fn parses_cmd_output_with_crlf_and_unset_variables() {
336 let output = "\r\nC:\\L;C:\\PF;%PROGRAMFILES(X86)%;C:\\T\r\n";
337 let map = parse_windows_variables(output).unwrap();
338 assert_eq!(map["LOCALAPPDATA"], r"C:\L");
339 assert_eq!(map["TEMP"], r"C:\T");
340 assert!(!map.contains_key("PROGRAMFILES(X86)"));
341 assert!(parse_windows_variables("%LOCALAPPDATA%;a;b;c").is_none());
342 assert!(parse_windows_variables("garbage").is_none());
343 }
344
345 #[test]
346 fn finds_first_existing_candidate() {
347 let search = ChromeSearch::Files(vec!["/a/chrome.exe".into(), "/b/chrome.exe".into()]);
348 let found = find_chrome(&search, &OsString::new(), &|path| path.starts_with("/b")).unwrap();
349 assert_eq!(found, PathBuf::from("/b/chrome.exe"));
350 assert!(find_chrome(&search, &OsString::new(), &|_| false).is_err());
351 }
352
353 #[test]
354 fn finds_named_chrome_on_path_in_name_priority_per_directory() {
355 let search = ChromeSearch::Named(vec!["google-chrome".into(), "chromium".into()]);
356 // join_paths picks the host's PATH separator so split_paths splits it here too.
357 let path = std::env::join_paths(["/usr/local/bin", "/usr/bin"]).unwrap();
358 let found = find_chrome(&search, &path, &|candidate| {
359 candidate == Path::new("/usr/bin/chromium") || candidate == Path::new("/usr/bin/google-chrome")
360 })
361 .unwrap();
362 assert_eq!(found, PathBuf::from("/usr/bin/google-chrome"));
363 }
364}