on 384ea38 help sign in
bat/src/assets.rs
517 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 input.kind.is_theme_preview_file() {
197 self.syntax_set
198 .find_syntax_by_name("Rust")
199 .ok_or_else(|| ErrorKind::UnknownSyntax("Rust".to_owned()).into())
200 } else if let Some(language) = language {
201 self.syntax_set
202 .find_syntax_by_token(language)
203 .ok_or_else(|| ErrorKind::UnknownSyntax(language.to_owned()).into())
204 } else {
205 let line_syntax = self.get_first_line_syntax(&mut input.reader);
207 // Get the path of the file:
208 // If this was set by the metadata, that will take priority.
209 // If it wasn't, it will use the real file path (if available).
210 let path_str =
211 input
212 .metadata
213 .user_provided_name
214 .as_ref()
215 .or_else(|| match input.kind {
216 OpenedInputKind::OrdinaryFile(ref path) => Some(path),
217 _ => None,
218 });
220 if let Some(path_str) = path_str {
221 // If a path was provided, we try and detect the syntax based on extension mappings.
222 let path = Path::new(path_str);
223 let absolute_path = PathAbs::new(path)
224 .ok()
225 .map(|p| p.as_path().to_path_buf())
226 .unwrap_or_else(|| path.to_owned());
228 match mapping.get_syntax_for(absolute_path) {
229 Some(MappingTarget::MapToUnknown) => line_syntax.ok_or_else(|| {
230 ErrorKind::UndetectedSyntax(path.to_string_lossy().into()).into()
231 }),
233 Some(MappingTarget::MapTo(syntax_name)) => self
234 .syntax_set
235 .find_syntax_by_name(syntax_name)
236 .ok_or_else(|| ErrorKind::UnknownSyntax(syntax_name.to_owned()).into()),
238 None => {
239 let file_name = path.file_name().unwrap_or_default();
240 self.get_extension_syntax(file_name)
241 .or(line_syntax)
242 .ok_or_else(|| {
243 ErrorKind::UndetectedSyntax(path.to_string_lossy().into()).into()
244 })
245 }
246 }
247 } else {
248 // If a path wasn't provided, we fall back to the detect first-line syntax.
249 line_syntax.ok_or_else(|| ErrorKind::UndetectedSyntax("[unknown]".into()).into())
250 }
251 }
252 }
254 fn get_extension_syntax(&self, file_name: &OsStr) -> Option<&SyntaxReference> {
255 self.syntax_set
256 .find_syntax_by_extension(file_name.to_str().unwrap_or_default())
257 .or_else(|| {
258 self.syntax_set.find_syntax_by_extension(
259 Path::new(file_name)
260 .extension()
261 .and_then(|x| x.to_str())
262 .unwrap_or_default(),
263 )
264 })
265 }
267 fn get_first_line_syntax(&self, reader: &mut InputReader) -> Option<&SyntaxReference> {
268 String::from_utf8(reader.first_line.clone())
269 .ok()
270 .and_then(|l| self.syntax_set.find_syntax_by_first_line(&l))
271 }
274#[cfg(test)]
275mod tests {
276 use super::*;
278 use std::ffi::OsStr;
280 use std::fs::File;
281 use std::io::Write;
282 use tempdir::TempDir;
284 use crate::input::Input;
286 struct SyntaxDetectionTest<'a> {
287 assets: HighlightingAssets,
288 pub syntax_mapping: SyntaxMapping<'a>,
289 pub temp_dir: TempDir,
290 }
292 impl<'a> SyntaxDetectionTest<'a> {
293 fn new() -> Self {
294 SyntaxDetectionTest {
295 assets: HighlightingAssets::from_binary(),
296 syntax_mapping: SyntaxMapping::builtin(),
297 temp_dir: TempDir::new("bat_syntax_detection_tests")
298 .expect("creation of temporary directory"),
299 }
300 }
302 fn syntax_for_real_file_with_content_os(
303 &self,
304 file_name: &OsStr,
305 first_line: &str,
306 ) -> String {
307 let file_path = self.temp_dir.path().join(file_name);
308 {
309 let mut temp_file = File::create(&file_path).unwrap();
310 writeln!(temp_file, "{}", first_line).unwrap();
311 }
313 let input = Input::ordinary_file(file_path.as_os_str());
314 let dummy_stdin: &[u8] = &[];
315 let mut opened_input = input.open(dummy_stdin).unwrap();
317 self.assets
318 .get_syntax(None, &mut opened_input, &self.syntax_mapping)
319 .unwrap_or_else(|_| self.assets.syntax_set.find_syntax_plain_text())
320 .name
321 .clone()
322 }
324 fn syntax_for_file_with_content_os(&self, file_name: &OsStr, first_line: &str) -> String {
325 let file_path = self.temp_dir.path().join(file_name);
326 let input = Input::from_reader(Box::new(BufReader::new(first_line.as_bytes())))
327 .with_name(Some(file_path.as_os_str()));
328 let dummy_stdin: &[u8] = &[];
329 let mut opened_input = input.open(dummy_stdin).unwrap();
331 self.assets
332 .get_syntax(None, &mut opened_input, &self.syntax_mapping)
333 .unwrap_or_else(|_| self.assets.syntax_set.find_syntax_plain_text())
334 .name
335 .clone()
336 }
338 fn syntax_for_file_os(&self, file_name: &OsStr) -> String {
339 self.syntax_for_file_with_content_os(file_name, "")
340 }
342 fn syntax_for_file_with_content(&self, file_name: &str, first_line: &str) -> String {
343 self.syntax_for_file_with_content_os(OsStr::new(file_name), first_line)
344 }
346 fn syntax_for_file(&self, file_name: &str) -> String {
347 self.syntax_for_file_with_content(file_name, "")
348 }
350 fn syntax_for_stdin_with_content(&self, file_name: &str, content: &[u8]) -> String {
351 let input = Input::stdin().with_name(Some(OsStr::new(file_name)));
352 let mut opened_input = input.open(content).unwrap();
354 self.assets
355 .get_syntax(None, &mut opened_input, &self.syntax_mapping)
356 .unwrap_or_else(|_| self.assets.syntax_set.find_syntax_plain_text())
357 .name
358 .clone()
359 }
361 fn syntax_is_same_for_inputkinds(&self, file_name: &str, content: &str) -> bool {
362 let as_file = self.syntax_for_real_file_with_content_os(file_name.as_ref(), content);
363 let as_reader = self.syntax_for_file_with_content_os(file_name.as_ref(), content);
364 let consistent = as_file == as_reader;
365 // TODO: Compare StdIn somehow?
367 if !consistent {
368 eprintln!(
369 "Inconsistent syntax detection:\nFor File: {}\nFor Reader: {}",
370 as_file, as_reader
371 )
372 }
374 consistent
375 }
376 }
378 #[test]
379 fn syntax_detection_basic() {
380 let test = SyntaxDetectionTest::new();
382 assert_eq!(test.syntax_for_file("test.rs"), "Rust");
383 assert_eq!(test.syntax_for_file("test.cpp"), "C++");
384 assert_eq!(test.syntax_for_file("test.build"), "NAnt Build File");
385 assert_eq!(
386 test.syntax_for_file("PKGBUILD"),
387 "Bourne Again Shell (bash)"
388 );
389 assert_eq!(test.syntax_for_file(".bashrc"), "Bourne Again Shell (bash)");
390 assert_eq!(test.syntax_for_file("Makefile"), "Makefile");
391 }
393 #[cfg(unix)]
394 #[test]
395 fn syntax_detection_invalid_utf8() {
396 use std::os::unix::ffi::OsStrExt;
398 let test = SyntaxDetectionTest::new();
400 assert_eq!(
401 test.syntax_for_file_os(OsStr::from_bytes(b"invalid_\xFEutf8_filename.rs")),
402 "Rust"
403 );
404 }
406 #[test]
407 fn syntax_detection_same_for_inputkinds() {
408 let mut test = SyntaxDetectionTest::new();
410 test.syntax_mapping
411 .insert("*.myext", MappingTarget::MapTo("C"))
412 .ok();
413 test.syntax_mapping
414 .insert("MY_FILE", MappingTarget::MapTo("Markdown"))
415 .ok();
417 assert!(test.syntax_is_same_for_inputkinds("Test.md", ""));
418 assert!(test.syntax_is_same_for_inputkinds("Test.txt", "#!/bin/bash"));
419 assert!(test.syntax_is_same_for_inputkinds(".bashrc", ""));
420 assert!(test.syntax_is_same_for_inputkinds("test.h", ""));
421 assert!(test.syntax_is_same_for_inputkinds("test.js", "#!/bin/bash"));
422 assert!(test.syntax_is_same_for_inputkinds("test.myext", ""));
423 assert!(test.syntax_is_same_for_inputkinds("MY_FILE", ""));
424 assert!(test.syntax_is_same_for_inputkinds("MY_FILE", "<?php"));
425 }
427 #[test]
428 fn syntax_detection_well_defined_mapping_for_duplicate_extensions() {
429 let test = SyntaxDetectionTest::new();
431 assert_eq!(test.syntax_for_file("test.h"), "C++");
432 assert_eq!(test.syntax_for_file("test.sass"), "Sass");
433 assert_eq!(test.syntax_for_file("test.js"), "JavaScript (Babel)");
434 }
436 #[test]
437 fn syntax_detection_first_line() {
438 let test = SyntaxDetectionTest::new();
440 assert_eq!(
441 test.syntax_for_file_with_content("my_script", "#!/bin/bash"),
442 "Bourne Again Shell (bash)"
443 );
444 assert_eq!(
445 test.syntax_for_file_with_content("build", "#!/bin/bash"),
446 "Bourne Again Shell (bash)"
447 );
448 assert_eq!(
449 test.syntax_for_file_with_content("my_script", "<?php"),
450 "PHP"
451 );
452 }
454 #[test]
455 fn syntax_detection_with_custom_mapping() {
456 let mut test = SyntaxDetectionTest::new();
458 assert_eq!(test.syntax_for_file("test.h"), "C++");
459 test.syntax_mapping
460 .insert("*.h", MappingTarget::MapTo("C"))
461 .ok();
462 assert_eq!(test.syntax_for_file("test.h"), "C");
463 }
465 #[test]
466 fn syntax_detection_is_case_sensitive() {
467 let mut test = SyntaxDetectionTest::new();
469 assert_ne!(test.syntax_for_file("README.MD"), "Markdown");
470 test.syntax_mapping
471 .insert("*.MD", MappingTarget::MapTo("Markdown"))
472 .ok();
473 assert_eq!(test.syntax_for_file("README.MD"), "Markdown");
474 }
476 #[test]
477 fn syntax_detection_stdin_filename() {
478 let test = SyntaxDetectionTest::new();
480 // from file extension
481 assert_eq!(test.syntax_for_stdin_with_content("test.cpp", b"a"), "C++");
482 // from first line (fallback)
483 assert_eq!(
484 test.syntax_for_stdin_with_content("my_script", b"#!/bin/bash"),
485 "Bourne Again Shell (bash)"
486 );
487 }
489 #[cfg(unix)]
490 #[test]
491 fn syntax_detection_for_symlinked_file() {
492 use std::os::unix::fs::symlink;
494 let test = SyntaxDetectionTest::new();
495 let file_path = test.temp_dir.path().join("my_ssh_config_filename");
496 {
497 File::create(&file_path).unwrap();
498 }
499 let file_path_symlink = test.temp_dir.path().join(".ssh").join("config");
501 std::fs::create_dir(test.temp_dir.path().join(".ssh"))
502 .expect("creation of directory succeeds");
503 symlink(&file_path, &file_path_symlink).expect("creation of symbolic link succeeds");
505 let input = Input::ordinary_file(file_path_symlink.as_os_str());
506 let dummy_stdin: &[u8] = &[];
507 let mut opened_input = input.open(dummy_stdin).unwrap();
509 assert_eq!(
510 test.assets
511 .get_syntax(None, &mut opened_input, &test.syntax_mapping)
512 .unwrap_or_else(|_| test.assets.syntax_set.find_syntax_plain_text())
513 .name,
514 "SSH Config"
515 );
516 }