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