on v0.14.0 help sign in
bat/src/syntax_mapping.rs
114 lines 3.2 kB history raw
1use std::path::Path;
3use crate::error::Result;
5use globset::{Candidate, GlobBuilder, GlobMatcher};
7#[derive(Debug, Clone, Copy, PartialEq)]
8pub enum MappingTarget<'a> {
9 MapTo(&'a str),
10 MapToUnknown,
13#[derive(Debug, Clone, Default)]
14pub struct SyntaxMapping<'a> {
15 mappings: Vec<(GlobMatcher, MappingTarget<'a>)>,
18impl<'a> SyntaxMapping<'a> {
19 pub fn empty() -> SyntaxMapping<'a> {
20 Default::default()
21 }
23 pub fn builtin() -> SyntaxMapping<'a> {
24 let mut mapping = Self::empty();
25 mapping.insert("*.h", MappingTarget::MapTo("C++")).unwrap();
26 mapping
27 .insert("build", MappingTarget::MapToUnknown)
28 .unwrap();
29 mapping
30 .insert("**/.ssh/config", MappingTarget::MapTo("SSH Config"))
31 .unwrap();
32 mapping
33 .insert("**/bat/config", MappingTarget::MapTo("Bourne Again Shell (bash)"))
34 .unwrap();
35 mapping
36 .insert(
37 "/etc/profile",
38 MappingTarget::MapTo("Bourne Again Shell (bash)"),
39 )
40 .unwrap();
42 mapping
43 }
45 pub fn insert(&mut self, from: &str, to: MappingTarget<'a>) -> Result<()> {
46 let glob = GlobBuilder::new(from)
47 .case_insensitive(false)
48 .literal_separator(true)
49 .build()?;
50 self.mappings.push((glob.compile_matcher(), to));
51 Ok(())
52 }
54 pub(crate) fn get_syntax_for(&self, path: impl AsRef<Path>) -> Option<MappingTarget<'a>> {
55 let candidate = Candidate::new(path.as_ref());
56 let canddidate_filename = path.as_ref().file_name().map(Candidate::new);
57 for (ref glob, ref syntax) in self.mappings.iter().rev() {
58 if glob.is_match_candidate(&candidate)
59 || canddidate_filename
60 .as_ref()
61 .map_or(false, |filename| glob.is_match_candidate(filename))
62 {
63 return Some(*syntax);
64 }
65 }
66 None
67 }
70#[test]
71fn basic() {
72 let mut map = SyntaxMapping::empty();
73 map.insert("/path/to/Cargo.lock", MappingTarget::MapTo("TOML"))
74 .ok();
75 map.insert("/path/to/.ignore", MappingTarget::MapTo("Git Ignore"))
76 .ok();
78 assert_eq!(
79 map.get_syntax_for("/path/to/Cargo.lock"),
80 Some(MappingTarget::MapTo("TOML"))
81 );
82 assert_eq!(map.get_syntax_for("/path/to/other.lock"), None);
84 assert_eq!(
85 map.get_syntax_for("/path/to/.ignore"),
86 Some(MappingTarget::MapTo("Git Ignore"))
87 );
90#[test]
91fn user_can_override_builtin_mappings() {
92 let mut map = SyntaxMapping::builtin();
94 assert_eq!(
95 map.get_syntax_for("/etc/profile"),
96 Some(MappingTarget::MapTo("Bourne Again Shell (bash)"))
97 );
98 map.insert("/etc/profile", MappingTarget::MapTo("My Syntax"))
99 .ok();
100 assert_eq!(
101 map.get_syntax_for("/etc/profile"),
102 Some(MappingTarget::MapTo("My Syntax"))
103 );
106#[test]
107fn builtin_mappings() {
108 let map = SyntaxMapping::builtin();
110 assert_eq!(
111 map.get_syntax_for("/path/to/build"),
112 Some(MappingTarget::MapToUnknown)
113 );