Skip to content

Commit 7f62d89

Browse files
authored
Avoid string matching on errors (#853)
* Avoid string matching on errors Use concrete error types for testing for attaching help messages. * Fix non-Rust builds
1 parent 3b2678c commit 7f62d89

File tree

2 files changed

+27
-9
lines changed

2 files changed

+27
-9
lines changed

crates/rust/src/lib.rs

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,7 @@ impl RustWasm {
276276
ExportKey::Name(name) => format!("\"{name}\""),
277277
};
278278
if self.opts.exports.is_empty() {
279-
bail!("no `exports` map provided in configuration - provide an `exports` map a key `{key}`")
279+
bail!(MissingExportsMap { key });
280280
}
281281
bail!("expected `exports` map to contain key `{key}`")
282282
}
@@ -869,3 +869,20 @@ impl fmt::Display for RustFlagsRepr {
869869
}
870870
}
871871
}
872+
873+
#[derive(Debug)]
874+
pub struct MissingExportsMap {
875+
key: String,
876+
}
877+
878+
impl fmt::Display for MissingExportsMap {
879+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
880+
write!(
881+
f,
882+
"no `exports` map provided in configuration - provide an `exports` map a key `{key}`",
883+
key = self.key,
884+
)
885+
}
886+
}
887+
888+
impl std::error::Error for MissingExportsMap {}

src/bin/wit-bindgen.rs

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -157,16 +157,17 @@ fn gen_world(
157157
let mut resolve = Resolve::default();
158158
let (pkg, _files) = resolve.push_path(&opts.wit)?;
159159
let world = resolve.select_world(pkg, opts.world.as_deref())?;
160-
if let Err(e) = generator.generate(&resolve, world, files) {
161-
if e.to_string().starts_with("no `exports` map provided") {
162-
bail!(
163-
"{e:?}\n\n\
164-
help: Specify export implementations using the `--exports` option.\n \
165-
For example: `--exports world=MyWorld,ns:pkg/iface=MyIface`\n \
166-
Alternatively, specify `--stubs` to generate stub implementations."
160+
if let Err(mut e) = generator.generate(&resolve, world, files) {
161+
#[cfg(feature = "rust")]
162+
if e.is::<wit_bindgen_rust::MissingExportsMap>() {
163+
e = e.context(
164+
"no `--exports` option was found but one was required, \
165+
this can be passed as `--exports world=MyWorld,ns:pkg/iface=MyIface` \
166+
for example\n\
167+
Alternatively, specify `--stubs` to generate stub implementations.",
167168
);
168169
}
169-
bail!("{e:?}");
170+
return Err(e);
170171
}
171172

172173
Ok(())

0 commit comments

Comments
 (0)