diff --git a/compiler-cli/src/fs.rs b/compiler-cli/src/fs.rs index cc7edcc9117..4f68d99e57a 100644 --- a/compiler-cli/src/fs.rs +++ b/compiler-cli/src/fs.rs @@ -55,29 +55,29 @@ pub fn get_project_root(path: Utf8PathBuf) -> Result { } pub fn get_os() -> OS { - parse_os(std::env::consts::OS, get_linux_distro_str().as_str()) + parse_os(std::env::consts::OS, get_distro_str().as_str()) } -pub fn get_linux_distro_str() -> String { +// try to extract the distro id from /etc/os-release +pub fn extract_distro_id(os_release: String) -> String { + let distro = os_release.lines().find(|line| line.starts_with("ID=")); + if let Some(distro) = distro { + let id = distro.split('=').nth(1).unwrap_or("").replace("\"", ""); + return id; + } + "".to_string() +} + +pub fn get_distro_str() -> String { let path = Utf8Path::new("/etc/os-release"); if std::env::consts::OS != "linux" || !path.exists() { return "other".to_string(); } let os_release = read(path); - if os_release.is_err() { - return "other".to_string(); - } - let os_release = os_release.unwrap_or_default(); - let distro = os_release.lines().find(|line| line.starts_with("ID=")); - if let Some(distro) = distro { - let id = distro - .split('=') - .nth(1) - .unwrap_or("other") - .replace("\"", ""); - return id; + match os_release { + Ok(os_release) => extract_distro_id(os_release), + Err(_) => "other".to_string(), } - "other".to_string() } /// A `FileWriter` implementation that writes to the file system. diff --git a/compiler-cli/src/fs/tests.rs b/compiler-cli/src/fs/tests.rs index e2ccc48514b..45d24ea88d6 100644 --- a/compiler-cli/src/fs/tests.rs +++ b/compiler-cli/src/fs/tests.rs @@ -99,3 +99,47 @@ fn is_gleam_path_test() { Utf8Path::new("/some-prefix/") )); } + +#[test] +fn extract_distro_id_test() { + let os_release = " +PRETTY_NAME=\"Debian GNU/Linux 12 (bookworm)\" +NAME=\"Debian GNU/Linux\" +VERSION_ID=\"12\" +VERSION=\"12 (bookworm)\" +VERSION_CODENAME=bookworm +ID=debian +HOME_URL=\"https://www.debian.org/\" +"; + assert_eq!(super::extract_distro_id(os_release.to_string()), "debian"); + + let os_release = " +VERSION_CODENAME=jammy +ID=ubuntu +ID_LIKE=debian +HOME_URL=\"https://www.ubuntu.com/\" +"; + assert_eq!(super::extract_distro_id(os_release.to_string()), "ubuntu"); + + assert_eq!(super::extract_distro_id("".to_string()), ""); + assert_eq!(super::extract_distro_id("\n".to_string()), ""); + assert_eq!(super::extract_distro_id("ID=".to_string()), ""); + assert_eq!(super::extract_distro_id("ID= ".to_string()), " "); + assert_eq!( + super::extract_distro_id("ID= space test ".to_string()), + " space test " + ); + assert_eq!(super::extract_distro_id("id=ubuntu".to_string()), ""); + assert_eq!( + super::extract_distro_id("NAME=\"Debian\"\nID=debian".to_string()), + "debian" + ); + assert_eq!( + super::extract_distro_id("\n\nNAME=\n\n\nID=test123\n".to_string()), + "test123" + ); + assert_eq!( + super::extract_distro_id("\nID=\"id first\"\nID=another_id".to_string()), + "id first" + ); +}