on fcecd97 help sign in
bat/src/app.rs
213 lines 7.6 kB history raw
1use atty::{self, Stream};
2use clap::{App as ClapApp, AppSettings, Arg, ArgGroup, ArgMatches, SubCommand};
3use console::Term;
4use errors::*;
5use std::collections::HashSet;
6use std::env;
7use style::{OutputComponent, OutputComponents};
9#[cfg(windows)]
10use ansi_term;
12pub struct App {
13 pub matches: ArgMatches<'static>,
14 interactive_output: bool,
17impl App {
18 pub fn new() -> Self {
19 let interactive_output = atty::is(Stream::Stdout);
21 #[cfg(windows)]
22 let interactive_output = interactive_output && ansi_term::enable_ansi_support().is_ok();
24 App {
25 matches: Self::matches(interactive_output),
26 interactive_output,
27 }
28 }
30 fn matches(interactive_output: bool) -> ArgMatches<'static> {
31 let clap_color_setting = if interactive_output {
32 AppSettings::ColoredHelp
33 } else {
34 AppSettings::ColorNever
35 };
37 ClapApp::new(crate_name!())
38 .version(crate_version!())
39 .global_setting(clap_color_setting)
40 .global_setting(AppSettings::DeriveDisplayOrder)
41 .global_setting(AppSettings::UnifiedHelpMessage)
42 .global_setting(AppSettings::NextLineHelp)
43 .setting(AppSettings::InferSubcommands)
44 .setting(AppSettings::ArgsNegateSubcommands)
45 .setting(AppSettings::DisableHelpSubcommand)
46 .setting(AppSettings::VersionlessSubcommands)
47 .max_term_width(90)
48 .about(crate_description!())
49 .arg(
50 Arg::with_name("language")
51 .short("l")
52 .long("language")
53 .help("Set the language for highlighting")
54 .takes_value(true),
55 )
56 .arg(
57 Arg::with_name("FILE")
58 .help("File(s) to print")
59 .multiple(true)
60 .empty_values(false),
61 )
62 .arg(
63 Arg::with_name("style")
64 .long("style")
65 .use_delimiter(true)
66 .takes_value(true)
67 .possible_values(&[
68 "auto", "full", "plain", "changes", "header", "grid", "numbers",
69 ])
70 .default_value("auto")
71 .help("Additional info to display along with content"),
72 )
73 .arg(
74 Arg::with_name("color")
75 .long("color")
76 .takes_value(true)
77 .possible_values(&["auto", "never", "always"])
78 .default_value("auto")
79 .help("When to use colors"),
80 )
81 .arg(
82 Arg::with_name("paging")
83 .long("paging")
84 .takes_value(true)
85 .possible_values(&["auto", "never", "always"])
86 .default_value("auto")
87 .help("When to use the pager"),
88 )
89 .arg(
90 Arg::with_name("list-languages")
91 .long("list-languages")
92 .help("Displays supported languages"),
93 )
94 .arg(
95 Arg::with_name("theme")
96 .long("theme")
97 .takes_value(true)
98 .help("Set the theme for highlighting"),
99 )
100 .arg(
101 Arg::with_name("list-themes")
102 .long("list-themes")
103 .help("Displays supported themes"),
104 )
105 .subcommand(
106 SubCommand::with_name("cache")
107 .about("Modify the syntax-definition and theme cache")
108 .arg(
109 Arg::with_name("init")
110 .long("init")
111 .short("i")
112 .help("Initialize the cache by loading from the config dir"),
113 )
114 .arg(
115 Arg::with_name("clear")
116 .long("clear")
117 .short("c")
118 .help("Reset the cache"),
119 )
120 .arg(
121 Arg::with_name("config-dir")
122 .long("config-dir")
123 .short("d")
124 .help("Show the configuration directory"),
125 )
126 .group(
127 ArgGroup::with_name("cache-actions")
128 .args(&["init", "clear", "config-dir"])
129 .required(true),
130 ),
131 )
132 .help_message("Print this help message.")
133 .version_message("Show version information.")
134 .get_matches()
135 }
137 pub fn config(&self) -> Result<Config> {
138 let files = self.files();
140 Ok(Config {
141 true_color: is_truecolor_terminal(),
142 output_components: self.output_components()?,
143 language: self.matches.value_of("language"),
144 colored_output: match self.matches.value_of("color") {
145 Some("always") => true,
146 Some("never") => false,
147 Some("auto") | _ => self.interactive_output,
148 },
149 paging: match self.matches.value_of("paging") {
150 Some("always") => true,
151 Some("never") => false,
152 Some("auto") | _ => if files.contains(&None) {
153 // If we are reading from stdin, only enable paging if we write to an
154 // interactive terminal and if we do not *read* from an interactive
155 // terminal.
156 self.interactive_output && !atty::is(Stream::Stdin)
157 } else {
158 self.interactive_output
159 },
160 },
161 term_width: Term::stdout().size().1 as usize,
162 files,
163 theme: self.matches.value_of("theme"),
164 })
165 }
167 fn files(&self) -> Vec<Option<&str>> {
168 self.matches
169 .values_of("FILE")
170 .map(|values| {
171 values
172 .map(|filename| {
173 if filename == "-" {
174 None
175 } else {
176 Some(filename)
177 }
178 })
179 .collect()
180 })
181 .unwrap_or_else(|| vec![None]) // read from stdin (None) if no args are given
182 }
184 fn output_components(&self) -> Result<OutputComponents> {
185 let matches = &self.matches;
186 Ok(OutputComponents(
187 values_t!(matches.values_of("style"), OutputComponent)?
188 .into_iter()
189 .map(|style| style.components(self.interactive_output))
190 .fold(HashSet::new(), |mut acc, components| {
191 acc.extend(components.iter().cloned());
192 acc
193 }),
194 ))
195 }
198pub struct Config<'a> {
199 pub true_color: bool,
200 pub output_components: OutputComponents,
201 pub language: Option<&'a str>,
202 pub colored_output: bool,
203 pub paging: bool,
204 pub term_width: usize,
205 pub files: Vec<Option<&'a str>>,
206 pub theme: Option<&'a str>,
209fn is_truecolor_terminal() -> bool {
210 env::var("COLORTERM")
211 .map(|colorterm| colorterm == "truecolor" || colorterm == "24bit")
212 .unwrap_or(false)