Skip to content

Commit ff60653

Browse files
authored
Add a --check option to wit-bindgen. (#486)
* Add a `--check` option to wit-bindgen. Add a `--check` option to wit-bindgen for testing whether generated files are already up to date. With this flag, if the generated files differ from what would be generated, the wit-bindgen command exits with an error. * Use `read` instead of `read_to_string` to handle binary data. * Issue a specific error message if two files differ only in line ending.
1 parent a984031 commit ff60653

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

src/bin/wit-bindgen.rs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use anyhow::{anyhow, bail, Context, Result};
22
use clap::Parser;
33
use std::path::PathBuf;
4+
use std::str;
45
use wit_bindgen_core::{wit_parser, Files, WorldGenerator};
56
use wit_parser::{Resolve, UnresolvedPackage};
67

@@ -64,6 +65,11 @@ struct Common {
6465
/// it's `foo.bar` which is the world named `bar` within document `foo`.
6566
#[clap(short, long)]
6667
world: Option<String>,
68+
69+
/// Indicates that no files are written and instead files are checked if
70+
/// they're up-to-date with the source files.
71+
#[clap(long)]
72+
check: bool,
6773
}
6874

6975
fn main() -> Result<()> {
@@ -87,6 +93,31 @@ fn main() -> Result<()> {
8793
None => name.into(),
8894
};
8995
println!("Generating {:?}", dst);
96+
97+
if opt.check {
98+
let prev = std::fs::read(&dst).with_context(|| format!("failed to read {:?}", dst))?;
99+
if prev != contents {
100+
// The contents differ. If it looks like textual contents, do a
101+
// line-by-line comparison so that we can tell users what the
102+
// problem is directly.
103+
if let (Ok(utf8_prev), Ok(utf8_contents)) =
104+
(str::from_utf8(&prev), str::from_utf8(contents))
105+
{
106+
if !utf8_prev
107+
.chars()
108+
.any(|c| c.is_control() && !matches!(c, '\n' | '\r' | '\t'))
109+
&& utf8_prev.lines().eq(utf8_contents.lines())
110+
{
111+
bail!("{} differs only in line endings (CRLF vs. LF). If this is a text file, configure git to mark the file as `text eol=lf`.", dst.display());
112+
}
113+
}
114+
// The contents are binary or there are other differences; just
115+
// issue a generic error.
116+
bail!("not up to date: {}", dst.display());
117+
}
118+
continue;
119+
}
120+
90121
if let Some(parent) = dst.parent() {
91122
std::fs::create_dir_all(parent)
92123
.with_context(|| format!("failed to create {:?}", parent))?;

0 commit comments

Comments
 (0)