on f711fb5 help sign in
bat/src/app.rs
194 lines 7.0 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 .subcommand(
89 SubCommand::with_name("cache")
90 .about("Modify the syntax-definition and theme cache")
91 .arg(
92 Arg::with_name("init")
93 .long("init")
94 .short("i")
95 .help("Initialize the cache by loading from the config dir"),
96 )
97 .arg(
98 Arg::with_name("clear")
99 .long("clear")
100 .short("c")
101 .help("Reset the cache"),
102 )
103 .arg(
104 Arg::with_name("config-dir")
105 .long("config-dir")
106 .short("d")
107 .help("Show the configuration directory"),
108 )
109 .group(
110 ArgGroup::with_name("cache-actions")
111 .args(&["init", "clear", "config-dir"])
112 .required(true),
113 ),
114 )
115 .help_message("Print this help message.")
116 .version_message("Show version information.")
117 .get_matches()
118 }
120 pub fn config(&self) -> Result<Config> {
121 let files = self.files();
123 Ok(Config {
124 true_color: is_truecolor_terminal(),
125 output_components: self.output_components()?,
126 language: self.matches.value_of("language"),
127 colored_output: match self.matches.value_of("color") {
128 Some("always") => true,
129 Some("never") => false,
130 Some("auto") | _ => self.interactive_output,
131 },
132 paging: match self.matches.value_of("paging") {
133 Some("always") => true,
134 Some("never") => false,
135 Some("auto") | _ => if files.contains(&None) {
136 // If we are reading from stdin, only enable paging if we write to an
137 // interactive terminal and if we do not *read* from an interactive
138 // terminal.
139 self.interactive_output && !atty::is(Stream::Stdin)
140 } else {
141 self.interactive_output
142 },
143 },
144 term_width: Term::stdout().size().1 as usize,
145 files,
146 })
147 }
149 fn files(&self) -> Vec<Option<&str>> {
150 self.matches
151 .values_of("FILE")
152 .map(|values| {
153 values
154 .map(|filename| {
155 if filename == "-" {
156 None
157 } else {
158 Some(filename)
159 }
160 })
161 .collect()
162 })
163 .unwrap_or_else(|| vec![None]) // read from stdin (None) if no args are given
164 }
166 fn output_components(&self) -> Result<OutputComponents> {
167 let matches = &self.matches;
168 Ok(OutputComponents(
169 values_t!(matches.values_of("style"), OutputComponent)?
170 .into_iter()
171 .map(|style| style.components(self.interactive_output))
172 .fold(HashSet::new(), |mut acc, components| {
173 acc.extend(components.iter().cloned());
174 acc
175 }),
176 ))
177 }
180pub struct Config<'a> {
181 pub true_color: bool,
182 pub output_components: OutputComponents,
183 pub language: Option<&'a str>,
184 pub colored_output: bool,
185 pub paging: bool,
186 pub term_width: usize,
187 pub files: Vec<Option<&'a str>>,
190fn is_truecolor_terminal() -> bool {
191 env::var("COLORTERM")
192 .map(|colorterm| colorterm == "truecolor" || colorterm == "24bit")
193 .unwrap_or(false)