on 88fcfd7 help sign in
bat/src/output.rs
87 lines 2.6 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 shell_words;
9use app::PagingMode;
10use errors::*;
12pub enum OutputType {
13 Pager(Child),
14 Stdout(io::Stdout),
17impl OutputType {
18 pub fn from_mode(mode: PagingMode) -> Result<Self> {
19 use self::PagingMode::*;
20 Ok(match mode {
21 Always => OutputType::try_pager(false)?,
22 QuitIfOneScreen => OutputType::try_pager(true)?,
23 _ => OutputType::stdout(),
24 })
25 }
27 /// Try to launch the pager. Fall back to stdout in case of errors.
28 fn try_pager(quit_if_one_screen: bool) -> Result<Self> {
29 let pager = env::var("BAT_PAGER")
30 .or_else(|_| env::var("PAGER"))
31 .unwrap_or(String::from("less"));
33 let pagerflags = shell_words::split(&pager)
34 .chain_err(|| "Could not parse (BAT_)PAGER environment variable.")?;
36 match pagerflags.split_first() {
37 Some((pager_name, args)) => {
38 let pager_path = PathBuf::from(pager_name);
39 let is_less = pager_path.file_stem() == Some(&OsString::from("less"));
41 let mut process = if is_less {
42 let mut p = Command::new(&pager_path);
43 if args.is_empty() {
44 p.args(vec!["--RAW-CONTROL-CHARS", "--no-init"]);
45 if quit_if_one_screen {
46 p.arg("--quit-if-one-screen");
47 }
48 }
49 p.env("LESSCHARSET", "UTF-8");
50 p
51 } else {
52 Command::new(&pager_path)
53 };
55 Ok(process
56 .args(args)
57 .stdin(Stdio::piped())
58 .spawn()
59 .map(OutputType::Pager)
60 .unwrap_or_else(|_| OutputType::stdout()))
61 }
62 None => Ok(OutputType::stdout()),
63 }
64 }
66 fn stdout() -> Self {
67 OutputType::Stdout(io::stdout())
68 }
70 pub fn handle(&mut self) -> Result<&mut Write> {
71 Ok(match *self {
72 OutputType::Pager(ref mut command) => command
73 .stdin
74 .as_mut()
75 .chain_err(|| "Could not open stdin for pager")?,
76 OutputType::Stdout(ref mut handle) => handle,
77 })
78 }
81impl Drop for OutputType {
82 fn drop(&mut self) {
83 if let OutputType::Pager(ref mut command) = *self {
84 let _ = command.wait();
85 }
86 }