on 6faf615 help sign in
bat/src/assets.rs
515 lines 18 kB history raw
1use std::collections::BTreeMap;
2use std::ffi::OsStr;
3use std::fs::{self, File};
4use std::io::BufReader;
5use std::path::Path;
7use syntect::dumps::{dump_to_file, from_binary, from_reader};
8use syntect::highlighting::{Theme, ThemeSet};
9use syntect::parsing::{SyntaxReference, SyntaxSet, SyntaxSetBuilder};
11use path_abs::PathAbs;
13use crate::assets_metadata::AssetsMetadata;
14use crate::error::*;
15use crate::input::{InputReader, OpenedInput, OpenedInputKind};
16use crate::syntax_mapping::{MappingTarget, SyntaxMapping};
18#[derive(Debug)]
19pub struct HighlightingAssets {
20 pub(crate) syntax_set: SyntaxSet,
21 pub(crate) theme_set: ThemeSet,
22 fallback_theme: Option<&'static str>,
25impl HighlightingAssets {
26 pub fn default_theme() -> &'static str {
27 "Monokai Extended"
28 }
30 pub fn from_files(source_dir: &Path, include_integrated_assets: bool) -> Result<Self> {
31 let mut theme_set = if include_integrated_assets {
32 Self::get_integrated_themeset()
33 } else {
34 ThemeSet {
35 themes: BTreeMap::new(),
36 }
37 };
39 let theme_dir = source_dir.join("themes");
41 let res = theme_set.add_from_folder(&theme_dir);
42 if res.is_err() {
43 println!(
44 "No themes were found in '{}', using the default set",
45 theme_dir.to_string_lossy()
46 );
47 }
49 let mut syntax_set_builder = if !include_integrated_assets {
50 let mut builder = SyntaxSetBuilder::new();
51 builder.add_plain_text_syntax();
52 builder
53 } else {
54 Self::get_integrated_syntaxset().into_builder()
55 };
57 let syntax_dir = source_dir.join("syntaxes");
58 if syntax_dir.exists() {
59 syntax_set_builder.add_from_folder(syntax_dir, true)?;
60 } else {
61 println!(
62 "No syntaxes were found in '{}', using the default set.",
63 syntax_dir.to_string_lossy()
64 );
65 }
67 Ok(HighlightingAssets {
68 syntax_set: syntax_set_builder.build(),
69 theme_set,
70 fallback_theme: None,
71 })
72 }
74 pub fn from_cache(cache_path: &Path) -> Result<Self> {
75 let syntax_set_path = cache_path.join("syntaxes.bin");
76 let theme_set_path = cache_path.join("themes.bin");
78 let syntax_set_file = File::open(&syntax_set_path).chain_err(|| {
79 format!(
80 "Could not load cached syntax set '{}'",
81 syntax_set_path.to_string_lossy()
82 )
83 })?;
84 let syntax_set: SyntaxSet = from_reader(BufReader::new(syntax_set_file))
85 .chain_err(|| "Could not parse cached syntax set")?;
87 let theme_set_file = File::open(&theme_set_path).chain_err(|| {
88 format!(
89 "Could not load cached theme set '{}'",
90 theme_set_path.to_string_lossy()
91 )
92 })?;
93 let theme_set: ThemeSet = from_reader(BufReader::new(theme_set_file))
94 .chain_err(|| "Could not parse cached theme set")?;
96 Ok(HighlightingAssets {
97 syntax_set,
98 theme_set,
99 fallback_theme: None,
100 })
101 }
103 fn get_integrated_syntaxset() -> SyntaxSet {
104 from_binary(include_bytes!("../assets/syntaxes.bin"))
105 }
107 fn get_integrated_themeset() -> ThemeSet {
108 from_binary(include_bytes!("../assets/themes.bin"))
109 }
111 pub fn from_binary() -> Self {
112 let syntax_set = Self::get_integrated_syntaxset();
113 let theme_set = Self::get_integrated_themeset();
115 HighlightingAssets {
116 syntax_set,
117 theme_set,
118 fallback_theme: None,
119 }
120 }
122 pub fn save_to_cache(&self, target_dir: &Path, current_version: &str) -> Result<()> {
123 let _ = fs::create_dir_all(target_dir);
124 let theme_set_path = target_dir.join("themes.bin");
125 let syntax_set_path = target_dir.join("syntaxes.bin");
127 print!(
128 "Writing theme set to {} ... ",
129 theme_set_path.to_string_lossy()
130 );
131 dump_to_file(&self.theme_set, &theme_set_path).chain_err(|| {
132 format!(
133 "Could not save theme set to {}",
134 theme_set_path.to_string_lossy()
135 )
136 })?;
137 println!("okay");
139 print!(
140 "Writing syntax set to {} ... ",
141 syntax_set_path.to_string_lossy()
142 );
143 dump_to_file(&self.syntax_set, &syntax_set_path).chain_err(|| {
144 format!(
145 "Could not save syntax set to {}",
146 syntax_set_path.to_string_lossy()
147 )
148 })?;
149 println!("okay");
151 print!(
152 "Writing metadata to folder {} ... ",
153 target_dir.to_string_lossy()
154 );
155 AssetsMetadata::new(current_version).save_to_folder(target_dir)?;
156 println!("okay");
158 Ok(())
159 }
161 pub fn set_fallback_theme(&mut self, theme: &'static str) {
162 self.fallback_theme = Some(theme);
163 }
165 pub fn syntaxes(&self) -> &[SyntaxReference] {
166 self.syntax_set.syntaxes()
167 }
169 pub fn themes(&self) -> impl Iterator<Item = &str> {
170 self.theme_set.themes.keys().map(|s| s.as_ref())
171 }
173 pub(crate) fn get_theme(&self, theme: &str) -> &Theme {
174 match self.theme_set.themes.get(theme) {
175 Some(theme) => theme,
176 None => {
177 if theme != "" {
178 use ansi_term::Colour::Yellow;
179 eprintln!(
180 "{}: Unknown theme '{}', using default.",
181 Yellow.paint("[bat warning]"),
182 theme
183 );
184 }
185 &self.theme_set.themes[self.fallback_theme.unwrap_or_else(|| Self::default_theme())]
186 }
187 }
188 }
190 pub(crate) fn get_syntax(
191 &self,
192 language: Option<&str>,
193 input: &mut OpenedInput,
194 mapping: &SyntaxMapping,
195 ) -> Result<&SyntaxReference> {
196 if let Some(language) = language {
197 self.syntax_set
198 .find_syntax_by_token(language)
199 .ok_or_else(|| ErrorKind::UnknownSyntax(language.to_owned()).into())
200 } else {
201 let line_syntax = self.get_first_line_syntax(&mut input.reader);
203 // Get the path of the file:
204 // If this was set by the metadata, that will take priority.
205 // If it wasn't, it will use the real file path (if available).
206 let path_str =
207 input
208 .metadata
209 .user_provided_name
210 .as_ref()
211 .or_else(|| match input.kind {
212 OpenedInputKind::OrdinaryFile(ref path) => Some(path),
213 _ => None,
214 });
216 if let Some(path_str) = path_str {
217 // If a path was provided, we try and detect the syntax based on extension mappings.
218 let path = Path::new(path_str);
219 let absolute_path = PathAbs::new(path)
220 .ok()
221 .map(|p| p.as_path().to_path_buf())
222 .unwrap_or_else(|| path.to_owned());
224 match mapping.get_syntax_for(absolute_path) {
225 Some(MappingTarget::MapToUnknown) => line_syntax.ok_or_else(|| {
226 ErrorKind::UndetectedSyntax(path.to_string_lossy().into()).into()
227 }),
229 Some(MappingTarget::MapTo(syntax_name)) => self
230 .syntax_set
231 .find_syntax_by_name(syntax_name)
232 .ok_or_else(|| ErrorKind::UnknownSyntax(syntax_name.to_owned()).into()),
234 None => {
235 let file_name = path.file_name().unwrap_or_default();
236 self.get_extension_syntax(file_name)
237 .or(line_syntax)
238 .ok_or_else(|| {
239 ErrorKind::UndetectedSyntax(path.to_string_lossy().into()).into()
240 })
241 }
242 }
243 } else {
244 // If a path wasn't provided, we fall back to the detect first-line syntax.
245 line_syntax.ok_or_else(|| ErrorKind::UndetectedSyntax("[unknown]".into()).into())
246 }
247 }
248 }
250 fn get_extension_syntax(&self, file_name: &OsStr) -> Option<&SyntaxReference> {
251 self.syntax_set
252 .find_syntax_by_extension(file_name.to_str().unwrap_or_default())
253 .or_else(|| {
254 self.syntax_set.find_syntax_by_extension(
255 Path::new(file_name)
256 .extension()
257 .and_then(|x| x.to_str())
258 .unwrap_or_default(),
259 )
260 })
261 }
263 fn get_first_line_syntax(&self, reader: &mut InputReader) -> Option<&SyntaxReference> {
264 String::from_utf8(reader.first_line.clone())
265 .ok()
266 .and_then(|l| self.syntax_set.find_syntax_by_first_line(&l))
267 }
270#[cfg(test)]
271mod tests {
272 use super::*;
274 use std::ffi::OsStr;
276 use std::fs::File;
277 use std::io::Write;
278 use tempdir::TempDir;
280 use crate::input::Input;
282 struct SyntaxDetectionTest<'a> {
283 assets: HighlightingAssets,
284 pub syntax_mapping: SyntaxMapping<'a>,
285 pub temp_dir: TempDir,
286 }
288 impl<'a> SyntaxDetectionTest<'a> {
289 fn new() -> Self {
290 SyntaxDetectionTest {
291 assets: HighlightingAssets::from_binary(),
292 syntax_mapping: SyntaxMapping::builtin(),
293 temp_dir: TempDir::new("bat_syntax_detection_tests")
294 .expect("creation of temporary directory"),
295 }
296 }
298 fn syntax_for_real_file_with_content_os(
299 &self,
300 file_name: &OsStr,
301 first_line: &str,
302 ) -> String {
303 let file_path = self.temp_dir.path().join(file_name);
304 {
305 let mut temp_file = File::create(&file_path).unwrap();
306 writeln!(temp_file, "{}", first_line).unwrap();
307 }
309 let input = Input::ordinary_file(file_path.as_os_str());
310 let dummy_stdin: &[u8] = &[];
311 let mut opened_input = input.open(dummy_stdin).unwrap();
313 self.assets
314 .get_syntax(None, &mut opened_input, &self.syntax_mapping)
315 .unwrap_or_else(|_| self.assets.syntax_set.find_syntax_plain_text())
316 .name
317 .clone()
318 }
320 fn syntax_for_file_with_content_os(&self, file_name: &OsStr, first_line: &str) -> String {
321 let file_path = self.temp_dir.path().join(file_name);
322 let input = Input::from_reader(Box::new(BufReader::new(first_line.as_bytes())))
323 .with_name(Some(file_path.as_os_str()));
324 let dummy_stdin: &[u8] = &[];
325 let mut opened_input = input.open(dummy_stdin).unwrap();
327 self.assets
328 .get_syntax(None, &mut opened_input, &self.syntax_mapping)
329 .unwrap_or_else(|_| self.assets.syntax_set.find_syntax_plain_text())
330 .name
331 .clone()
332 }
334 #[cfg(unix)]
335 fn syntax_for_file_os(&self, file_name: &OsStr) -> String {
336 self.syntax_for_file_with_content_os(file_name, "")
337 }
339 fn syntax_for_file_with_content(&self, file_name: &str, first_line: &str) -> String {
340 self.syntax_for_file_with_content_os(OsStr::new(file_name), first_line)
341 }
343 fn syntax_for_file(&self, file_name: &str) -> String {
344 self.syntax_for_file_with_content(file_name, "")
345 }
347 fn syntax_for_stdin_with_content(&self, file_name: &str, content: &[u8]) -> String {
348 let input = Input::stdin().with_name(Some(OsStr::new(file_name)));
349 let mut opened_input = input.open(content).unwrap();
351 self.assets
352 .get_syntax(None, &mut opened_input, &self.syntax_mapping)
353 .unwrap_or_else(|_| self.assets.syntax_set.find_syntax_plain_text())
354 .name
355 .clone()
356 }
358 fn syntax_is_same_for_inputkinds(&self, file_name: &str, content: &str) -> bool {
359 let as_file = self.syntax_for_real_file_with_content_os(file_name.as_ref(), content);
360 let as_reader = self.syntax_for_file_with_content_os(file_name.as_ref(), content);
361 let consistent = as_file == as_reader;
362 // TODO: Compare StdIn somehow?
364 if !consistent {
365 eprintln!(
366 "Inconsistent syntax detection:\nFor File: {}\nFor Reader: {}",
367 as_file, as_reader
368 )
369 }
371 consistent
372 }
373 }
375 #[test]
376 fn syntax_detection_basic() {
377 let test = SyntaxDetectionTest::new();
379 assert_eq!(test.syntax_for_file("test.rs"), "Rust");
380 assert_eq!(test.syntax_for_file("test.cpp"), "C++");
381 assert_eq!(test.syntax_for_file("test.build"), "NAnt Build File");
382 assert_eq!(
383 test.syntax_for_file("PKGBUILD"),
384 "Bourne Again Shell (bash)"
385 );
386 assert_eq!(test.syntax_for_file(".bashrc"), "Bourne Again Shell (bash)");
387 assert_eq!(test.syntax_for_file("Makefile"), "Makefile");
388 }
390 #[cfg(unix)]
391 #[test]
392 fn syntax_detection_invalid_utf8() {
393 use std::os::unix::ffi::OsStrExt;
395 let test = SyntaxDetectionTest::new();
397 assert_eq!(
398 test.syntax_for_file_os(OsStr::from_bytes(b"invalid_\xFEutf8_filename.rs")),
399 "Rust"
400 );
401 }
403 #[test]
404 fn syntax_detection_same_for_inputkinds() {
405 let mut test = SyntaxDetectionTest::new();
407 test.syntax_mapping
408 .insert("*.myext", MappingTarget::MapTo("C"))
409 .ok();
410 test.syntax_mapping
411 .insert("MY_FILE", MappingTarget::MapTo("Markdown"))
412 .ok();
414 assert!(test.syntax_is_same_for_inputkinds("Test.md", ""));
415 assert!(test.syntax_is_same_for_inputkinds("Test.txt", "#!/bin/bash"));
416 assert!(test.syntax_is_same_for_inputkinds(".bashrc", ""));
417 assert!(test.syntax_is_same_for_inputkinds("test.h", ""));
418 assert!(test.syntax_is_same_for_inputkinds("test.js", "#!/bin/bash"));
419 assert!(test.syntax_is_same_for_inputkinds("test.myext", ""));
420 assert!(test.syntax_is_same_for_inputkinds("MY_FILE", ""));
421 assert!(test.syntax_is_same_for_inputkinds("MY_FILE", "<?php"));
422 }
424 #[test]
425 fn syntax_detection_well_defined_mapping_for_duplicate_extensions() {
426 let test = SyntaxDetectionTest::new();
428 assert_eq!(test.syntax_for_file("test.h"), "C++");
429 assert_eq!(test.syntax_for_file("test.sass"), "Sass");
430 assert_eq!(test.syntax_for_file("test.js"), "JavaScript (Babel)");
431 assert_eq!(test.syntax_for_file("test.fs"), "F#");
432 }
434 #[test]
435 fn syntax_detection_first_line() {
436 let test = SyntaxDetectionTest::new();
438 assert_eq!(
439 test.syntax_for_file_with_content("my_script", "#!/bin/bash"),
440 "Bourne Again Shell (bash)"
441 );
442 assert_eq!(
443 test.syntax_for_file_with_content("build", "#!/bin/bash"),
444 "Bourne Again Shell (bash)"
445 );
446 assert_eq!(
447 test.syntax_for_file_with_content("my_script", "<?php"),
448 "PHP"
449 );
450 }
452 #[test]
453 fn syntax_detection_with_custom_mapping() {
454 let mut test = SyntaxDetectionTest::new();
456 assert_eq!(test.syntax_for_file("test.h"), "C++");
457 test.syntax_mapping
458 .insert("*.h", MappingTarget::MapTo("C"))
459 .ok();
460 assert_eq!(test.syntax_for_file("test.h"), "C");
461 }
463 #[test]
464 fn syntax_detection_is_case_sensitive() {
465 let mut test = SyntaxDetectionTest::new();
467 assert_ne!(test.syntax_for_file("README.MD"), "Markdown");
468 test.syntax_mapping
469 .insert("*.MD", MappingTarget::MapTo("Markdown"))
470 .ok();
471 assert_eq!(test.syntax_for_file("README.MD"), "Markdown");
472 }
474 #[test]
475 fn syntax_detection_stdin_filename() {
476 let test = SyntaxDetectionTest::new();
478 // from file extension
479 assert_eq!(test.syntax_for_stdin_with_content("test.cpp", b"a"), "C++");
480 // from first line (fallback)
481 assert_eq!(
482 test.syntax_for_stdin_with_content("my_script", b"#!/bin/bash"),
483 "Bourne Again Shell (bash)"
484 );
485 }
487 #[cfg(unix)]
488 #[test]
489 fn syntax_detection_for_symlinked_file() {
490 use std::os::unix::fs::symlink;
492 let test = SyntaxDetectionTest::new();
493 let file_path = test.temp_dir.path().join("my_ssh_config_filename");
494 {
495 File::create(&file_path).unwrap();
496 }
497 let file_path_symlink = test.temp_dir.path().join(".ssh").join("config");
499 std::fs::create_dir(test.temp_dir.path().join(".ssh"))
500 .expect("creation of directory succeeds");
501 symlink(&file_path, &file_path_symlink).expect("creation of symbolic link succeeds");
503 let input = Input::ordinary_file(file_path_symlink.as_os_str());
504 let dummy_stdin: &[u8] = &[];
505 let mut opened_input = input.open(dummy_stdin).unwrap();
507 assert_eq!(
508 test.assets
509 .get_syntax(None, &mut opened_input, &test.syntax_mapping)
510 .unwrap_or_else(|_| test.assets.syntax_set.find_syntax_plain_text())
511 .name,
512 "SSH Config"
513 );
514 }