Skip to content

Commit

Permalink
Avoid string matching on errors (#853)
Browse files Browse the repository at this point in the history
* Avoid string matching on errors

Use concrete error types for testing for attaching help messages.

* Fix non-Rust builds
  • Loading branch information
alexcrichton authored Feb 21, 2024
1 parent 3b2678c commit 7f62d89
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 9 deletions.
19 changes: 18 additions & 1 deletion crates/rust/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ impl RustWasm {
ExportKey::Name(name) => format!("\"{name}\""),
};
if self.opts.exports.is_empty() {
bail!("no `exports` map provided in configuration - provide an `exports` map a key `{key}`")
bail!(MissingExportsMap { key });
}
bail!("expected `exports` map to contain key `{key}`")
}
Expand Down Expand Up @@ -869,3 +869,20 @@ impl fmt::Display for RustFlagsRepr {
}
}
}

#[derive(Debug)]
pub struct MissingExportsMap {
key: String,
}

impl fmt::Display for MissingExportsMap {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"no `exports` map provided in configuration - provide an `exports` map a key `{key}`",
key = self.key,
)
}
}

impl std::error::Error for MissingExportsMap {}
17 changes: 9 additions & 8 deletions src/bin/wit-bindgen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,16 +157,17 @@ fn gen_world(
let mut resolve = Resolve::default();
let (pkg, _files) = resolve.push_path(&opts.wit)?;
let world = resolve.select_world(pkg, opts.world.as_deref())?;
if let Err(e) = generator.generate(&resolve, world, files) {
if e.to_string().starts_with("no `exports` map provided") {
bail!(
"{e:?}\n\n\
help: Specify export implementations using the `--exports` option.\n \
For example: `--exports world=MyWorld,ns:pkg/iface=MyIface`\n \
Alternatively, specify `--stubs` to generate stub implementations."
if let Err(mut e) = generator.generate(&resolve, world, files) {
#[cfg(feature = "rust")]
if e.is::<wit_bindgen_rust::MissingExportsMap>() {
e = e.context(
"no `--exports` option was found but one was required, \
this can be passed as `--exports world=MyWorld,ns:pkg/iface=MyIface` \
for example\n\
Alternatively, specify `--stubs` to generate stub implementations.",
);
}
bail!("{e:?}");
return Err(e);
}

Ok(())
Expand Down

0 comments on commit 7f62d89

Please sign in to comment.