bat/src/main.rs

224 lines
6.4 KiB
Rust
Raw Normal View History

2018-04-21 12:51:43 +02:00
extern crate ansi_term;
extern crate atty;
extern crate console;
2018-04-21 17:12:25 +02:00
extern crate git2;
2018-04-21 12:51:43 +02:00
extern crate syntect;
#[macro_use]
extern crate clap;
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::io::{self, BufRead, ErrorKind, Result, 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, ArgMatches};
use console::Term;
2018-04-21 17:12:25 +02:00
use git2::{DiffOptions, IntoCString, Repository};
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;
use syntect::util::as_24_bit_terminal_escaped;
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,
) -> io::Result<()> {
2018-04-22 14:05:43 +02:00
let bar = "".repeat(term_width - (PANEL_WIDTH + 1));
let line = format!("{}{}{}", "".repeat(PANEL_WIDTH), grid_char, bar);
2018-04-22 14:37:32 +02:00
write!(handle, "{}\n", Fixed(GRID_COLOR).paint(line))?;
Ok(())
2018-04-22 13:53:04 +02:00
}
2018-04-22 13:27:20 +02:00
fn print_file<P: AsRef<Path>>(
theme: &Theme,
2018-04-22 14:05:43 +02:00
syntax_set: &SyntaxSet,
2018-04-22 13:27:20 +02:00
filename: P,
line_changes: Option<LineChanges>,
) -> io::Result<()> {
2018-04-22 14:05:43 +02:00
let mut highlighter = HighlightFile::new(filename.as_ref().clone(), 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-22 14:37:32 +02:00
write!(
handle,
"{}{} {}\n",
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-21 12:51:43 +02:00
let line = maybe_line.unwrap_or("<INVALID UTF-8>".into());
let regions = highlighter.highlight_lines.highlight(&line);
2018-04-21 17:12:25 +02:00
let line_change = if let Some(ref changes) = line_changes {
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-22 14:37:32 +02:00
write!(
handle,
"{} {} {} {}\n",
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-21 12:51:43 +02:00
as_24_bit_terminal_escaped(&regions, false)
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-22 15:11:35 +02:00
fn get_git_diff(filename: String) -> Option<LineChanges> {
2018-04-21 17:12:25 +02:00
let repo = Repository::open_from_env().ok()?;
let mut diff_options = DiffOptions::new();
2018-04-22 13:27:20 +02:00
diff_options.pathspec(filename.into_c_string().ok()?);
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,
Some(&mut |_, hunk| {
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 {
if new_start <= 0 {
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)
}
2018-04-21 12:51:43 +02:00
fn run(matches: &ArgMatches) -> Result<()> {
2018-04-22 16:03:47 +02:00
let home_dir = env::home_dir().ok_or(io::Error::new(
ErrorKind::Other,
"Could not get home directory",
))?;
let theme_dir = home_dir.join(".config").join("bat").join("themes");
let theme_set = ThemeSet::load_from_folder(theme_dir)
.map_err(|_| io::Error::new(ErrorKind::Other, "Could not load themes"))?;
2018-04-22 13:27:20 +02:00
let theme = &theme_set.themes["Monokai"];
2018-04-22 14:05:43 +02:00
let syntax_set = SyntaxSet::load_defaults_nonewlines();
2018-04-22 13:45:40 +02:00
if let Some(files) = matches.values_of("FILE") {
2018-04-21 12:51:43 +02:00
for file in files {
2018-04-22 15:11:35 +02:00
let line_changes = get_git_diff(file.to_string());
2018-04-22 14:05:43 +02:00
print_file(theme, &syntax_set, file, line_changes)?;
2018-04-21 12:51:43 +02:00
}
}
Ok(())
}
fn main() {
let clap_color_setting = if atty::is(Stream::Stdout) {
AppSettings::ColoredHelp
} else {
AppSettings::ColorNever
};
2018-04-22 13:45:40 +02:00
let 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),
)
.help_message("Print this help message.")
.version_message("Show version information.")
.get_matches();
let result = run(&matches);
if let Err(e) = result {
2018-04-22 14:37:32 +02:00
if e.kind() != ErrorKind::BrokenPipe {
eprintln!("{}: {}", Red.paint("[bat error]"), e);
process::exit(1);
}
2018-04-21 12:51:43 +02:00
}
}