@@ -17,6 +17,8 @@ extern crate directories;
1717extern crate git2;
1818extern crate syntect;
1919
20+mod assets;
21+mod diff;
2022mod printer;
2123mod terminal;
2224
@@ -24,7 +26,6 @@ use std::collections::{HashMap, HashSet};
2426use std::env;
2527use std::fs::{self, File};
2628use std::io::{self, BufRead, BufReader, Write};
27−use std::path::{Path, PathBuf};
2829use std::process::{self, Child, Command, Stdio};
2930use std::str::FromStr;
3031
@@ -35,20 +36,15 @@ use ansi_term::Colour::{Fixed, Green, Red, White, Yellow};
3536use ansi_term::Style;
3637use atty::Stream;
3738use clap::{App, AppSettings, Arg, ArgGroup, SubCommand};
38−use directories::ProjectDirs;
39−use git2::{DiffOptions, IntoCString, Repository};
4039
41−use syntect::dumps::{dump_to_file, from_binary, from_reader};
4240use syntect::easy::HighlightLines;
43−use syntect::highlighting::{Theme, ThemeSet};
41+use syntect::highlighting::Theme;
4442use syntect::parsing::SyntaxSet;
4543
44+use assets::{config_dir, syntax_set_path, theme_set_path, HighlightingAssets};
45+use diff::get_git_diff;
4646use printer::Printer;
4747
48−lazy_static! {
49− static ref PROJECT_DIRS: ProjectDirs = ProjectDirs::from("", "", crate_name!());
50−}
51−
5248mod errors {
5349 error_chain! {
5450 foreign_links {
@@ -181,16 +177,6 @@ impl Drop for OutputType {
181177 }
182178}
183179
184−#[derive(Copy, Clone, Debug)]
185−pub enum LineChange {
186− Added,
187− RemovedAbove,
188− RemovedBelow,
189− Modified,
190−}
191−
192−pub type LineChanges = HashMap<u32, LineChange>;
193−
194180const GRID_COLOR: u8 = 238;
195181const LINE_NUMBER_COLOR: u8 = 244;
196182
@@ -291,68 +277,6 @@ fn print_file(
291277 Ok(())
292278}
293279
294−fn get_git_diff(filename: &str) -> Option<LineChanges> {
295− let repo = Repository::discover(&filename).ok()?;
296− let path_absolute = fs::canonicalize(&filename).ok()?;
297− let path_relative_to_repo = path_absolute.strip_prefix(repo.workdir()?).ok()?;
298−
299− let mut diff_options = DiffOptions::new();
300− let pathspec = path_relative_to_repo.into_c_string().ok()?;
301− diff_options.pathspec(pathspec);
302− diff_options.context_lines(0);
303−
304− let diff = repo.diff_index_to_workdir(None, Some(&mut diff_options))
305− .ok()?;
306−
307− let mut line_changes: LineChanges = HashMap::new();
308−
309− let mark_section =
310− |line_changes: &mut LineChanges, start: u32, end: i32, change: LineChange| {
311− for line in start..(end + 1) as u32 {
312− line_changes.insert(line, change);
313− }
314− };
315−
316− let _ = diff.foreach(
317− &mut |_, _| true,
318− None,
319− Some(&mut |delta, hunk| {
320− let path = delta.new_file().path().unwrap_or_else(|| Path::new(""));
321−
322− if path_relative_to_repo != path {
323− return false;
324− }
325−
326− let old_lines = hunk.old_lines();
327− let new_start = hunk.new_start();
328− let new_lines = hunk.new_lines();
329− let new_end = (new_start + new_lines) as i32 - 1;
330−
331− if old_lines == 0 && new_lines > 0 {
332− mark_section(&mut line_changes, new_start, new_end, LineChange::Added);
333− } else if new_lines == 0 && old_lines > 0 {
334− if new_start == 0 {
335− mark_section(&mut line_changes, 1, 1, LineChange::RemovedAbove);
336− } else {
337− mark_section(
338− &mut line_changes,
339− new_start,
340− new_start as i32,
341− LineChange::RemovedBelow,
342− );
343− }
344− } else {
345− mark_section(&mut line_changes, new_start, new_end, LineChange::Modified);
346− }
347−
348− true
349− }),
350− None,
351− );
352−
353− Some(line_changes)
354−}
355−
356280fn get_output_type(paging: bool) -> OutputType {
357281 if paging {
358282 OutputType::pager().unwrap_or_else(|_| OutputType::stdout())
@@ -367,129 +291,6 @@ fn is_truecolor_terminal() -> bool {
367291 .unwrap_or(false)
368292}
369293
370−struct HighlightingAssets {
371− pub syntax_set: SyntaxSet,
372− pub theme_set: ThemeSet,
373−}
374−
375−impl HighlightingAssets {
376− fn theme_set_path() -> PathBuf {
377− PROJECT_DIRS.cache_dir().join("theme_set")
378− }
379−
380− fn syntax_set_path() -> PathBuf {
381− PROJECT_DIRS.cache_dir().join("syntax_set")
382− }
383−
384− fn from_files() -> Result<Self> {
385− let config_dir = PROJECT_DIRS.config_dir();
386−
387− let theme_dir = config_dir.join("themes");
388−
389− let theme_set = ThemeSet::load_from_folder(&theme_dir).map_err(|_| {
390− io::Error::new(
391− io::ErrorKind::Other,
392− format!(
393− "Could not load themes from '{}'",
394− theme_dir.to_string_lossy()
395− ),
396− )
397− })?;
398−
399− let mut syntax_set = SyntaxSet::new();
400− let syntax_dir = config_dir.join("syntax");
401− let _ = syntax_set.load_syntaxes(syntax_dir, true);
402− syntax_set.load_plain_text_syntax();
403−
404− Ok(HighlightingAssets {
405− syntax_set,
406− theme_set,
407− })
408− }
409−
410− fn save(&self) -> Result<()> {
411− let cache_dir = PROJECT_DIRS.cache_dir();
412− let _ = fs::create_dir(cache_dir);
413−
414− print!(
415− "Writing theme set to {} ... ",
416− Self::theme_set_path().to_string_lossy()
417− );
418− dump_to_file(&self.theme_set, &Self::theme_set_path()).map_err(|_| {
419− io::Error::new(
420− io::ErrorKind::Other,
421− format!(
422− "Could not save theme set to {}",
423− Self::theme_set_path().to_string_lossy()
424− ),
425− )
426− })?;
427− println!("okay");
428−
429− print!(
430− "Writing syntax set to {} ... ",
431− Self::syntax_set_path().to_string_lossy()
432− );
433− dump_to_file(&self.syntax_set, &Self::syntax_set_path()).map_err(|_| {
434− io::Error::new(
435− io::ErrorKind::Other,
436− format!(
437− "Could not save syntax set to {}",
438− Self::syntax_set_path().to_string_lossy()
439− ),
440− )
441− })?;
442− println!("okay");
443−
444− Ok(())
445− }
446−
447− fn from_cache() -> Result<Self> {
448− let syntax_set_file = File::open(&Self::syntax_set_path()).chain_err(|| {
449− format!(
450− "Could not load cached syntax set '{}'",
451− Self::syntax_set_path().to_string_lossy()
452− )
453− })?;
454− let mut syntax_set: SyntaxSet = from_reader(syntax_set_file).map_err(|_| {
455− io::Error::new(
456− io::ErrorKind::Other,
457− format!("Could not parse cached syntax set"),
458− )
459− })?;
460− syntax_set.link_syntaxes();
461−
462− let theme_set_file = File::open(&Self::theme_set_path()).chain_err(|| {
463− format!(
464− "Could not load cached theme set '{}'",
465− Self::theme_set_path().to_string_lossy()
466− )
467− })?;
468− let theme_set: ThemeSet = from_reader(theme_set_file).map_err(|_| {
469− io::Error::new(
470− io::ErrorKind::Other,
471− format!("Could not parse cached theme set"),
472− )
473− })?;
474−
475− Ok(HighlightingAssets {
476− syntax_set,
477− theme_set,
478− })
479− }
480−
481− fn from_binary() -> Self {
482− let mut syntax_set: SyntaxSet = from_binary(include_bytes!("../assets/syntax_set"));
483− syntax_set.link_syntaxes();
484− let theme_set: ThemeSet = from_binary(include_bytes!("../assets/theme_set"));
485−
486− HighlightingAssets {
487− syntax_set,
488− theme_set,
489− }
490− }
491−}
492−
493294fn run() -> Result<()> {
494295 let interactive_terminal = atty::is(Stream::Stdout);
495296
@@ -592,14 +393,14 @@ fn run() -> Result<()> {
592393 assets.save()?;
593394 } else if cache_matches.is_present("clear") {
594395 print!("Clearing theme set cache ... ");
595− fs::remove_file(HighlightingAssets::theme_set_path())?;
396+ fs::remove_file(theme_set_path())?;
596397 println!("okay");
597398
598399 print!("Clearing syntax set cache ... ");
599− fs::remove_file(HighlightingAssets::syntax_set_path())?;
400+ fs::remove_file(syntax_set_path())?;
600401 println!("okay");
601402 } else if cache_matches.is_present("config-dir") {
602− println!("{}", PROJECT_DIRS.config_dir().to_string_lossy());
403+ println!("{}", config_dir());
603404 }
604405 }
605406 _ => {
@@ -650,15 +451,8 @@ fn run() -> Result<()> {
650451 term_width: console::Term::stdout().size().1 as usize,
651452 };
652453
653− let assets =
654− HighlightingAssets::from_cache().unwrap_or(HighlightingAssets::from_binary());
655−
656− let theme = assets.theme_set.themes.get("Default").ok_or_else(|| {
657− io::Error::new(
658− io::ErrorKind::Other,
659− format!("Could not find 'Default' theme"),
660− )
661− })?;
454+ let assets = HighlightingAssets::new();
455+ let theme = assets.default_theme()?;
662456
663457 if app_matches.is_present("list-languages") {
664458 let languages = assets.syntax_set.syntaxes();