Simplify HighlightingAssets::get_syntax() first_line logic (#1852)

And make self.get_first_line_syntax() be called lazily.
This commit is contained in:
Martin Nordholts 2021-09-16 17:01:12 +02:00 committed by GitHub
parent e84b702309
commit 9ed9a6fc3d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 31 additions and 8 deletions

View File

@ -198,8 +198,6 @@ impl HighlightingAssets {
.ok_or_else(|| Error::UnknownSyntax(language.to_owned()));
}
let line_syntax = self.get_first_line_syntax(&mut input.reader)?;
// Get the path of the file:
// If this was set by the metadata, that will take priority.
// If it wasn't, it will use the real file path (if available).
@ -212,7 +210,7 @@ impl HighlightingAssets {
_ => None,
});
if let Some(path_str) = path_str {
let path_syntax = if let Some(path_str) = path_str {
// If a path was provided, we try and detect the syntax based on extension mappings.
let path = Path::new(path_str);
let absolute_path = PathAbs::new(path)
@ -221,8 +219,9 @@ impl HighlightingAssets {
.unwrap_or_else(|| path.to_owned());
match mapping.get_syntax_for(absolute_path) {
Some(MappingTarget::MapToUnknown) => line_syntax
.ok_or_else(|| Error::UndetectedSyntax(path.to_string_lossy().into())),
Some(MappingTarget::MapToUnknown) => {
Err(Error::UndetectedSyntax(path.to_string_lossy().into()))
}
Some(MappingTarget::MapTo(syntax_name)) => self
.find_syntax_by_name(syntax_name)?
@ -231,13 +230,20 @@ impl HighlightingAssets {
None => {
let file_name = path.file_name().unwrap_or_default();
self.get_extension_syntax(file_name)?
.or(line_syntax)
.ok_or_else(|| Error::UndetectedSyntax(path.to_string_lossy().into()))
}
}
} else {
// If a path wasn't provided, we fall back to the detect first-line syntax.
line_syntax.ok_or_else(|| Error::UndetectedSyntax("[unknown]".into()))
Err(Error::UndetectedSyntax("[unknown]".into()))
};
match path_syntax {
// If a path wasn't provided, or if path based syntax detection
// above failed, we fall back to first-line syntax detection.
Err(Error::UndetectedSyntax(path)) => self
.get_first_line_syntax(&mut input.reader)?
.ok_or(Error::UndetectedSyntax(path)),
_ => path_syntax,
}
}

View File

@ -0,0 +1,2 @@
#!/usr/bin/env bash
echo "Hello"

View File

@ -1127,6 +1127,21 @@ fn do_not_detect_different_syntax_for_stdin_and_files() {
);
}
#[test]
fn no_first_line_fallback_when_mapping_to_invalid_syntax() {
let file = "regression_tests/first_line_fallback.invalid-syntax";
bat()
.arg("--color=always")
.arg("--map-syntax=*.invalid-syntax:InvalidSyntax")
.arg(&format!("--file-name={}", file))
.arg("--style=plain")
.arg(file)
.assert()
.failure()
.stderr(predicate::str::contains("unknown syntax: 'InvalidSyntax'"));
}
#[test]
fn show_all_mode() {
bat()