Skip to content

Commit 888deeb

Browse files
committed
Detect decoding errors when reading from stdin
1 parent 677fc49 commit 888deeb

File tree

2 files changed

+14
-13
lines changed

2 files changed

+14
-13
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
2626
- Lexing of unterminated asm text literals at EOF.
2727
- `--config-file` no longer erroneously accepts a path to a directory and searches from it for a
2828
`pasfmt.toml` file. It is now an error to provide a path to a directory.
29+
- Detection of decoding errors when reading from stdin.
2930

3031
## [0.3.0] - 2024-05-29
3132

orchestrator/src/file_formatter.rs

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ struct DecodedFile<'a> {
1818
bom: Option<&'a [u8]>,
1919
contents: Cow<'a, str>,
2020
encoding: &'static Encoding,
21-
replacements: bool,
2221
}
2322

2423
pub struct FileFormatter {
@@ -75,8 +74,9 @@ impl FileFormatter {
7574
fn decode_file<'a>(
7675
&self,
7776
file: &mut impl Read,
77+
name: impl Display,
7878
buf: &'a mut Vec<u8>,
79-
) -> std::io::Result<DecodedFile<'a>> {
79+
) -> anyhow::Result<DecodedFile<'a>> {
8080
file.read_to_end(buf)?;
8181

8282
let (encoding, (bom, contents)) = match Encoding::for_bom(buf) {
@@ -87,11 +87,19 @@ impl FileFormatter {
8787
};
8888
let (contents, replacements) = encoding.decode_without_bom_handling(contents);
8989

90+
if replacements {
91+
bail!(
92+
"File '{}' has malformed sequences (in encoding '{}'{})",
93+
name,
94+
encoding.name(),
95+
bom.map(|_| " - inferred from BOM").unwrap_or(""),
96+
);
97+
}
98+
9099
Ok(DecodedFile {
91100
bom,
92101
contents,
93102
encoding,
94-
replacements,
95103
})
96104
}
97105

@@ -123,17 +131,9 @@ impl FileFormatter {
123131
.with_context(|| format!("Failed to open '{}'", file_path.display()))?;
124132

125133
let decoded_file = self
126-
.decode_file(&mut file, input_buf)
134+
.decode_file(&mut file, file_path.display(), input_buf)
127135
.with_context(|| format!("Failed to read '{}'", file_path.display()))?;
128136

129-
if decoded_file.replacements {
130-
bail!(
131-
"File '{}' had malformed sequences (in encoding '{}')",
132-
file_path.display(),
133-
decoded_file.encoding.name()
134-
);
135-
}
136-
137137
self.formatter
138138
.format_into_buf(&decoded_file.contents, output_buf);
139139
result_operation(&mut file, &file_path, &decoded_file, output_buf)
@@ -239,7 +239,7 @@ impl FileFormatter {
239239
}
240240
let mut stdin = std::io::stdin().lock();
241241

242-
self.decode_file(&mut stdin, buf)
242+
self.decode_file(&mut stdin, "<stdin>", buf)
243243
.context("Failed to read from stdin")
244244
}
245245

0 commit comments

Comments
 (0)