on 206bf5b help sign in
bat/src/syntax_mapping.rs
229 lines 6.8 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)]
11pub enum MappingTarget<'a> {
12 /// For mapping a path to a specific syntax.
13 MapTo(&'a str),
15 /// For mapping a path (typically an extension-less file name) to an unknown
16 /// syntax. This typically means later using the contents of the first line
17 /// of the file to determine what syntax to use.
18 MapToUnknown,
20 /// For mapping a file extension (e.g. `*.conf`) to an unknown syntax. This
21 /// typically means later using the contents of the first line of the file
22 /// to determine what syntax to use. However, if a syntax handles a file
23 /// name that happens to have the given file extension (e.g. `resolv.conf`),
24 /// then that association will have higher precedence, and the mapping will
25 /// be ignored.
26 MapExtensionToUnknown,
29#[derive(Debug, Clone, Default)]
30pub struct SyntaxMapping<'a> {
31 mappings: Vec<(GlobMatcher, MappingTarget<'a>)>,
32 pub(crate) ignored_suffixes: IgnoredSuffixes<'a>,
35impl<'a> SyntaxMapping<'a> {
36 pub fn empty() -> SyntaxMapping<'a> {
37 Default::default()
38 }
40 pub fn builtin() -> SyntaxMapping<'a> {
41 let mut mapping = Self::empty();
42 mapping.insert("*.h", MappingTarget::MapTo("C++")).unwrap();
43 mapping.insert("*.fs", MappingTarget::MapTo("F#")).unwrap();
44 mapping
45 .insert("build", MappingTarget::MapToUnknown)
46 .unwrap();
47 mapping
48 .insert("**/.ssh/config", MappingTarget::MapTo("SSH Config"))
49 .unwrap();
50 mapping
51 .insert(
52 "**/bat/config",
53 MappingTarget::MapTo("Bourne Again Shell (bash)"),
54 )
55 .unwrap();
56 mapping
57 .insert(
58 "/etc/profile",
59 MappingTarget::MapTo("Bourne Again Shell (bash)"),
60 )
61 .unwrap();
62 mapping
63 .insert("*.pac", MappingTarget::MapTo("JavaScript (Babel)"))
64 .unwrap();
66 // See #1008
67 mapping
68 .insert("rails", MappingTarget::MapToUnknown)
69 .unwrap();
71 // Nginx and Apache syntax files both want to style all ".conf" files
72 // see #1131 and #1137
73 mapping
74 .insert("*.conf", MappingTarget::MapExtensionToUnknown)
75 .unwrap();
77 for glob in &[
78 "/etc/nginx/**/*.conf",
79 "/etc/nginx/sites-*/**/*",
80 "nginx.conf",
81 "mime.types",
82 ] {
83 mapping.insert(glob, MappingTarget::MapTo("nginx")).unwrap();
84 }
86 for glob in &[
87 "/etc/apache2/**/*.conf",
88 "/etc/apache2/sites-*/**/*",
89 "httpd.conf",
90 ] {
91 mapping
92 .insert(glob, MappingTarget::MapTo("Apache Conf"))
93 .unwrap();
94 }
96 for glob in &[
97 "**/systemd/**/*.conf",
98 "**/systemd/**/*.example",
99 "*.automount",
100 "*.device",
101 "*.dnssd",
102 "*.link",
103 "*.mount",
104 "*.netdev",
105 "*.network",
106 "*.nspawn",
107 "*.path",
108 "*.service",
109 "*.scope",
110 "*.slice",
111 "*.socket",
112 "*.swap",
113 "*.target",
114 "*.timer",
115 ] {
116 mapping.insert(glob, MappingTarget::MapTo("INI")).unwrap();
117 }
119 // pacman hooks
120 mapping
121 .insert("*.hook", MappingTarget::MapTo("INI"))
122 .unwrap();
124 if let Some(xdg_config_home) = std::env::var_os("XDG_CONFIG_HOME") {
125 let git_config_path = Path::new(&xdg_config_home).join("git");
127 mapping
128 .insert(
129 &git_config_path.join("config").to_string_lossy(),
130 MappingTarget::MapTo("Git Config"),
131 )
132 .ok();
134 mapping
135 .insert(
136 &git_config_path.join("ignore").to_string_lossy(),
137 MappingTarget::MapTo("Git Ignore"),
138 )
139 .ok();
141 mapping
142 .insert(
143 &git_config_path.join("attributes").to_string_lossy(),
144 MappingTarget::MapTo("Git Attributes"),
145 )
146 .ok();
147 }
149 mapping
150 }
152 pub fn insert(&mut self, from: &str, to: MappingTarget<'a>) -> Result<()> {
153 let glob = GlobBuilder::new(from)
154 .case_insensitive(false)
155 .literal_separator(true)
156 .build()?;
157 self.mappings.push((glob.compile_matcher(), to));
158 Ok(())
159 }
161 pub fn mappings(&self) -> &[(GlobMatcher, MappingTarget<'a>)] {
162 &self.mappings
163 }
165 pub(crate) fn get_syntax_for(&self, path: impl AsRef<Path>) -> Option<MappingTarget<'a>> {
166 let candidate = Candidate::new(&path);
167 let candidate_filename = path.as_ref().file_name().map(Candidate::new);
168 for (ref glob, ref syntax) in self.mappings.iter().rev() {
169 if glob.is_match_candidate(&candidate)
170 || candidate_filename
171 .as_ref()
172 .map_or(false, |filename| glob.is_match_candidate(filename))
173 {
174 return Some(*syntax);
175 }
176 }
177 None
178 }
180 pub fn insert_ignored_suffix(&mut self, suffix: &'a str) {
181 self.ignored_suffixes.add_suffix(suffix);
182 }
185#[test]
186fn basic() {
187 let mut map = SyntaxMapping::empty();
188 map.insert("/path/to/Cargo.lock", MappingTarget::MapTo("TOML"))
189 .ok();
190 map.insert("/path/to/.ignore", MappingTarget::MapTo("Git Ignore"))
191 .ok();
193 assert_eq!(
194 map.get_syntax_for("/path/to/Cargo.lock"),
195 Some(MappingTarget::MapTo("TOML"))
196 );
197 assert_eq!(map.get_syntax_for("/path/to/other.lock"), None);
199 assert_eq!(
200 map.get_syntax_for("/path/to/.ignore"),
201 Some(MappingTarget::MapTo("Git Ignore"))
202 );
205#[test]
206fn user_can_override_builtin_mappings() {
207 let mut map = SyntaxMapping::builtin();
209 assert_eq!(
210 map.get_syntax_for("/etc/profile"),
211 Some(MappingTarget::MapTo("Bourne Again Shell (bash)"))
212 );
213 map.insert("/etc/profile", MappingTarget::MapTo("My Syntax"))
214 .ok();
215 assert_eq!(
216 map.get_syntax_for("/etc/profile"),
217 Some(MappingTarget::MapTo("My Syntax"))
218 );
221#[test]
222fn builtin_mappings() {
223 let map = SyntaxMapping::builtin();
225 assert_eq!(
226 map.get_syntax_for("/path/to/build"),
227 Some(MappingTarget::MapToUnknown)
228 );