on 5ebf021 help sign in
bat/src/assets.rs
513 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 fn syntax_for_file_os(&self, file_name: &OsStr) -> String {
335 self.syntax_for_file_with_content_os(file_name, "")
336 }
338 fn syntax_for_file_with_content(&self, file_name: &str, first_line: &str) -> String {
339 self.syntax_for_file_with_content_os(OsStr::new(file_name), first_line)
340 }
342 fn syntax_for_file(&self, file_name: &str) -> String {
343 self.syntax_for_file_with_content(file_name, "")
344 }
346 fn syntax_for_stdin_with_content(&self, file_name: &str, content: &[u8]) -> String {
347 let input = Input::stdin().with_name(Some(OsStr::new(file_name)));
348 let mut opened_input = input.open(content).unwrap();
350 self.assets
351 .get_syntax(None, &mut opened_input, &self.syntax_mapping)
352 .unwrap_or_else(|_| self.assets.syntax_set.find_syntax_plain_text())
353 .name
354 .clone()
355 }
357 fn syntax_is_same_for_inputkinds(&self, file_name: &str, content: &str) -> bool {
358 let as_file = self.syntax_for_real_file_with_content_os(file_name.as_ref(), content);
359 let as_reader = self.syntax_for_file_with_content_os(file_name.as_ref(), content);
360 let consistent = as_file == as_reader;
361 // TODO: Compare StdIn somehow?
363 if !consistent {
364 eprintln!(
365 "Inconsistent syntax detection:\nFor File: {}\nFor Reader: {}",
366 as_file, as_reader
367 )
368 }
370 consistent
371 }
372 }
374 #[test]
375 fn syntax_detection_basic() {
376 let test = SyntaxDetectionTest::new();
378 assert_eq!(test.syntax_for_file("test.rs"), "Rust");
379 assert_eq!(test.syntax_for_file("test.cpp"), "C++");
380 assert_eq!(test.syntax_for_file("test.build"), "NAnt Build File");
381 assert_eq!(
382 test.syntax_for_file("PKGBUILD"),
383 "Bourne Again Shell (bash)"
384 );
385 assert_eq!(test.syntax_for_file(".bashrc"), "Bourne Again Shell (bash)");
386 assert_eq!(test.syntax_for_file("Makefile"), "Makefile");
387 }
389 #[cfg(unix)]
390 #[test]
391 fn syntax_detection_invalid_utf8() {
392 use std::os::unix::ffi::OsStrExt;
394 let test = SyntaxDetectionTest::new();
396 assert_eq!(
397 test.syntax_for_file_os(OsStr::from_bytes(b"invalid_\xFEutf8_filename.rs")),
398 "Rust"
399 );
400 }
402 #[test]
403 fn syntax_detection_same_for_inputkinds() {
404 let mut test = SyntaxDetectionTest::new();
406 test.syntax_mapping
407 .insert("*.myext", MappingTarget::MapTo("C"))
408 .ok();
409 test.syntax_mapping
410 .insert("MY_FILE", MappingTarget::MapTo("Markdown"))
411 .ok();
413 assert!(test.syntax_is_same_for_inputkinds("Test.md", ""));
414 assert!(test.syntax_is_same_for_inputkinds("Test.txt", "#!/bin/bash"));
415 assert!(test.syntax_is_same_for_inputkinds(".bashrc", ""));
416 assert!(test.syntax_is_same_for_inputkinds("test.h", ""));
417 assert!(test.syntax_is_same_for_inputkinds("test.js", "#!/bin/bash"));
418 assert!(test.syntax_is_same_for_inputkinds("test.myext", ""));
419 assert!(test.syntax_is_same_for_inputkinds("MY_FILE", ""));
420 assert!(test.syntax_is_same_for_inputkinds("MY_FILE", "<?php"));
421 }
423 #[test]
424 fn syntax_detection_well_defined_mapping_for_duplicate_extensions() {
425 let test = SyntaxDetectionTest::new();
427 assert_eq!(test.syntax_for_file("test.h"), "C++");
428 assert_eq!(test.syntax_for_file("test.sass"), "Sass");
429 assert_eq!(test.syntax_for_file("test.js"), "JavaScript (Babel)");
430 }
432 #[test]
433 fn syntax_detection_first_line() {
434 let test = SyntaxDetectionTest::new();
436 assert_eq!(
437 test.syntax_for_file_with_content("my_script", "#!/bin/bash"),
438 "Bourne Again Shell (bash)"
439 );
440 assert_eq!(
441 test.syntax_for_file_with_content("build", "#!/bin/bash"),
442 "Bourne Again Shell (bash)"
443 );
444 assert_eq!(
445 test.syntax_for_file_with_content("my_script", "<?php"),
446 "PHP"
447 );
448 }
450 #[test]
451 fn syntax_detection_with_custom_mapping() {
452 let mut test = SyntaxDetectionTest::new();
454 assert_eq!(test.syntax_for_file("test.h"), "C++");
455 test.syntax_mapping
456 .insert("*.h", MappingTarget::MapTo("C"))
457 .ok();
458 assert_eq!(test.syntax_for_file("test.h"), "C");
459 }
461 #[test]
462 fn syntax_detection_is_case_sensitive() {
463 let mut test = SyntaxDetectionTest::new();
465 assert_ne!(test.syntax_for_file("README.MD"), "Markdown");
466 test.syntax_mapping
467 .insert("*.MD", MappingTarget::MapTo("Markdown"))
468 .ok();
469 assert_eq!(test.syntax_for_file("README.MD"), "Markdown");
470 }
472 #[test]
473 fn syntax_detection_stdin_filename() {
474 let test = SyntaxDetectionTest::new();
476 // from file extension
477 assert_eq!(test.syntax_for_stdin_with_content("test.cpp", b"a"), "C++");
478 // from first line (fallback)
479 assert_eq!(
480 test.syntax_for_stdin_with_content("my_script", b"#!/bin/bash"),
481 "Bourne Again Shell (bash)"
482 );
483 }
485 #[cfg(unix)]
486 #[test]
487 fn syntax_detection_for_symlinked_file() {
488 use std::os::unix::fs::symlink;
490 let test = SyntaxDetectionTest::new();
491 let file_path = test.temp_dir.path().join("my_ssh_config_filename");
492 {
493 File::create(&file_path).unwrap();
494 }
495 let file_path_symlink = test.temp_dir.path().join(".ssh").join("config");
497 std::fs::create_dir(test.temp_dir.path().join(".ssh"))
498 .expect("creation of directory succeeds");
499 symlink(&file_path, &file_path_symlink).expect("creation of symbolic link succeeds");
501 let input = Input::ordinary_file(file_path_symlink.as_os_str());
502 let dummy_stdin: &[u8] = &[];
503 let mut opened_input = input.open(dummy_stdin).unwrap();
505 assert_eq!(
506 test.assets
507 .get_syntax(None, &mut opened_input, &test.syntax_mapping)
508 .unwrap_or_else(|_| test.assets.syntax_set.find_syntax_plain_text())
509 .name,
510 "SSH Config"
511 );
512 }