rustfmt.rs 691 B

12345678910111213141516171819202122232425
  1. use std::{
  2. io::{self, Write},
  3. process::{Command, Stdio},
  4. };
  5. pub fn format(code: &str) -> Result<String, io::Error> {
  6. let mut child = Command::new("rustfmt")
  7. .stdin(Stdio::piped())
  8. .stdout(Stdio::piped())
  9. .spawn()?;
  10. let stdin = child.stdin.as_mut().unwrap();
  11. stdin.write_all(code.as_bytes())?;
  12. let output = child.wait_with_output()?;
  13. if !output.status.success() {
  14. return Err(io::Error::new(
  15. io::ErrorKind::Other,
  16. format!(
  17. "rustfmt failed with exit code: {}",
  18. output.status.code().unwrap()
  19. ),
  20. ));
  21. }
  22. Ok(String::from_utf8(output.stdout).unwrap())
  23. }