on v0.21.0 help sign in
bat/src/syntax_mapping.rs
252 lines 7.7 kB history raw
1use std::path::Path;
3use crate::error::Result;
4use ignored_suffixes::IgnoredSuffixes;
6use globset::{Candidate, GlobBuilder, GlobMatcher};
8pub mod ignored_suffixes;
10#[derive(Debug, Clone, Copy, PartialEq)]
11#[non_exhaustive]
12pub enum MappingTarget<'a> {
13 /// For mapping a path to a specific syntax.
14 MapTo(&'a str),
16 /// For mapping a path (typically an extension-less file name) to an unknown
17 /// syntax. This typically means later using the contents of the first line
18 /// of the file to determine what syntax to use.
19 MapToUnknown,
21 /// For mapping a file extension (e.g. `*.conf`) to an unknown syntax. This
22 /// typically means later using the contents of the first line of the file
23 /// to determine what syntax to use. However, if a syntax handles a file
24 /// name that happens to have the given file extension (e.g. `resolv.conf`),
25 /// then that association will have higher precedence, and the mapping will
26 /// be ignored.
27 MapExtensionToUnknown,
30#[derive(Debug, Clone, Default)]
31pub struct SyntaxMapping<'a> {
32 mappings: Vec<(GlobMatcher, MappingTarget<'a>)>,
33 pub(crate) ignored_suffixes: IgnoredSuffixes<'a>,
36impl<'a> SyntaxMapping<'a> {
37 pub fn empty() -> SyntaxMapping<'a> {
38 Default::default()
39 }
41 pub fn builtin() -> SyntaxMapping<'a> {
42 let mut mapping = Self::empty();
43 mapping.insert("*.h", MappingTarget::MapTo("C++")).unwrap();
44 mapping
45 .insert(".clang-format", MappingTarget::MapTo("YAML"))
46 .unwrap();
47 mapping.insert("*.fs", MappingTarget::MapTo("F#")).unwrap();
48 mapping
49 .insert("build", MappingTarget::MapToUnknown)
50 .unwrap();
51 mapping
52 .insert("**/.ssh/config", MappingTarget::MapTo("SSH Config"))
53 .unwrap();
54 mapping
55 .insert(
56 "**/bat/config",
57 MappingTarget::MapTo("Bourne Again Shell (bash)"),
58 )
59 .unwrap();
60 mapping
61 .insert(
62 "/etc/profile",
63 MappingTarget::MapTo("Bourne Again Shell (bash)"),
64 )
65 .unwrap();
66 mapping
67 .insert("*.pac", MappingTarget::MapTo("JavaScript (Babel)"))
68 .unwrap();
70 // See #1008
71 mapping
72 .insert("rails", MappingTarget::MapToUnknown)
73 .unwrap();
75 // Nginx and Apache syntax files both want to style all ".conf" files
76 // see #1131 and #1137
77 mapping
78 .insert("*.conf", MappingTarget::MapExtensionToUnknown)
79 .unwrap();
81 for glob in &[
82 "/etc/nginx/**/*.conf",
83 "/etc/nginx/sites-*/**/*",
84 "nginx.conf",
85 "mime.types",
86 ] {
87 mapping.insert(glob, MappingTarget::MapTo("nginx")).unwrap();
88 }
90 for glob in &[
91 "/etc/apache2/**/*.conf",
92 "/etc/apache2/sites-*/**/*",
93 "httpd.conf",
94 ] {
95 mapping
96 .insert(glob, MappingTarget::MapTo("Apache Conf"))
97 .unwrap();
98 }
100 for glob in &[
101 "**/systemd/**/*.conf",
102 "**/systemd/**/*.example",
103 "*.automount",
104 "*.device",
105 "*.dnssd",
106 "*.link",
107 "*.mount",
108 "*.netdev",
109 "*.network",
110 "*.nspawn",
111 "*.path",
112 "*.service",
113 "*.scope",
114 "*.slice",
115 "*.socket",
116 "*.swap",
117 "*.target",
118 "*.timer",
119 ] {
120 mapping.insert(glob, MappingTarget::MapTo("INI")).unwrap();
121 }
123 // unix mail spool
124 for glob in &["/var/spool/mail/*", "/var/mail/*"] {
125 mapping.insert(glob, MappingTarget::MapTo("Email")).unwrap()
126 }
128 // pacman hooks
129 mapping
130 .insert("*.hook", MappingTarget::MapTo("INI"))
131 .unwrap();
133 // Global git config files rooted in `$XDG_CONFIG_HOME/git/` or `$HOME/.config/git/`
134 // See e.g. https://git-scm.com/docs/git-config#FILES
135 if let Some(xdg_config_home) =
136 std::env::var_os("XDG_CONFIG_HOME").filter(|val| !val.is_empty())
137 {
138 insert_git_config_global(&mut mapping, &xdg_config_home);
139 }
140 if let Some(default_config_home) = std::env::var_os("HOME")
141 .filter(|val| !val.is_empty())
142 .map(|home| Path::new(&home).join(".config"))
143 {
144 insert_git_config_global(&mut mapping, &default_config_home);
145 }
147 fn insert_git_config_global(mapping: &mut SyntaxMapping, config_home: impl AsRef<Path>) {
148 let git_config_path = config_home.as_ref().join("git");
150 mapping
151 .insert(
152 &git_config_path.join("config").to_string_lossy(),
153 MappingTarget::MapTo("Git Config"),
154 )
155 .ok();
157 mapping
158 .insert(
159 &git_config_path.join("ignore").to_string_lossy(),
160 MappingTarget::MapTo("Git Ignore"),
161 )
162 .ok();
164 mapping
165 .insert(
166 &git_config_path.join("attributes").to_string_lossy(),
167 MappingTarget::MapTo("Git Attributes"),
168 )
169 .ok();
170 }
172 mapping
173 }
175 pub fn insert(&mut self, from: &str, to: MappingTarget<'a>) -> Result<()> {
176 let glob = GlobBuilder::new(from)
177 .case_insensitive(false)
178 .literal_separator(true)
179 .build()?;
180 self.mappings.push((glob.compile_matcher(), to));
181 Ok(())
182 }
184 pub fn mappings(&self) -> &[(GlobMatcher, MappingTarget<'a>)] {
185 &self.mappings
186 }
188 pub(crate) fn get_syntax_for(&self, path: impl AsRef<Path>) -> Option<MappingTarget<'a>> {
189 let candidate = Candidate::new(&path);
190 let candidate_filename = path.as_ref().file_name().map(Candidate::new);
191 for (ref glob, ref syntax) in self.mappings.iter().rev() {
192 if glob.is_match_candidate(&candidate)
193 || candidate_filename
194 .as_ref()
195 .map_or(false, |filename| glob.is_match_candidate(filename))
196 {
197 return Some(*syntax);
198 }
199 }
200 None
201 }
203 pub fn insert_ignored_suffix(&mut self, suffix: &'a str) {
204 self.ignored_suffixes.add_suffix(suffix);
205 }
208#[test]
209fn basic() {
210 let mut map = SyntaxMapping::empty();
211 map.insert("/path/to/Cargo.lock", MappingTarget::MapTo("TOML"))
212 .ok();
213 map.insert("/path/to/.ignore", MappingTarget::MapTo("Git Ignore"))
214 .ok();
216 assert_eq!(
217 map.get_syntax_for("/path/to/Cargo.lock"),
218 Some(MappingTarget::MapTo("TOML"))
219 );
220 assert_eq!(map.get_syntax_for("/path/to/other.lock"), None);
222 assert_eq!(
223 map.get_syntax_for("/path/to/.ignore"),
224 Some(MappingTarget::MapTo("Git Ignore"))
225 );
228#[test]
229fn user_can_override_builtin_mappings() {
230 let mut map = SyntaxMapping::builtin();
232 assert_eq!(
233 map.get_syntax_for("/etc/profile"),
234 Some(MappingTarget::MapTo("Bourne Again Shell (bash)"))
235 );
236 map.insert("/etc/profile", MappingTarget::MapTo("My Syntax"))
237 .ok();
238 assert_eq!(
239 map.get_syntax_for("/etc/profile"),
240 Some(MappingTarget::MapTo("My Syntax"))
241 );
244#[test]
245fn builtin_mappings() {
246 let map = SyntaxMapping::builtin();
248 assert_eq!(
249 map.get_syntax_for("/path/to/build"),
250 Some(MappingTarget::MapToUnknown)
251 );