on 0a42d2b help sign in
bat/src/output.rs
119 lines 3.9 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 crate::errors::*;
10use crate::PagingMode;
12#[derive(Debug)]
13pub enum OutputType {
14 Pager(Child),
15 Stdout(io::Stdout),
18impl OutputType {
19 pub fn from_mode(mode: PagingMode, pager: Option<&str>) -> Result<Self> {
20 use self::PagingMode::*;
21 Ok(match mode {
22 Always => OutputType::try_pager(false, pager)?,
23 QuitIfOneScreen => OutputType::try_pager(true, pager)?,
24 _ => OutputType::stdout(),
25 })
26 }
28 /// Try to launch the pager. Fall back to stdout in case of errors.
29 fn try_pager(quit_if_one_screen: bool, pager_from_config: Option<&str>) -> Result<Self> {
30 let mut replace_arguments_to_less = false;
32 let pager_from_env = match (env::var("BAT_PAGER"), env::var("PAGER")) {
33 (Ok(bat_pager), _) => Some(bat_pager),
34 (_, Ok(pager)) => {
35 // less needs to be called with the '-R' option in order to properly interpret the
36 // ANSI color sequences printed by bat. If someone has set PAGER="less -F", we
37 // therefore need to overwrite the arguments and add '-R'.
38 //
39 // We only do this for PAGER (as it is not specific to 'bat'), not for BAT_PAGER
40 // or bats '--pager' command line option.
41 replace_arguments_to_less = true;
42 Some(pager)
43 }
44 _ => None,
45 };
47 let pager_from_config = pager_from_config.map(|p| p.to_string());
49 if pager_from_config.is_some() {
50 replace_arguments_to_less = false;
51 }
53 let pager = pager_from_config
54 .or(pager_from_env)
55 .unwrap_or_else(|| String::from("less"));
57 let pagerflags =
58 shell_words::split(&pager).chain_err(|| "Could not parse pager command.")?;
60 match pagerflags.split_first() {
61 Some((pager_name, args)) => {
62 let mut pager_path = PathBuf::from(pager_name);
64 if pager_path.file_stem() == Some(&OsString::from("bat")) {
65 pager_path = PathBuf::from("less");
66 }
68 let is_less = pager_path.file_stem() == Some(&OsString::from("less"));
70 let mut process = if is_less {
71 let mut p = Command::new(&pager_path);
72 if args.is_empty() || replace_arguments_to_less {
73 p.args(vec!["--RAW-CONTROL-CHARS", "--no-init"]);
74 if quit_if_one_screen {
75 p.arg("--quit-if-one-screen");
76 }
77 } else {
78 p.args(args);
79 }
80 p.env("LESSCHARSET", "UTF-8");
81 p
82 } else {
83 let mut p = Command::new(&pager_path);
84 p.args(args);
85 p
86 };
88 Ok(process
89 .stdin(Stdio::piped())
90 .spawn()
91 .map(OutputType::Pager)
92 .unwrap_or_else(|_| OutputType::stdout()))
93 }
94 None => Ok(OutputType::stdout()),
95 }
96 }
98 fn stdout() -> Self {
99 OutputType::Stdout(io::stdout())
100 }
102 pub fn handle(&mut self) -> Result<&mut dyn Write> {
103 Ok(match *self {
104 OutputType::Pager(ref mut command) => command
105 .stdin
106 .as_mut()
107 .chain_err(|| "Could not open stdin for pager")?,
108 OutputType::Stdout(ref mut handle) => handle,
109 })
110 }
113impl Drop for OutputType {
114 fn drop(&mut self) {
115 if let OutputType::Pager(ref mut command) = *self {
116 let _ = command.wait();
117 }
118 }