BlueGit

ict rusty-teams

Files

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

config.rs

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