diff --git a/Cargo.lock b/Cargo.lock index 7cd0d2a..fc18742 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -749,11 +749,13 @@ dependencies = [ "bson", "chrono", "compliance-core", + "encoding_rs", "futures-util", "mongodb", "petgraph", "serde", "tantivy", + "thiserror 2.0.18", "tokio", "tracing", "tree-sitter", diff --git a/Cargo.toml b/Cargo.toml index 9f32eb9..bc7337b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,6 +28,8 @@ chrono = { version = "0.4", features = ["serde"] } mongodb = { version = "3", features = ["rustls-tls", "compat-3-0-0"] } reqwest = { version = "0.12", features = ["json", "rustls-tls", "multipart", "cookies", "stream"], default-features = false } thiserror = "2" +# Source files in UTF-16 or Windows-1252 (code graph, PLC, .NET). +encoding_rs = "0.8" sha2 = "0.10" hex = "0.4" uuid = { version = "1", features = ["v4", "v5", "serde"] } diff --git a/compliance-agent/src/api/handlers/graph.rs b/compliance-agent/src/api/handlers/graph.rs index 2d49e6c..0ff79e6 100644 --- a/compliance-agent/src/api/handlers/graph.rs +++ b/compliance-agent/src/api/handlers/graph.rs @@ -199,6 +199,9 @@ pub struct GraphSummary { pub entry_points: u32, /// Language codes, sorted (`c`, `csharp`, `structured_text`, …). pub languages: Vec, + /// Source files left out because they could not be read as text; 0 when + /// none were, or the build did not count them. + pub unreadable_files: u32, } impl GraphSummary { @@ -213,6 +216,8 @@ impl GraphSummary { units: build.node_count.saturating_sub(build.file_count?), entry_points: build.entry_point_count?, languages: build.languages_parsed, + // Not `?`: a build from before this count still shows its card. + unreadable_files: build.unreadable_file_count.unwrap_or(0), }) } } @@ -406,7 +411,9 @@ pub async fn get_file_content( return Err(StatusCode::FORBIDDEN); } - let content = std::fs::read_to_string(&canonical).map_err(|_| StatusCode::NOT_FOUND)?; + // Decoded as the graph read it, so a UTF-16 or Windows-1252 file opens. + let content = + compliance_graph::encoding::read_source(&canonical).map_err(|_| StatusCode::NOT_FOUND)?; // Cap at 10,000 lines let truncated: String = content.lines().take(10_000).collect::>().join("\n"); @@ -550,4 +557,16 @@ mod tests { assert!(GraphSummary::of(failed).is_none()); assert!(GraphSummary::of(completed(10, None, None)).is_none()); } + + #[test] + fn unreadable_files_are_shown_and_an_uncounted_build_has_none() { + let mut build = completed(10, Some(2), Some(1)); + build.unreadable_file_count = Some(3); + assert_eq!(GraphSummary::of(build).expect("shown").unreadable_files, 3); + let uncounted = completed(10, Some(2), Some(1)); + assert_eq!( + GraphSummary::of(uncounted).expect("shown").unreadable_files, + 0 + ); + } } diff --git a/compliance-agent/src/controls/scan_triage.rs b/compliance-agent/src/controls/scan_triage.rs index 0e5d79a..2969c0f 100644 --- a/compliance-agent/src/controls/scan_triage.rs +++ b/compliance-agent/src/controls/scan_triage.rs @@ -215,7 +215,7 @@ pub async fn grounded_surface_findings( /// Read a window of lines around `line` (1-based) from `repo_path/file`. fn fetch_region(repo_path: &Path, file: &str, line: u32) -> Option { - let content = std::fs::read_to_string(repo_path.join(file)).ok()?; + let content = compliance_graph::encoding::read_source(&repo_path.join(file)).ok()?; let lines: Vec<&str> = content.lines().collect(); if lines.is_empty() { return None; diff --git a/compliance-agent/src/llm/triage.rs b/compliance-agent/src/llm/triage.rs index b853c89..3546de8 100644 --- a/compliance-agent/src/llm/triage.rs +++ b/compliance-agent/src/llm/triage.rs @@ -861,7 +861,7 @@ fn read_surrounding_context(finding: &Finding) -> Option { let line = finding.line_number? as usize; // Try to read the file — this works because the repo is cloned locally - let content = std::fs::read_to_string(file_path).ok()?; + let content = compliance_graph::encoding::read_source(std::path::Path::new(file_path)).ok()?; let lines: Vec<&str> = content.lines().collect(); let start = line.saturating_sub(25); diff --git a/compliance-agent/src/pipeline/dotnet/mod.rs b/compliance-agent/src/pipeline/dotnet/mod.rs index 6d008e4..92b59d4 100644 --- a/compliance-agent/src/pipeline/dotnet/mod.rs +++ b/compliance-agent/src/pipeline/dotnet/mod.rs @@ -145,33 +145,15 @@ pub(crate) fn relative(root: &Path, path: &Path) -> String { } /// The text of a file that may start with a byte-order mark (Visual Studio -/// writes UTF-8 with BOM, older tools UTF-16). `None` for a file too large or +/// writes UTF-8 with BOM, older tools UTF-16) or be Windows-1252, decoded by +/// [`compliance_graph::encoding::read_source`]. `None` for a file too large or /// unreadable. pub(crate) fn read_text(path: &Path) -> Option { let meta = std::fs::metadata(path).ok()?; if meta.len() > MAX_FILE_BYTES { return None; } - let bytes = std::fs::read(path).ok()?; - let utf16 = |bytes: &[u8], le: bool| { - let units: Vec = bytes - .chunks_exact(2) - .map(|c| { - if le { - u16::from_le_bytes([c[0], c[1]]) - } else { - u16::from_be_bytes([c[0], c[1]]) - } - }) - .collect(); - String::from_utf16(&units).ok() - }; - match bytes.as_slice() { - [0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8(rest.to_vec()).ok(), - [0xFF, 0xFE, rest @ ..] => utf16(rest, true), - [0xFE, 0xFF, rest @ ..] => utf16(rest, false), - _ => String::from_utf8(bytes).ok(), - } + compliance_graph::encoding::read_source(path).ok() } /// Parse XML the way project and configuration files need: a DTD is allowed diff --git a/compliance-agent/src/pipeline/embedded_versions.rs b/compliance-agent/src/pipeline/embedded_versions.rs index b481988..5f6b956 100644 --- a/compliance-agent/src/pipeline/embedded_versions.rs +++ b/compliance-agent/src/pipeline/embedded_versions.rs @@ -147,7 +147,8 @@ pub fn detect(root: &Path, repo_id: &str) -> Vec { }) { let small = entry.metadata().is_ok_and(|m| m.len() <= MAX_HEADER_BYTES); let Some(text) = small - .then(|| std::fs::read_to_string(entry.path()).ok()) + // Vendor SDK headers are often Windows-1252 (a "©" in the banner). + .then(|| compliance_graph::encoding::read_source(entry.path()).ok()) .flatten() else { continue; diff --git a/compliance-agent/src/pipeline/plc/mod.rs b/compliance-agent/src/pipeline/plc/mod.rs index 081467e..6095fab 100644 --- a/compliance-agent/src/pipeline/plc/mod.rs +++ b/compliance-agent/src/pipeline/plc/mod.rs @@ -59,8 +59,13 @@ pub(crate) struct PlcFile { /// Read every PLC source file under `root` (Structured Text, and PLCopen XML /// exports) into its POUs. Files with no POU are left out. +/// +/// Each file is decoded by [`compliance_graph::encoding::read_source`]: +/// CODESYS and TIA exports are often Windows-1252 or UTF-16. Files still not +/// readable as text are logged as one warning per tree. pub(crate) fn read_tree(root: &Path) -> Vec { let mut files = Vec::new(); + let mut unreadable: u32 = 0; for entry in walkdir::WalkDir::new(root) .into_iter() .filter_map(|e| e.ok()) @@ -79,8 +84,17 @@ pub(crate) fn read_tree(root: &Path) -> Vec { if !is_st && !is_xml { continue; } - let Ok(content) = std::fs::read_to_string(path) else { - continue; + let content = match compliance_graph::encoding::read_source(path) { + Ok(text) => text, + Err(error) => { + // A binary `.project` is CODESYS's native format, which + // [`native_projects`] reports; anything else is a loss. + if ext != "project" { + tracing::debug!(file = %path.display(), %error, "PLC source file not readable"); + unreadable += 1; + } + continue; + } }; // A `.project` is read only as a PLCopen export; CODESYS's native one // is binary ([`native_projects`] reports it). @@ -106,6 +120,13 @@ pub(crate) fn read_tree(root: &Path) -> Vec { pous, }); } + // One line per tree; the paths are logged at debug level only. + if unreadable > 0 { + tracing::warn!( + unreadable_files = unreadable, + "PLC source files left out: not readable as text" + ); + } files } @@ -188,10 +209,9 @@ pub fn native_projects(root: &Path) -> Vec { .unwrap_or("") .to_ascii_lowercase(); let native = match ext.as_str() { - "project" => !std::fs::read(path) - .ok() - .and_then(|bytes| String::from_utf8(bytes).ok()) - .is_some_and(|text| looks_like_xml(&text)), + // Decoded as [`read_tree`] reads it: a UTF-16 export is no native one. + "project" => !compliance_graph::encoding::read_source(path) + .is_ok_and(|text| looks_like_xml(&text)), "projectarchive" => sbom::check_archive(path).is_ok(), _ => false, }; @@ -385,4 +405,41 @@ mod tests { // The binary project yields no POUs and no error. assert!(analyze_tree(&root.0, "t").is_empty()); } + + #[test] + fn windows_1252_and_utf16_sources_are_read() { + // Arrange: Structured Text as older CODESYS saves it (Windows-1252: + // "Größe" is F6 DF, "€" is 80), and a PLCopen export in UTF-16 LE. + let root = + Scratch(std::env::temp_dir().join(format!("cs-plc-enc-{}", uuid::Uuid::new_v4()))); + std::fs::create_dir_all(&root.0).expect("mkdir"); + std::fs::write( + root.0.join("legacy.st"), + b"PROGRAM Legacy\nVAR\n s : STRING := 'Gr\xF6\xDFe in \x80';\nEND_VAR\n\ + s := 'x'; (* Gr\xF6\xDFe *)\nEND_PROGRAM\n", + ) + .expect("write st"); + let xml = "\ + \ + \ + \ + x := 1;\ + "; + let utf16: Vec = [0xFF, 0xFE] + .into_iter() + .chain(xml.encode_utf16().flat_map(u16::to_le_bytes)) + .collect(); + std::fs::write(root.0.join("wide.xml"), utf16).expect("write xml"); + + // Act + let files = read_tree(&root.0); + + // Assert + let mut pous: Vec<&str> = files + .iter() + .flat_map(|f| f.pous.iter().map(|p| p.name.as_str())) + .collect(); + pous.sort_unstable(); + assert_eq!(pous, ["Legacy", "Wide"]); + } } diff --git a/compliance-agent/src/pipeline/source_text.rs b/compliance-agent/src/pipeline/source_text.rs index 4d837ae..c35630f 100644 --- a/compliance-agent/src/pipeline/source_text.rs +++ b/compliance-agent/src/pipeline/source_text.rs @@ -19,9 +19,10 @@ pub fn relative_path(root: &Path, path: &str) -> String { rel.to_string_lossy().replace('\\', "/") } -/// The whole text of `root/rel`. `None` when the file is unreadable or the -/// path would leave `root`: scanner output is not trusted to stay inside the -/// tree. +/// The whole text of `root/rel`, decoded by +/// [`compliance_graph::encoding::read_source`]. `None` when the file is +/// unreadable or the path would leave `root`: scanner output is not trusted +/// to stay inside the tree. pub fn read_text(root: &Path, rel: &str) -> Option { let rel_path = Path::new(rel); if rel_path.is_absolute() @@ -31,7 +32,8 @@ pub fn read_text(root: &Path, rel: &str) -> Option { { return None; } - std::fs::read_to_string(root.join(rel_path)).ok() + // UTF-16 with a BOM and Windows-1252 too, as the code graph reads them. + compliance_graph::encoding::read_source(&root.join(rel_path)).ok() } /// Lines `start..=end` (1-based, inclusive) of `root/rel`, capped at diff --git a/compliance-core/src/models/graph.rs b/compliance-core/src/models/graph.rs index c62cb48..27b176c 100644 --- a/compliance-core/src/models/graph.rs +++ b/compliance-core/src/models/graph.rs @@ -129,6 +129,12 @@ pub struct GraphBuildRun { /// handlers, PLC programs). `None` on a build stored before it was counted. #[serde(default)] pub entry_point_count: Option, + /// Source files left out because they could not be read as text (not + /// UTF-8, UTF-16 with a byte-order mark or Windows-1252, or an I/O + /// error). `None` on a build stored before it was counted, and on a PLC + /// build, whose files are read by the PLC stage. + #[serde(default)] + pub unreadable_file_count: Option, pub error_message: Option, #[serde(with = "super::serde_helpers::bson_datetime")] pub started_at: DateTime, @@ -149,6 +155,7 @@ impl GraphBuildRun { languages_parsed: Vec::new(), file_count: None, entry_point_count: None, + unreadable_file_count: None, error_message: None, started_at: Utc::now(), completed_at: None, @@ -197,3 +204,25 @@ impl ImpactAnalysis { } } } + +#[cfg(test)] +#[allow(clippy::expect_used)] +mod tests { + use super::*; + + #[test] + fn a_build_stored_before_the_counts_still_reads() { + // Arrange: a stored build as t82 and earlier wrote it. + let mut stored = bson::to_document(&GraphBuildRun::new("r".to_string())).expect("bson"); + for field in ["file_count", "entry_point_count", "unreadable_file_count"] { + stored.remove(field); + } + + // Act + let build: GraphBuildRun = bson::from_document(stored).expect("old build reads"); + + // Assert + assert_eq!(build.file_count, None); + assert_eq!(build.unreadable_file_count, None); + } +} diff --git a/compliance-dashboard/assets/main.css b/compliance-dashboard/assets/main.css index 83b7e3d..1707634 100644 --- a/compliance-dashboard/assets/main.css +++ b/compliance-dashboard/assets/main.css @@ -4907,6 +4907,13 @@ tbody tr:last-child td { color: var(--text-secondary); } +/* Files the graph left out: a fact to notice, not an alarm. */ +.target-graph-unreadable { + margin: 0 0 4px; + font-size: 13px; + color: var(--warning); +} + .target-graph-note { margin: 0; font-size: 12px; diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index 49c71a1..dee1059 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -1157,6 +1157,16 @@ pub mod targets { de: "Anzeigen", en: "Show", }; + /// The code graph's source files it could not read as text: + /// "1 Datei nicht lesbar", "3 files unreadable". + pub fn unreadable_files(count: u32, lang: super::super::Lang) -> String { + match (lang, count) { + (super::super::Lang::De, 1) => "1 Datei nicht lesbar".to_string(), + (super::super::Lang::De, n) => format!("{n} Dateien nicht lesbar"), + (super::super::Lang::En, 1) => "1 file unreadable".to_string(), + (super::super::Lang::En, n) => format!("{n} files unreadable"), + } + } pub const GRAPH_NOTE: Text = Text { de: "Die Bewertung der Befunde berücksichtigt, ob ein Einstiegspunkt die Stelle erreicht.", en: "Triage takes into account whether an entry point reaches a finding.", @@ -1286,6 +1296,14 @@ pub mod targets { assert_eq!(count(1, Lang::En), "1 target"); assert_eq!(count(0, Lang::En), "0 targets"); } + + #[test] + fn the_unreadable_files_line_reads_like_the_language() { + assert_eq!(unreadable_files(1, Lang::De), "1 Datei nicht lesbar"); + assert_eq!(unreadable_files(4, Lang::De), "4 Dateien nicht lesbar"); + assert_eq!(unreadable_files(1, Lang::En), "1 file unreadable"); + assert_eq!(unreadable_files(4, Lang::En), "4 files unreadable"); + } } } diff --git a/compliance-dashboard/src/infrastructure/graph.rs b/compliance-dashboard/src/infrastructure/graph.rs index 3b3eedc..544a763 100644 --- a/compliance-dashboard/src/infrastructure/graph.rs +++ b/compliance-dashboard/src/infrastructure/graph.rs @@ -53,12 +53,17 @@ pub struct SearchResponse { } /// What the target page shows of a code graph: its declarations (functions, -/// methods, types, PLC blocks), its entry points and its languages. +/// methods, types, PLC blocks), its entry points, its languages and the +/// source files it could not read. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct GraphSummary { pub units: u32, pub entry_points: u32, pub languages: Vec, + /// Source files left out as not readable as text; 0 from an agent that + /// does not send the count yet. + #[serde(default)] + pub unreadable_files: u32, } /// The latest code graph's summary for a target; `None` when it has no diff --git a/compliance-dashboard/src/pages/target.rs b/compliance-dashboard/src/pages/target.rs index 251134c..e3f7c92 100644 --- a/compliance-dashboard/src/pages/target.rs +++ b/compliance-dashboard/src/pages/target.rs @@ -293,6 +293,11 @@ pub fn TargetPage(id: String) -> Element { p { class: "target-graph-languages", {graph.languages.iter().map(|l| language_name(l)).collect::>().join(", ")} } + if graph.unreadable_files > 0 { + p { class: "target-graph-unreadable", + {tx::unreadable_files(graph.unreadable_files, lang)} + } + } p { class: "target-graph-note", {tx::GRAPH_NOTE.get(lang)} } } } diff --git a/compliance-graph/Cargo.toml b/compliance-graph/Cargo.toml index 794c2f8..00212f8 100644 --- a/compliance-graph/Cargo.toml +++ b/compliance-graph/Cargo.toml @@ -13,6 +13,10 @@ chrono = { workspace = true } tracing = { workspace = true } tokio = { workspace = true } mongodb = { workspace = true } +thiserror = { workspace = true } + +# Decoding source files: BOM sniffing, UTF-16, Windows-1252 +encoding_rs = { workspace = true } # Tree-sitter parsing tree-sitter = "0.24" diff --git a/compliance-graph/src/encoding.rs b/compliance-graph/src/encoding.rs new file mode 100644 index 0000000..cb75553 --- /dev/null +++ b/compliance-graph/src/encoding.rs @@ -0,0 +1,170 @@ +//! Source files as text, whatever encoding the tool that wrote them chose. +//! +//! Visual Studio writes UTF-8 with a byte-order mark (BOM) or UTF-16, older +//! .NET and PLC tools write Windows-1252. `std::fs::read_to_string` accepts +//! only UTF-8 (and keeps a UTF-8 BOM as a leading `U+FEFF`), so every reader +//! of source files decodes through [`read_source`] instead: +//! +//! 1. a BOM (UTF-8 `EF BB BF`, UTF-16 LE `FF FE`, UTF-16 BE `FE FF`) names the +//! encoding; the BOM itself is dropped; +//! 2. without one, the bytes are UTF-8 if they are valid UTF-8; +//! 3. otherwise they are Windows-1252, unless they contain a NUL byte: no +//! 1252 text does, but binaries and UTF-16 without a BOM do. + +use std::path::Path; + +use encoding_rs::{Encoding, UTF_8, WINDOWS_1252}; + +/// Why a file could not be read as text. +#[derive(Debug, thiserror::Error)] +pub enum SourceTextError { + /// The file could not be read at all (missing, no permission, ...). + #[error("cannot read the file: {0}")] + Io(#[from] std::io::Error), + /// The file's BOM names an encoding its bytes don't follow, e.g. UTF-16 + /// with an odd byte count or an unpaired surrogate. + #[error("the file is not valid {0} although its byte-order mark says so")] + Malformed(&'static str), + /// The file has no BOM, is not UTF-8 and contains a NUL byte: a binary + /// file, or UTF-16 we can't tell the byte order of. + #[error("the file is binary or of an unknown encoding")] + Binary, +} + +/// Read the file at `path` as text, decoded as the module docs describe. +/// +/// # Arguments +/// +/// * `path` - the file to read +/// +/// # Returns +/// +/// The file's text, without a byte-order mark. +/// +/// # Errors +/// +/// Returns [`SourceTextError::Io`] when the file can't be read, and the +/// errors of [`decode`] when its bytes aren't text. +pub fn read_source(path: &Path) -> Result { + decode(std::fs::read(path)?) +} + +/// Decode a source file's bytes, as the module docs describe. +/// +/// Takes the bytes by value so that the common case, UTF-8 without a BOM, +/// becomes the `String` without copying: a Rust `String` is a UTF-8 byte +/// buffer, so `String::from_utf8` only validates and reuses the `Vec`. +/// +/// # Arguments +/// +/// * `bytes` - the whole file +/// +/// # Returns +/// +/// The text, without a byte-order mark. +/// +/// # Errors +/// +/// Returns [`SourceTextError::Malformed`] when a BOM names an encoding the +/// bytes don't follow, and [`SourceTextError::Binary`] for non-UTF-8 bytes +/// that contain a NUL. +/// +/// # Examples +/// +/// ``` +/// use compliance_graph::encoding::decode; +/// +/// // "€" is 0x80 in Windows-1252. +/// assert_eq!(decode(b"// 5 \x80".to_vec()).ok().as_deref(), Some("// 5 €")); +/// ``` +pub fn decode(mut bytes: Vec) -> Result { + if let Some((encoding, bom_len)) = Encoding::for_bom(&bytes) { + if encoding == UTF_8 { + // Drop the BOM in place, then validate without another copy. + bytes.drain(..bom_len); + return String::from_utf8(bytes).map_err(|_| SourceTextError::Malformed("UTF-8")); + } + // UTF-16 LE or BE: `None` on an odd byte count or unpaired surrogate. + return encoding + .decode_without_bom_handling_and_without_replacement(&bytes[bom_len..]) + .map(|text| text.into_owned()) + .ok_or(SourceTextError::Malformed(encoding.name())); + } + match String::from_utf8(bytes) { + Ok(text) => Ok(text), + Err(not_utf8) => { + // Hand the buffer back; `from_utf8` gave up ownership on failure. + let bytes = not_utf8.into_bytes(); + if bytes.contains(&0) { + return Err(SourceTextError::Binary); + } + // Windows-1252 maps every byte, so this decoding can't fail. + let (text, _had_errors) = WINDOWS_1252.decode_without_bom_handling(&bytes); + Ok(text.into_owned()) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_tree::utf16; + + #[test] + fn utf8_without_a_bom_is_kept_as_it_is() { + let text = decode("int größe = 1; // €".as_bytes().to_vec()); + assert_eq!(text.ok().as_deref(), Some("int größe = 1; // €")); + } + + #[test] + fn a_utf8_bom_is_dropped() { + let mut bytes = vec![0xEF, 0xBB, 0xBF]; + bytes.extend_from_slice(b"class A {}"); + assert_eq!(decode(bytes).ok().as_deref(), Some("class A {}")); + } + + #[test] + fn utf16_with_a_bom_is_decoded_in_both_byte_orders() { + for little_endian in [true, false] { + let text = decode(utf16("class Größe {}", little_endian)); + assert_eq!(text.ok().as_deref(), Some("class Größe {}")); + } + } + + #[test] + fn windows_1252_is_the_fallback() { + // "Größe" and "€" as Windows-1252 writes them: 0xF6 0xDF and 0x80. + let text = decode(b"// Gr\xF6\xDFe in \x80".to_vec()); + assert_eq!(text.ok().as_deref(), Some("// Größe in €")); + } + + #[test] + fn malformed_utf16_and_binaries_are_not_text() { + // An odd byte count after a UTF-16 LE BOM. + assert!(matches!( + decode(vec![0xFF, 0xFE, 0x41]), + Err(SourceTextError::Malformed("UTF-16LE")) + )); + // An unpaired high surrogate (D800) in UTF-16 BE. + assert!(matches!( + decode(vec![0xFE, 0xFF, 0xD8, 0x00, 0x00, 0x41]), + Err(SourceTextError::Malformed("UTF-16BE")) + )); + // Invalid UTF-8 after a UTF-8 BOM. + assert!(matches!( + decode(vec![0xEF, 0xBB, 0xBF, 0xFF]), + Err(SourceTextError::Malformed("UTF-8")) + )); + // Not UTF-8 and a NUL: a binary. + assert!(matches!( + decode(vec![0x7F, b'E', b'L', b'F', 0x00, 0xFF]), + Err(SourceTextError::Binary) + )); + } + + #[test] + fn a_missing_file_is_an_io_error() { + let missing = std::env::temp_dir().join("compliance-graph-no-such-file.cs"); + assert!(matches!(read_source(&missing), Err(SourceTextError::Io(_)))); + } +} diff --git a/compliance-graph/src/graph/chunking.rs b/compliance-graph/src/graph/chunking.rs index 9ba2b39..87e0175 100644 --- a/compliance-graph/src/graph/chunking.rs +++ b/compliance-graph/src/graph/chunking.rs @@ -29,7 +29,8 @@ pub fn extract_chunks( for node in nodes { let file = repo_path.join(&node.file_path); - let source = match std::fs::read_to_string(&file) { + // Decoded as the graph's parser read it, so every node has its lines. + let source = match crate::encoding::read_source(&file) { Ok(s) => s, Err(_) => continue, }; diff --git a/compliance-graph/src/graph/engine.rs b/compliance-graph/src/graph/engine.rs index 83e52ca..54d6e12 100644 --- a/compliance-graph/src/graph/engine.rs +++ b/compliance-graph/src/graph/engine.rs @@ -204,13 +204,15 @@ impl GraphEngine { graph_build_id: &str, ) -> Result<(CodeGraph, GraphBuildRun), CoreError> { info!(repo_id, path = %repo_path.display(), "Starting graph build"); - let parse_output = self.parser_registry.parse_directory( + let parsed = self.parser_registry.parse_directory( repo_path, repo_id, graph_build_id, self.max_nodes, )?; - self.assemble(parse_output, repo_id) + let (code_graph, mut build_run) = self.assemble(parsed.output, repo_id)?; + build_run.unreadable_file_count = Some(parsed.unreadable_files); + Ok((code_graph, build_run)) } /// Build a code graph from nodes and edges parsed elsewhere, e.g. by a @@ -756,5 +758,20 @@ mod tests { assert_eq!(run.file_count, Some(2)); assert_eq!(run.entry_point_count, Some(1)); assert_eq!(run.languages_parsed, ["c", "rust"]); + // Assembled from nodes parsed elsewhere: nothing was read here. + assert_eq!(run.unreadable_file_count, None); + } + + #[test] + fn a_tree_build_records_its_unreadable_files() { + let tree = crate::test_tree::TempTree::in_every_encoding("engine"); + + let (_, run) = GraphEngine::new(1000) + .build_graph(tree.path(), "test", "build") + .expect("builds"); + + // Five readable files, the broken UTF-16 one and the binary not. + assert_eq!(run.file_count, Some(5)); + assert_eq!(run.unreadable_file_count, Some(2)); } } diff --git a/compliance-graph/src/lib.rs b/compliance-graph/src/lib.rs index bceea55..78ce9da 100644 --- a/compliance-graph/src/lib.rs +++ b/compliance-graph/src/lib.rs @@ -1,9 +1,13 @@ #![allow(clippy::only_used_in_recursion)] #![allow(clippy::too_many_arguments)] +pub mod encoding; pub mod graph; pub mod parsers; pub mod search; +#[cfg(test)] +#[allow(clippy::expect_used)] +mod test_tree; pub use graph::engine::GraphEngine; pub use parsers::registry::ParserRegistry; diff --git a/compliance-graph/src/parsers/registry.rs b/compliance-graph/src/parsers/registry.rs index 2846b74..1534ad5 100644 --- a/compliance-graph/src/parsers/registry.rs +++ b/compliance-graph/src/parsers/registry.rs @@ -3,7 +3,7 @@ use std::path::Path; use compliance_core::error::CoreError; use compliance_core::traits::graph_builder::{LanguageParser, ParseOutput}; -use tracing::{debug, info}; +use tracing::{debug, info, warn}; use super::c::CParser; use super::csharp::CSharpParser; @@ -12,6 +12,16 @@ use super::python::PythonParser; use super::rust_parser::RustParser; use super::typescript::TypeScriptParser; +/// What [`ParserRegistry::parse_directory`] made of a tree. +#[derive(Debug, Default)] +pub struct DirectoryParse { + /// Every parsed file's nodes and edges. + pub output: ParseOutput, + /// Source files of a supported language that could not be read as text + /// (I/O error, malformed UTF-16, binary): left out of `output`. + pub unreadable_files: u32, +} + /// Registry of language parsers, indexed by file extension pub struct ParserRegistry { parsers: Vec>, @@ -79,15 +89,36 @@ impl ParserRegistry { Ok(Some(output)) } - /// Parse all supported files in a directory tree + /// Parse all supported files in a directory tree. + /// + /// Each file is decoded by [`crate::encoding::read_source`] (UTF-8, + /// UTF-16 with a BOM, Windows-1252); a file still not readable as text + /// is counted, not parsed. + /// + /// # Arguments + /// + /// * `dir` - the tree's root; node paths are relative to it + /// * `repo_id` - the repository the nodes belong to + /// * `graph_build_id` - the build the nodes belong to + /// * `max_nodes` - parsing stops once this many nodes are collected + /// + /// # Returns + /// + /// The nodes and edges of every parsed file, and how many files could + /// not be read. + /// + /// # Errors + /// + /// Returns `CoreError::Graph` when a directory can't be listed, and a + /// parser's error. pub fn parse_directory( &self, dir: &Path, repo_id: &str, graph_build_id: &str, max_nodes: u32, - ) -> Result { - let mut combined = ParseOutput::default(); + ) -> Result { + let mut combined = DirectoryParse::default(); let mut node_count: u32 = 0; self.walk_directory( @@ -100,9 +131,17 @@ impl ParserRegistry { &mut combined, )?; + // One line per build; the paths are logged at debug level only. + if combined.unreadable_files > 0 { + warn!( + unreadable_files = combined.unreadable_files, + "Source files left out of the code graph: not readable as text" + ); + } info!( - nodes = combined.nodes.len(), - edges = combined.edges.len(), + nodes = combined.output.nodes.len(), + edges = combined.output.edges.len(), + unreadable_files = combined.unreadable_files, "Directory parsing complete" ); @@ -117,7 +156,7 @@ impl ParserRegistry { graph_build_id: &str, max_nodes: u32, node_count: &mut u32, - combined: &mut ParseOutput, + combined: &mut DirectoryParse, ) -> Result<(), CoreError> { let entries = std::fs::read_dir(dir).map_err(|e| { CoreError::Graph(format!("Failed to read directory {}: {e}", dir.display())) @@ -166,15 +205,19 @@ impl ParserRegistry { // Use relative path from base let rel_path = path.strip_prefix(base).unwrap_or(&path); - let source = match std::fs::read_to_string(&path) { - Ok(s) => s, - Err(_) => continue, // Skip binary/unreadable files + let source = match crate::encoding::read_source(&path) { + Ok(text) => text, + Err(error) => { + debug!(file = %rel_path.display(), %error, "Source file not readable"); + combined.unreadable_files += 1; + continue; + } }; if let Some(output) = self.parse_file(rel_path, &source, repo_id, graph_build_id)? { *node_count += output.nodes.len() as u32; - combined.nodes.extend(output.nodes); - combined.edges.extend(output.edges); + combined.output.nodes.extend(output.nodes); + combined.output.edges.extend(output.edges); } } } @@ -294,6 +337,41 @@ mod tests { assert!(!output.nodes.is_empty()); } + #[test] + fn files_in_every_encoding_parse_and_unreadable_ones_are_counted() { + // Arrange + let tree = crate::test_tree::TempTree::in_every_encoding("registry"); + + // Act + let parsed = ParserRegistry::new() + .parse_directory(tree.path(), "repo1", "build1", 1000) + .expect("tree parses"); + + // Assert: each file's declaration is a node, under the file's path. + let has = |file: &str, name: &str| { + parsed + .output + .nodes + .iter() + .any(|n| n.file_path == file && n.name == name) + }; + for (file, class) in [ + ("Plain.cs", "Utf8Plain"), + ("Bom.cs", "Utf8Bom"), + ("Le.cs", "Utf16Le"), + ("Be.cs", "Utf16Be"), + ] { + assert!(has(file, class), "no class {class} in {file}"); + assert!(has(file, "Run"), "no method Run in {file}"); + } + assert!( + has("legacy.c", "unit"), + "no function in the Windows-1252 file" + ); + // The broken UTF-16 file and the binary; not the PNG. + assert_eq!(parsed.unreadable_files, 2); + } + #[test] fn test_default_trait() { let registry = ParserRegistry::default(); diff --git a/compliance-graph/src/test_tree.rs b/compliance-graph/src/test_tree.rs new file mode 100644 index 0000000..52793ac --- /dev/null +++ b/compliance-graph/src/test_tree.rs @@ -0,0 +1,73 @@ +//! A source tree on disk for tests, in every encoding the registry reads. + +use std::path::{Path, PathBuf}; + +/// A directory under the system temp dir, removed when dropped (Rust runs +/// `Drop::drop` when the value goes out of scope, like a `with` block's exit). +pub(crate) struct TempTree(PathBuf); + +impl TempTree { + /// An empty directory named after the test and this process. + pub(crate) fn new(test: &str) -> Self { + let dir = + std::env::temp_dir().join(format!("compliance-graph-{test}-{}", std::process::id())); + // A leftover from an aborted run would add files. + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("temp dir"); + Self(dir) + } + + /// The directory. + pub(crate) fn path(&self) -> &Path { + &self.0 + } + + /// Write `bytes` to `rel` in the tree. + pub(crate) fn write(&self, rel: &str, bytes: &[u8]) { + std::fs::write(self.0.join(rel), bytes).expect("write"); + } + + /// A tree with one C# class or C function in each encoding the registry + /// reads, and two files it can't read (plus a binary it doesn't try to). + pub(crate) fn in_every_encoding(test: &str) -> Self { + let tree = Self::new(test); + tree.write("Plain.cs", b"class Utf8Plain { void Run() { } }\n"); + tree.write("Bom.cs", b"\xEF\xBB\xBFclass Utf8Bom { void Run() { } }\n"); + tree.write("Le.cs", &utf16("class Utf16Le { void Run() { } }\n", true)); + tree.write("Be.cs", &utf16("class Utf16Be { void Run() { } }\n", false)); + // "Größe" and "€" as Windows-1252 writes them. + tree.write( + "legacy.c", + b"/* Gr\xF6\xDFe */\nconst char *unit(void) { return \"\x80\"; }\n", + ); + // An odd byte count after a UTF-16 BOM, and a binary with a C name. + tree.write("Broken.cs", b"\xFF\xFE\x41"); + tree.write("blob.c", b"\x7FELF\x00\xFF\xFE"); + // Not a source file: neither parsed nor counted. + tree.write("logo.png", b"\x89PNG\x00\xFF"); + tree + } +} + +impl Drop for TempTree { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// `text` as UTF-16 with its byte-order mark. +pub(crate) fn utf16(text: &str, little_endian: bool) -> Vec { + let bom: [u8; 2] = if little_endian { + [0xFF, 0xFE] + } else { + [0xFE, 0xFF] + }; + let units = text.encode_utf16().flat_map(|unit| { + if little_endian { + unit.to_le_bytes() + } else { + unit.to_be_bytes() + } + }); + bom.into_iter().chain(units).collect() +}