on 384ea38 help sign in
bat/src/syntax_mapping.rs
122 lines 3.3 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 // See #1008
46 mapping
47 .insert("rails", MappingTarget::MapToUnknown)
48 .unwrap();
50 mapping
51 }
53 pub fn insert(&mut self, from: &str, to: MappingTarget<'a>) -> Result<()> {
54 let glob = GlobBuilder::new(from)
55 .case_insensitive(false)
56 .literal_separator(true)
57 .build()?;
58 self.mappings.push((glob.compile_matcher(), to));
59 Ok(())
60 }
62 pub(crate) fn get_syntax_for(&self, path: impl AsRef<Path>) -> Option<MappingTarget<'a>> {
63 let candidate = Candidate::new(path.as_ref());
64 let canddidate_filename = path.as_ref().file_name().map(Candidate::new);
65 for (ref glob, ref syntax) in self.mappings.iter().rev() {
66 if glob.is_match_candidate(&candidate)
67 || canddidate_filename
68 .as_ref()
69 .map_or(false, |filename| glob.is_match_candidate(filename))
70 {
71 return Some(*syntax);
72 }
73 }
74 None
75 }
78#[test]
79fn basic() {
80 let mut map = SyntaxMapping::empty();
81 map.insert("/path/to/Cargo.lock", MappingTarget::MapTo("TOML"))
82 .ok();
83 map.insert("/path/to/.ignore", MappingTarget::MapTo("Git Ignore"))
84 .ok();
86 assert_eq!(
87 map.get_syntax_for("/path/to/Cargo.lock"),
88 Some(MappingTarget::MapTo("TOML"))
89 );
90 assert_eq!(map.get_syntax_for("/path/to/other.lock"), None);
92 assert_eq!(
93 map.get_syntax_for("/path/to/.ignore"),
94 Some(MappingTarget::MapTo("Git Ignore"))
95 );
98#[test]
99fn user_can_override_builtin_mappings() {
100 let mut map = SyntaxMapping::builtin();
102 assert_eq!(
103 map.get_syntax_for("/etc/profile"),
104 Some(MappingTarget::MapTo("Bourne Again Shell (bash)"))
105 );
106 map.insert("/etc/profile", MappingTarget::MapTo("My Syntax"))
107 .ok();
108 assert_eq!(
109 map.get_syntax_for("/etc/profile"),
110 Some(MappingTarget::MapTo("My Syntax"))
111 );
114#[test]
115fn builtin_mappings() {
116 let map = SyntaxMapping::builtin();
118 assert_eq!(
119 map.get_syntax_for("/path/to/build"),
120 Some(MappingTarget::MapToUnknown)
121 );