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