Skip to content

Commit 7fe3f0c

Browse files
committed
Improves error handling for rustfmt
1 parent 80c7428 commit 7fe3f0c

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
@@ -1347,8 +1347,7 @@ impl<'ctx> Bindings<'ctx> {
13471347
self.write(Box::new(file))?;
13481348
}
13491349

1350-
self.format_generated_file(path.as_ref());
1351-
Ok(())
1350+
self.rustfmt_generated_file(path.as_ref())
13521351
}
13531352

13541353
/// Write these bindings as source text to the given `Write`able.
@@ -1372,28 +1371,60 @@ impl<'ctx> Bindings<'ctx> {
13721371
ps.s.out.flush()
13731372
}
13741373

1375-
/// Checks if format_bindings is set and runs rustfmt on the file
1376-
fn format_generated_file(&self, file: &Path) {
1377-
if !self.context.options().format_bindings {
1378-
return;
1374+
/// Checks if rustfmt_bindings is set and runs rustfmt on the file
1375+
fn rustfmt_generated_file(&self, file: &Path) -> io::Result<()> {
1376+
if !self.context.options().rustfmt_bindings {
1377+
return Ok(());
13791378
}
13801379

13811380
let rustfmt = if let Ok(rustfmt) = which::which("rustfmt") {
13821381
rustfmt
13831382
} else {
1384-
error!("Could not find rustfmt in the global path.");
1385-
return;
1383+
return Err(io::Error::new(
1384+
io::ErrorKind::Other,
1385+
"Rustfmt activated, but it could not be found in global path.",
1386+
));
13861387
};
13871388

13881389
let mut cmd = Command::new(rustfmt);
13891390

1390-
if let Some(path) = self.context.options().format_configuration_file.as_ref().and_then(
1391-
|f| f.to_str()) {
1391+
if let Some(path) = self.context
1392+
.options()
1393+
.rustfmt_configuration_file
1394+
.as_ref()
1395+
.and_then(|f| f.to_str())
1396+
{
13921397
cmd.args(&["--config-path", path]);
13931398
}
13941399

1395-
if let Err(e) = cmd.arg(file).status() {
1396-
error!("Error executing rustfmt (exit code: {:?}).", e);
1400+
if let Ok(output) = cmd.arg(file).output() {
1401+
if !output.status.success() {
1402+
let stderr = String::from_utf8_lossy(&output.stderr);
1403+
match output.status.code() {
1404+
Some(2) => Err(io::Error::new(
1405+
io::ErrorKind::Other,
1406+
format!("Rustfmt parsing errors:\n{}", stderr),
1407+
)),
1408+
Some(3) => {
1409+
warn!(
1410+
"Rustfmt could not format some lines:\n{}",
1411+
stderr
1412+
);
1413+
Ok(())
1414+
}
1415+
_ => Err(io::Error::new(
1416+
io::ErrorKind::Other,
1417+
format!("Internal rustfmt error:\n{}", stderr),
1418+
)),
1419+
}
1420+
} else {
1421+
Ok(())
1422+
}
1423+
} else {
1424+
Err(io::Error::new(
1425+
io::ErrorKind::Other,
1426+
"Error executing rustfmt!",
1427+
))
13971428
}
13981429
}
13991430
}

0 commit comments

Comments
 (0)