templater: add helper method that unwraps Option<T> property

I'll add a few more optional property types, and I don't want to duplicate the
error message. Type names are capitalized for consistency.
This commit is contained in:
Yuya Nishihara 2024-05-02 13:31:20 +09:00
parent 04063a0efd
commit c2c160f635
4 changed files with 16 additions and 9 deletions

View file

@ -38,7 +38,7 @@ use crate::template_builder::{
use crate::template_parser::{self, FunctionCallNode, TemplateParseError, TemplateParseResult};
use crate::templater::{
self, PlainTextFormattedProperty, Template, TemplateFormatter, TemplateProperty,
TemplatePropertyError, TemplatePropertyExt as _,
TemplatePropertyExt as _,
};
use crate::{revset_util, text_util};
@ -130,9 +130,7 @@ impl<'repo> TemplateLanguage<'repo> for CommitTemplateLanguage<'repo> {
let type_name = "Commit";
let table = &self.build_fn_table.commit_methods;
let build = template_parser::lookup_method(type_name, table, function)?;
let inner_property = property.and_then(|opt| {
opt.ok_or_else(|| TemplatePropertyError("No commit available".into()))
});
let inner_property = property.try_unwrap(type_name);
build(self, build_ctx, Box::new(inner_property), function)
}
CommitTemplatePropertyKind::CommitList(property) => {
@ -154,9 +152,7 @@ impl<'repo> TemplateLanguage<'repo> for CommitTemplateLanguage<'repo> {
let type_name = "RefName";
let table = &self.build_fn_table.ref_name_methods;
let build = template_parser::lookup_method(type_name, table, function)?;
let inner_property = property.and_then(|opt| {
opt.ok_or_else(|| TemplatePropertyError("No RefName available".into()))
});
let inner_property = property.try_unwrap(type_name);
build(self, build_ctx, Box::new(inner_property), function)
}
CommitTemplatePropertyKind::RefNameList(property) => {

View file

@ -349,6 +349,17 @@ pub trait TemplatePropertyExt: TemplateProperty {
TemplateFunction::new(self, move |value| Ok(function(value)))
}
/// Translates to a property that will unwrap an extracted `Option` value
/// of the specified `type_name`, mapping `None` to `Err`.
fn try_unwrap<O>(self, type_name: &str) -> impl TemplateProperty<Output = O>
where
Self: TemplateProperty<Output = Option<O>> + Sized,
{
self.and_then(move |opt| {
opt.ok_or_else(|| TemplatePropertyError(format!("No {type_name} available").into()))
})
}
/// Converts this property into `Template`.
fn into_template<'a>(self) -> Box<dyn Template + 'a>
where

View file

@ -473,7 +473,7 @@ fn test_color_ui_messages() {
);
insta::assert_snapshot!(stdout, @r###"
167f90e7600a50f85c4f909b53eaf546faa82879
<Error: No commit available> (elided revisions)
<Error: No Commit available> (elided revisions)
0000000000000000000000000000000000000000
"###);

View file

@ -100,7 +100,7 @@ fn test_tag_list() {
[conflicted_tag]
present: true
conflict: true
normal_target: <Error: No commit available>
normal_target: <Error: No Commit available>
removed_targets: commit1
added_targets: commit2 commit3
[test_tag]