on f140f6d help sign in
bat/src/output.rs
75 lines 2.0 kB history raw
1use std::env;
2use std::ffi::OsString;
3use std::io::{self, Write};
4use std::path::PathBuf;
5use std::process::{Child, Command, Stdio};
7use app::PagingMode;
8use errors::*;
10pub enum OutputType {
11 Pager(Child),
12 Stdout(io::Stdout),
15impl OutputType {
16 pub fn from_mode(mode: PagingMode) -> Self {
17 use self::PagingMode::*;
18 match mode {
19 Always => OutputType::try_pager(false),
20 QuitIfOneScreen => OutputType::try_pager(true),
21 _ => OutputType::stdout(),
22 }
23 }
25 /// Try to launch the pager. Fall back to stdout in case of errors.
26 fn try_pager(quit_if_one_screen: bool) -> Self {
27 let pager = env::var("BAT_PAGER")
28 .or_else(|_| env::var("PAGER"))
29 .unwrap_or(String::from("less"));
31 let less_path = PathBuf::from(&pager);
32 let is_less = less_path.file_stem() == Some(&OsString::from("less"));
34 let mut process = if is_less {
35 let mut args = vec!["--RAW-CONTROL-CHARS", "--no-init"];
36 if quit_if_one_screen {
37 args.push("--quit-if-one-screen");
38 }
40 let mut p = Command::new(&less_path);
41 p.args(&args).env("LESSCHARSET", "UTF-8");
42 p
43 } else {
44 Command::new(pager)
45 };
47 process
48 .stdin(Stdio::piped())
49 .spawn()
50 .map(OutputType::Pager)
51 .unwrap_or_else(|_| OutputType::stdout())
52 }
54 fn stdout() -> Self {
55 OutputType::Stdout(io::stdout())
56 }
58 pub fn handle(&mut self) -> Result<&mut Write> {
59 Ok(match *self {
60 OutputType::Pager(ref mut command) => command
61 .stdin
62 .as_mut()
63 .chain_err(|| "Could not open stdin for pager")?,
64 OutputType::Stdout(ref mut handle) => handle,
65 })
66 }
69impl Drop for OutputType {
70 fn drop(&mut self) {
71 if let OutputType::Pager(ref mut command) = *self {
72 let _ = command.wait();
73 }
74 }