Run Pint via stdin and return the formatted content. Command: ` --stdin-filename= ` Pint reads from stdin and writes the formatted output to stdout when `--stdin-filename` is provided.
(
tool_path: &Path,
content: &str,
file_path: &Path,
timeout: Duration,
)
| 364 | /// Pint reads from stdin and writes the formatted output to stdout |
| 365 | /// when `--stdin-filename` is provided. |
| 366 | fn run_pint( |
| 367 | tool_path: &Path, |
| 368 | content: &str, |
| 369 | file_path: &Path, |
| 370 | timeout: Duration, |
| 371 | ) -> Result<String, String> { |
| 372 | let mut child = Command::new(tool_path) |
| 373 | .arg(format!("--stdin-filename={}", file_path.display())) |
| 374 | .stdin(Stdio::piped()) |
| 375 | .stdout(Stdio::piped()) |
| 376 | .stderr(Stdio::piped()) |
| 377 | .spawn() |
| 378 | .map_err(|e| format!("Failed to spawn pint: {}", e))?; |
| 379 | |
| 380 | if let Some(mut stdin) = child.stdin.take() { |
| 381 | stdin |
| 382 | .write_all(content.as_bytes()) |
| 383 | .map_err(|e| format!("Failed to write to pint stdin: {}", e))?; |
| 384 | } |
| 385 | |
| 386 | let start = std::time::Instant::now(); |
| 387 | loop { |
| 388 | match child.try_wait() { |
| 389 | Ok(Some(status)) => { |
| 390 | let mut stdout = String::new(); |
| 391 | if let Some(mut out) = child.stdout.take() { |
| 392 | std::io::Read::read_to_string(&mut out, &mut stdout) |
| 393 | .map_err(|e| format!("Failed to read pint stdout: {}", e))?; |
| 394 | } |
| 395 | |
| 396 | let code = status.code().unwrap_or(-1); |
| 397 | if code == 0 { |
| 398 | return Ok(stdout); |
| 399 | } |
| 400 | |
| 401 | let mut stderr = String::new(); |
| 402 | if let Some(mut err) = child.stderr.take() { |
| 403 | let _ = std::io::Read::read_to_string(&mut err, &mut stderr); |
| 404 | } |
| 405 | return Err(format!( |
| 406 | "pint exited with code {} (stderr: {})", |
| 407 | code, |
| 408 | stderr.trim() |
| 409 | )); |
| 410 | } |
| 411 | Ok(None) => { |
| 412 | if start.elapsed() >= timeout { |
| 413 | let _ = child.kill(); |
| 414 | let _ = child.wait(); |
| 415 | return Err(format!( |
| 416 | "Formatter timed out after {}ms", |
| 417 | timeout.as_millis() |
| 418 | )); |
| 419 | } |
| 420 | std::thread::sleep(Duration::from_millis(50)); |
| 421 | } |
| 422 | Err(e) => { |
| 423 | let _ = child.kill(); |