BlueGit

ict rusty-teams

Files

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

config.rs

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