bat/src/main.rs

225 lines
6.6 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-05-10 23:39:13 +02:00
mod app;
mod assets;
mod decorations;
mod diff;
2018-05-21 14:59:42 +02:00
mod output;
mod printer;
2018-05-11 02:32:31 +02:00
mod style;
2018-04-23 23:56:47 +02:00
mod terminal;
use std::fs::{self, File};
2018-05-21 14:59:42 +02:00
use std::io::{self, BufRead, BufReader};
use std::path::Path;
2018-05-21 14:59:42 +02:00
use std::process;
2018-04-21 12:51:43 +02:00
2018-05-21 14:59:42 +02:00
use ansi_term::Colour::{Green, Red};
2018-04-21 12:51:43 +02:00
2018-05-02 14:29:07 +02:00
use syntect::easy::HighlightLines;
use syntect::highlighting::Theme;
use syntect::parsing::SyntaxDefinition;
2018-04-23 23:56:47 +02:00
2018-05-21 14:59:42 +02:00
use app::App;
use assets::{config_dir, syntax_set_path, theme_set_path, HighlightingAssets};
use diff::get_git_diff;
2018-05-21 14:59:42 +02:00
use output::OutputType;
use printer::Printer;
2018-04-23 23:56:47 +02:00
2018-04-30 11:09:24 +02:00
mod errors {
error_chain! {
2018-04-30 11:09:24 +02:00
foreign_links {
Clap(::clap::Error);
2018-04-30 11:09:24 +02:00
Io(::std::io::Error);
}
}
}
use errors::*;
fn print_file(
2018-04-22 13:27:20 +02:00
theme: &Theme,
syntax: &SyntaxDefinition,
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)?)),
};
2018-05-02 14:29:07 +02:00
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
2018-05-18 11:56:25 +02:00
let mut buffer = Vec::new();
while reader.read_until(b'\n', &mut buffer)? > 0 {
{
let line = String::from_utf8_lossy(&buffer);
let regions = highlighter.highlight(line.as_ref());
2018-04-21 12:51:43 +02:00
2018-05-18 11:56:25 +02:00
printer.print_line(&regions)?;
}
buffer.clear();
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-05-19 11:46:41 +02:00
/// Returns `Err(..)` upon fatal errors. Otherwise, returns `Some(true)` on full success and
/// `Some(false)` if any intermediate errors occured (were printed).
fn run() -> Result<bool> {
2018-05-10 23:39:13 +02:00
let app = App::new();
2018-04-21 12:51:43 +02:00
2018-05-10 23:39:13 +02:00
match app.matches.subcommand() {
("cache", Some(cache_matches)) => {
if cache_matches.is_present("init") {
let source_dir = cache_matches.value_of("source").map(Path::new);
let target_dir = cache_matches.value_of("target").map(Path::new);
let assets = HighlightingAssets::from_files(source_dir)?;
assets.save(target_dir)?;
} else if cache_matches.is_present("clear") {
print!("Clearing theme set cache ... ");
fs::remove_file(theme_set_path()).ok();
println!("okay");
print!("Clearing syntax set cache ... ");
fs::remove_file(syntax_set_path()).ok();
println!("okay");
} else if cache_matches.is_present("config-dir") {
println!("{}", config_dir());
}
2018-05-19 11:46:41 +02:00
return Ok(true);
}
_ => {
2018-05-10 23:39:13 +02:00
let config = app.config()?;
let assets = HighlightingAssets::new();
2018-05-11 13:53:17 +02:00
let theme = assets.get_theme(config.theme.unwrap_or("Default"))?;
2018-05-10 23:39:13 +02:00
if app.matches.is_present("list-languages") {
2018-05-14 16:59:57 +02:00
let mut languages = assets.syntax_set.syntaxes().to_owned();
2018-05-14 19:49:00 +02:00
languages.sort_by_key(|lang| lang.name.to_uppercase());
let longest = languages
.iter()
2018-05-10 12:50:40 +02:00
.filter(|s| !s.hidden && !s.file_extensions.is_empty())
.map(|s| s.name.len())
.max()
.unwrap_or(32); // Fallback width if they have no language definitions.
2018-05-08 22:29:38 +02:00
let separator = " ";
for lang in languages {
2018-05-10 12:50:40 +02:00
if lang.hidden || lang.file_extensions.is_empty() {
2018-05-08 20:50:56 +02:00
continue;
}
print!("{:width$}{}", lang.name, separator, width = longest);
// Line-wrapping for the possible file extension overflow.
2018-05-10 23:39:13 +02:00
let desired_width = config.term_width - longest - separator.len();
// Number of characters on this line so far, wrap before `desired_width`
let mut num_chars = 0;
let comma_separator = ", ";
let mut extension = lang.file_extensions.iter().peekable();
while let Some(word) = extension.next() {
// If we can't fit this word in, then create a line break and align it in.
let new_chars = word.len() + comma_separator.len();
if num_chars + new_chars >= desired_width {
num_chars = 0;
print!("\n{:width$}{}", "", separator, width = longest);
}
num_chars += new_chars;
2018-05-08 22:29:38 +02:00
print!("{}", Green.paint(word as &str));
if extension.peek().is_some() {
print!("{}", comma_separator);
}
}
println!();
}
2018-05-19 11:46:41 +02:00
return Ok(true);
}
2018-05-11 13:53:17 +02:00
if app.matches.is_present("list-themes") {
let themes = &assets.theme_set.themes;
for (theme, _) in themes.iter() {
println!("{}", theme);
}
2018-05-19 11:46:41 +02:00
return Ok(true);
2018-05-11 13:53:17 +02:00
}
let mut output_type = OutputType::from_mode(config.paging_mode);
let handle = output_type.handle()?;
2018-05-10 23:39:13 +02:00
let mut printer = Printer::new(handle, &config);
2018-05-19 11:46:41 +02:00
let mut no_errors: bool = true;
2018-05-10 23:39:13 +02:00
for file in &config.files {
printer.line_changes = file.and_then(|filename| get_git_diff(filename));
2018-05-19 11:46:41 +02:00
let syntax = assets.get_syntax(config.language, *file);
let result = print_file(theme, &syntax, &mut printer, *file);
2018-05-19 11:46:41 +02:00
if let Err(error) = result {
handle_error(&error);
no_errors = false;
}
}
2018-05-19 11:46:41 +02:00
Ok(no_errors)
}
}
2018-05-19 11:46:41 +02:00
}
2018-05-19 11:46:41 +02:00
fn handle_error(error: &Error) {
match error {
&Error(ErrorKind::Io(ref io_error), _) if io_error.kind() == io::ErrorKind::BrokenPipe => {
process::exit(0);
}
_ => {
eprintln!("{}: {}", Red.paint("[bat error]"), error);
}
};
}
fn main() {
let result = run();
2018-04-21 12:51:43 +02:00
2018-05-19 11:46:41 +02:00
match result {
Err(error) => {
handle_error(&error);
process::exit(1);
}
Ok(false) => {
process::exit(1);
}
Ok(true) => {
process::exit(0);
}
2018-04-21 12:51:43 +02:00
}
}