Files
pruefwerk/compliance-graph/src/encoding.rs
T
Sharang ParnerkarandClaude Opus 5.5 68f73afde6
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Agent integration (pull_request) Successful in 4m36s
CI / Check (pull_request) Successful in 18m48s
fix(graph): read UTF-16 and Windows-1252 source files into the code graph (t84)
The graph registry read source files with read_to_string and skipped any
that were not UTF-8, so Visual Studio's UTF-16 files and older .NET/PLC
tools' Windows-1252 files never reached the graph, in every language. A
UTF-8 BOM was kept as a leading U+FEFF.

- compliance_graph::encoding::read_source: a BOM (UTF-8, UTF-16 LE/BE)
  names the encoding and is dropped; otherwise UTF-8, else Windows-1252
  (encoding_rs, already in the lock). Malformed UTF-16, a NUL in non-UTF-8
  bytes (a binary) and I/O errors are errors.
- The registry counts the files it still can't read, warns once per build
  (paths at debug only) and the tree build stores the count on the build
  run (unreadable_file_count, serde default for older runs).
- GET /api/v1/graph/{id}/summary returns unreadable_files; the target
  page's Codegraph card shows "N Dateien nicht lesbar" / "N files
  unreadable" when it is above 0.
- The same decoder where a file is read again or in the same stage: graph
  chunking, the graph's file view, PLC read_tree and native_projects,
  .NET read_text (replaces its own BOM code), finding snippets
  (source_text), embedded header versions, LLM and control triage context.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 08:52:31 +01:00

171 lines
6.0 KiB
Rust

//! 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<String, SourceTextError> {
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<u8>) -> Result<String, SourceTextError> {
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(_))));
}
}