Files
tools/graph/src/language.rs
T

65 lines
2.2 KiB
Rust
Raw Normal View History

2026-08-12 14:11:47 -04:00
use oxigraph::model::TermRef;
2026-07-01 17:42:23 -04:00
use oxilangtag::LanguageTag;
2026-08-08 23:50:04 -04:00
use std::sync::LazyLock;
2026-07-01 17:42:23 -04:00
pub const ENGLISH_PRIMARY: &str = "en";
pub static ENGLISH_OR_UNTAGGED: LazyLock<LanguageCondition> = LazyLock::new(|| {
2026-08-08 23:50:04 -04:00
LanguageCondition::ExactMatchOrUntagged(
LanguageTag::parse(ENGLISH_PRIMARY.to_string()).unwrap(),
)
2026-07-01 17:42:23 -04:00
});
2026-08-16 15:50:10 -04:00
#[derive(Clone)]
2026-07-01 17:42:23 -04:00
pub enum LanguageCondition {
ExactMatchOnly(LanguageTag<String>),
ExactMatchOrUntagged(LanguageTag<String>),
UntaggedOnly,
AnyOrNone,
}
impl LanguageCondition {
2026-08-05 11:21:25 -04:00
pub fn primary_matches_term<'a>(&self, term: impl Into<TermRef<'a>>) -> bool {
if let TermRef::Literal(literal) = term.into() {
2026-08-08 23:50:04 -04:00
let tag = literal
.language()
2026-07-01 17:42:23 -04:00
.map(LanguageTag::parse_and_normalize)
.and_then(Result::ok);
match (tag, self) {
2026-08-08 23:50:04 -04:00
(Some(language), LanguageCondition::ExactMatchOnly(expectation))
| (Some(language), LanguageCondition::ExactMatchOrUntagged(expectation)) => {
language.primary_language() == expectation.primary_language()
}
2026-07-01 17:42:23 -04:00
(None, LanguageCondition::ExactMatchOrUntagged(_)) => true,
(None, LanguageCondition::UntaggedOnly) => true,
(_, LanguageCondition::AnyOrNone) => true,
_ => false,
}
} else {
false
}
}
2026-08-05 11:21:25 -04:00
pub fn primary_language(&self) -> Option<&str> {
match self {
LanguageCondition::ExactMatchOnly(tag) => Some(tag.primary_language()),
LanguageCondition::ExactMatchOrUntagged(tag) => Some(tag.primary_language()),
_ => None,
}
}
2026-07-01 17:42:23 -04:00
pub fn to_filter_expression(&self, var: &str) -> String {
match self {
2026-08-08 23:50:04 -04:00
LanguageCondition::ExactMatchOnly(language) => {
format!(r#"FILTER(langMATCHES(LANG(?{var}), "{language}"))"#)
}
LanguageCondition::ExactMatchOrUntagged(language) => {
format!(r#"FILTER(langMATCHES(LANG(?{var}), "{language}") || !hasLANG(?{var}))"#)
}
2026-07-01 17:42:23 -04:00
LanguageCondition::UntaggedOnly => format!("FILTER(!hasLANG(?{var}))"),
LanguageCondition::AnyOrNone => "".to_string(),
}
}
2026-08-08 23:50:04 -04:00
}