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