Skip to content

Commit d134eb1

Browse files
committed
Improves error handling for rustfmt
1 parent 35627a8 commit d134eb1

File tree

1 file changed

+43
-12
lines changed

1 file changed

+43
-12
lines changed

src/lib.rs

+43-12
Original file line numberDiff line numberDiff line change
@@ -1382,8 +1382,7 @@ impl<'ctx> Bindings<'ctx> {
13821382
self.write(Box::new(file))?;
13831383
}
13841384

1385-
self.format_generated_file(path.as_ref());
1386-
Ok(())
1385+
self.rustfmt_generated_file(path.as_ref())
13871386
}
13881387

13891388
/// Write these bindings as source text to the given `Write`able.
@@ -1407,28 +1406,60 @@ impl<'ctx> Bindings<'ctx> {
14071406
ps.s.out.flush()
14081407
}
14091408

1410-
/// Checks if format_bindings is set and runs rustfmt on the file
1411-
fn format_generated_file(&self, file: &Path) {
1412-
if !self.context.options().format_bindings {
1413-
return;
1409+
/// Checks if rustfmt_bindings is set and runs rustfmt on the file
1410+
fn rustfmt_generated_file(&self, file: &Path) -> io::Result<()> {
1411+
if !self.context.options().rustfmt_bindings {
1412+
return Ok(());
14141413
}
14151414

14161415
let rustfmt = if let Ok(rustfmt) = which::which("rustfmt") {
14171416
rustfmt
14181417
} else {
1419-
error!("Could not find rustfmt in the global path.");
1420-
return;
1418+
return Err(io::Error::new(
1419+
io::ErrorKind::Other,
1420+
"Rustfmt activated, but it could not be found in global path.",
1421+
));
14211422
};
14221423

14231424
let mut cmd = Command::new(rustfmt);
14241425

1425-
if let Some(path) = self.context.options().format_configuration_file.as_ref().and_then(
1426-
|f| f.to_str()) {
1426+
if let Some(path) = self.context
1427+
.options()
1428+
.rustfmt_configuration_file
1429+
.as_ref()
1430+
.and_then(|f| f.to_str())
1431+
{
14271432
cmd.args(&["--config-path", path]);
14281433
}
14291434

1430-
if let Err(e) = cmd.arg(file).status() {
1431-
error!("Error executing rustfmt (exit code: {:?}).", e);
1435+
if let Ok(output) = cmd.arg(file).output() {
1436+
if !output.status.success() {
1437+
let stderr = String::from_utf8_lossy(&output.stderr);
1438+
match output.status.code() {
1439+
Some(2) => Err(io::Error::new(
1440+
io::ErrorKind::Other,
1441+
format!("Rustfmt parsing errors:\n{}", stderr),
1442+
)),
1443+
Some(3) => {
1444+
warn!(
1445+
"Rustfmt could not format some lines:\n{}",
1446+
stderr
1447+
);
1448+
Ok(())
1449+
}
1450+
_ => Err(io::Error::new(
1451+
io::ErrorKind::Other,
1452+
format!("Internal rustfmt error:\n{}", stderr),
1453+
)),
1454+
}
1455+
} else {
1456+
Ok(())
1457+
}
1458+
} else {
1459+
Err(io::Error::new(
1460+
io::ErrorKind::Other,
1461+
"Error executing rustfmt!",
1462+
))
14321463
}
14331464
}
14341465
}

0 commit comments

Comments
 (0)