Skip to content

Commit 2011561

Browse files
committed
Automatically pipe output through rustfmt and bat.
1 parent 196588e commit 2011561

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

tools/unstable-api/Cargo.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,6 @@ version = "0.3"
1919

2020
[dependencies.anyhow]
2121
version = "1"
22+
23+
[target.'cfg(unix)'.dependencies]
24+
nix = "0.20"

tools/unstable-api/src/main.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@ fn main() -> Result<(), Error> {
2727
None => find_repo_root()?,
2828
};
2929

30+
#[cfg(unix)]
31+
setup_output_formatting();
32+
3033
let libs = vec![
3134
repo_root.clone().join("library/core"),
3235
repo_root.clone().join("library/alloc"),
@@ -52,3 +55,34 @@ fn find_repo_root() -> Result<PathBuf, Error> {
5255
path.pop();
5356
Ok(path)
5457
}
58+
59+
#[cfg(unix)]
60+
fn setup_output_formatting() {
61+
use nix::unistd::{isatty, dup2};
62+
use std::os::unix::io::AsRawFd;
63+
use std::process::{Command, Stdio};
64+
65+
if isatty(1) == Ok(true) {
66+
// Pipe the output through `bat` for nice formatting and paging, if available.
67+
if let Ok(mut bat) = Command::new("bat")
68+
.arg("--language=rust")
69+
.arg("--plain") // Disable line numbers for easy copy-pasting.
70+
.stdin(Stdio::piped())
71+
.stdout(Stdio::inherit())
72+
.spawn()
73+
{
74+
// Replace our stdout by the pipe into `bat`.
75+
dup2(bat.stdin.take().unwrap().as_raw_fd(), 1).unwrap();
76+
}
77+
}
78+
79+
// Pipe the output through `rustfmt`, if available.
80+
if let Ok(mut rustfmt) = Command::new("rustfmt")
81+
.stdin(Stdio::piped())
82+
.stdout(Stdio::inherit()) // This pipes into `bat` if it was executed above.
83+
.spawn()
84+
{
85+
// Replace our stdout by the pipe into `rustfmt`.
86+
dup2(rustfmt.stdin.take().unwrap().as_raw_fd(), 1).unwrap();
87+
}
88+
}

0 commit comments

Comments
 (0)