BlueGit

ict rusty-teams

Files

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

config.rs

config.rs 20.8 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",
13 "google-chrome-stable",
14 "chromium",
15 "chromium-browser",
16 "chrome",
17];
18const MACOS_CHROME_NAMES: [&str; 3] = ["google-chrome", "chromium", "chrome"];
19const MACOS_CHROME_APP_PATHS: [&str; 2] = [
20 "Google Chrome.app/Contents/MacOS/Google Chrome",
21 "Chromium.app/Contents/MacOS/Chromium",
22];
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum Platform {
26 Wsl,
27 Windows,
28 Linux,
29 Macos,
30}
31
32impl Platform {
33 pub fn detect() -> Platform {
34 if cfg!(windows) {
35 return Platform::Windows;
36 }
37 if cfg!(target_os = "macos") {
38 return Platform::Macos;
39 }
40 let proc_version = std::fs::read_to_string("/proc/version").ok();
41 Platform::from_proc_version(proc_version.as_deref())
42 }
43
44 pub fn from_proc_version(content: Option<&str>) -> Platform {
45 match content {
46 Some(text) if text.to_ascii_lowercase().contains("microsoft") => Platform::Wsl,
47 _ => Platform::Linux,
48 }
49 }
50
51 pub fn uses_unix_paths(self) -> bool {
52 matches!(self, Platform::Linux | Platform::Macos)
53 }
54}
55
56#[derive(Debug, Clone)]
57pub(crate) enum ChromeSearch {
58 Files(Vec<PathBuf>),
59 Named(Vec<String>),
60 /// Absolute install paths first, then PATH names (macOS Application bundles + CLI).
61 FilesThenNamed {
62 files: Vec<PathBuf>,
63 names: Vec<String>,
64 },
65}
66
67#[derive(Debug, Clone)]
68pub struct Config {
69 pub platform: Platform,
70 pub port: u16,
71 pub profile: String,
72 pub mode_file: PathBuf,
73 profile_parent: String,
74 mode_parent: PathBuf,
75 pub(crate) chrome_search: ChromeSearch,
76}
77
78pub struct ConfigInputs<'a> {
79 pub windows_variables: HashMap<String, String>,
80 pub linux_data_dir: Option<PathBuf>,
81 pub home_dir: Option<PathBuf>,
82 pub to_local: &'a dyn Fn(&str) -> String,
83}
84
85impl Config {
86 pub fn detect() -> Result<Config, BrowserError> {
87 let platform = Platform::detect();
88 let windows_variables = match platform {
89 Platform::Linux | Platform::Macos => HashMap::new(),
90 Platform::Windows => WINDOWS_VARIABLES
91 .iter()
92 .filter_map(|name| {
93 std::env::var(name)
94 .ok()
95 .map(|value| ((*name).to_owned(), value))
96 })
97 .collect(),
98 Platform::Wsl => wsl_windows_variables()?,
99 };
100 let base = directories::BaseDirs::new();
101 let linux_data_dir = base.as_ref().map(|dirs| dirs.data_dir().to_path_buf());
102 let home_dir = base.as_ref().map(|dirs| dirs.home_dir().to_path_buf());
103 let to_local = |windows_path: &str| match platform {
104 Platform::Wsl => {
105 wslpath(windows_path).unwrap_or_else(|| windows_path_to_wsl(windows_path))
106 }
107 _ => windows_path.to_owned(),
108 };
109 Config::resolve(
110 platform,
111 DEFAULT_PORT,
112 &ConfigInputs {
113 windows_variables,
114 linux_data_dir,
115 home_dir,
116 to_local: &to_local,
117 },
118 )
119 }
120
121 pub fn resolve(
122 platform: Platform,
123 port: u16,
124 inputs: &ConfigInputs,
125 ) -> Result<Config, BrowserError> {
126 let to_local = inputs.to_local;
127 let missing = |name: &str| BrowserError::Environment(format!("%{name}% is not set"));
128 let config = match platform {
129 Platform::Linux => {
130 let data_dir = inputs
131 .linux_data_dir
132 .clone()
133 .ok_or_else(|| BrowserError::Environment("no XDG data directory".into()))?;
134 Config {
135 platform,
136 port,
137 // Built with the platform's '/' like with_profile_name, not the
138 // host's separator: the string is a Linux path whoever builds it.
139 profile: format!("{}/{}", path_text(&data_dir), PROFILE_NAME),
140 mode_file: data_dir.join(format!("{PROFILE_NAME}.mode")),
141 profile_parent: path_text(&data_dir),
142 mode_parent: data_dir,
143 chrome_search: ChromeSearch::Named(
144 LINUX_CHROME_NAMES
145 .iter()
146 .map(|name| (*name).to_owned())
147 .collect(),
148 ),
149 }
150 }
151 Platform::Macos => {
152 let data_dir = inputs.linux_data_dir.clone().ok_or_else(|| {
153 BrowserError::Environment("no Application Support directory".into())
154 })?;
155 let mut files = Vec::new();
156 for root in [PathBuf::from("/Applications")]
157 .into_iter()
158 .chain(inputs.home_dir.iter().map(|home| home.join("Applications")))
159 {
160 for relative in MACOS_CHROME_APP_PATHS {
161 files.push(root.join(relative));
162 }
163 }
164 Config {
165 platform,
166 port,
167 profile: format!("{}/{}", path_text(&data_dir), PROFILE_NAME),
168 mode_file: data_dir.join(format!("{PROFILE_NAME}.mode")),
169 profile_parent: path_text(&data_dir),
170 mode_parent: data_dir,
171 chrome_search: ChromeSearch::FilesThenNamed {
172 files,
173 names: MACOS_CHROME_NAMES
174 .iter()
175 .map(|name| (*name).to_owned())
176 .collect(),
177 },
178 }
179 }
180 Platform::Windows | Platform::Wsl => {
181 let local = inputs
182 .windows_variables
183 .get("LOCALAPPDATA")
184 .ok_or_else(|| missing("LOCALAPPDATA"))?;
185 let candidates = ["PROGRAMFILES", "PROGRAMFILES(X86)", "LOCALAPPDATA"]
186 .iter()
187 .filter_map(|name| inputs.windows_variables.get(*name))
188 .map(|root| PathBuf::from(to_local(&format!("{root}\\{CHROME_RELATIVE}"))))
189 .collect();
190 Config {
191 platform,
192 port,
193 profile: format!("{local}\\{PROFILE_NAME}"),
194 mode_file: PathBuf::from(to_local(&format!("{local}\\{PROFILE_NAME}.mode"))),
195 profile_parent: local.clone(),
196 mode_parent: PathBuf::from(to_local(local)),
197 chrome_search: ChromeSearch::Files(candidates),
198 }
199 }
200 };
201 Ok(config)
202 }
203
204 pub fn with_port(mut self, port: u16) -> Config {
205 self.port = port;
206 self
207 }
208
209 pub fn with_profile_name(mut self, name: &str) -> Config {
210 let separator = if self.platform.uses_unix_paths() {
211 "/"
212 } else {
213 "\\"
214 };
215 self.profile = format!("{}{separator}{name}", self.profile_parent);
216 self.mode_file = self.mode_parent.join(format!("{name}.mode"));
217 self
218 }
219
220 pub fn chrome_executable(&self) -> Result<PathBuf, BrowserError> {
221 let path_variable = std::env::var_os("PATH").unwrap_or_default();
222 find_chrome(&self.chrome_search, &path_variable, &|path| path.is_file())
223 }
224}
225
226fn path_text(path: &Path) -> String {
227 path.to_string_lossy().into_owned()
228}
229
230fn find_named_chrome(
231 names: &[String],
232 path_variable: &std::ffi::OsStr,
233 exists: &dyn Fn(&Path) -> bool,
234) -> Option<PathBuf> {
235 std::env::split_paths(path_variable)
236 .flat_map(|directory| names.iter().map(move |name| directory.join(name)))
237 .find(|candidate| exists(candidate))
238}
239
240pub(crate) fn find_chrome(
241 search: &ChromeSearch,
242 path_variable: &std::ffi::OsStr,
243 exists: &dyn Fn(&Path) -> bool,
244) -> Result<PathBuf, BrowserError> {
245 match search {
246 ChromeSearch::Files(candidates) => candidates
247 .iter()
248 .find(|candidate| exists(candidate))
249 .cloned()
250 .ok_or_else(|| {
251 BrowserError::ChromeNotFound("not under Program Files or LocalAppData".into())
252 }),
253 ChromeSearch::Named(names) => {
254 find_named_chrome(names, path_variable, exists).ok_or_else(|| {
255 BrowserError::ChromeNotFound(format!("none of {} on PATH", names.join(", ")))
256 })
257 }
258 ChromeSearch::FilesThenNamed { files, names } => files
259 .iter()
260 .find(|candidate| exists(candidate))
261 .cloned()
262 .or_else(|| find_named_chrome(names, path_variable, exists))
263 .ok_or_else(|| {
264 BrowserError::ChromeNotFound(
265 "not under /Applications, ~/Applications, or PATH".into(),
266 )
267 }),
268 }
269}
270
271pub fn windows_path_to_wsl(windows_path: &str) -> String {
272 match windows_path.split_once(':') {
273 Some((drive, rest)) if drive.len() == 1 => {
274 format!(
275 "/mnt/{}{}",
276 drive.to_ascii_lowercase(),
277 rest.replace('\\', "/")
278 )
279 }
280 _ => windows_path.replace('\\', "/"),
281 }
282}
283
284fn wslpath(windows_path: &str) -> Option<String> {
285 let output = Command::new("wslpath")
286 .arg("-u")
287 .arg(windows_path)
288 .output()
289 .ok()?;
290 if !output.status.success() {
291 return None;
292 }
293 let text = String::from_utf8(output.stdout).ok()?;
294 let trimmed = text.trim();
295 (!trimmed.is_empty()).then(|| trimmed.to_owned())
296}
297
298pub(crate) fn parse_windows_variables(output: &str) -> Option<HashMap<String, String>> {
299 let line = output
300 .lines()
301 .map(str::trim)
302 .rfind(|line| !line.is_empty())?;
303 let values: Vec<&str> = line.split(';').collect();
304 if values.len() != WINDOWS_VARIABLES.len() {
305 return None;
306 }
307 let map: HashMap<String, String> = WINDOWS_VARIABLES
308 .iter()
309 .zip(values)
310 .filter(|(name, value)| *value != format!("%{name}%"))
311 .map(|(name, value)| ((*name).to_owned(), value.to_owned()))
312 .collect();
313 map.contains_key("LOCALAPPDATA").then_some(map)
314}
315
316fn wsl_windows_variables() -> Result<HashMap<String, String>, BrowserError> {
317 let echo = WINDOWS_VARIABLES
318 .iter()
319 .map(|name| format!("%{name}%"))
320 .collect::<Vec<_>>()
321 .join(";");
322 let output = Command::new("/mnt/c/Windows/System32/cmd.exe")
323 .args(["/c", &format!("echo {echo}")])
324 .current_dir("/mnt/c")
325 .output()
326 .map_err(|error| BrowserError::Environment(format!("cmd.exe: {error}")))?;
327 parse_windows_variables(&String::from_utf8_lossy(&output.stdout))
328 .ok_or_else(|| BrowserError::Environment("cmd.exe returned no %LOCALAPPDATA%".into()))
329}
330
331#[cfg(test)]
332mod tests {
333 use super::*;
334 use std::ffi::OsString;
335
336 fn windows_inputs(to_local: &dyn Fn(&str) -> String) -> ConfigInputs<'_> {
337 let variables = [
338 ("LOCALAPPDATA", r"C:\Users\me\AppData\Local"),
339 ("PROGRAMFILES", r"C:\Program Files"),
340 ("PROGRAMFILES(X86)", r"C:\Program Files (x86)"),
341 ];
342 ConfigInputs {
343 windows_variables: variables
344 .iter()
345 .map(|(k, v)| ((*k).into(), (*v).into()))
346 .collect(),
347 linux_data_dir: None,
348 home_dir: None,
349 to_local,
350 }
351 }
352
353 #[test]
354 fn detects_platform_from_proc_version() {
355 let wsl = "Linux version 6.18.33.2-microsoft-standard-WSL2 (root@x)";
356 assert_eq!(Platform::from_proc_version(Some(wsl)), Platform::Wsl);
357 assert_eq!(
358 Platform::from_proc_version(Some("Linux version 6.8.0-generic")),
359 Platform::Linux
360 );
361 assert_eq!(Platform::from_proc_version(None), Platform::Linux);
362 }
363
364 #[test]
365 fn converts_windows_paths() {
366 assert_eq!(
367 windows_path_to_wsl(r"C:\Users\me\x.mode"),
368 "/mnt/c/Users/me/x.mode"
369 );
370 assert_eq!(windows_path_to_wsl(r"D:\a"), "/mnt/d/a");
371 }
372
373 #[test]
374 fn resolves_wsl_config() {
375 let to_local = |path: &str| windows_path_to_wsl(path);
376 let config = Config::resolve(Platform::Wsl, 9222, &windows_inputs(&to_local)).unwrap();
377 assert_eq!(
378 config.profile,
379 r"C:\Users\me\AppData\Local\rusty-teams-chrome"
380 );
381 assert_eq!(
382 config.mode_file,
383 PathBuf::from("/mnt/c/Users/me/AppData/Local/rusty-teams-chrome.mode")
384 );
385 let ChromeSearch::Files(files) = &config.chrome_search else {
386 panic!("expected files")
387 };
388 assert_eq!(
389 files[0],
390 PathBuf::from("/mnt/c/Program Files/Google/Chrome/Application/chrome.exe")
391 );
392 assert_eq!(files.len(), 3);
393 }
394
395 #[test]
396 fn resolves_windows_config_without_conversion() {
397 let to_local = |path: &str| path.to_owned();
398 let config = Config::resolve(Platform::Windows, 9222, &windows_inputs(&to_local)).unwrap();
399 assert_eq!(
400 config.mode_file,
401 PathBuf::from(r"C:\Users\me\AppData\Local\rusty-teams-chrome.mode")
402 );
403 }
404
405 #[test]
406 fn native_windows_uses_the_app_profile_and_chrome_install_dirs() {
407 let to_local = |path: &str| path.to_owned();
408 let config = Config::resolve(Platform::Windows, 9222, &windows_inputs(&to_local)).unwrap();
409 assert_eq!(
410 config.profile,
411 r"C:\Users\me\AppData\Local\rusty-teams-chrome"
412 );
413 let ChromeSearch::Files(files) = &config.chrome_search else {
414 panic!("expected files")
415 };
416 let expected = [
417 r"C:\Program Files\Google\Chrome\Application\chrome.exe",
418 r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
419 r"C:\Users\me\AppData\Local\Google\Chrome\Application\chrome.exe",
420 ];
421 assert_eq!(
422 files
423 .iter()
424 .map(|file| file.to_string_lossy().into_owned())
425 .collect::<Vec<_>>(),
426 expected
427 );
428 }
429
430 #[test]
431 fn native_windows_with_only_localappdata_still_finds_a_per_user_chrome() {
432 let to_local = |path: &str| path.to_owned();
433 let inputs = ConfigInputs {
434 windows_variables: [("LOCALAPPDATA".to_owned(), r"D:\L".to_owned())].into(),
435 linux_data_dir: None,
436 home_dir: None,
437 to_local: &to_local,
438 };
439 let config = Config::resolve(Platform::Windows, 9222, &inputs).unwrap();
440 let ChromeSearch::Files(files) = &config.chrome_search else {
441 panic!("expected files")
442 };
443 assert_eq!(
444 files,
445 &[PathBuf::from(r"D:\L\Google\Chrome\Application\chrome.exe")]
446 );
447 assert_eq!(config.with_profile_name("x").profile, r"D:\L\x");
448 }
449
450 #[test]
451 fn wsl_profile_stays_a_windows_path_while_files_are_mounted() {
452 let to_local = |path: &str| windows_path_to_wsl(path);
453 let config = Config::resolve(Platform::Wsl, 9222, &windows_inputs(&to_local)).unwrap();
454 assert!(config.profile.starts_with(r"C:\"));
455 assert!(config.mode_file.starts_with("/mnt/c"));
456 }
457
458 #[test]
459 fn resolves_linux_config_under_xdg_data_dir() {
460 let to_local = |path: &str| path.to_owned();
461 let inputs = ConfigInputs {
462 windows_variables: HashMap::new(),
463 linux_data_dir: Some(PathBuf::from("/home/u/.local/share")),
464 home_dir: None,
465 to_local: &to_local,
466 };
467 let config = Config::resolve(Platform::Linux, 9222, &inputs).unwrap();
468 assert_eq!(config.profile, "/home/u/.local/share/rusty-teams-chrome");
469 assert_eq!(
470 config.mode_file,
471 PathBuf::from("/home/u/.local/share/rusty-teams-chrome.mode")
472 );
473 }
474
475 #[test]
476 fn resolves_macos_config_under_application_support() {
477 let to_local = |path: &str| path.to_owned();
478 let inputs = ConfigInputs {
479 windows_variables: HashMap::new(),
480 linux_data_dir: Some(PathBuf::from("/Users/joe/Library/Application Support")),
481 home_dir: Some(PathBuf::from("/Users/joe")),
482 to_local: &to_local,
483 };
484 let config = Config::resolve(Platform::Macos, 9222, &inputs).unwrap();
485 assert_eq!(
486 config.profile,
487 "/Users/joe/Library/Application Support/rusty-teams-chrome"
488 );
489 assert_eq!(
490 config.mode_file,
491 PathBuf::from("/Users/joe/Library/Application Support/rusty-teams-chrome.mode")
492 );
493 let ChromeSearch::FilesThenNamed { files, names } = &config.chrome_search else {
494 panic!("expected files then named")
495 };
496 assert_eq!(
497 files[0],
498 PathBuf::from("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome")
499 );
500 assert_eq!(
501 files[2],
502 PathBuf::from("/Users/joe/Applications/Google Chrome.app/Contents/MacOS/Google Chrome")
503 );
504 assert!(names.iter().any(|name| name == "google-chrome"));
505 assert_eq!(
506 config.with_profile_name("x").profile,
507 "/Users/joe/Library/Application Support/x"
508 );
509 }
510
511 #[test]
512 fn missing_localappdata_is_an_error() {
513 let to_local = |path: &str| path.to_owned();
514 let inputs = ConfigInputs {
515 windows_variables: HashMap::new(),
516 linux_data_dir: None,
517 home_dir: None,
518 to_local: &to_local,
519 };
520 assert!(Config::resolve(Platform::Windows, 9222, &inputs).is_err());
521 }
522
523 #[test]
524 fn finds_macos_chrome_under_applications_before_path() {
525 let search = ChromeSearch::FilesThenNamed {
526 files: vec![
527 "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome".into(),
528 "/Users/joe/Applications/Chromium.app/Contents/MacOS/Chromium".into(),
529 ],
530 names: vec!["google-chrome".into()],
531 };
532 let path = std::env::join_paths(["/usr/local/bin"]).unwrap();
533 let found = find_chrome(&search, &path, &|candidate| {
534 candidate.ends_with("Google Chrome") || candidate.ends_with("google-chrome")
535 })
536 .unwrap();
537 assert_eq!(
538 found,
539 PathBuf::from("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome")
540 );
541 }
542
543 #[test]
544 fn overrides_port_and_profile_name() {
545 let to_local = |path: &str| windows_path_to_wsl(path);
546 let config = Config::resolve(Platform::Wsl, 9222, &windows_inputs(&to_local))
547 .unwrap()
548 .with_port(9333)
549 .with_profile_name("rusty-teams-chrome-test");
550 assert_eq!(config.port, 9333);
551 assert_eq!(
552 config.profile,
553 r"C:\Users\me\AppData\Local\rusty-teams-chrome-test"
554 );
555 assert!(config.mode_file.ends_with("rusty-teams-chrome-test.mode"));
556 }
557
558 #[test]
559 fn parses_cmd_output_with_crlf_and_unset_variables() {
560 let output = "\r\nC:\\L;C:\\PF;%PROGRAMFILES(X86)%;C:\\T\r\n";
561 let map = parse_windows_variables(output).unwrap();
562 assert_eq!(map["LOCALAPPDATA"], r"C:\L");
563 assert_eq!(map["TEMP"], r"C:\T");
564 assert!(!map.contains_key("PROGRAMFILES(X86)"));
565 assert!(parse_windows_variables("%LOCALAPPDATA%;a;b;c").is_none());
566 assert!(parse_windows_variables("garbage").is_none());
567 }
568
569 #[test]
570 fn finds_first_existing_candidate() {
571 let search = ChromeSearch::Files(vec!["/a/chrome.exe".into(), "/b/chrome.exe".into()]);
572 let found = find_chrome(&search, &OsString::new(), &|path| path.starts_with("/b")).unwrap();
573 assert_eq!(found, PathBuf::from("/b/chrome.exe"));
574 assert!(find_chrome(&search, &OsString::new(), &|_| false).is_err());
575 }
576
577 #[test]
578 fn finds_named_chrome_on_path_in_name_priority_per_directory() {
579 let search = ChromeSearch::Named(vec!["google-chrome".into(), "chromium".into()]);
580 // join_paths picks the host's PATH separator so split_paths splits it here too.
581 let path = std::env::join_paths(["/usr/local/bin", "/usr/bin"]).unwrap();
582 let found = find_chrome(&search, &path, &|candidate| {
583 candidate == Path::new("/usr/bin/chromium")
584 || candidate == Path::new("/usr/bin/google-chrome")
585 })
586 .unwrap();
587 assert_eq!(found, PathBuf::from("/usr/bin/google-chrome"));
588 }
589}