on f7d9f49 help sign in
bat/src/main.rs
255 lines 7.0 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 directories;
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::{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 }
68 pub fn handle_error(error: &Error) {
69 match error {
70 &Error(ErrorKind::Io(ref io_error), _)
71 if io_error.kind() == super::io::ErrorKind::BrokenPipe =>
72 {
73 super::process::exit(0);
74 }
75 _ => {
76 use ansi_term::Colour::Red;
77 eprintln!("{}: {}", Red.paint("[bat error]"), error);
78 }
79 };
80 }
83use errors::*;
85fn run_cache_subcommand(matches: &clap::ArgMatches) -> Result<()> {
86 if matches.is_present("init") {
87 let source_dir = matches.value_of("source").map(Path::new);
88 let target_dir = matches.value_of("target").map(Path::new);
90 let blank = matches.is_present("blank");
92 let assets = HighlightingAssets::from_files(source_dir, blank)?;
93 assets.save(target_dir)?;
94 } else if matches.is_present("clear") {
95 clear_assets();
96 } else if matches.is_present("config-dir") {
97 writeln!(io::stdout(), "{}", config_dir())?;
98 }
100 Ok(())
103pub fn list_languages(config: &Config) -> Result<()> {
104 let assets = HighlightingAssets::new();
105 let mut languages = assets
106 .syntax_set
107 .syntaxes()
108 .iter()
109 .filter(|syntax| !syntax.hidden && !syntax.file_extensions.is_empty())
110 .collect::<Vec<_>>();
111 languages.sort_by_key(|lang| lang.name.to_uppercase());
113 let longest = languages
114 .iter()
115 .map(|syntax| syntax.name.len())
116 .max()
117 .unwrap_or(32); // Fallback width if they have no language definitions.
119 let comma_separator = ", ";
120 let separator = " ";
121 // Line-wrapping for the possible file extension overflow.
122 let desired_width = config.term_width - longest - separator.len();
124 let stdout = io::stdout();
125 let mut stdout = stdout.lock();
127 let style = if config.colored_output {
128 Green.normal()
129 } else {
130 Style::default()
131 };
133 for lang in languages {
134 write!(stdout, "{:width$}{}", lang.name, separator, width = longest)?;
136 // Number of characters on this line so far, wrap before `desired_width`
137 let mut num_chars = 0;
139 let mut extension = lang.file_extensions.iter().peekable();
140 while let Some(word) = extension.next() {
141 // If we can't fit this word in, then create a line break and align it in.
142 let new_chars = word.len() + comma_separator.len();
143 if num_chars + new_chars >= desired_width {
144 num_chars = 0;
145 write!(stdout, "\n{:width$}{}", "", separator, width = longest)?;
146 }
148 num_chars += new_chars;
149 write!(stdout, "{}", style.paint(&word[..]))?;
150 if extension.peek().is_some() {
151 write!(stdout, "{}", comma_separator)?;
152 }
153 }
154 writeln!(stdout)?;
155 }
157 Ok(())
160pub fn list_themes(cfg: &Config) -> Result<()> {
161 let assets = HighlightingAssets::new();
162 let themes = &assets.theme_set.themes;
163 let mut config = cfg.clone();
164 let mut style = HashSet::new();
165 style.insert(OutputComponent::Plain);
166 config.files = vec![InputFile::ThemePreviewFile];
167 config.output_components = OutputComponents(style);
169 let stdout = io::stdout();
170 let mut stdout = stdout.lock();
172 if config.colored_output {
173 for (theme, _) in themes.iter() {
174 writeln!(
175 stdout,
176 "Theme: {}\n",
177 Style::new().bold().paint(theme.to_string())
178 )?;
179 config.theme = theme.to_string();
180 let _controller = Controller::new(&config, &assets).run();
181 writeln!(stdout)?;
182 }
183 } else {
184 for (theme, _) in themes.iter() {
185 writeln!(stdout, "{}", theme)?;
186 }
187 }
189 Ok(())
192fn run_controller(config: &Config) -> Result<bool> {
193 let assets = HighlightingAssets::new();
194 let controller = Controller::new(&config, &assets);
195 controller.run()
198/// Returns `Err(..)` upon fatal errors. Otherwise, returns `Some(true)` on full success and
199/// `Some(false)` if any intermediate errors occurred (were printed).
200fn run() -> Result<bool> {
201 let app = App::new()?;
203 match app.matches.subcommand() {
204 ("cache", Some(cache_matches)) => {
205 // If there is a file named 'cache' in the current working directory,
206 // arguments for subcommand 'cache' are not mandatory.
207 // If there are non-zero arguments, execute the subcommand cache, else, open the file cache.
208 if !cache_matches.args.is_empty() {
209 run_cache_subcommand(cache_matches)?;
210 Ok(true)
211 } else {
212 let mut config = app.config()?;
213 config.files = vec![InputFile::Ordinary(&"cache")];
215 run_controller(&config)
216 }
217 }
218 _ => {
219 let config = app.config()?;
221 if app.matches.is_present("list-languages") {
222 list_languages(&config)?;
224 Ok(true)
225 } else if app.matches.is_present("list-themes") {
226 list_themes(&config)?;
228 Ok(true)
229 } else if app.matches.is_present("config-file") {
230 println!("{}", config_file().to_string_lossy());
232 Ok(true)
233 } else {
234 run_controller(&config)
235 }
236 }
237 }
240fn main() {
241 let result = run();
243 match result {
244 Err(error) => {
245 handle_error(&error);
246 process::exit(1);
247 }
248 Ok(false) => {
249 process::exit(1);
250 }
251 Ok(true) => {
252 process::exit(0);
253 }
254 }