bat/src/main.rs

545 lines
16 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;
mod printer;
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-05-07 22:49:55 +02:00
use std::io::{self, BufRead, BufReader, Write};
2018-04-21 12:51:43 +02:00
use std::path::Path;
2018-05-06 14:53:52 +02:00
use std::process::{self, Child, Command, Stdio};
2018-04-21 12:51:43 +02:00
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};
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-05-02 14:29:07 +02:00
use syntect::easy::HighlightLines;
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 printer::Printer;
2018-04-23 23:56:47 +02:00
lazy_static! {
static ref PROJECT_DIRS: ProjectDirs = ProjectDirs::from("", "", crate_name!());
}
2018-04-30 11:09:24 +02:00
mod errors {
error_chain! {
2018-04-30 11:09:24 +02:00
foreign_links {
Io(::std::io::Error);
}
}
}
use errors::*;
pub enum OptionsStyle {
Plain,
LineNumbers,
Full,
}
pub struct Options<'a> {
pub true_color: bool,
pub style: OptionsStyle,
pub language: Option<&'a str>,
pub colored_output: bool,
pub paging: bool,
2018-05-03 18:12:03 +02:00
}
2018-05-07 22:49:55 +02:00
enum OutputType {
2018-05-03 18:12:03 +02:00
Pager(Child),
2018-05-07 22:49:55 +02:00
Stdout(io::Stdout),
2018-05-03 18:12:03 +02:00
}
2018-05-07 22:49:55 +02:00
impl OutputType {
2018-05-06 19:26:41 +02:00
fn pager() -> Result<Self> {
2018-05-03 18:12:03 +02:00
Ok(OutputType::Pager(Command::new("less")
.args(&["--quit-if-one-screen", "--RAW-CONTROL-CHARS", "--no-init"])
.stdin(Stdio::piped())
.spawn()
2018-05-06 14:53:52 +02:00
.chain_err(|| "Could not spawn pager")?))
2018-05-03 18:12:03 +02:00
}
2018-05-07 22:49:55 +02:00
fn stdout() -> Self {
OutputType::Stdout(io::stdout())
2018-05-03 18:12:03 +02:00
}
2018-05-06 19:26:41 +02:00
fn handle(&mut self) -> Result<&mut Write> {
2018-05-03 18:12:03 +02:00
Ok(match *self {
2018-05-06 14:53:52 +02:00
OutputType::Pager(ref mut command) => command
.stdin
.as_mut()
.chain_err(|| "Could not open stdin for pager")?,
2018-05-03 18:12:03 +02:00
OutputType::Stdout(ref mut handle) => handle,
})
}
}
2018-05-07 22:49:55 +02:00
impl Drop for OutputType {
2018-05-03 18:12:03 +02:00
fn drop(&mut self) {
if let OutputType::Pager(ref mut command) = *self {
let _ = command.wait();
}
}
2018-04-23 23:56:47 +02:00
}
2018-04-21 12:51:43 +02:00
2018-04-21 17:12:25 +02:00
#[derive(Copy, Clone, Debug)]
pub enum LineChange {
2018-04-21 17:12:25 +02:00
Added,
RemovedAbove,
RemovedBelow,
Modified,
}
pub type LineChanges = HashMap<u32, LineChange>;
2018-04-21 17:12:25 +02:00
2018-04-22 14:05:43 +02:00
const GRID_COLOR: u8 = 238;
const LINE_NUMBER_COLOR: u8 = 244;
#[derive(Default)]
pub struct Colors {
pub grid: Style,
pub filename: Style,
pub git_added: Style,
pub git_removed: Style,
pub git_modified: Style,
pub line_number: Style,
}
impl Colors {
fn plain() -> Self {
Colors::default()
}
fn colored() -> Self {
Colors {
grid: Fixed(GRID_COLOR).normal(),
filename: White.bold(),
git_added: Green.normal(),
git_removed: Red.normal(),
git_modified: Yellow.normal(),
line_number: Fixed(LINE_NUMBER_COLOR).normal(),
}
}
}
2018-04-22 13:53:04 +02:00
fn print_file(
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,
printer: &mut Printer,
filename: Option<&str>,
2018-04-30 11:09:24 +02:00
) -> Result<()> {
let stdin = io::stdin(); // TODO: this is not always needed
let mut reader: Box<BufRead> = match filename {
None => Box::new(stdin.lock()),
Some(filename) => Box::new(BufReader::new(File::open(filename)?)),
};
let syntax = match (options.language, filename) {
(Some(language), _) => syntax_set.find_syntax_by_token(language),
(None, Some(filename)) => syntax_set.find_syntax_for_file(filename)?,
(None, None) => None,
2018-05-02 14:29:07 +02:00
};
2018-05-02 14:29:07 +02:00
let syntax = syntax.unwrap_or_else(|| syntax_set.find_syntax_plain_text());
let mut highlighter = HighlightLines::new(syntax, theme);
2018-04-21 12:51:43 +02:00
printer.print_header(filename)?;
2018-04-21 17:36:57 +02:00
let mut line_nr = 1;
let mut line_buffer = String::new();
loop {
line_buffer.clear();
let num_bytes = reader.read_line(&mut line_buffer);
let line = match num_bytes {
Ok(0) => {
break;
}
Ok(_) => &line_buffer,
Err(_) => "<bat: INVALID UTF-8>\n",
};
let regions = highlighter.highlight(line);
2018-04-21 12:51:43 +02:00
printer.print_line(line_nr, &regions)?;
line_nr += 1;
2018-04-21 12:51:43 +02:00
}
printer.print_footer()?;
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> {
let repo = Repository::discover(&filename).ok()?;
let path_absolute = fs::canonicalize(&filename).ok()?;
let path_relative_to_repo = path_absolute.strip_prefix(repo.workdir()?).ok()?;
2018-04-21 17:12:25 +02:00
let mut diff_options = DiffOptions::new();
let pathspec = path_relative_to_repo.into_c_string().ok()?;
2018-04-24 21:57:40 +02:00
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 path_relative_to_repo != path {
2018-04-24 21:57:40 +02:00
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)
}
2018-05-07 22:49:55 +02:00
fn get_output_type(paging: bool) -> OutputType {
2018-05-06 19:38:28 +02:00
if paging {
2018-05-07 22:49:55 +02:00
OutputType::pager().unwrap_or_else(|_| OutputType::stdout())
2018-05-06 19:26:41 +02:00
} else {
2018-05-07 22:49:55 +02:00
OutputType::stdout()
2018-05-06 19:26:41 +02:00
}
}
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, true);
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-05-03 18:12:03 +02:00
let interactive_terminal = atty::is(Stream::Stdout);
let clap_color_setting = if interactive_terminal {
2018-04-21 12:51:43 +02:00
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!())
.arg(
Arg::with_name("language")
.short("l")
.long("language")
.help("Set the language for highlighting")
.takes_value(true),
2018-05-02 14:29:07 +02:00
)
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),
)
.arg(
Arg::with_name("style")
.long("style")
.possible_values(&["auto", "plain", "line-numbers", "full"])
.default_value("auto")
.help("Additional info to display along with content"),
)
.arg(
Arg::with_name("color")
.long("color")
.takes_value(true)
.possible_values(&["auto", "never", "always"])
.default_value("auto")
2018-05-06 14:53:52 +02:00
.help("When to use colors"),
)
2018-05-06 19:38:28 +02:00
.arg(
Arg::with_name("paging")
.long("paging")
.takes_value(true)
.possible_values(&["auto", "never", "always"])
.default_value("auto")
.help("When to use the pager"),
2018-05-06 19:38:28 +02:00
)
.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 files: Vec<Option<&str>> = app_matches
.values_of("FILE")
.map(|values| {
values
.map(|filename| {
if filename == "-" {
None
} else {
Some(filename)
}
})
.collect()
})
.unwrap_or_else(|| vec![None]); // read from stdin (None) if no args are given
let options = Options {
true_color: is_truecolor_terminal(),
style: match app_matches.value_of("style") {
Some("plain") => OptionsStyle::Plain,
Some("line-numbers") => OptionsStyle::LineNumbers,
Some("full") => OptionsStyle::Full,
Some("auto") | _ => if interactive_terminal {
OptionsStyle::Full
} else {
OptionsStyle::Plain
},
},
2018-05-02 14:29:07 +02:00
language: app_matches.value_of("language"),
colored_output: match app_matches.value_of("color") {
Some("always") => true,
Some("never") => false,
_ => interactive_terminal,
},
2018-05-06 19:38:28 +02:00
paging: match app_matches.value_of("paging") {
Some("always") => true,
Some("never") => false,
Some("auto") | _ => if files.contains(&None) {
// If we are reading from stdin, only enable paging if we write to an
// interactive terminal and if we do not *read* from an interactive
// terminal.
interactive_terminal && !atty::is(Stream::Stdin)
} else {
interactive_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"),
)
})?;
2018-05-07 22:49:55 +02:00
let mut output_type = get_output_type(options.paging);
let handle = output_type.handle()?;
let mut printer = Printer::new(handle, &options);
for file in files {
printer.line_changes = file.and_then(|filename| get_git_diff(filename));
print_file(&options, theme, &assets.syntax_set, &mut printer, file)?;
}
}
}
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), _)
2018-05-06 14:53:52 +02:00
if io_error.kind() == io::ErrorKind::BrokenPipe => {}
2018-04-30 11:09:24 +02:00
_ => {
eprintln!("{}: {}", Red.paint("[bat error]"), error);
process::exit(1);
}
};
2018-04-21 12:51:43 +02:00
}
}