Commit e28cfc2e authored by Cyril Plisko's avatar Cyril Plisko 🤔

Add Pager::skip_on_notty()

parent 0fa11396
......@@ -59,6 +59,19 @@ fn main() {
}
```
Sometimes you may want to bypass pager if the output of you executable
is not a `tty`. If this case you may use `.skip_on_notty()` to get the
desirable effect.
```rust
extern crate pager;
use pager::Pager;
fn main() {
Pager::new().skip_on_notty().setup();
// The rest of your program goes here
}
```
If you need to disable pager altogether set environment variable `NOPAGER`
and Pager::setup() will skip initialization. The host application will continue
as normal. Pager::is_on() will reflect the fact that no Pager is active.
......@@ -49,6 +49,18 @@
//! running as usual. `Pager` cleans after itself and doesn't leak resources in
//! case of setup failure.
//!
//! Sometimes you may want to bypass pager if the output of you executable is not a `tty`.
//! If this case you may use `.skip_on_notty()` to get the desirable effect.
//!
//! ```rust
//! extern crate pager;
//! use pager::Pager;
//! fn main() {
//! Pager::new().skip_on_notty().setup();
//! // The rest of your program goes here
//! }
//! ```
//!
//! If you need to disable pager altogether set environment variable `NOPAGER` and `Pager::setup()`
//! will skip initialization. The host application will continue as normal. `Pager::is_on()` will
//! reflect the fact that no Pager is active.
......@@ -67,6 +79,7 @@ pub struct Pager {
pager: Option<OsString>,
env: Option<String>,
on: bool,
skip_on_notty: bool,
}
impl Pager {
......@@ -83,6 +96,7 @@ impl Pager {
pager: pager,
env: String::from(env).into(),
on: true,
skip_on_notty: false,
}
}
......@@ -97,6 +111,15 @@ impl Pager {
pager: OsString::from(pager).into(),
env: None,
on: true,
skip_on_notty: false,
}
}
/// Instructs `Pager` to bypass invoking pager if output is not a `tty`
pub fn skip_on_notty(self) -> Self {
Pager {
skip_on_notty: true,
..self
}
}
......@@ -108,6 +131,10 @@ impl Pager {
/// Initiates Pager framework and sets up all the necessary environment for sending standard
/// output to the activated pager.
pub fn setup(&mut self) {
if self.skip_on_notty && !utils::isatty(libc::STDOUT_FILENO) {
self.on = false;
return;
}
if let Some(ref pager) = self.pager {
let (pager_stdin, main_stdout) = utils::pipe();
let pid = utils::fork();
......
......@@ -68,6 +68,11 @@ pub fn find_pager(env: &str) -> Option<OsString> {
env::var_os(env).or_else(default_pager)
}
pub fn isatty(fd: i32) -> bool {
let isatty = unsafe { libc::isatty(fd) };
isatty != 0
}
#[cfg(test)]
mod tests {
use super::*;
......
......@@ -12,3 +12,10 @@ fn nopager() {
env::remove_var("NOPAGER");
assert!(!pager.is_on());
}
#[test]
fn notty() {
let mut pager = Pager::new().skip_on_notty();
pager.setup();
assert!(!pager.is_on());
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment