on 2eee685 help sign in
bat/src/app.rs
232 lines 8.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, OutputWrap};
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("wrap")
91 .long("wrap")
92 .takes_value(true)
93 .possible_values(&["character", "never"])
94 .default_value("character")
95 .help("When to wrap text"),
96 )
97 .arg(
98 Arg::with_name("list-languages")
99 .long("list-languages")
100 .help("Displays supported languages"),
101 )
102 .arg(
103 Arg::with_name("theme")
104 .long("theme")
105 .takes_value(true)
106 .help("Set the theme for highlighting"),
107 )
108 .arg(
109 Arg::with_name("list-themes")
110 .long("list-themes")
111 .help("Displays supported themes"),
112 )
113 .subcommand(
114 SubCommand::with_name("cache")
115 .about("Modify the syntax-definition and theme cache")
116 .arg(
117 Arg::with_name("init")
118 .long("init")
119 .short("i")
120 .help("Initialize the cache by loading from the config dir"),
121 )
122 .arg(
123 Arg::with_name("clear")
124 .long("clear")
125 .short("c")
126 .help("Reset the cache"),
127 )
128 .arg(
129 Arg::with_name("config-dir")
130 .long("config-dir")
131 .short("d")
132 .help("Show the configuration directory"),
133 )
134 .group(
135 ArgGroup::with_name("cache-actions")
136 .args(&["init", "clear", "config-dir"])
137 .required(true),
138 ),
139 )
140 .help_message("Print this help message.")
141 .version_message("Show version information.")
142 .get_matches()
143 }
145 pub fn config(&self) -> Result<Config> {
146 let files = self.files();
148 Ok(Config {
149 true_color: is_truecolor_terminal(),
150 output_components: self.output_components()?,
151 language: self.matches.value_of("language"),
152 output_wrap: if !self.interactive_output {
153 // We don't have the tty width when piping to another program.
154 // There's no point in wrapping when this is the case.
155 OutputWrap::None
156 } else {
157 match self.matches.value_of("wrap") {
158 Some("character") => OutputWrap::Character,
159 Some("never") | _ => OutputWrap::None,
160 }
161 },
162 colored_output: match self.matches.value_of("color") {
163 Some("always") => true,
164 Some("never") => false,
165 Some("auto") | _ => self.interactive_output,
166 },
167 paging: match self.matches.value_of("paging") {
168 Some("always") => true,
169 Some("never") => false,
170 Some("auto") | _ => if files.contains(&None) {
171 // If we are reading from stdin, only enable paging if we write to an
172 // interactive terminal and if we do not *read* from an interactive
173 // terminal.
174 self.interactive_output && !atty::is(Stream::Stdin)
175 } else {
176 self.interactive_output
177 },
178 },
179 term_width: Term::stdout().size().1 as usize,
180 files,
181 theme: self.matches.value_of("theme"),
182 })
183 }
185 fn files(&self) -> Vec<Option<&str>> {
186 self.matches
187 .values_of("FILE")
188 .map(|values| {
189 values
190 .map(|filename| {
191 if filename == "-" {
192 None
193 } else {
194 Some(filename)
195 }
196 })
197 .collect()
198 })
199 .unwrap_or_else(|| vec![None]) // read from stdin (None) if no args are given
200 }
202 fn output_components(&self) -> Result<OutputComponents> {
203 let matches = &self.matches;
204 Ok(OutputComponents(
205 values_t!(matches.values_of("style"), OutputComponent)?
206 .into_iter()
207 .map(|style| style.components(self.interactive_output))
208 .fold(HashSet::new(), |mut acc, components| {
209 acc.extend(components.iter().cloned());
210 acc
211 }),
212 ))
213 }
216pub struct Config<'a> {
217 pub true_color: bool,
218 pub output_wrap: OutputWrap,
219 pub output_components: OutputComponents,
220 pub language: Option<&'a str>,
221 pub colored_output: bool,
222 pub paging: bool,
223 pub term_width: usize,
224 pub files: Vec<Option<&'a str>>,
225 pub theme: Option<&'a str>,
228fn is_truecolor_terminal() -> bool {
229 env::var("COLORTERM")
230 .map(|colorterm| colorterm == "truecolor" || colorterm == "24bit")
231 .unwrap_or(false)