1
0
mirror of https://github.com/sharkdp/bat.git synced 2025-09-03 03:42:26 +01:00

Initial implementation of glob-based syntax mapping

This commit is contained in:
sharkdp
2020-03-22 09:55:13 +01:00
committed by David Peter
parent ba29e07636
commit bd8a13dbc9
7 changed files with 137 additions and 42 deletions

View File

@@ -1,35 +1,85 @@
use std::borrow::Cow;
use std::collections::HashMap;
use std::path::Path;
use crate::errors::Result;
use globset::{Candidate, GlobBuilder, GlobMatcher};
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum MappingTarget<'a> {
MapTo(&'a str),
MapToUnknown,
}
#[derive(Debug, Clone, Default)]
pub struct SyntaxMapping(HashMap<String, String>);
pub struct SyntaxMapping<'a> {
mappings: Vec<(GlobMatcher, MappingTarget<'a>)>,
}
impl SyntaxMapping {
pub fn new() -> SyntaxMapping {
impl<'a> SyntaxMapping<'a> {
pub fn empty() -> SyntaxMapping<'a> {
Default::default()
}
pub fn insert(&mut self, from: impl Into<String>, to: impl Into<String>) -> Option<String> {
self.0.insert(from.into(), to.into())
pub fn builtin() -> SyntaxMapping<'a> {
let mut mapping = Self::empty();
mapping
.insert("build", MappingTarget::MapToUnknown)
.unwrap();
mapping
}
pub(crate) fn replace<'a>(&self, input: impl Into<Cow<'a, str>>) -> Cow<'a, str> {
let input = input.into();
match self.0.get(input.as_ref()) {
Some(s) => Cow::from(s.clone()),
None => input,
pub fn insert(&mut self, from: &str, to: MappingTarget<'a>) -> Result<()> {
let glob = GlobBuilder::new(from)
.case_insensitive(false)
.literal_separator(true)
.build()?;
self.mappings.push((glob.compile_matcher(), to));
Ok(())
}
pub(crate) fn get_syntax_for(&self, path: impl AsRef<Path>) -> Option<MappingTarget<'a>> {
let candidate = Candidate::new(path.as_ref());
let canddidate_filename = path.as_ref().file_name().map(Candidate::new);
for (ref glob, ref syntax) in &self.mappings {
if glob.is_match_candidate(&candidate)
|| canddidate_filename
.as_ref()
.map_or(false, |filename| glob.is_match_candidate(filename))
{
return Some(*syntax);
}
}
None
}
}
#[test]
fn basic() {
let mut map = SyntaxMapping::new();
map.insert("Cargo.lock", "toml");
map.insert(".ignore", ".gitignore");
let mut map = SyntaxMapping::empty();
map.insert("/path/to/Cargo.lock", MappingTarget::MapTo("TOML"))
.ok();
map.insert("/path/to/.ignore", MappingTarget::MapTo("Git Ignore"))
.ok();
assert_eq!("toml", map.replace("Cargo.lock"));
assert_eq!("other.lock", map.replace("other.lock"));
assert_eq!(
map.get_syntax_for("/path/to/Cargo.lock"),
Some(MappingTarget::MapTo("TOML"))
);
assert_eq!(map.get_syntax_for("/path/to/other.lock"), None);
assert_eq!(".gitignore", map.replace(".ignore"));
assert_eq!(
map.get_syntax_for("/path/to/.ignore"),
Some(MappingTarget::MapTo("Git Ignore"))
);
}
#[test]
fn builtin_mappings() {
let map = SyntaxMapping::builtin();
assert_eq!(
map.get_syntax_for("/path/to/build"),
Some(MappingTarget::MapToUnknown)
);
}