@@ -7,9 +7,13 @@ extern crate error_chain;
77#[macro_use]
88extern crate clap;
99
10+#[macro_use]
11+extern crate lazy_static;
12+
1013extern crate ansi_term;
1114extern crate atty;
1215extern crate console;
16+extern crate directories;
1317extern crate git2;
1418extern crate syntect;
1519
@@ -17,6 +21,7 @@ mod terminal;
1721
1822use std::collections::HashMap;
1923use std::env;
24+use std::fs::{self, File};
2025use std::io::{self, BufRead, StdoutLock, Write};
2126use std::path::Path;
2227use std::process;
@@ -24,16 +29,22 @@ use std::process;
2429use ansi_term::Colour::{Fixed, Green, Red, White, Yellow};
2530use ansi_term::Style;
2631use atty::Stream;
27−use clap::{App, AppSettings, Arg, ArgMatches};
32+use clap::{App, AppSettings, Arg, SubCommand};
2833use console::Term;
34+use directories::ProjectDirs;
2935use git2::{DiffOptions, IntoCString, Repository};
3036
37+use syntect::dumps::{dump_to_file, from_reader};
3138use syntect::easy::HighlightFile;
3239use syntect::highlighting::{Theme, ThemeSet};
3340use syntect::parsing::SyntaxSet;
3441
3542use terminal::as_terminal_escaped;
3643
44+lazy_static! {
45+ static ref PROJECT_DIRS: ProjectDirs = ProjectDirs::from("", "", crate_name!());
46+}
47+
3748mod errors {
3849 error_chain!{
3950 foreign_links {
@@ -197,54 +208,113 @@ fn get_git_diff(filename: &str) -> Option<LineChanges> {
197208 Some(line_changes)
198209}
199210
200−fn run(matches: &ArgMatches) -> Result<()> {
201− let home_dir = env::home_dir().chain_err(|| "Could not get home directory")?;
211+fn is_truecolor_terminal() -> bool {
212+ env::var("COLORTERM")
213+ .map(|colorterm| colorterm == "truecolor" || colorterm == "24bit")
214+ .unwrap_or(false)
215+}
202216
203− let colorterm = env::var("COLORTERM").unwrap_or_else(|_| "".into());
217+struct HighlightingAssets {
218+ pub syntax_set: SyntaxSet,
219+ pub theme_set: ThemeSet,
220+}
204221
205− let options = Options {
206− true_color: colorterm == "truecolor" || colorterm == "24bit",
207− };
222+impl HighlightingAssets {
223+ fn from_files() -> Result<Self> {
224+ let config_dir = PROJECT_DIRS.config_dir();
225+
226+ let theme_dir = config_dir.join("themes");
227+
228+ let theme_set = ThemeSet::load_from_folder(&theme_dir).map_err(|_| {
229+ io::Error::new(
230+ io::ErrorKind::Other,
231+ format!(
232+ "Could not load themes from '{}'",
233+ theme_dir.to_string_lossy()
234+ ),
235+ )
236+ })?;
237+
238+ let mut syntax_set = SyntaxSet::new();
239+ let syntax_dir = config_dir.join("syntax");
240+ let _ = syntax_set.load_syntaxes(syntax_dir, false);
241+ syntax_set.load_plain_text_syntax();
242+
243+ Ok(HighlightingAssets {
244+ syntax_set,
245+ theme_set,
246+ })
247+ }
208248
209− let theme_dir = home_dir.join(".config").join("bat").join("themes");
210− let theme_set = ThemeSet::load_from_folder(theme_dir).map_err(|_| {
211− io::Error::new(
212− io::ErrorKind::Other,
213− "Could not load themes from ~/.config/bat/themes",
214− )
215− })?;
216− let theme = &theme_set.themes.get("Default").ok_or_else(|| {
217− io::Error::new(
218− io::ErrorKind::Other,
219− "Could not load default theme (~/.config/bat/themes/Default.tmTheme)",
220− )
221− })?;
222−
223− // TODO: let mut syntax_set = SyntaxSet::load_defaults_nonewlines();
224− let mut syntax_set = SyntaxSet::new();
225− let syntax_dir = home_dir.join(".config").join("bat").join("syntax");
226− let _ = syntax_set.load_syntaxes(syntax_dir, false);
227− syntax_set.load_plain_text_syntax();
228− syntax_set.link_syntaxes();
229−
230− if let Some(files) = matches.values_of("FILE") {
231− for file in files {
232− let line_changes = get_git_diff(&file.to_string());
233− print_file(&options, theme, &syntax_set, file, &line_changes)?;
234− }
249+ fn save(&self) -> Result<()> {
250+ let cache_dir = PROJECT_DIRS.cache_dir();
251+ let theme_set_path = cache_dir.join("theme_set");
252+ let syntax_set_path = cache_dir.join("syntax_set");
253+
254+ let _ = fs::create_dir(cache_dir);
255+
256+ dump_to_file(&self.theme_set, &theme_set_path).map_err(|_| {
257+ io::Error::new(
258+ io::ErrorKind::Other,
259+ format!(
260+ "Could not save theme set to {}",
261+ theme_set_path.to_string_lossy()
262+ ),
263+ )
264+ })?;
265+ println!("Wrote theme set to {}", theme_set_path.to_string_lossy());
266+
267+ dump_to_file(&self.syntax_set, &syntax_set_path).map_err(|_| {
268+ io::Error::new(
269+ io::ErrorKind::Other,
270+ format!(
271+ "Could not save syntax set to {}",
272+ syntax_set_path.to_string_lossy()
273+ ),
274+ )
275+ })?;
276+ println!("Wrote syntax set to {}", syntax_set_path.to_string_lossy());
277+
278+ Ok(())
235279 }
236280
237− Ok(())
281+ fn from_cache() -> Result<Self> {
282+ let cache_dir = PROJECT_DIRS.cache_dir();
283+ let theme_set_path = cache_dir.join("theme_set");
284+ let syntax_set_path = cache_dir.join("syntax_set");
285+
286+ let syntax_set_file = File::open(syntax_set_path)?;
287+ let mut syntax_set: SyntaxSet = from_reader(syntax_set_file).map_err(|_| {
288+ io::Error::new(
289+ io::ErrorKind::Other,
290+ format!("Could not load cached syntax set"),
291+ )
292+ })?;
293+ syntax_set.link_syntaxes();
294+
295+ let theme_set_file = File::open(theme_set_path)?;
296+ let theme_set: ThemeSet = from_reader(theme_set_file).map_err(|_| {
297+ io::Error::new(
298+ io::ErrorKind::Other,
299+ format!("Could not load cached theme set"),
300+ )
301+ })?;
302+
303+ Ok(HighlightingAssets {
304+ syntax_set,
305+ theme_set,
306+ })
307+ }
238308}
239309
240−fn main() {
310+fn run() -> Result<()> {
241311 let clap_color_setting = if atty::is(Stream::Stdout) {
242312 AppSettings::ColoredHelp
243313 } else {
244314 AppSettings::ColorNever
245315 };
246316
247− let matches = App::new(crate_name!())
317+ let app_matches = App::new(crate_name!())
248318 .version(crate_version!())
249319 .setting(clap_color_setting)
250320 .setting(AppSettings::DeriveDisplayOrder)
@@ -259,11 +329,47 @@ fn main() {
259329 .multiple(true)
260330 .empty_values(false),
261331 )
332+ .subcommand(
333+ SubCommand::with_name("init-cache")
334+ .about("Load syntax definitions and themes into cache"),
335+ )
262336 .help_message("Print this help message.")
263337 .version_message("Show version information.")
264338 .get_matches();
265339
266− let result = run(&matches);
340+ match app_matches.subcommand() {
341+ ("init-cache", Some(_)) => {
342+ let assets = HighlightingAssets::from_files()?;
343+ assets.save()?;
344+ }
345+ _ => {
346+ let options = Options {
347+ true_color: is_truecolor_terminal(),
348+ };
349+
350+ let assets = HighlightingAssets::from_cache()?;
351+
352+ let theme = assets.theme_set.themes.get("Default").ok_or_else(|| {
353+ io::Error::new(
354+ io::ErrorKind::Other,
355+ format!("Could not find 'Default' theme"),
356+ )
357+ })?;
358+
359+ if let Some(files) = app_matches.values_of("FILE") {
360+ for file in files {
361+ let line_changes = get_git_diff(&file.to_string());
362+ print_file(&options, theme, &assets.syntax_set, file, &line_changes)?;
363+ }
364+ }
365+ }
366+ }
367+
368+ Ok(())
369+}
370+
371+fn main() {
372+ let result = run();
267373
268374 if let Err(error) = result {
269375 match error {