on a236a9b help sign in
bat/src/app.rs
333 lines 11 kB history raw
1use std::collections::HashSet;
2use std::env;
3use std::str::FromStr;
5use atty::{self, Stream};
7use clap::ArgMatches;
8use clap_app;
9use wild;
11use console::Term;
13#[cfg(windows)]
14use ansi_term;
16use assets::BAT_THEME_DEFAULT;
17use config::{get_args_from_config_file, get_args_from_env_var};
18use errors::*;
19use inputfile::InputFile;
20use line_range::{LineRange, LineRanges};
21use style::{OutputComponent, OutputComponents, OutputWrap};
22use syntax_mapping::SyntaxMapping;
23use util::transpose;
25#[derive(Debug, Clone, Copy, PartialEq)]
26pub enum PagingMode {
27 Always,
28 QuitIfOneScreen,
29 Never,
32#[derive(Clone)]
33pub struct Config<'a> {
34 /// List of files to print
35 pub files: Vec<InputFile<'a>>,
37 /// The explicitly configured language, if any
38 pub language: Option<&'a str>,
40 /// Whether or not to show/replace non-printable characters like space, tab and newline.
41 pub show_nonprintable: bool,
43 /// The character width of the terminal
44 pub term_width: usize,
46 /// The width of tab characters.
47 /// Currently, a value of 0 will cause tabs to be passed through without expanding them.
48 pub tab_width: usize,
50 /// Whether or not to simply loop through all input (`cat` mode)
51 pub loop_through: bool,
53 /// Whether or not the output should be colorized
54 pub colored_output: bool,
56 /// Whether or not the output terminal supports true color
57 pub true_color: bool,
59 /// Style elements (grid, line numbers, ...)
60 pub output_components: OutputComponents,
62 /// Text wrapping mode
63 pub output_wrap: OutputWrap,
65 /// Pager or STDOUT
66 pub paging_mode: PagingMode,
68 /// Specifies the lines that should be printed
69 pub line_ranges: LineRanges,
71 /// The syntax highlighting theme
72 pub theme: String,
74 /// File extension/name mappings
75 pub syntax_mapping: SyntaxMapping,
77 /// Command to start the pager
78 pub pager: Option<&'a str>,
80 /// Whether or not to use ANSI italics
81 pub use_italic_text: bool,
83 /// A line to highlight
84 pub highlight_line: Option<usize>,
87fn is_truecolor_terminal() -> bool {
88 env::var("COLORTERM")
89 .map(|colorterm| colorterm == "truecolor" || colorterm == "24bit")
90 .unwrap_or(false)
93pub struct App {
94 pub matches: ArgMatches<'static>,
95 interactive_output: bool,
98impl App {
99 pub fn new() -> Result<Self> {
100 #[cfg(windows)]
101 let _ = ansi_term::enable_ansi_support();
103 let interactive_output = atty::is(Stream::Stdout);
105 Ok(App {
106 matches: Self::matches(interactive_output)?,
107 interactive_output,
108 })
109 }
111 fn matches(interactive_output: bool) -> Result<ArgMatches<'static>> {
112 let args = if wild::args_os().nth(1) == Some("cache".into())
113 || wild::args_os().any(|arg| arg == "--no-config")
114 {
115 // Skip the arguments in bats config file
117 wild::args_os().collect::<Vec<_>>()
118 } else {
119 let mut cli_args = wild::args_os();
121 // Read arguments from bats config file
122 let mut args = get_args_from_env_var()
123 .unwrap_or_else(|| get_args_from_config_file())
124 .chain_err(|| "Could not parse configuration file")?;
126 // Put the zero-th CLI argument (program name) first
127 args.insert(0, cli_args.next().unwrap());
129 // .. and the rest at the end
130 cli_args.for_each(|a| args.push(a));
132 args
133 };
135 Ok(clap_app::build_app(interactive_output).get_matches_from(args))
136 }
138 pub fn config(&self) -> Result<Config> {
139 let files = self.files();
140 let output_components = self.output_components()?;
142 let paging_mode = match self.matches.value_of("paging") {
143 Some("always") => PagingMode::Always,
144 Some("never") => PagingMode::Never,
145 Some("auto") | _ => {
146 if files.contains(&InputFile::StdIn) {
147 // If we are reading from stdin, only enable paging if we write to an
148 // interactive terminal and if we do not *read* from an interactive
149 // terminal.
150 if self.interactive_output && !atty::is(Stream::Stdin) {
151 PagingMode::QuitIfOneScreen
152 } else {
153 PagingMode::Never
154 }
155 } else {
156 if self.interactive_output {
157 PagingMode::QuitIfOneScreen
158 } else {
159 PagingMode::Never
160 }
161 }
162 }
163 };
165 let mut syntax_mapping = SyntaxMapping::new();
167 if let Some(values) = self.matches.values_of("map-syntax") {
168 for from_to in values {
169 let parts: Vec<_> = from_to.split(":").collect();
171 if parts.len() != 2 {
172 return Err("Invalid syntax mapping. The format of the -m/--map-syntax option is 'from:to'.".into());
173 }
175 syntax_mapping.insert(parts[0], parts[1]);
176 }
177 }
179 Ok(Config {
180 true_color: is_truecolor_terminal(),
181 language: self.matches.value_of("language").or_else(|| {
182 if self.matches.is_present("show-all") {
183 Some("show-nonprintable")
184 } else {
185 None
186 }
187 }),
188 show_nonprintable: self.matches.is_present("show-all"),
189 output_wrap: if !self.interactive_output {
190 // We don't have the tty width when piping to another program.
191 // There's no point in wrapping when this is the case.
192 OutputWrap::None
193 } else {
194 match self.matches.value_of("wrap") {
195 Some("character") => OutputWrap::Character,
196 Some("never") => OutputWrap::None,
197 Some("auto") | _ => {
198 if output_components.plain() {
199 OutputWrap::None
200 } else {
201 OutputWrap::Character
202 }
203 }
204 }
205 },
206 colored_output: match self.matches.value_of("color") {
207 Some("always") => true,
208 Some("never") => false,
209 Some("auto") | _ => self.interactive_output,
210 },
211 paging_mode,
212 term_width: self
213 .matches
214 .value_of("terminal-width")
215 .and_then(|w| {
216 if w.starts_with("+") || w.starts_with("-") {
217 // Treat argument as a delta to the current terminal width
218 w.parse().ok().map(|delta: i16| {
219 let old_width: u16 = Term::stdout().size().1;
220 let new_width: i32 = old_width as i32 + delta as i32;
222 if new_width <= 0 {
223 old_width as usize
224 } else {
225 new_width as usize
226 }
227 })
228 } else {
229 w.parse().ok()
230 }
231 })
232 .unwrap_or(Term::stdout().size().1 as usize),
233 loop_through: !(self.interactive_output
234 || self.matches.value_of("color") == Some("always")
235 || self.matches.value_of("decorations") == Some("always")),
236 files,
237 tab_width: self
238 .matches
239 .value_of("tabs")
240 .map(String::from)
241 .or_else(|| env::var("BAT_TABS").ok())
242 .and_then(|t| t.parse().ok())
243 .unwrap_or(
244 if output_components.plain() && paging_mode == PagingMode::Never {
245 0
246 } else {
247 4
248 },
249 ),
250 theme: self
251 .matches
252 .value_of("theme")
253 .map(String::from)
254 .or_else(|| env::var("BAT_THEME").ok())
255 .unwrap_or(String::from(BAT_THEME_DEFAULT)),
256 line_ranges: LineRanges::from(
257 transpose(
258 self.matches
259 .values_of("line-range")
260 .map(|vs| vs.map(LineRange::from).collect()),
261 )?
262 .unwrap_or(vec![]),
263 ),
264 output_components,
265 syntax_mapping,
266 pager: self.matches.value_of("pager"),
267 use_italic_text: match self.matches.value_of("italic-text") {
268 Some("always") => true,
269 _ => false,
270 },
271 highlight_line: self
272 .matches
273 .value_of("highlight-line")
274 .and_then(|w| w.parse().ok()),
275 })
276 }
278 fn files(&self) -> Vec<InputFile> {
279 self.matches
280 .values_of("FILE")
281 .map(|values| {
282 values
283 .map(|filename| {
284 if filename == "-" {
285 InputFile::StdIn
286 } else {
287 InputFile::Ordinary(filename)
288 }
289 })
290 .collect()
291 })
292 .unwrap_or_else(|| vec![InputFile::StdIn])
293 }
295 fn output_components(&self) -> Result<OutputComponents> {
296 let matches = &self.matches;
297 Ok(OutputComponents(
298 if matches.value_of("decorations") == Some("never") {
299 HashSet::new()
300 } else if matches.is_present("number") {
301 [OutputComponent::Numbers].iter().cloned().collect()
302 } else if matches.is_present("plain") {
303 [OutputComponent::Plain].iter().cloned().collect()
304 } else {
305 let env_style_components: Option<Vec<OutputComponent>> =
306 transpose(env::var("BAT_STYLE").ok().map(|style_str| {
307 style_str
308 .split(",")
309 .map(|x| OutputComponent::from_str(&x))
310 .collect::<Result<Vec<OutputComponent>>>()
311 }))?;
313 matches
314 .value_of("style")
315 .map(|styles| {
316 styles
317 .split(",")
318 .map(|style| style.parse::<OutputComponent>())
319 .filter_map(|style| style.ok())
320 .collect::<Vec<_>>()
321 })
322 .or(env_style_components)
323 .unwrap_or(vec![OutputComponent::Full])
324 .into_iter()
325 .map(|style| style.components(self.interactive_output))
326 .fold(HashSet::new(), |mut acc, components| {
327 acc.extend(components.iter().cloned());
328 acc
329 })
330 },
331 ))
332 }