on v0.20.0 help sign in
bat/src/syntax_mapping.rs
244 lines 7.5 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.insert("*.fs", MappingTarget::MapTo("F#")).unwrap();
45 mapping
46 .insert("build", MappingTarget::MapToUnknown)
47 .unwrap();
48 mapping
49 .insert("**/.ssh/config", MappingTarget::MapTo("SSH Config"))
50 .unwrap();
51 mapping
52 .insert(
53 "**/bat/config",
54 MappingTarget::MapTo("Bourne Again Shell (bash)"),
55 )
56 .unwrap();
57 mapping
58 .insert(
59 "/etc/profile",
60 MappingTarget::MapTo("Bourne Again Shell (bash)"),
61 )
62 .unwrap();
63 mapping
64 .insert("*.pac", MappingTarget::MapTo("JavaScript (Babel)"))
65 .unwrap();
67 // See #1008
68 mapping
69 .insert("rails", MappingTarget::MapToUnknown)
70 .unwrap();
72 // Nginx and Apache syntax files both want to style all ".conf" files
73 // see #1131 and #1137
74 mapping
75 .insert("*.conf", MappingTarget::MapExtensionToUnknown)
76 .unwrap();
78 for glob in &[
79 "/etc/nginx/**/*.conf",
80 "/etc/nginx/sites-*/**/*",
81 "nginx.conf",
82 "mime.types",
83 ] {
84 mapping.insert(glob, MappingTarget::MapTo("nginx")).unwrap();
85 }
87 for glob in &[
88 "/etc/apache2/**/*.conf",
89 "/etc/apache2/sites-*/**/*",
90 "httpd.conf",
91 ] {
92 mapping
93 .insert(glob, MappingTarget::MapTo("Apache Conf"))
94 .unwrap();
95 }
97 for glob in &[
98 "**/systemd/**/*.conf",
99 "**/systemd/**/*.example",
100 "*.automount",
101 "*.device",
102 "*.dnssd",
103 "*.link",
104 "*.mount",
105 "*.netdev",
106 "*.network",
107 "*.nspawn",
108 "*.path",
109 "*.service",
110 "*.scope",
111 "*.slice",
112 "*.socket",
113 "*.swap",
114 "*.target",
115 "*.timer",
116 ] {
117 mapping.insert(glob, MappingTarget::MapTo("INI")).unwrap();
118 }
120 // pacman hooks
121 mapping
122 .insert("*.hook", MappingTarget::MapTo("INI"))
123 .unwrap();
125 // Global git config files rooted in `$XDG_CONFIG_HOME/git/` or `$HOME/.config/git/`
126 // See e.g. https://git-scm.com/docs/git-config#FILES
127 if let Some(xdg_config_home) =
128 std::env::var_os("XDG_CONFIG_HOME").filter(|val| !val.is_empty())
129 {
130 insert_git_config_global(&mut mapping, &xdg_config_home);
131 }
132 if let Some(default_config_home) = std::env::var_os("HOME")
133 .filter(|val| !val.is_empty())
134 .map(|home| Path::new(&home).join(".config"))
135 {
136 insert_git_config_global(&mut mapping, &default_config_home);
137 }
139 fn insert_git_config_global(mapping: &mut SyntaxMapping, config_home: impl AsRef<Path>) {
140 let git_config_path = config_home.as_ref().join("git");
142 mapping
143 .insert(
144 &git_config_path.join("config").to_string_lossy(),
145 MappingTarget::MapTo("Git Config"),
146 )
147 .ok();
149 mapping
150 .insert(
151 &git_config_path.join("ignore").to_string_lossy(),
152 MappingTarget::MapTo("Git Ignore"),
153 )
154 .ok();
156 mapping
157 .insert(
158 &git_config_path.join("attributes").to_string_lossy(),
159 MappingTarget::MapTo("Git Attributes"),
160 )
161 .ok();
162 }
164 mapping
165 }
167 pub fn insert(&mut self, from: &str, to: MappingTarget<'a>) -> Result<()> {
168 let glob = GlobBuilder::new(from)
169 .case_insensitive(false)
170 .literal_separator(true)
171 .build()?;
172 self.mappings.push((glob.compile_matcher(), to));
173 Ok(())
174 }
176 pub fn mappings(&self) -> &[(GlobMatcher, MappingTarget<'a>)] {
177 &self.mappings
178 }
180 pub(crate) fn get_syntax_for(&self, path: impl AsRef<Path>) -> Option<MappingTarget<'a>> {
181 let candidate = Candidate::new(&path);
182 let candidate_filename = path.as_ref().file_name().map(Candidate::new);
183 for (ref glob, ref syntax) in self.mappings.iter().rev() {
184 if glob.is_match_candidate(&candidate)
185 || candidate_filename
186 .as_ref()
187 .map_or(false, |filename| glob.is_match_candidate(filename))
188 {
189 return Some(*syntax);
190 }
191 }
192 None
193 }
195 pub fn insert_ignored_suffix(&mut self, suffix: &'a str) {
196 self.ignored_suffixes.add_suffix(suffix);
197 }
200#[test]
201fn basic() {
202 let mut map = SyntaxMapping::empty();
203 map.insert("/path/to/Cargo.lock", MappingTarget::MapTo("TOML"))
204 .ok();
205 map.insert("/path/to/.ignore", MappingTarget::MapTo("Git Ignore"))
206 .ok();
208 assert_eq!(
209 map.get_syntax_for("/path/to/Cargo.lock"),
210 Some(MappingTarget::MapTo("TOML"))
211 );
212 assert_eq!(map.get_syntax_for("/path/to/other.lock"), None);
214 assert_eq!(
215 map.get_syntax_for("/path/to/.ignore"),
216 Some(MappingTarget::MapTo("Git Ignore"))
217 );
220#[test]
221fn user_can_override_builtin_mappings() {
222 let mut map = SyntaxMapping::builtin();
224 assert_eq!(
225 map.get_syntax_for("/etc/profile"),
226 Some(MappingTarget::MapTo("Bourne Again Shell (bash)"))
227 );
228 map.insert("/etc/profile", MappingTarget::MapTo("My Syntax"))
229 .ok();
230 assert_eq!(
231 map.get_syntax_for("/etc/profile"),
232 Some(MappingTarget::MapTo("My Syntax"))
233 );
236#[test]
237fn builtin_mappings() {
238 let map = SyntaxMapping::builtin();
240 assert_eq!(
241 map.get_syntax_for("/path/to/build"),
242 Some(MappingTarget::MapToUnknown)
243 );