on cec9cc0 help sign in
bat/src/main.rs
262 lines 7.2 kB history raw
1// `error_chain!` can recurse deeply
2#![recursion_limit = "1024"]
4#[macro_use]
5extern crate error_chain;
7#[macro_use]
8extern crate clap;
10#[macro_use]
11extern crate lazy_static;
13extern crate ansi_term;
14extern crate atty;
15extern crate console;
16extern crate content_inspector;
17extern crate dirs as dirs_rs;
18extern crate encoding;
19extern crate git2;
20extern crate shell_words;
21extern crate syntect;
22extern crate wild;
24mod app;
25mod assets;
26mod clap_app;
27mod config;
28mod controller;
29mod decorations;
30mod diff;
31mod dirs;
32mod inputfile;
33mod line_range;
34mod output;
35mod preprocessor;
36mod printer;
37mod style;
38mod syntax_mapping;
39mod terminal;
40mod util;
42use std::collections::HashSet;
43use std::io;
44use std::io::Write;
45use std::path::Path;
46use std::process;
48use ansi_term::Colour::Green;
49use ansi_term::Style;
51use app::{App, Config};
52use assets::{cache_dir, clear_assets, config_dir, HighlightingAssets};
53use config::config_file;
54use controller::Controller;
55use inputfile::InputFile;
56use style::{OutputComponent, OutputComponents};
58mod errors {
59 error_chain! {
60 foreign_links {
61 Clap(::clap::Error);
62 Io(::std::io::Error);
63 SyntectError(::syntect::LoadingError);
64 ParseIntError(::std::num::ParseIntError);
65 }
66 errors {
67 ImmediateEOF
68 }
69 }
71 pub fn handle_error(error: &Error) {
72 match error {
73 &Error(ErrorKind::Io(ref io_error), _)
74 if io_error.kind() == super::io::ErrorKind::BrokenPipe =>
75 {
76 super::process::exit(0);
77 }
78 _ => {
79 use ansi_term::Colour::Red;
80 eprintln!("{}: {}", Red.paint("[bat error]"), error);
81 }
82 };
83 }
86use errors::*;
88fn run_cache_subcommand(matches: &clap::ArgMatches) -> Result<()> {
89 if matches.is_present("build") {
90 let source_dir = matches.value_of("source").map(Path::new);
91 let target_dir = matches.value_of("target").map(Path::new);
93 let blank = matches.is_present("blank");
95 let assets = HighlightingAssets::from_files(source_dir, blank)?;
96 assets.save(target_dir)?;
97 } else if matches.is_present("clear") {
98 clear_assets();
99 }
101 Ok(())
104pub fn list_languages(config: &Config) -> Result<()> {
105 let assets = HighlightingAssets::new();
106 let mut languages = assets
107 .syntax_set
108 .syntaxes()
109 .iter()
110 .filter(|syntax| !syntax.hidden && !syntax.file_extensions.is_empty())
111 .collect::<Vec<_>>();
112 languages.sort_by_key(|lang| lang.name.to_uppercase());
114 let longest = languages
115 .iter()
116 .map(|syntax| syntax.name.len())
117 .max()
118 .unwrap_or(32); // Fallback width if they have no language definitions.
120 let comma_separator = ", ";
121 let separator = " ";
122 // Line-wrapping for the possible file extension overflow.
123 let desired_width = config.term_width - longest - separator.len();
125 let stdout = io::stdout();
126 let mut stdout = stdout.lock();
128 let style = if config.colored_output {
129 Green.normal()
130 } else {
131 Style::default()
132 };
134 for lang in languages {
135 write!(stdout, "{:width$}{}", lang.name, separator, width = longest)?;
137 // Number of characters on this line so far, wrap before `desired_width`
138 let mut num_chars = 0;
140 let mut extension = lang.file_extensions.iter().peekable();
141 while let Some(word) = extension.next() {
142 // If we can't fit this word in, then create a line break and align it in.
143 let new_chars = word.len() + comma_separator.len();
144 if num_chars + new_chars >= desired_width {
145 num_chars = 0;
146 write!(stdout, "\n{:width$}{}", "", separator, width = longest)?;
147 }
149 num_chars += new_chars;
150 write!(stdout, "{}", style.paint(&word[..]))?;
151 if extension.peek().is_some() {
152 write!(stdout, "{}", comma_separator)?;
153 }
154 }
155 writeln!(stdout)?;
156 }
158 Ok(())
161pub fn list_themes(cfg: &Config) -> Result<()> {
162 let assets = HighlightingAssets::new();
163 let themes = &assets.theme_set.themes;
164 let mut config = cfg.clone();
165 let mut style = HashSet::new();
166 style.insert(OutputComponent::Plain);
167 config.files = vec![InputFile::ThemePreviewFile];
168 config.output_components = OutputComponents(style);
170 let stdout = io::stdout();
171 let mut stdout = stdout.lock();
173 if config.colored_output {
174 for (theme, _) in themes.iter() {
175 writeln!(
176 stdout,
177 "Theme: {}\n",
178 Style::new().bold().paint(theme.to_string())
179 )?;
180 config.theme = theme.to_string();
181 let _controller = Controller::new(&config, &assets).run();
182 writeln!(stdout)?;
183 }
184 } else {
185 for (theme, _) in themes.iter() {
186 writeln!(stdout, "{}", theme)?;
187 }
188 }
190 Ok(())
193fn run_controller(config: &Config) -> Result<bool> {
194 let assets = HighlightingAssets::new();
195 let controller = Controller::new(&config, &assets);
196 controller.run()
199/// Returns `Err(..)` upon fatal errors. Otherwise, returns `Ok(true)` on full success and
200/// `Ok(false)` if any intermediate errors occurred (were printed).
201fn run() -> Result<bool> {
202 let app = App::new()?;
204 match app.matches.subcommand() {
205 ("cache", Some(cache_matches)) => {
206 // If there is a file named 'cache' in the current working directory,
207 // arguments for subcommand 'cache' are not mandatory.
208 // If there are non-zero arguments, execute the subcommand cache, else, open the file cache.
209 if !cache_matches.args.is_empty() {
210 run_cache_subcommand(cache_matches)?;
211 Ok(true)
212 } else {
213 let mut config = app.config()?;
214 config.files = vec![InputFile::Ordinary(&"cache")];
216 run_controller(&config)
217 }
218 }
219 _ => {
220 let config = app.config()?;
222 if app.matches.is_present("list-languages") {
223 list_languages(&config)?;
225 Ok(true)
226 } else if app.matches.is_present("list-themes") {
227 list_themes(&config)?;
229 Ok(true)
230 } else if app.matches.is_present("config-file") {
231 println!("{}", config_file().to_string_lossy());
233 Ok(true)
234 } else if app.matches.is_present("config-dir") {
235 writeln!(io::stdout(), "{}", config_dir())?;
236 Ok(true)
237 } else if app.matches.is_present("cache-dir") {
238 writeln!(io::stdout(), "{}", cache_dir())?;
239 Ok(true)
240 } else {
241 run_controller(&config)
242 }
243 }
244 }
247fn main() {
248 let result = run();
250 match result {
251 Err(error) => {
252 handle_error(&error);
253 process::exit(1);
254 }
255 Ok(false) => {
256 process::exit(1);
257 }
258 Ok(true) => {
259 process::exit(0);
260 }
261 }