on master help sign in
Split modules (#86)

* Split diffing to separate module * Split assets to separate module

commit25cee002f90f2d67311fe448f4489f9afe48f904 authorEzinwa Okpoechi <1738373+BrainMaestro@users.noreply.github.com> dateThu 10 May 2018, 12:36 (8 years ago) parent13a53d2
4 files changed+244−217
src/assets.rs+156 src/diff.rs+76 src/main.rs+10−216 src/printer.rs+2−1
src/assets.rsnew file+156
@@ -0,0 +1,156 @@
1+use directories::ProjectDirs;
2+use errors::*;
3+use std::borrow::Cow;
4+use std::fs::{self, File};
5+use std::io;
6+use std::path::PathBuf;
7+use syntect::dumps::{dump_to_file, from_binary, from_reader};
8+use syntect::highlighting::{Theme, ThemeSet};
9+use syntect::parsing::SyntaxSet;
10+
11+lazy_static! {
12+ static ref PROJECT_DIRS: ProjectDirs = ProjectDirs::from("", "", crate_name!());
13+}
14+
15+pub struct HighlightingAssets {
16+ pub syntax_set: SyntaxSet,
17+ pub theme_set: ThemeSet,
18+}
19+
20+impl HighlightingAssets {
21+ pub fn new() -> Self {
22+ Self::from_cache().unwrap_or_else(|_| Self::from_binary())
23+ }
24+
25+ pub fn from_files() -> Result<Self> {
26+ let config_dir = PROJECT_DIRS.config_dir();
27+
28+ let theme_dir = config_dir.join("themes");
29+
30+ let theme_set = ThemeSet::load_from_folder(&theme_dir).map_err(|_| {
31+ io::Error::new(
32+ io::ErrorKind::Other,
33+ format!(
34+ "Could not load themes from '{}'",
35+ theme_dir.to_string_lossy()
36+ ),
37+ )
38+ })?;
39+
40+ let mut syntax_set = SyntaxSet::new();
41+ let syntax_dir = config_dir.join("syntax");
42+ let _ = syntax_set.load_syntaxes(syntax_dir, true);
43+ syntax_set.load_plain_text_syntax();
44+
45+ Ok(HighlightingAssets {
46+ syntax_set,
47+ theme_set,
48+ })
49+ }
50+
51+ fn from_cache() -> Result<Self> {
52+ let theme_set_path = theme_set_path();
53+ let syntax_set_file = File::open(&syntax_set_path()).chain_err(|| {
54+ format!(
55+ "Could not load cached syntax set '{}'",
56+ syntax_set_path().to_string_lossy()
57+ )
58+ })?;
59+ let mut syntax_set: SyntaxSet = from_reader(syntax_set_file).map_err(|_| {
60+ io::Error::new(
61+ io::ErrorKind::Other,
62+ format!("Could not parse cached syntax set"),
63+ )
64+ })?;
65+ syntax_set.link_syntaxes();
66+
67+ let theme_set_file = File::open(&theme_set_path).chain_err(|| {
68+ format!(
69+ "Could not load cached theme set '{}'",
70+ theme_set_path.to_string_lossy()
71+ )
72+ })?;
73+ let theme_set: ThemeSet = from_reader(theme_set_file).map_err(|_| {
74+ io::Error::new(
75+ io::ErrorKind::Other,
76+ format!("Could not parse cached theme set"),
77+ )
78+ })?;
79+
80+ Ok(HighlightingAssets {
81+ syntax_set,
82+ theme_set,
83+ })
84+ }
85+
86+ fn from_binary() -> Self {
87+ let mut syntax_set: SyntaxSet = from_binary(include_bytes!("../assets/syntax_set"));
88+ syntax_set.link_syntaxes();
89+ let theme_set: ThemeSet = from_binary(include_bytes!("../assets/theme_set"));
90+
91+ HighlightingAssets {
92+ syntax_set,
93+ theme_set,
94+ }
95+ }
96+
97+ pub fn save(&self) -> Result<()> {
98+ let cache_dir = PROJECT_DIRS.cache_dir();
99+ let _ = fs::create_dir(cache_dir);
100+ let theme_set_path = theme_set_path();
101+ let syntax_set_path = syntax_set_path();
102+
103+ print!(
104+ "Writing theme set to {} ... ",
105+ theme_set_path.to_string_lossy()
106+ );
107+ dump_to_file(&self.theme_set, &theme_set_path).map_err(|_| {
108+ io::Error::new(
109+ io::ErrorKind::Other,
110+ format!(
111+ "Could not save theme set to {}",
112+ theme_set_path.to_string_lossy()
113+ ),
114+ )
115+ })?;
116+ println!("okay");
117+
118+ print!(
119+ "Writing syntax set to {} ... ",
120+ syntax_set_path.to_string_lossy()
121+ );
122+ dump_to_file(&self.syntax_set, &syntax_set_path).map_err(|_| {
123+ io::Error::new(
124+ io::ErrorKind::Other,
125+ format!(
126+ "Could not save syntax set to {}",
127+ syntax_set_path.to_string_lossy()
128+ ),
129+ )
130+ })?;
131+ println!("okay");
132+
133+ Ok(())
134+ }
135+
136+ pub fn default_theme(&self) -> Result<&Theme> {
137+ Ok(self.theme_set.themes.get("Default").ok_or_else(|| {
138+ io::Error::new(
139+ io::ErrorKind::Other,
140+ format!("Could not find 'Default' theme"),
141+ )
142+ })?)
143+ }
144+}
145+
146+pub fn theme_set_path() -> PathBuf {
147+ PROJECT_DIRS.cache_dir().join("theme_set")
148+}
149+
150+pub fn syntax_set_path() -> PathBuf {
151+ PROJECT_DIRS.cache_dir().join("syntax_set")
152+}
153+
154+pub fn config_dir() -> Cow<'static, str> {
155+ PROJECT_DIRS.config_dir().to_string_lossy()
156+}
src/diff.rsnew file+76
@@ -0,0 +1,76 @@
1+use git2::{DiffOptions, IntoCString, Repository};
2+use std::collections::HashMap;
3+use std::fs;
4+use std::path::Path;
5+
6+#[derive(Copy, Clone, Debug)]
7+pub enum LineChange {
8+ Added,
9+ RemovedAbove,
10+ RemovedBelow,
11+ Modified,
12+}
13+
14+pub type LineChanges = HashMap<u32, LineChange>;
15+
16+pub fn get_git_diff(filename: &str) -> Option<LineChanges> {
17+ let repo = Repository::discover(&filename).ok()?;
18+ let path_absolute = fs::canonicalize(&filename).ok()?;
19+ let path_relative_to_repo = path_absolute.strip_prefix(repo.workdir()?).ok()?;
20+
21+ let mut diff_options = DiffOptions::new();
22+ let pathspec = path_relative_to_repo.into_c_string().ok()?;
23+ diff_options.pathspec(pathspec);
24+ diff_options.context_lines(0);
25+
26+ let diff = repo.diff_index_to_workdir(None, Some(&mut diff_options))
27+ .ok()?;
28+
29+ let mut line_changes: LineChanges = HashMap::new();
30+
31+ let mark_section =
32+ |line_changes: &mut LineChanges, start: u32, end: i32, change: LineChange| {
33+ for line in start..(end + 1) as u32 {
34+ line_changes.insert(line, change);
35+ }
36+ };
37+
38+ let _ = diff.foreach(
39+ &mut |_, _| true,
40+ None,
41+ Some(&mut |delta, hunk| {
42+ let path = delta.new_file().path().unwrap_or_else(|| Path::new(""));
43+
44+ if path_relative_to_repo != path {
45+ return false;
46+ }
47+
48+ let old_lines = hunk.old_lines();
49+ let new_start = hunk.new_start();
50+ let new_lines = hunk.new_lines();
51+ let new_end = (new_start + new_lines) as i32 - 1;
52+
53+ if old_lines == 0 && new_lines > 0 {
54+ mark_section(&mut line_changes, new_start, new_end, LineChange::Added);
55+ } else if new_lines == 0 && old_lines > 0 {
56+ if new_start == 0 {
57+ mark_section(&mut line_changes, 1, 1, LineChange::RemovedAbove);
58+ } else {
59+ mark_section(
60+ &mut line_changes,
61+ new_start,
62+ new_start as i32,
63+ LineChange::RemovedBelow,
64+ );
65+ }
66+ } else {
67+ mark_section(&mut line_changes, new_start, new_end, LineChange::Modified);
68+ }
69+
70+ true
71+ }),
72+ None,
73+ );
74+
75+ Some(line_changes)
76+}
src/main.rs+10−216
@@ -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();
src/printer.rs+2−1
@@ -1,9 +1,10 @@
11use ansi_term::Style;
2+use diff::{LineChange, LineChanges};
23use errors::*;
34use std::io::Write;
45use syntect::highlighting;
56use terminal::as_terminal_escaped;
6−use {Colors, LineChange, LineChanges, Options};
7+use {Colors, Options};
78
89const PANEL_WIDTH: usize = 7;
910