Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HighlightingAssets: Extract new public API method get_syntax_for_path() #1862

Merged
merged 3 commits into from
Sep 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@

## `bat` as a library

- Deprecate `HighlightingAssets::syntaxes()` and `HighlightingAssets::syntax_for_file_name()`. Use `HighlightingAssets::get_syntaxes()` and `HighlightingAssets::get_syntax_for_file_name()` instead. They return a `Result` which is needed for upcoming lazy-loading work to improve startup performance. They also return what `SyntaxSet` the returned `SyntaxReference` belongs to. See #1747, #1755 and #1776 (@Enselic)
- Deprecate `HighlightingAssets::syntaxes()` and `HighlightingAssets::syntax_for_file_name()`. Use `HighlightingAssets::get_syntaxes()` and `HighlightingAssets::get_syntax_for_path()` instead. They return a `Result` which is needed for upcoming lazy-loading work to improve startup performance. They also return which `SyntaxSet` the returned `SyntaxReference` belongs to. See #1747, #1755, #1776, #1862 (@Enselic)
- Remove `HighlightingAssets::from_files` and `HighlightingAssets::save_to_cache`. Instead of calling the former and then the latter you now make a single call to `bat::assets::build`. See #1802 (@Enselic)
- Replace the `error::Error(error::ErrorKind, _)` struct and enum with an `error::Error` enum. `Error(ErrorKind::UnknownSyntax, _)` becomes `Error::UnknownSyntax`, etc. Also remove the `error::ResultExt` trait. These changes stem from replacing `error-chain` with `thiserror`. See #1820 (@Enselic)

Expand Down
75 changes: 44 additions & 31 deletions src/assets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,31 +140,58 @@ impl HighlightingAssets {
}
}

/// Use [Self::get_syntax_for_file_name] instead
/// Use [Self::get_syntax_for_path] instead
#[deprecated]
pub fn syntax_for_file_name(
&self,
file_name: impl AsRef<Path>,
mapping: &SyntaxMapping,
) -> Option<&SyntaxReference> {
self.get_syntax_for_file_name(file_name, mapping)
.expect(
".syntax_for_file_name() is deprecated, use .get_syntax_for_file_name() instead",
)
self.get_syntax_for_path(file_name, mapping)
.ok()
.map(|syntax_in_set| syntax_in_set.syntax)
}

pub fn get_syntax_for_file_name(
/// Detect the syntax based on, in order:
keith-hall marked this conversation as resolved.
Show resolved Hide resolved
/// 1. Syntax mappings (e.g. `/etc/profile` -> `Bourne Again Shell (bash)`)
/// 2. The file name (e.g. `Dockerfile`)
/// 3. The file name extension (e.g. `.rs`)
///
/// When detecting syntax based on syntax mappings, the full path is taken
/// into account. When detecting syntax based on file name, no regard is
/// taken to the path of the file. Only the file name itself matters. When
/// detecting syntax based on file name extension, only the file name
/// extension itself matters.
///
/// Returns [Error::UndetectedSyntax] if it was not possible detect syntax
/// based on path/file name/extension (or if the path was mapped to
/// [MappingTarget::MapToUnknown]). In this case it is appropriate to fall
/// back to other methods to detect syntax. Such as using the contents of
/// the first line of the file.
///
/// Returns [Error::UnknownSyntax] if a syntax mapping exist, but the mapped
/// syntax does not exist.
pub fn get_syntax_for_path(
&self,
file_name: impl AsRef<Path>,
path: impl AsRef<Path>,
mapping: &SyntaxMapping,
) -> Result<Option<SyntaxReferenceInSet>> {
let file_name = file_name.as_ref();
Ok(match mapping.get_syntax_for(file_name) {
Some(MappingTarget::MapToUnknown) => None,
Some(MappingTarget::MapTo(syntax_name)) => self.find_syntax_by_name(syntax_name)?,
None => self.get_extension_syntax(file_name.as_os_str())?,
})
) -> Result<SyntaxReferenceInSet> {
let path = path.as_ref();
match mapping.get_syntax_for(path) {
Some(MappingTarget::MapToUnknown) => {
Err(Error::UndetectedSyntax(path.to_string_lossy().into()))
}

Some(MappingTarget::MapTo(syntax_name)) => self
.find_syntax_by_name(syntax_name)?
.ok_or_else(|| Error::UnknownSyntax(syntax_name.to_owned())),

None => {
let file_name = path.file_name().unwrap_or_default();
self.get_extension_syntax(file_name)?
.ok_or_else(|| Error::UndetectedSyntax(path.to_string_lossy().into()))
}
}
}

pub(crate) fn get_theme(&self, theme: &str) -> &Theme {
Expand Down Expand Up @@ -211,24 +238,10 @@ impl HighlightingAssets {
});

let path_syntax = if let Some(path) = path {
// If a path was provided, we try and detect the syntax based on extension mappings.
match mapping.get_syntax_for(
self.get_syntax_for_path(
PathAbs::new(path).map_or_else(|_| path.to_owned(), |p| p.as_path().to_path_buf()),
) {
Some(MappingTarget::MapToUnknown) => {
Err(Error::UndetectedSyntax(path.to_string_lossy().into()))
}

Some(MappingTarget::MapTo(syntax_name)) => self
.find_syntax_by_name(syntax_name)?
.ok_or_else(|| Error::UnknownSyntax(syntax_name.to_owned())),

None => {
let file_name = path.file_name().unwrap_or_default();
self.get_extension_syntax(file_name)?
.ok_or_else(|| Error::UndetectedSyntax(path.to_string_lossy().into()))
}
}
mapping,
)
} else {
Err(Error::UndetectedSyntax("[unknown]".into()))
};
Expand Down
6 changes: 2 additions & 4 deletions src/bin/bat/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,10 +104,8 @@ pub fn get_languages(config: &Config) -> Result<String> {
}

let test_file = Path::new("test").with_extension(extension);
let syntax_in_set = assets
.get_syntax_for_file_name(test_file, &config.syntax_mapping)
.unwrap(); // safe since .get_syntaxes() above worked
matches!(syntax_in_set, Some(syntax_in_set) if syntax_in_set.syntax.name == lang_name)
let syntax_in_set = assets.get_syntax_for_path(test_file, &config.syntax_mapping);
matches!(syntax_in_set, Ok(syntax_in_set) if syntax_in_set.syntax.name == lang_name)
});
}

Expand Down