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