on v0.15.0 help sign in
bat/src/syntax_mapping.rs
117 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(
34 "**/bat/config",
35 MappingTarget::MapTo("Bourne Again Shell (bash)"),
36 )
37 .unwrap();
38 mapping
39 .insert(
40 "/etc/profile",
41 MappingTarget::MapTo("Bourne Again Shell (bash)"),
42 )
43 .unwrap();
45 mapping
46 }
48 pub fn insert(&mut self, from: &str, to: MappingTarget<'a>) -> Result<()> {
49 let glob = GlobBuilder::new(from)
50 .case_insensitive(false)
51 .literal_separator(true)
52 .build()?;
53 self.mappings.push((glob.compile_matcher(), to));
54 Ok(())
55 }
57 pub(crate) fn get_syntax_for(&self, path: impl AsRef<Path>) -> Option<MappingTarget<'a>> {
58 let candidate = Candidate::new(path.as_ref());
59 let canddidate_filename = path.as_ref().file_name().map(Candidate::new);
60 for (ref glob, ref syntax) in self.mappings.iter().rev() {
61 if glob.is_match_candidate(&candidate)
62 || canddidate_filename
63 .as_ref()
64 .map_or(false, |filename| glob.is_match_candidate(filename))
65 {
66 return Some(*syntax);
67 }
68 }
69 None
70 }
73#[test]
74fn basic() {
75 let mut map = SyntaxMapping::empty();
76 map.insert("/path/to/Cargo.lock", MappingTarget::MapTo("TOML"))
77 .ok();
78 map.insert("/path/to/.ignore", MappingTarget::MapTo("Git Ignore"))
79 .ok();
81 assert_eq!(
82 map.get_syntax_for("/path/to/Cargo.lock"),
83 Some(MappingTarget::MapTo("TOML"))
84 );
85 assert_eq!(map.get_syntax_for("/path/to/other.lock"), None);
87 assert_eq!(
88 map.get_syntax_for("/path/to/.ignore"),
89 Some(MappingTarget::MapTo("Git Ignore"))
90 );
93#[test]
94fn user_can_override_builtin_mappings() {
95 let mut map = SyntaxMapping::builtin();
97 assert_eq!(
98 map.get_syntax_for("/etc/profile"),
99 Some(MappingTarget::MapTo("Bourne Again Shell (bash)"))
100 );
101 map.insert("/etc/profile", MappingTarget::MapTo("My Syntax"))
102 .ok();
103 assert_eq!(
104 map.get_syntax_for("/etc/profile"),
105 Some(MappingTarget::MapTo("My Syntax"))
106 );
109#[test]
110fn builtin_mappings() {
111 let map = SyntaxMapping::builtin();
113 assert_eq!(
114 map.get_syntax_for("/path/to/build"),
115 Some(MappingTarget::MapToUnknown)
116 );