on d3d795f help sign in
bat/src/output.rs
96 lines 3.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 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, pager: Option<&str>) -> Result<Self> {
19 use self::PagingMode::*;
20 Ok(match mode {
21 Always => OutputType::try_pager(false, pager)?,
22 QuitIfOneScreen => OutputType::try_pager(true, pager)?,
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, pager_from_config: Option<&str>) -> Result<Self> {
29 let pager_from_env = env::var("BAT_PAGER").or_else(|_| env::var("PAGER"));
31 let pager = pager_from_config
32 .map(|p| p.to_string())
33 .or(pager_from_env.ok())
34 .unwrap_or(String::from("less"));
36 let pagerflags = shell_words::split(&pager)
37 .chain_err(|| "Could not parse (BAT_)PAGER environment variable.")?;
39 match pagerflags.split_first() {
40 Some((pager_name, mut args)) => {
41 let mut pager_path = PathBuf::from(pager_name);
43 if pager_path.file_stem() == Some(&OsString::from("bat")) {
44 pager_path = PathBuf::from("less");
45 args = &[];
46 }
48 let is_less = pager_path.file_stem() == Some(&OsString::from("less"));
50 let mut process = if is_less {
51 let mut p = Command::new(&pager_path);
52 if args.is_empty() {
53 p.args(vec!["--RAW-CONTROL-CHARS", "--no-init"]);
54 if quit_if_one_screen {
55 p.arg("--quit-if-one-screen");
56 }
57 }
58 p.env("LESSCHARSET", "UTF-8");
59 p
60 } else {
61 Command::new(&pager_path)
62 };
64 Ok(process
65 .args(args)
66 .stdin(Stdio::piped())
67 .spawn()
68 .map(OutputType::Pager)
69 .unwrap_or_else(|_| OutputType::stdout()))
70 }
71 None => Ok(OutputType::stdout()),
72 }
73 }
75 fn stdout() -> Self {
76 OutputType::Stdout(io::stdout())
77 }
79 pub fn handle(&mut self) -> Result<&mut Write> {
80 Ok(match *self {
81 OutputType::Pager(ref mut command) => command
82 .stdin
83 .as_mut()
84 .chain_err(|| "Could not open stdin for pager")?,
85 OutputType::Stdout(ref mut handle) => handle,
86 })
87 }
90impl Drop for OutputType {
91 fn drop(&mut self) {
92 if let OutputType::Pager(ref mut command) = *self {
93 let _ = command.wait();
94 }
95 }