bat/src/main.rs

408 lines
12 KiB
Rust
Raw Normal View History

2018-04-30 11:09:24 +02:00
// `error_chain!` can recurse deeply
#![recursion_limit = "1024"]
#[macro_use]
extern crate error_chain;
#[macro_use]
extern crate clap;
#[macro_use]
extern crate lazy_static;
2018-04-21 12:51:43 +02:00
extern crate ansi_term;
extern crate atty;
extern crate console;
extern crate directories;
2018-04-21 17:12:25 +02:00
extern crate git2;
2018-04-21 12:51:43 +02:00
extern crate syntect;
2018-04-23 23:56:47 +02:00
mod terminal;
2018-04-21 17:12:25 +02:00
use std::collections::HashMap;
2018-04-22 16:03:47 +02:00
use std::env;
use std::fs::{self, File};
2018-04-30 11:09:24 +02:00
use std::io::{self, BufRead, StdoutLock, Write};
2018-04-21 12:51:43 +02:00
use std::path::Path;
use std::process;
2018-04-22 13:27:20 +02:00
use ansi_term::Colour::{Fixed, Green, Red, White, Yellow};
2018-04-22 14:05:43 +02:00
use ansi_term::Style;
2018-04-21 12:51:43 +02:00
use atty::Stream;
use clap::{App, AppSettings, Arg, SubCommand};
2018-04-21 12:51:43 +02:00
use console::Term;
use directories::ProjectDirs;
2018-04-21 17:12:25 +02:00
use git2::{DiffOptions, IntoCString, Repository};
2018-04-21 12:51:43 +02:00
2018-04-30 15:31:27 +02:00
use syntect::dumps::{dump_to_file, from_binary, from_reader};
2018-04-21 12:51:43 +02:00
use syntect::easy::HighlightFile;
2018-04-22 13:27:20 +02:00
use syntect::highlighting::{Theme, ThemeSet};
2018-04-21 12:51:43 +02:00
use syntect::parsing::SyntaxSet;
2018-04-23 23:56:47 +02:00
use terminal::as_terminal_escaped;
lazy_static! {
static ref PROJECT_DIRS: ProjectDirs = ProjectDirs::from("", "", crate_name!());
}
2018-04-30 11:09:24 +02:00
mod errors {
error_chain!{
foreign_links {
Io(::std::io::Error);
}
}
}
use errors::*;
2018-04-23 23:56:47 +02:00
struct Options {
true_color: bool,
}
2018-04-21 12:51:43 +02:00
2018-04-21 17:12:25 +02:00
#[derive(Copy, Clone, Debug)]
enum LineChange {
Added,
RemovedAbove,
RemovedBelow,
Modified,
}
type LineChanges = HashMap<u32, LineChange>;
2018-04-22 14:05:43 +02:00
const PANEL_WIDTH: usize = 7;
const GRID_COLOR: u8 = 238;
2018-04-22 13:53:04 +02:00
2018-04-22 16:03:47 +02:00
fn print_horizontal_line(
handle: &mut StdoutLock,
grid_char: char,
term_width: usize,
2018-04-30 11:09:24 +02:00
) -> Result<()> {
2018-04-26 07:58:31 +02:00
let hline = "".repeat(term_width - (PANEL_WIDTH + 1));
let hline = format!("{}{}{}", "".repeat(PANEL_WIDTH), grid_char, hline);
2018-04-22 14:05:43 +02:00
2018-04-26 07:58:31 +02:00
writeln!(handle, "{}", Fixed(GRID_COLOR).paint(hline))?;
2018-04-22 14:37:32 +02:00
Ok(())
2018-04-22 13:53:04 +02:00
}
2018-04-22 13:27:20 +02:00
fn print_file<P: AsRef<Path>>(
2018-04-23 23:56:47 +02:00
options: &Options,
2018-04-22 13:27:20 +02:00
theme: &Theme,
2018-04-22 14:05:43 +02:00
syntax_set: &SyntaxSet,
2018-04-22 13:27:20 +02:00
filename: P,
2018-04-26 07:58:31 +02:00
line_changes: &Option<LineChanges>,
2018-04-30 11:09:24 +02:00
) -> Result<()> {
2018-04-26 07:58:31 +02:00
let mut highlighter = HighlightFile::new(filename.as_ref(), syntax_set, theme)?;
2018-04-21 12:51:43 +02:00
2018-04-22 14:37:32 +02:00
let stdout = io::stdout();
let mut handle = stdout.lock();
2018-04-21 12:51:43 +02:00
let term = Term::stdout();
2018-04-22 13:53:04 +02:00
let (_, term_width) = term.size();
let term_width = term_width as usize;
2018-04-21 12:51:43 +02:00
2018-04-22 14:37:32 +02:00
print_horizontal_line(&mut handle, '┬', term_width)?;
2018-04-21 12:51:43 +02:00
2018-04-26 07:58:31 +02:00
writeln!(
2018-04-22 14:37:32 +02:00
handle,
2018-04-26 07:58:31 +02:00
"{}{} File {}",
2018-04-22 14:05:43 +02:00
" ".repeat(PANEL_WIDTH),
2018-04-22 13:53:04 +02:00
Fixed(GRID_COLOR).paint(""),
2018-04-21 17:36:57 +02:00
White.bold().paint(filename.as_ref().to_string_lossy())
2018-04-22 14:37:32 +02:00
)?;
2018-04-21 17:36:57 +02:00
2018-04-22 14:37:32 +02:00
print_horizontal_line(&mut handle, '┼', term_width)?;
2018-04-21 17:36:57 +02:00
2018-04-21 17:12:25 +02:00
for (idx, maybe_line) in highlighter.reader.lines().enumerate() {
let line_nr = idx + 1;
2018-04-26 07:58:31 +02:00
let line = maybe_line.unwrap_or_else(|_| "<INVALID UTF-8>".into());
2018-04-21 12:51:43 +02:00
let regions = highlighter.highlight_lines.highlight(&line);
2018-04-26 07:58:31 +02:00
let line_change = if let Some(ref changes) = *line_changes {
2018-04-21 17:12:25 +02:00
match changes.get(&(line_nr as u32)) {
Some(&LineChange::Added) => Green.paint("+"),
Some(&LineChange::RemovedAbove) => Red.paint(""),
Some(&LineChange::RemovedBelow) => Red.paint("_"),
Some(&LineChange::Modified) => Yellow.paint("~"),
2018-04-22 14:05:43 +02:00
_ => Style::default().paint(" "),
2018-04-21 17:12:25 +02:00
}
} else {
2018-04-22 14:05:43 +02:00
Style::default().paint(" ")
2018-04-21 17:12:25 +02:00
};
2018-04-26 07:58:31 +02:00
writeln!(
2018-04-22 14:37:32 +02:00
handle,
2018-04-26 07:58:31 +02:00
"{} {} {} {}",
2018-04-21 12:51:43 +02:00
Fixed(244).paint(format!("{:4}", line_nr)),
2018-04-21 17:12:25 +02:00
line_change,
2018-04-22 13:53:04 +02:00
Fixed(GRID_COLOR).paint(""),
2018-04-23 23:56:47 +02:00
as_terminal_escaped(&regions, options.true_color)
2018-04-22 14:37:32 +02:00
)?;
2018-04-21 12:51:43 +02:00
}
2018-04-22 14:37:32 +02:00
print_horizontal_line(&mut handle, '┴', term_width)?;
2018-04-21 17:12:25 +02:00
2018-04-21 12:51:43 +02:00
Ok(())
}
2018-04-26 07:58:31 +02:00
fn get_git_diff(filename: &str) -> Option<LineChanges> {
2018-04-21 17:12:25 +02:00
let repo = Repository::open_from_env().ok()?;
2018-04-24 21:57:40 +02:00
let workdir = repo.workdir()?;
let current_dir = env::current_dir().ok()?;
let filepath = current_dir.join(Path::new(&filename));
2018-04-21 17:12:25 +02:00
let mut diff_options = DiffOptions::new();
2018-04-24 21:57:40 +02:00
let pathspec = format!("*{}", filename).into_c_string().ok()?;
diff_options.pathspec(pathspec);
2018-04-21 17:12:25 +02:00
diff_options.context_lines(0);
let diff = repo.diff_index_to_workdir(None, Some(&mut diff_options))
2018-04-22 13:27:20 +02:00
.ok()?;
2018-04-21 17:12:25 +02:00
let mut line_changes: LineChanges = HashMap::new();
let mark_section =
|line_changes: &mut LineChanges, start: u32, end: i32, change: LineChange| {
for line in start..(end + 1) as u32 {
line_changes.insert(line, change);
}
};
let _ = diff.foreach(
&mut |_, _| true,
None,
2018-04-24 21:57:40 +02:00
Some(&mut |delta, hunk| {
2018-04-26 07:58:31 +02:00
let path = delta.new_file().path().unwrap_or_else(|| Path::new(""));
2018-04-24 21:57:40 +02:00
if filepath != workdir.join(path) {
return false;
}
2018-04-21 17:12:25 +02:00
let old_lines = hunk.old_lines();
let new_start = hunk.new_start();
let new_lines = hunk.new_lines();
let new_end = (new_start + new_lines) as i32 - 1;
if old_lines == 0 && new_lines > 0 {
mark_section(&mut line_changes, new_start, new_end, LineChange::Added);
} else if new_lines == 0 && old_lines > 0 {
2018-04-26 07:58:31 +02:00
if new_start == 0 {
2018-04-21 17:12:25 +02:00
mark_section(&mut line_changes, 1, 1, LineChange::RemovedAbove);
} else {
mark_section(
&mut line_changes,
new_start,
new_start as i32,
LineChange::RemovedBelow,
);
}
} else {
mark_section(&mut line_changes, new_start, new_end, LineChange::Modified);
}
true
}),
None,
);
Some(line_changes)
}
fn is_truecolor_terminal() -> bool {
env::var("COLORTERM")
.map(|colorterm| colorterm == "truecolor" || colorterm == "24bit")
.unwrap_or(false)
}
2018-04-22 16:03:47 +02:00
struct HighlightingAssets {
pub syntax_set: SyntaxSet,
pub theme_set: ThemeSet,
}
2018-04-23 23:56:47 +02:00
impl HighlightingAssets {
fn from_files() -> Result<Self> {
let config_dir = PROJECT_DIRS.config_dir();
let theme_dir = config_dir.join("themes");
let theme_set = ThemeSet::load_from_folder(&theme_dir).map_err(|_| {
io::Error::new(
io::ErrorKind::Other,
format!(
"Could not load themes from '{}'",
theme_dir.to_string_lossy()
),
)
})?;
let mut syntax_set = SyntaxSet::new();
let syntax_dir = config_dir.join("syntax");
let _ = syntax_set.load_syntaxes(syntax_dir, false);
syntax_set.load_plain_text_syntax();
Ok(HighlightingAssets {
syntax_set,
theme_set,
})
}
2018-04-23 23:56:47 +02:00
fn save(&self) -> Result<()> {
let cache_dir = PROJECT_DIRS.cache_dir();
let theme_set_path = cache_dir.join("theme_set");
let syntax_set_path = cache_dir.join("syntax_set");
let _ = fs::create_dir(cache_dir);
dump_to_file(&self.theme_set, &theme_set_path).map_err(|_| {
io::Error::new(
io::ErrorKind::Other,
format!(
"Could not save theme set to {}",
theme_set_path.to_string_lossy()
),
)
})?;
println!("Wrote theme set to {}", theme_set_path.to_string_lossy());
dump_to_file(&self.syntax_set, &syntax_set_path).map_err(|_| {
io::Error::new(
io::ErrorKind::Other,
format!(
"Could not save syntax set to {}",
syntax_set_path.to_string_lossy()
),
)
})?;
println!("Wrote syntax set to {}", syntax_set_path.to_string_lossy());
Ok(())
2018-04-21 12:51:43 +02:00
}
fn from_cache() -> Result<Self> {
let cache_dir = PROJECT_DIRS.cache_dir();
let theme_set_path = cache_dir.join("theme_set");
let syntax_set_path = cache_dir.join("syntax_set");
2018-04-30 15:20:00 +02:00
let syntax_set_file = File::open(&syntax_set_path).chain_err(|| {
format!(
"Could not load cached syntax set '{}'",
syntax_set_path.to_string_lossy()
)
})?;
let mut syntax_set: SyntaxSet = from_reader(syntax_set_file).map_err(|_| {
io::Error::new(
io::ErrorKind::Other,
2018-04-30 15:20:00 +02:00
format!("Could not parse cached syntax set"),
)
})?;
syntax_set.link_syntaxes();
2018-04-30 15:20:00 +02:00
let theme_set_file = File::open(&theme_set_path).chain_err(|| {
format!(
"Could not load cached theme set '{}'",
theme_set_path.to_string_lossy()
)
})?;
let theme_set: ThemeSet = from_reader(theme_set_file).map_err(|_| {
io::Error::new(
io::ErrorKind::Other,
2018-04-30 15:20:00 +02:00
format!("Could not parse cached theme set"),
)
})?;
Ok(HighlightingAssets {
syntax_set,
theme_set,
})
}
2018-04-30 15:31:27 +02:00
fn from_binary() -> Self {
let mut syntax_set: SyntaxSet = from_binary(include_bytes!("../assets/syntax_set"));
syntax_set.link_syntaxes();
let theme_set: ThemeSet = from_binary(include_bytes!("../assets/theme_set"));
HighlightingAssets {
syntax_set,
theme_set,
}
}
2018-04-21 12:51:43 +02:00
}
fn run() -> Result<()> {
2018-04-21 12:51:43 +02:00
let clap_color_setting = if atty::is(Stream::Stdout) {
AppSettings::ColoredHelp
} else {
AppSettings::ColorNever
};
let app_matches = App::new(crate_name!())
2018-04-21 12:51:43 +02:00
.version(crate_version!())
.setting(clap_color_setting)
.setting(AppSettings::DeriveDisplayOrder)
.setting(AppSettings::UnifiedHelpMessage)
.setting(AppSettings::NextLineHelp)
2018-04-22 13:45:40 +02:00
.setting(AppSettings::DisableVersion)
2018-04-21 12:51:43 +02:00
.max_term_width(90)
2018-04-22 13:45:40 +02:00
.about(crate_description!())
2018-04-21 12:51:43 +02:00
.arg(
2018-04-22 13:45:40 +02:00
Arg::with_name("FILE")
.help("File(s) to print")
2018-04-21 12:51:43 +02:00
.multiple(true)
.empty_values(false),
)
.subcommand(
SubCommand::with_name("init-cache")
.about("Load syntax definitions and themes into cache"),
)
2018-04-21 12:51:43 +02:00
.help_message("Print this help message.")
.version_message("Show version information.")
.get_matches();
match app_matches.subcommand() {
("init-cache", Some(_)) => {
let assets = HighlightingAssets::from_files()?;
assets.save()?;
}
_ => {
let options = Options {
true_color: is_truecolor_terminal(),
};
2018-04-30 16:03:33 +02:00
let assets =
HighlightingAssets::from_cache().unwrap_or(HighlightingAssets::from_binary());
let theme = assets.theme_set.themes.get("Default").ok_or_else(|| {
io::Error::new(
io::ErrorKind::Other,
format!("Could not find 'Default' theme"),
)
})?;
if let Some(files) = app_matches.values_of("FILE") {
for file in files {
let line_changes = get_git_diff(&file.to_string());
print_file(&options, theme, &assets.syntax_set, file, &line_changes)?;
}
}
}
}
Ok(())
}
fn main() {
let result = run();
2018-04-21 12:51:43 +02:00
2018-04-30 11:09:24 +02:00
if let Err(error) = result {
match error {
Error(ErrorKind::Io(ref io_error), _)
if io_error.kind() == io::ErrorKind::BrokenPipe => {}
_ => {
eprintln!("{}: {}", Red.paint("[bat error]"), error);
process::exit(1);
}
};
2018-04-21 12:51:43 +02:00
}
}