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