diff --git a/Cargo.lock b/Cargo.lock index fbe6413f72..e4154e6839 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4232,8 +4232,10 @@ name = "ide-build" version = "0.1.40" dependencies = [ "blake3", + "chardetng", "dirs 6.0.0", "dunce", + "encoding_rs", "ide-core", "serde", "serde_json", diff --git a/crates/ide-build/Cargo.toml b/crates/ide-build/Cargo.toml index 0de84af239..f0194fe83e 100644 --- a/crates/ide-build/Cargo.toml +++ b/crates/ide-build/Cargo.toml @@ -7,7 +7,9 @@ license.workspace = true [dependencies] blake3.workspace = true +chardetng.workspace = true dunce.workspace = true +encoding_rs.workspace = true ide-core.workspace = true zip.workspace = true serde.workspace = true diff --git a/crates/ide-build/src/maven.rs b/crates/ide-build/src/maven.rs index c4263186b6..ca6d2bd499 100644 --- a/crates/ide-build/src/maven.rs +++ b/crates/ide-build/src/maven.rs @@ -499,7 +499,7 @@ pub fn user_settings_file(root: &Path, settings: &ide_core::settings::MavenSetti /// IDEA lists them): checked by default when `` names them or they are /// `activeByDefault`. pub fn settings_profiles(settings: &Path) -> Vec { - let Some(root) = std::fs::read_to_string(settings).ok().and_then(|text| xml::parse(&text)) else { + let Some(root) = xml::read_text(settings).as_deref().and_then(xml::parse) else { return Vec::new(); }; let active: Vec = @@ -519,7 +519,7 @@ pub fn settings_profiles(settings: &Path) -> Vec { /// `` of a settings file, when it names one: the repository a build /// with `-s ` resolves into, which is not necessarily the user's default. pub fn local_repository_of(settings: &Path) -> Option { - let text = std::fs::read_to_string(settings).ok()?; + let text = xml::read_text(settings)?; let root = xml::parse(&text)?; let repo = root.text_of("localRepository")?.trim().to_owned(); if repo.is_empty() { @@ -545,7 +545,7 @@ impl Resolver { fn pom(&mut self, path: &Path) -> Option { self.poms .entry(path.to_path_buf()) - .or_insert_with(|| std::fs::read_to_string(path).ok().and_then(|t| parse_pom(&t))) + .or_insert_with(|| xml::read_text(path).as_deref().and_then(parse_pom)) .clone() } @@ -736,7 +736,7 @@ pub(crate) fn launch_inputs( return None; } out.push(path.clone()); - let text = std::fs::read_to_string(&path).ok()?; + let text = xml::read_text(&path)?; roots(&xml::parse(&text)?, "", &dir, &mut out)?; let raw = resolver.pom(&path)?; let Some(parent) = raw.parent else { break }; @@ -1640,7 +1640,7 @@ fn parent_chain(path: &Path, text: &str, local_repo: Option) -> Vec<(Pa let Some(parent) = pom.and_then(|p| p.parent) else { return chain }; let Some(pp) = resolver.parent_path(&dir, &parent) else { return chain }; let pp = dunce::canonicalize(&pp).unwrap_or(pp); - let Ok(next) = std::fs::read_to_string(&pp) else { return chain }; + let Some(next) = xml::read_text(&pp) else { return chain }; pom = resolver.pom(&pp); dir = pp.parent().unwrap_or(Path::new("")).to_path_buf(); chain.push((pp, next)); @@ -2297,6 +2297,24 @@ mod tests { assert!(!is_maven_project(&root.join("c"))); } + #[test] + fn non_utf8_pom_with_declared_encoding_is_a_build() { + // Issue #2439: a GBK `pom.xml` is not valid UTF-8; it must still load + // instead of vanishing as "No maven project". + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let (bytes, _, _) = encoding_rs::GBK.encode( + "\ng\ + 应用1演示", + ); + std::fs::write(root.join("pom.xml"), bytes.as_ref()).unwrap(); + let model = load_with_repo(root, None); + assert_eq!(model.projects.len(), 1); + assert_eq!(model.projects[0].artifact_id, "应用"); + assert_eq!(model.projects[0].display_name, "演示"); + assert!(is_maven_project(root)); + } + #[test] fn aggregate_pom_in_src_is_a_build() { // Issue #1001: `src/pom.xml` aggregating modules under `src/` is recognized, diff --git a/crates/ide-build/src/xml.rs b/crates/ide-build/src/xml.rs index 86dec9db2d..3cdab443a4 100644 --- a/crates/ide-build/src/xml.rs +++ b/crates/ide-build/src/xml.rs @@ -3,6 +3,57 @@ //! skipped. Namespace prefixes are dropped (`` → `project`). //! Elements keep their byte offsets in the source, for edits ([`crate::pom_edit`]). +use encoding_rs::Encoding; +use std::path::Path; + +/// Reads an XML file, honoring its `encoding="…"` declaration: a GBK POM +/// (issue #2439) is not valid UTF-8, and `read_to_string` would drop the +/// whole project as "No maven project" while CLI Maven reads it fine. +pub fn read_text(path: &Path) -> Option { + std::fs::read(path).ok().map(|bytes| decode_bytes(&bytes)) +} + +/// Decodes XML bytes: BOM first, then the `encoding` declaration (ASCII in +/// every single-byte encoding, so the head scans before decoding), then +/// UTF-8, then a chardetng guess. +pub fn decode_bytes(bytes: &[u8]) -> String { + if let Some((enc, len)) = Encoding::for_bom(bytes) { + let (text, _) = enc.decode_without_bom_handling(&bytes[len..]); + return text.into_owned(); + } + if let Some(enc) = declared_encoding(bytes) { + let (text, _) = enc.decode_without_bom_handling(bytes); + return text.into_owned(); + } + if let Ok(text) = std::str::from_utf8(bytes) { + return text.to_owned(); + } + let mut detector = chardetng::EncodingDetector::new(); + detector.feed(bytes, true); + let (text, _) = detector.guess(None, true).decode_without_bom_handling(bytes); + text.into_owned() +} + +fn declared_encoding(bytes: &[u8]) -> Option<&'static Encoding> { + let head = std::str::from_utf8(bytes.get(..bytes.len().min(1024))?).ok()?; + let mut rest = head.split("?>").next().unwrap_or(head); + while let Some(i) = rest.find("encoding") { + rest = &rest[i + "encoding".len()..]; + let Some(value) = rest.trim_start().strip_prefix('=') else { continue }; + let value = value.trim_start(); + let ("e, after) = value.as_bytes().split_first()?; + if quote != b'"' && quote != b'\'' { + continue; + } + let after = std::str::from_utf8(after).ok()?; + let end = after.find(quote as char)?; + if let Some(enc) = Encoding::for_label(after[..end].trim().as_bytes()) { + return Some(enc); + } + } + None +} + #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Element { pub name: String, @@ -210,4 +261,19 @@ mod tests { assert!(parse("").is_none()); assert!(parse("just text").is_none()); } + + #[test] + fn decodes_the_declared_encoding() { + // Issue #2439: a GBK POM is not valid UTF-8; decoding must honor the declaration. + let (bytes, _, _) = + encoding_rs::GBK.encode("\n中文"); + let text = decode_bytes(&bytes); + assert_eq!(parse(&text).unwrap().text_of("name").as_deref(), Some("中文")); + // An unknown label falls back to UTF-8 rather than mis-decoding. + let text = decode_bytes(b"\nok"); + assert_eq!(parse(&text).unwrap().text_of("name").as_deref(), Some("ok")); + // No declaration: plain UTF-8 passes through untouched. + let text = decode_bytes("plain".as_bytes()); + assert_eq!(parse(&text).unwrap().text_of("name").as_deref(), Some("plain")); + } }