BlueGit

ict rusty-teams

Files

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

config.rs

config.rs 26.5 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 FIREFOX_PROFILE_NAME: &str = "rusty-teams-firefox";
9pub const DEFAULT_PORT: u16 = 9222;
10const CHROME_RELATIVE: &str = r"Google\Chrome\Application\chrome.exe";
11const WINDOWS_VARIABLES: [&str; 4] = ["LOCALAPPDATA", "PROGRAMFILES", "PROGRAMFILES(X86)", "TEMP"];
12pub(crate) const LINUX_CHROME_NAMES: [&str; 5] = [
13 "google-chrome",
14 "google-chrome-stable",
15 "chromium",
16 "chromium-browser",
17 "chrome",
18];
19const MACOS_CHROME_NAMES: [&str; 3] = ["google-chrome", "chromium", "chrome"];
20/// Chromium-based browsers in order of preference; each one gets its own profile, so the user's
21/// everyday browser stays untouched.
22pub(crate) const MACOS_CHROME_APP_PATHS: [&str; 6] = [
23 "Google Chrome.app/Contents/MacOS/Google Chrome",
24 "Chromium.app/Contents/MacOS/Chromium",
25 "Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
26 "Brave Browser.app/Contents/MacOS/Brave Browser",
27 "Helium.app/Contents/MacOS/Helium",
28 "Vivaldi.app/Contents/MacOS/Vivaldi",
29];
30/// Firefox-based browsers, tried only when no Chromium browser is installed.
31pub(crate) const MACOS_FIREFOX_APP_PATHS: [&str; 4] = [
32 "Firefox.app/Contents/MacOS/firefox",
33 "Zen.app/Contents/MacOS/zen",
34 "LibreWolf.app/Contents/MacOS/librewolf",
35 "Floorp.app/Contents/MacOS/floorp",
36];
37pub(crate) const LINUX_FIREFOX_NAMES: [&str; 5] =
38 ["firefox", "zen-browser", "zen", "librewolf", "floorp"];
39
40/// The protocol family of the sign-in browser: Chromium speaks CDP, Firefox WebDriver BiDi.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum Engine {
43 Chromium,
44 Firefox,
45}
46
47impl Engine {
48 pub fn of_executable(path: &Path) -> Engine {
49 if crate::process::is_firefox_image(&path.to_string_lossy()) {
50 Engine::Firefox
51 } else {
52 Engine::Chromium
53 }
54 }
55}
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum Platform {
59 Wsl,
60 Windows,
61 Linux,
62 Macos,
63}
64
65impl Platform {
66 pub fn detect() -> Platform {
67 if cfg!(windows) {
68 return Platform::Windows;
69 }
70 if cfg!(target_os = "macos") {
71 return Platform::Macos;
72 }
73 let proc_version = std::fs::read_to_string("/proc/version").ok();
74 Platform::from_proc_version(proc_version.as_deref())
75 }
76
77 pub fn from_proc_version(content: Option<&str>) -> Platform {
78 match content {
79 Some(text) if text.to_ascii_lowercase().contains("microsoft") => Platform::Wsl,
80 _ => Platform::Linux,
81 }
82 }
83
84 pub fn uses_unix_paths(self) -> bool {
85 matches!(self, Platform::Linux | Platform::Macos)
86 }
87}
88
89#[derive(Debug, Clone)]
90pub(crate) enum BrowserSearch {
91 Files(Vec<PathBuf>),
92 Named(Vec<String>),
93 /// Absolute install paths first, then PATH names (macOS Application bundles + CLI).
94 FilesThenNamed {
95 files: Vec<PathBuf>,
96 names: Vec<String>,
97 },
98}
99
100#[derive(Debug, Clone)]
101pub struct Config {
102 pub platform: Platform,
103 pub engine: Engine,
104 pub port: u16,
105 pub profile: String,
106 pub mode_file: PathBuf,
107 profile_parent: String,
108 mode_parent: PathBuf,
109 pub(crate) search: BrowserSearch,
110}
111
112pub struct ConfigInputs<'a> {
113 pub windows_variables: HashMap<String, String>,
114 pub linux_data_dir: Option<PathBuf>,
115 pub home_dir: Option<PathBuf>,
116 pub to_local: &'a dyn Fn(&str) -> String,
117}
118
119impl Config {
120 pub fn detect() -> Result<Config, BrowserError> {
121 let platform = Platform::detect();
122 let windows_variables = match platform {
123 Platform::Linux | Platform::Macos => HashMap::new(),
124 Platform::Windows => WINDOWS_VARIABLES
125 .iter()
126 .filter_map(|name| {
127 std::env::var(name)
128 .ok()
129 .map(|value| ((*name).to_owned(), value))
130 })
131 .collect(),
132 Platform::Wsl => wsl_windows_variables()?,
133 };
134 let base = directories::BaseDirs::new();
135 let linux_data_dir = base.as_ref().map(|dirs| dirs.data_dir().to_path_buf());
136 let home_dir = base.as_ref().map(|dirs| dirs.home_dir().to_path_buf());
137 let to_local = |windows_path: &str| match platform {
138 Platform::Wsl => {
139 wslpath(windows_path).unwrap_or_else(|| windows_path_to_wsl(windows_path))
140 }
141 _ => windows_path.to_owned(),
142 };
143 let config = Config::resolve(
144 platform,
145 DEFAULT_PORT,
146 &ConfigInputs {
147 windows_variables,
148 linux_data_dir,
149 home_dir: home_dir.clone(),
150 to_local: &to_local,
151 },
152 )?;
153 let path_variable = std::env::var_os("PATH").unwrap_or_default();
154 let chosen = crate::sign_in_choice::chosen_executable(platform, home_dir.as_deref());
155 Ok(
156 config.select_browser(chosen, home_dir.as_deref(), &path_variable, &|path| {
157 path.is_file()
158 }),
159 )
160 }
161
162 /// Uses `chosen` as the sign-in browser, else the first Chromium browser, else the first
163 /// Firefox-based one on Linux and macOS. A Firefox browser gets its own profile.
164 pub(crate) fn select_browser(
165 mut self,
166 chosen: Option<PathBuf>,
167 home_dir: Option<&Path>,
168 path_variable: &std::ffi::OsStr,
169 exists: &dyn Fn(&Path) -> bool,
170 ) -> Config {
171 if let Some(path) = chosen {
172 self.engine = Engine::of_executable(&path);
173 self.search = BrowserSearch::Files(vec![path]);
174 } else if find_browser(&self.search, path_variable, exists).is_err()
175 && let Some(search) = firefox_search(self.platform, home_dir)
176 && find_browser(&search, path_variable, exists).is_ok()
177 {
178 self.engine = Engine::Firefox;
179 self.search = search;
180 }
181 if self.engine == Engine::Firefox {
182 self = self.with_profile_name(FIREFOX_PROFILE_NAME);
183 }
184 self
185 }
186
187 pub fn resolve(
188 platform: Platform,
189 port: u16,
190 inputs: &ConfigInputs,
191 ) -> Result<Config, BrowserError> {
192 let to_local = inputs.to_local;
193 let missing = |name: &str| BrowserError::Environment(format!("%{name}% is not set"));
194 let config = match platform {
195 Platform::Linux => {
196 let data_dir = inputs
197 .linux_data_dir
198 .clone()
199 .ok_or_else(|| BrowserError::Environment("no XDG data directory".into()))?;
200 Config {
201 platform,
202 engine: Engine::Chromium,
203 port,
204 // Built with the platform's '/' like with_profile_name, not the
205 // host's separator: the string is a Linux path whoever builds it.
206 profile: format!("{}/{}", path_text(&data_dir), PROFILE_NAME),
207 mode_file: data_dir.join(format!("{PROFILE_NAME}.mode")),
208 profile_parent: path_text(&data_dir),
209 mode_parent: data_dir,
210 search: BrowserSearch::Named(
211 LINUX_CHROME_NAMES
212 .iter()
213 .map(|name| (*name).to_owned())
214 .collect(),
215 ),
216 }
217 }
218 Platform::Macos => {
219 let data_dir = inputs.linux_data_dir.clone().ok_or_else(|| {
220 BrowserError::Environment("no Application Support directory".into())
221 })?;
222 let files = application_roots(inputs.home_dir.as_deref())
223 .flat_map(|root| MACOS_CHROME_APP_PATHS.map(|relative| root.join(relative)))
224 .collect();
225 Config {
226 platform,
227 engine: Engine::Chromium,
228 port,
229 profile: format!("{}/{}", path_text(&data_dir), PROFILE_NAME),
230 mode_file: data_dir.join(format!("{PROFILE_NAME}.mode")),
231 profile_parent: path_text(&data_dir),
232 mode_parent: data_dir,
233 search: BrowserSearch::FilesThenNamed {
234 files,
235 names: MACOS_CHROME_NAMES
236 .iter()
237 .map(|name| (*name).to_owned())
238 .collect(),
239 },
240 }
241 }
242 Platform::Windows | Platform::Wsl => {
243 let local = inputs
244 .windows_variables
245 .get("LOCALAPPDATA")
246 .ok_or_else(|| missing("LOCALAPPDATA"))?;
247 let candidates = ["PROGRAMFILES", "PROGRAMFILES(X86)", "LOCALAPPDATA"]
248 .iter()
249 .filter_map(|name| inputs.windows_variables.get(*name))
250 .map(|root| PathBuf::from(to_local(&format!("{root}\\{CHROME_RELATIVE}"))))
251 .collect();
252 Config {
253 platform,
254 engine: Engine::Chromium,
255 port,
256 profile: format!("{local}\\{PROFILE_NAME}"),
257 mode_file: PathBuf::from(to_local(&format!("{local}\\{PROFILE_NAME}.mode"))),
258 profile_parent: local.clone(),
259 mode_parent: PathBuf::from(to_local(local)),
260 search: BrowserSearch::Files(candidates),
261 }
262 }
263 };
264 Ok(config)
265 }
266
267 pub fn with_port(mut self, port: u16) -> Config {
268 self.port = port;
269 self
270 }
271
272 pub fn with_profile_name(mut self, name: &str) -> Config {
273 let separator = if self.platform.uses_unix_paths() {
274 "/"
275 } else {
276 "\\"
277 };
278 self.profile = format!("{}{separator}{name}", self.profile_parent);
279 self.mode_file = self.mode_parent.join(format!("{name}.mode"));
280 self
281 }
282
283 pub fn executable(&self) -> Result<PathBuf, BrowserError> {
284 let path_variable = std::env::var_os("PATH").unwrap_or_default();
285 find_browser(&self.search, &path_variable, &|path| path.is_file())
286 }
287}
288
289fn firefox_search(platform: Platform, home_dir: Option<&Path>) -> Option<BrowserSearch> {
290 let names = || LINUX_FIREFOX_NAMES.iter().map(|name| (*name).to_owned());
291 match platform {
292 Platform::Linux => Some(BrowserSearch::Named(names().collect())),
293 Platform::Macos => Some(BrowserSearch::FilesThenNamed {
294 files: application_roots(home_dir)
295 .flat_map(|root| MACOS_FIREFOX_APP_PATHS.map(|relative| root.join(relative)))
296 .collect(),
297 names: names().collect(),
298 }),
299 Platform::Windows | Platform::Wsl => None,
300 }
301}
302
303pub(crate) fn application_roots(home_dir: Option<&Path>) -> impl Iterator<Item = PathBuf> {
304 std::iter::once(PathBuf::from("/Applications"))
305 .chain(home_dir.map(|home| home.join("Applications")))
306}
307
308fn path_text(path: &Path) -> String {
309 path.to_string_lossy().into_owned()
310}
311
312fn find_named_chrome(
313 names: &[String],
314 path_variable: &std::ffi::OsStr,
315 exists: &dyn Fn(&Path) -> bool,
316) -> Option<PathBuf> {
317 std::env::split_paths(path_variable)
318 .flat_map(|directory| names.iter().map(move |name| directory.join(name)))
319 .find(|candidate| exists(candidate))
320}
321
322pub(crate) fn find_browser(
323 search: &BrowserSearch,
324 path_variable: &std::ffi::OsStr,
325 exists: &dyn Fn(&Path) -> bool,
326) -> Result<PathBuf, BrowserError> {
327 match search {
328 BrowserSearch::Files(candidates) => candidates
329 .iter()
330 .find(|candidate| exists(candidate))
331 .cloned()
332 .ok_or_else(|| {
333 BrowserError::ChromeNotFound("not under Program Files or LocalAppData".into())
334 }),
335 BrowserSearch::Named(names) => {
336 find_named_chrome(names, path_variable, exists).ok_or_else(|| {
337 BrowserError::ChromeNotFound(format!("none of {} on PATH", names.join(", ")))
338 })
339 }
340 BrowserSearch::FilesThenNamed { files, names } => files
341 .iter()
342 .find(|candidate| exists(candidate))
343 .cloned()
344 .or_else(|| find_named_chrome(names, path_variable, exists))
345 .ok_or_else(|| {
346 BrowserError::ChromeNotFound(
347 "no Chromium or Firefox browser under /Applications, ~/Applications, or PATH"
348 .into(),
349 )
350 }),
351 }
352}
353
354pub fn windows_path_to_wsl(windows_path: &str) -> String {
355 match windows_path.split_once(':') {
356 Some((drive, rest)) if drive.len() == 1 => {
357 format!(
358 "/mnt/{}{}",
359 drive.to_ascii_lowercase(),
360 rest.replace('\\', "/")
361 )
362 }
363 _ => windows_path.replace('\\', "/"),
364 }
365}
366
367fn wslpath(windows_path: &str) -> Option<String> {
368 let output = Command::new("wslpath")
369 .arg("-u")
370 .arg(windows_path)
371 .output()
372 .ok()?;
373 if !output.status.success() {
374 return None;
375 }
376 let text = String::from_utf8(output.stdout).ok()?;
377 let trimmed = text.trim();
378 (!trimmed.is_empty()).then(|| trimmed.to_owned())
379}
380
381pub(crate) fn parse_windows_variables(output: &str) -> Option<HashMap<String, String>> {
382 let line = output
383 .lines()
384 .map(str::trim)
385 .rfind(|line| !line.is_empty())?;
386 let values: Vec<&str> = line.split(';').collect();
387 if values.len() != WINDOWS_VARIABLES.len() {
388 return None;
389 }
390 let map: HashMap<String, String> = WINDOWS_VARIABLES
391 .iter()
392 .zip(values)
393 .filter(|(name, value)| *value != format!("%{name}%"))
394 .map(|(name, value)| ((*name).to_owned(), value.to_owned()))
395 .collect();
396 map.contains_key("LOCALAPPDATA").then_some(map)
397}
398
399fn wsl_windows_variables() -> Result<HashMap<String, String>, BrowserError> {
400 let echo = WINDOWS_VARIABLES
401 .iter()
402 .map(|name| format!("%{name}%"))
403 .collect::<Vec<_>>()
404 .join(";");
405 let output = Command::new("/mnt/c/Windows/System32/cmd.exe")
406 .args(["/c", &format!("echo {echo}")])
407 .current_dir("/mnt/c")
408 .output()
409 .map_err(|error| BrowserError::Environment(format!("cmd.exe: {error}")))?;
410 parse_windows_variables(&String::from_utf8_lossy(&output.stdout))
411 .ok_or_else(|| BrowserError::Environment("cmd.exe returned no %LOCALAPPDATA%".into()))
412}
413
414#[cfg(test)]
415mod tests {
416 use super::*;
417 use std::ffi::OsString;
418
419 fn windows_inputs(to_local: &dyn Fn(&str) -> String) -> ConfigInputs<'_> {
420 let variables = [
421 ("LOCALAPPDATA", r"C:\Users\me\AppData\Local"),
422 ("PROGRAMFILES", r"C:\Program Files"),
423 ("PROGRAMFILES(X86)", r"C:\Program Files (x86)"),
424 ];
425 ConfigInputs {
426 windows_variables: variables
427 .iter()
428 .map(|(k, v)| ((*k).into(), (*v).into()))
429 .collect(),
430 linux_data_dir: None,
431 home_dir: None,
432 to_local,
433 }
434 }
435
436 #[test]
437 fn detects_platform_from_proc_version() {
438 let wsl = "Linux version 6.18.33.2-microsoft-standard-WSL2 (root@x)";
439 assert_eq!(Platform::from_proc_version(Some(wsl)), Platform::Wsl);
440 assert_eq!(
441 Platform::from_proc_version(Some("Linux version 6.8.0-generic")),
442 Platform::Linux
443 );
444 assert_eq!(Platform::from_proc_version(None), Platform::Linux);
445 }
446
447 #[test]
448 fn converts_windows_paths() {
449 assert_eq!(
450 windows_path_to_wsl(r"C:\Users\me\x.mode"),
451 "/mnt/c/Users/me/x.mode"
452 );
453 assert_eq!(windows_path_to_wsl(r"D:\a"), "/mnt/d/a");
454 }
455
456 #[test]
457 fn resolves_wsl_config() {
458 let to_local = |path: &str| windows_path_to_wsl(path);
459 let config = Config::resolve(Platform::Wsl, 9222, &windows_inputs(&to_local)).unwrap();
460 assert_eq!(
461 config.profile,
462 r"C:\Users\me\AppData\Local\rusty-teams-chrome"
463 );
464 assert_eq!(
465 config.mode_file,
466 PathBuf::from("/mnt/c/Users/me/AppData/Local/rusty-teams-chrome.mode")
467 );
468 let BrowserSearch::Files(files) = &config.search else {
469 panic!("expected files")
470 };
471 assert_eq!(
472 files[0],
473 PathBuf::from("/mnt/c/Program Files/Google/Chrome/Application/chrome.exe")
474 );
475 assert_eq!(files.len(), 3);
476 }
477
478 #[test]
479 fn resolves_windows_config_without_conversion() {
480 let to_local = |path: &str| path.to_owned();
481 let config = Config::resolve(Platform::Windows, 9222, &windows_inputs(&to_local)).unwrap();
482 assert_eq!(
483 config.mode_file,
484 PathBuf::from(r"C:\Users\me\AppData\Local\rusty-teams-chrome.mode")
485 );
486 }
487
488 #[test]
489 fn native_windows_uses_the_app_profile_and_chrome_install_dirs() {
490 let to_local = |path: &str| path.to_owned();
491 let config = Config::resolve(Platform::Windows, 9222, &windows_inputs(&to_local)).unwrap();
492 assert_eq!(
493 config.profile,
494 r"C:\Users\me\AppData\Local\rusty-teams-chrome"
495 );
496 let BrowserSearch::Files(files) = &config.search else {
497 panic!("expected files")
498 };
499 let expected = [
500 r"C:\Program Files\Google\Chrome\Application\chrome.exe",
501 r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
502 r"C:\Users\me\AppData\Local\Google\Chrome\Application\chrome.exe",
503 ];
504 assert_eq!(
505 files
506 .iter()
507 .map(|file| file.to_string_lossy().into_owned())
508 .collect::<Vec<_>>(),
509 expected
510 );
511 }
512
513 #[test]
514 fn native_windows_with_only_localappdata_still_finds_a_per_user_chrome() {
515 let to_local = |path: &str| path.to_owned();
516 let inputs = ConfigInputs {
517 windows_variables: [("LOCALAPPDATA".to_owned(), r"D:\L".to_owned())].into(),
518 linux_data_dir: None,
519 home_dir: None,
520 to_local: &to_local,
521 };
522 let config = Config::resolve(Platform::Windows, 9222, &inputs).unwrap();
523 let BrowserSearch::Files(files) = &config.search else {
524 panic!("expected files")
525 };
526 assert_eq!(
527 files,
528 &[PathBuf::from(r"D:\L\Google\Chrome\Application\chrome.exe")]
529 );
530 assert_eq!(config.with_profile_name("x").profile, r"D:\L\x");
531 }
532
533 #[test]
534 fn wsl_profile_stays_a_windows_path_while_files_are_mounted() {
535 let to_local = |path: &str| windows_path_to_wsl(path);
536 let config = Config::resolve(Platform::Wsl, 9222, &windows_inputs(&to_local)).unwrap();
537 assert!(config.profile.starts_with(r"C:\"));
538 assert!(config.mode_file.starts_with("/mnt/c"));
539 }
540
541 #[test]
542 fn resolves_linux_config_under_xdg_data_dir() {
543 let to_local = |path: &str| path.to_owned();
544 let inputs = ConfigInputs {
545 windows_variables: HashMap::new(),
546 linux_data_dir: Some(PathBuf::from("/home/u/.local/share")),
547 home_dir: None,
548 to_local: &to_local,
549 };
550 let config = Config::resolve(Platform::Linux, 9222, &inputs).unwrap();
551 assert_eq!(config.profile, "/home/u/.local/share/rusty-teams-chrome");
552 assert_eq!(
553 config.mode_file,
554 PathBuf::from("/home/u/.local/share/rusty-teams-chrome.mode")
555 );
556 }
557
558 #[test]
559 fn resolves_macos_config_under_application_support() {
560 let to_local = |path: &str| path.to_owned();
561 let inputs = ConfigInputs {
562 windows_variables: HashMap::new(),
563 linux_data_dir: Some(PathBuf::from("/Users/joe/Library/Application Support")),
564 home_dir: Some(PathBuf::from("/Users/joe")),
565 to_local: &to_local,
566 };
567 let config = Config::resolve(Platform::Macos, 9222, &inputs).unwrap();
568 assert_eq!(
569 config.profile,
570 "/Users/joe/Library/Application Support/rusty-teams-chrome"
571 );
572 assert_eq!(
573 config.mode_file,
574 PathBuf::from("/Users/joe/Library/Application Support/rusty-teams-chrome.mode")
575 );
576 let BrowserSearch::FilesThenNamed { files, names } = &config.search else {
577 panic!("expected files then named")
578 };
579 assert_eq!(
580 files[0],
581 PathBuf::from("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome")
582 );
583 assert_eq!(
584 files[MACOS_CHROME_APP_PATHS.len()],
585 PathBuf::from("/Users/joe/Applications/Google Chrome.app/Contents/MacOS/Google Chrome")
586 );
587 assert!(files.contains(&PathBuf::from(
588 "/Applications/Helium.app/Contents/MacOS/Helium"
589 )));
590 assert!(names.iter().any(|name| name == "google-chrome"));
591 assert_eq!(
592 config.with_profile_name("x").profile,
593 "/Users/joe/Library/Application Support/x"
594 );
595 }
596
597 #[test]
598 fn missing_localappdata_is_an_error() {
599 let to_local = |path: &str| path.to_owned();
600 let inputs = ConfigInputs {
601 windows_variables: HashMap::new(),
602 linux_data_dir: None,
603 home_dir: None,
604 to_local: &to_local,
605 };
606 assert!(Config::resolve(Platform::Windows, 9222, &inputs).is_err());
607 }
608
609 #[test]
610 fn finds_macos_chrome_under_applications_before_path() {
611 let search = BrowserSearch::FilesThenNamed {
612 files: vec![
613 "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome".into(),
614 "/Users/joe/Applications/Chromium.app/Contents/MacOS/Chromium".into(),
615 ],
616 names: vec!["google-chrome".into()],
617 };
618 let path = std::env::join_paths(["/usr/local/bin"]).unwrap();
619 let found = find_browser(&search, &path, &|candidate| {
620 candidate.ends_with("Google Chrome") || candidate.ends_with("google-chrome")
621 })
622 .unwrap();
623 assert_eq!(
624 found,
625 PathBuf::from("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome")
626 );
627 }
628
629 #[test]
630 fn overrides_port_and_profile_name() {
631 let to_local = |path: &str| windows_path_to_wsl(path);
632 let config = Config::resolve(Platform::Wsl, 9222, &windows_inputs(&to_local))
633 .unwrap()
634 .with_port(9333)
635 .with_profile_name("rusty-teams-chrome-test");
636 assert_eq!(config.port, 9333);
637 assert_eq!(
638 config.profile,
639 r"C:\Users\me\AppData\Local\rusty-teams-chrome-test"
640 );
641 assert!(config.mode_file.ends_with("rusty-teams-chrome-test.mode"));
642 }
643
644 #[test]
645 fn parses_cmd_output_with_crlf_and_unset_variables() {
646 let output = "\r\nC:\\L;C:\\PF;%PROGRAMFILES(X86)%;C:\\T\r\n";
647 let map = parse_windows_variables(output).unwrap();
648 assert_eq!(map["LOCALAPPDATA"], r"C:\L");
649 assert_eq!(map["TEMP"], r"C:\T");
650 assert!(!map.contains_key("PROGRAMFILES(X86)"));
651 assert!(parse_windows_variables("%LOCALAPPDATA%;a;b;c").is_none());
652 assert!(parse_windows_variables("garbage").is_none());
653 }
654
655 #[test]
656 fn finds_first_existing_candidate() {
657 let search = BrowserSearch::Files(vec!["/a/chrome.exe".into(), "/b/chrome.exe".into()]);
658 let found =
659 find_browser(&search, &OsString::new(), &|path| path.starts_with("/b")).unwrap();
660 assert_eq!(found, PathBuf::from("/b/chrome.exe"));
661 assert!(find_browser(&search, &OsString::new(), &|_| false).is_err());
662 }
663
664 #[test]
665 fn finds_named_chrome_on_path_in_name_priority_per_directory() {
666 let search = BrowserSearch::Named(vec!["google-chrome".into(), "chromium".into()]);
667 // join_paths picks the host's PATH separator so split_paths splits it here too.
668 let path = std::env::join_paths(["/usr/local/bin", "/usr/bin"]).unwrap();
669 let found = find_browser(&search, &path, &|candidate| {
670 candidate == Path::new("/usr/bin/chromium")
671 || candidate == Path::new("/usr/bin/google-chrome")
672 })
673 .unwrap();
674 assert_eq!(found, PathBuf::from("/usr/bin/google-chrome"));
675 }
676
677 fn macos_config() -> Config {
678 let to_local = |path: &str| path.to_owned();
679 let inputs = ConfigInputs {
680 windows_variables: HashMap::new(),
681 linux_data_dir: Some(PathBuf::from("/Users/joe/Library/Application Support")),
682 home_dir: Some(PathBuf::from("/Users/joe")),
683 to_local: &to_local,
684 };
685 Config::resolve(Platform::Macos, 9222, &inputs).unwrap()
686 }
687
688 fn select(installed: &[&str], chosen: Option<&str>) -> Config {
689 macos_config().select_browser(
690 chosen.map(PathBuf::from),
691 Some(Path::new("/Users/joe")),
692 &OsString::new(),
693 &|path| {
694 installed
695 .iter()
696 .any(|installed| path == Path::new(installed))
697 },
698 )
699 }
700
701 #[test]
702 fn a_chromium_browser_wins_over_firefox() {
703 let config = select(
704 &[
705 "/Applications/Helium.app/Contents/MacOS/Helium",
706 "/Applications/Zen.app/Contents/MacOS/zen",
707 ],
708 None,
709 );
710 assert_eq!(config.engine, Engine::Chromium);
711 assert!(config.profile.ends_with(PROFILE_NAME));
712 }
713
714 #[test]
715 fn firefox_is_the_fallback_with_its_own_profile() {
716 let zen = "/Users/joe/Applications/Zen.app/Contents/MacOS/zen";
717 let config = select(&[zen], None);
718 assert_eq!(config.engine, Engine::Firefox);
719 assert_eq!(
720 config.profile,
721 "/Users/joe/Library/Application Support/rusty-teams-firefox"
722 );
723 let found = find_browser(&config.search, &OsString::new(), &|path| {
724 path == Path::new(zen)
725 });
726 assert_eq!(found.unwrap(), PathBuf::from(zen));
727 }
728
729 #[test]
730 fn the_chosen_browser_sets_the_engine() {
731 let helium = "/Applications/Helium.app/Contents/MacOS/Helium";
732 let firefox = select(&[helium], Some("/opt/zen/zen"));
733 assert_eq!(firefox.engine, Engine::Firefox);
734 let BrowserSearch::Files(files) = &firefox.search else {
735 panic!("expected the chosen path")
736 };
737 assert_eq!(files, &[PathBuf::from("/opt/zen/zen")]);
738 assert_eq!(select(&[], Some(helium)).engine, Engine::Chromium);
739 }
740}