on master help sign in
Allow specifying the theme via the `BAT_THEME` environment variable

The `--theme` command line option stills takes precedence and this change preserves how errors are handled when it's used: If a theme name that doesn't exist is specified using the argument, this error is fatal. However, if a theme that doesn't exist is specified using the environment variable, the error is logged to `stderr` and the "Default" theme is loaded as a fallback.

commitc68aa0f42432761c3f4bbcba70cb36c890901627 authorArmando Perez <gmandx@gmail.com> dateFri 20 Jul 2018, 23:26 (8 years ago) parent6b57f4e
3 files changed+23−3
src/app.rs+14−2 src/assets.rs+4 src/features.rs+5−1
src/app.rs+14−2
@@ -1,3 +1,4 @@
1+use assets::HighlightingAssets;
12use atty::{self, Stream};
23use clap::{App as ClapApp, AppSettings, Arg, ArgGroup, ArgMatches, SubCommand};
34use console::Term;
@@ -282,7 +283,18 @@ impl App {
282283 },
283284 term_width: Term::stdout().size().1 as usize,
284285 files,
285− theme: self.matches.value_of("theme"),
286+ theme: self.matches
287+ .value_of("theme")
288+ .and_then(|theme_name_arg| Some(String::from(theme_name_arg)))
289+ .or_else(|| {
290+ env::var("BAT_THEME").ok().and_then(|theme_name_env| {
291+ if HighlightingAssets::new().theme_exists(&theme_name_env) {
292+ Some(theme_name_env)
293+ } else {
294+ None
295+ }
296+ })
297+ }),
286298 line_range: transpose(self.matches.value_of("line-range").map(LineRange::from))?,
287299 })
288300 }
@@ -336,7 +348,7 @@ pub struct Config<'a> {
336348 pub paging_mode: PagingMode,
337349 pub term_width: usize,
338350 pub files: Vec<Option<&'a str>>,
339− pub theme: Option<&'a str>,
351+ pub theme: Option<String>,
340352 pub line_range: Option<LineRange>,
341353}
342354
src/assets.rs+4
@@ -132,6 +132,10 @@ impl HighlightingAssets {
132132 })?)
133133 }
134134
135+ pub fn theme_exists(&self, theme: &str) -> bool {
136+ self.theme_set.themes.contains_key(theme)
137+ }
138+
135139 pub fn get_syntax(&self, language: Option<&str>, filename: Option<&str>) -> &SyntaxDefinition {
136140 let syntax = match (language, filename) {
137141 (Some(language), _) => self.syntax_set.find_syntax_by_token(language),
src/features.rs+5−1
@@ -57,7 +57,11 @@ pub fn list_languages(assets: &HighlightingAssets, term_width: usize) {
5757}
5858
5959pub fn print_files(assets: &HighlightingAssets, config: &Config) -> Result<bool> {
60− let theme = assets.get_theme(config.theme.unwrap_or("Default"))?;
60+ let theme = assets.get_theme(match config.theme {
61+ Some(ref theme_name) => theme_name,
62+ None => "Default",
63+ })?;
64+
6165 let mut output_type = OutputType::from_mode(config.paging_mode);
6266 let handle = output_type.handle()?;
6367 let mut printer = Printer::new(handle, &config);