on 493a4e7 help sign in
bat/src/output.rs
118 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::app::PagingMode;
10use crate::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 mut replace_arguments_to_less = false;
31 let pager_from_env = match (env::var("BAT_PAGER"), env::var("PAGER")) {
32 (Ok(bat_pager), _) => Some(bat_pager),
33 (_, Ok(pager)) => {
34 // less needs to be called with the '-R' option in order to properly interpret the
35 // ANSI color sequences printed by bat. If someone has set PAGER="less -F", we
36 // therefore need to overwrite the arguments and add '-R'.
37 //
38 // We only do this for PAGER (as it is not specific to 'bat'), not for BAT_PAGER
39 // or bats '--pager' command line option.
40 replace_arguments_to_less = true;
41 Some(pager)
42 }
43 _ => None,
44 };
46 let pager_from_config = pager_from_config.map(|p| p.to_string());
48 if pager_from_config.is_some() {
49 replace_arguments_to_less = false;
50 }
52 let pager = pager_from_config
53 .or(pager_from_env)
54 .unwrap_or_else(|| String::from("less"));
56 let pagerflags =
57 shell_words::split(&pager).chain_err(|| "Could not parse pager command.")?;
59 match pagerflags.split_first() {
60 Some((pager_name, args)) => {
61 let mut pager_path = PathBuf::from(pager_name);
63 if pager_path.file_stem() == Some(&OsString::from("bat")) {
64 pager_path = PathBuf::from("less");
65 }
67 let is_less = pager_path.file_stem() == Some(&OsString::from("less"));
69 let mut process = if is_less {
70 let mut p = Command::new(&pager_path);
71 if args.is_empty() || replace_arguments_to_less {
72 p.args(vec!["--RAW-CONTROL-CHARS", "--no-init"]);
73 if quit_if_one_screen {
74 p.arg("--quit-if-one-screen");
75 }
76 } else {
77 p.args(args);
78 }
79 p.env("LESSCHARSET", "UTF-8");
80 p
81 } else {
82 let mut p = Command::new(&pager_path);
83 p.args(args);
84 p
85 };
87 Ok(process
88 .stdin(Stdio::piped())
89 .spawn()
90 .map(OutputType::Pager)
91 .unwrap_or_else(|_| OutputType::stdout()))
92 }
93 None => Ok(OutputType::stdout()),
94 }
95 }
97 fn stdout() -> Self {
98 OutputType::Stdout(io::stdout())
99 }
101 pub fn handle(&mut self) -> Result<&mut Write> {
102 Ok(match *self {
103 OutputType::Pager(ref mut command) => command
104 .stdin
105 .as_mut()
106 .chain_err(|| "Could not open stdin for pager")?,
107 OutputType::Stdout(ref mut handle) => handle,
108 })
109 }
112impl Drop for OutputType {
113 fn drop(&mut self) {
114 if let OutputType::Pager(ref mut command) = *self {
115 let _ = command.wait();
116 }
117 }