prefixmap/prefixmap.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
use colored::*;
use indexmap::map::Iter;
use indexmap::IndexMap;
use iri_s::*;
use serde_derive::{Deserialize, Serialize};
use crate::{IriRef, PrefixMapError};
use std::str::FromStr;
use std::{collections::HashMap, fmt};
/// Contains declarations of prefix maps which are used in TURTLE, SPARQL and ShEx
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Default)]
#[serde(transparent)]
pub struct PrefixMap {
/// Proper prefix map associations of an alias `String` to an `IriS`
pub map: IndexMap<String, IriS>,
/// Color of prefix aliases when qualifying an IRI that has an alias
#[serde(skip)]
qualify_prefix_color: Option<Color>,
/// Color of local names when qualifying an IRI that has an alias
#[serde(skip)]
qualify_localname_color: Option<Color>,
/// Color of semicolon when qualifying an IRI that has an alias
#[serde(skip)]
qualify_semicolon_color: Option<Color>,
/// Whether to generate hyperlink when qualifying an IRI
#[serde(skip)]
hyperlink: bool,
}
fn split(str: &str) -> Option<(&str, &str)> {
str.rsplit_once(':')
}
impl PrefixMap {
/// Creates an empty ("map
pub fn new() -> PrefixMap {
PrefixMap::default()
}
/// Change ("color when qualifying a IRI
pub fn with_qualify_prefix_color(mut self, color: Option<Color>) -> Self {
self.qualify_prefix_color = color;
self
}
/// Change color of localname when qualifying a IRI
pub fn with_qualify_localname_color(mut self, color: Option<Color>) -> Self {
self.qualify_localname_color = color;
self
}
/// Change color of semicolon when qualifying a IRI
pub fn with_qualify_semicolon_color(mut self, color: Option<Color>) -> Self {
self.qualify_semicolon_color = color;
self
}
pub fn without_rich_qualifying(self) -> Self {
self.with_hyperlink(false)
.with_qualify_localname_color(None)
.with_qualify_prefix_color(None)
.with_qualify_semicolon_color(None)
}
/// Inserts an alias association to an IRI
pub fn insert(&mut self, alias: &str, iri: &IriS) -> Result<(), PrefixMapError> {
match self.map.entry(alias.to_string()) {
indexmap::map::Entry::Occupied(mut e) => {
// TODO: Possible error with repeated aliases??
e.insert(iri.to_owned());
}
indexmap::map::Entry::Vacant(v) => {
v.insert(iri.to_owned());
}
};
Ok(())
}
pub fn find(&self, str: &str) -> Option<&IriS> {
self.map.get(str)
}
pub fn from_hashmap(hm: &HashMap<&str, &str>) -> Result<PrefixMap, PrefixMapError> {
let mut pm = PrefixMap::new();
for (a, s) in hm.iter() {
let iri = IriS::from_str(s)?;
pm.insert(a, &iri)?;
}
Ok(pm)
}
/// Return an iterator over the key-value pairs of the ("map, in their order
pub fn iter(&self) -> Iter<String, IriS> {
self.map.iter()
}
/// Resolves a string against a prefix map
/// Example:
/// Given a string like "ex:a" and a prefixmap that has alias "ex" with value "http://example.org/", the result will be "http://example.org/a"
/// ```
/// use std::collections::HashMap;
/// use prefixmap::PrefixMap;
/// use prefixmap::PrefixMapError;
/// use iri_s::*;
/// use std::str::FromStr;
///
///
/// let pm: PrefixMap = PrefixMap::from_hashmap(
/// &HashMap::from([
/// ("", "http://example.org/"),
/// ("schema", "http://schema.org/")])
/// )?;
/// let a = pm.resolve(":a")?;
/// let a_resolved = IriS::from_str("http://example.org/a")?;
/// assert_eq!(a, a_resolved);
/// Ok::<(), PrefixMapError>(());
///
/// let knows = pm.resolve("schema:knows")?;
/// let knows_resolved = IriS::from_str("http://schema.org/knows")?;
/// assert_eq!(knows, knows_resolved);
/// Ok::<(), PrefixMapError>(())
/// ```
pub fn resolve(&self, str: &str) -> Result<IriS, PrefixMapError> {
match split(str) {
Some((prefix, local)) => {
let iri = self.resolve_prefix_local(prefix, local)?;
Ok(iri)
}
None => {
let iri = IriS::from_str(str)?;
Ok(iri)
}
}
}
/// Resolves an IriRef against a prefix map
pub fn resolve_iriref(&self, iri_ref: &IriRef) -> Result<IriS, PrefixMapError> {
match iri_ref {
IriRef::Prefixed { prefix, local } => {
let iri = self.resolve_prefix_local(prefix, local)?;
Ok(iri)
}
IriRef::Iri(iri) => Ok(iri.clone()),
}
}
/// Resolves a prefixed alias and a local name in a prefix map to obtain the full IRI
/// ```
/// use std::collections::HashMap;
/// use prefixmap::PrefixMap;
/// # use prefixmap::PrefixMapError;
/// # use iri_s::*;
/// # use std::str::FromStr;
///
///
/// let pm = PrefixMap::from_hashmap(
/// &HashMap::from([
/// ("", "http://example.org/"),
/// ("schema", "http://schema.org/"),
/// ("xsd", "http://www.w3.org/2001/XMLSchema#")
/// ]))?;
///
/// let a = pm.resolve_prefix_local("", "a")?;
/// let a_resolved = IriS::from_str("http://example.org/a")?;
/// assert_eq!(a, a_resolved);
///
/// let knows = pm.resolve_prefix_local("schema","knows")?;
/// let knows_resolved = IriS::from_str("http://schema.org/knows")?;
/// assert_eq!(knows, knows_resolved);
///
/// let xsd_string = pm.resolve_prefix_local("xsd","string")?;
/// let xsd_string_resolved = IriS::from_str("http://www.w3.org/2001/XMLSchema#string")?;
/// assert_eq!(xsd_string, xsd_string_resolved);
/// # Ok::<(), PrefixMapError>(())
/// ```
pub fn resolve_prefix_local(&self, prefix: &str, local: &str) -> Result<IriS, PrefixMapError> {
match self.find(prefix) {
Some(iri) => {
let new_iri = iri.extend(local)?;
Ok(new_iri)
}
None => Err(PrefixMapError::PrefixNotFound {
prefix: prefix.to_string(),
prefixmap: self.clone(),
}),
}
}
/// Qualifies an IRI against a prefix map
///
/// If it can't qualify the IRI, it returns the iri between `<` and `>`
/// ```
/// # use std::collections::HashMap;
/// # use prefixmap::PrefixMap;
/// # use prefixmap::PrefixMapError;
/// # use iri_s::*;
/// # use std::str::FromStr;
/// let pm = PrefixMap::from_hashmap(
/// &HashMap::from([
/// ("", "http://example.org/"),
/// ("schema", "http://schema.org/")])
/// )?;
/// let a = IriS::from_str("http://example.org/a")?;
/// assert_eq!(pm.qualify(&a), ":a");
///
/// let knows = IriS::from_str("http://schema.org/knows")?;
/// assert_eq!(pm.qualify(&knows), "schema:knows");
///
/// let other = IriS::from_str("http://other.org/foo")?;
/// assert_eq!(pm.qualify(&other), "<http://other.org/foo>");
/// # Ok::<(), PrefixMapError>(())
/// ```
pub fn qualify(&self, iri: &IriS) -> String {
if let Some(qualified) = self.qualify_optional(iri) {
qualified
} else {
format!("<{iri}>")
}
}
/// Qualifies an IRI against a prefix map
///
/// If it can't qualify the IRI, returns None
///
/// ```
/// # use std::collections::HashMap;
/// # use prefixmap::PrefixMap;
/// # use prefixmap::PrefixMapError;
/// # use iri_s::*;
/// # use std::str::FromStr;
/// let pm = PrefixMap::from_hashmap(
/// &HashMap::from([
/// ("", "http://example.org/"),
/// ("schema", "http://schema.org/")])
/// )?;
/// let a = IriS::from_str("http://example.org/a")?;
/// assert_eq!(pm.qualify(&a), Some(":a"));
///
/// let knows = IriS::from_str("http://schema.org/knows")?;
/// assert_eq!(pm.qualify(&knows), Some("schema:knows"));
///
/// let other = IriS::from_str("http://other.org/foo")?;
/// assert_eq!(pm.qualify(&other), None);
/// # Ok::<(), PrefixMapError>(())
/// ```
pub fn qualify_optional(&self, iri: &IriS) -> Option<String> {
let mut founds: Vec<_> = self
.map
.iter()
.filter_map(|(alias, pm_iri)| {
iri.as_str()
.strip_prefix(pm_iri.as_str())
.map(|rest| (alias, rest))
})
.collect();
founds.sort_by_key(|(_, iri)| iri.len());
let str = if let Some((alias, rest)) = founds.first() {
let prefix_colored = match self.qualify_prefix_color {
Some(color) => alias.color(color),
None => ColoredString::from(alias.as_str()),
};
let rest_colored = match self.qualify_localname_color {
Some(color) => rest.color(color),
None => ColoredString::from(*rest),
};
let semicolon_colored = match self.qualify_semicolon_color {
Some(color) => ":".color(color),
None => ColoredString::from(":"),
};
Some(format!(
"{}{}{}",
prefix_colored, semicolon_colored, rest_colored
))
} else {
None
};
if self.hyperlink {
str.map(|s| format!("\u{1b}]8;;{}\u{1b}\\{}\u{1b}]8;;\u{1b}\\", s.as_str(), s))
} else {
str
}
}
/// Qualifies an IRI against a prefix map returning the length of the qualified string
/// ```
/// # use std::collections::HashMap;
/// # use prefixmap::PrefixMap;
/// # use prefixmap::PrefixMapError;
/// # use iri_s::*;
/// # use std::str::FromStr;
/// let pm = PrefixMap::from_hashmap(
/// &HashMap::from([
/// ("", "http://example.org/"),
/// ("schema", "http://schema.org/")])
/// )?;
/// let a = IriS::from_str("http://example.org/a")?;
/// assert_eq!(pm.qualify(&a), ":a");
///
/// let knows = IriS::from_str("http://schema.org/knows")?;
/// assert_eq!(pm.qualify(&knows), "schema:knows");
///
/// let other = IriS::from_str("http://other.org/foo")?;
/// assert_eq!(pm.qualify(&other), "<http://other.org/foo>");
/// # Ok::<(), PrefixMapError>(())
/// ```
pub fn qualify_and_length(&self, iri: &IriS) -> (String, usize) {
let mut founds: Vec<_> = self
.map
.iter()
.filter_map(|(alias, pm_iri)| {
iri.as_str()
.strip_prefix(pm_iri.as_str())
.map(|rest| (alias, rest))
})
.collect();
founds.sort_by_key(|(_, iri)| iri.len());
let (str, length) = if let Some((alias, rest)) = founds.first() {
let prefix_colored = match self.qualify_prefix_color {
Some(color) => alias.color(color),
None => ColoredString::from(alias.as_str()),
};
let rest_colored = match self.qualify_localname_color {
Some(color) => rest.color(color),
None => ColoredString::from(*rest),
};
let semicolon_colored = match self.qualify_semicolon_color {
Some(color) => ":".color(color),
None => ColoredString::from(":"),
};
let length = prefix_colored.len() + 1 + rest_colored.len();
(
format!("{}{}{}", prefix_colored, semicolon_colored, rest_colored),
length,
)
} else {
let length = format!("{iri}").len();
(format!("<{iri}>"), length)
};
if self.hyperlink {
(
format!(
"\u{1b}]8;;{}\u{1b}\\{}\u{1b}]8;;\u{1b}\\",
iri.as_str(),
str
),
length,
)
} else {
(str, length)
}
}
/// Qualify an IRI against a prefix map and obtains the local name
/// ```
/// # use std::collections::HashMap;
/// # use prefixmap::PrefixMap;
/// # use prefixmap::PrefixMapError;
/// # use iri_s::*;
/// # use std::str::FromStr;
/// let pm = PrefixMap::from_hashmap(
/// &HashMap::from([
/// ("", "http://example.org/"),
/// ("schema", "http://schema.org/")])
/// )?;
/// let a = IriS::from_str("http://example.org/a")?;
/// assert_eq!(pm.qualify_local(&a), Some("a".to_string()));
///
/// let knows = IriS::from_str("http://schema.org/knows")?;
/// assert_eq!(pm.qualify_local(&knows), Some("knows".to_string()));
///
/// let other = IriS::from_str("http://other.org/foo")?;
/// assert_eq!(pm.qualify_local(&other), None);
/// # Ok::<(), PrefixMapError>(())
/// ```
pub fn qualify_local(&self, iri: &IriS) -> Option<String> {
let mut founds: Vec<_> = self
.map
.iter()
.filter_map(|(alias, pm_iri)| {
iri.as_str()
.strip_prefix(pm_iri.as_str())
.map(|rest| (alias, rest))
})
.collect();
founds.sort_by_key(|(_, iri)| iri.len());
if let Some((_alias, rest)) = founds.first() {
Some(rest.to_string())
} else {
None
}
}
/// Basic prefixmap with common definitions
pub fn basic() -> PrefixMap {
PrefixMap::from_hashmap(&HashMap::from([
("", "http://example.org/"),
("dc", "http://purl.org/dc/elements/1.1/"),
("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"),
("rdfs", "http://www.w3.org/2000/01/rdf-schema#"),
("sh", "http://www.w3.org/ns/shacl#"),
("xsd", "http://www.w3.org/2001/XMLSchema#"),
]))
.unwrap()
}
/// Default Wikidata prefixmap
/// This source of this list is <https://www.mediawiki.org/wiki/Wikibase/Indexing/RDF_Dump_Format#Full_list_of_prefixes>
pub fn wikidata() -> PrefixMap {
PrefixMap::from_hashmap(&HashMap::from([
("bd", "http://www.bigdata.com/rdf#"),
("cc", "http://creativecommons.org/ns#"),
("dct", "http://purl.org/dc/terms/"),
("geo", "http://www.opengis.net/ont/geosparql#"),
("hint", "http://www.bigdata.com/queryHints#"),
("ontolex", "http://www.w3.org/ns/lemon/ontolex#"),
("owl", "http://www.w3.org/2002/07/owl#"),
("prov", "http://www.w3.org/ns/prov#"),
("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"),
("rdfs", "http://www.w3.org/2000/01/rdf-schema#"),
("schema", "http://schema.org/"),
("skos", "http://www.w3.org/2004/02/skos/core#"),
("xsd", "http://www.w3.org/2001/XMLSchema#"),
("p", "http://www.wikidata.org/prop/"),
("pq", "http://www.wikidata.org/prop/qualifier/"),
(
"pqn",
"http://www.wikidata.org/prop/qualifier/value-normalized/",
),
("pqv", "http://www.wikidata.org/prop/qualifier/value/"),
("pr", "http://www.wikidata.org/prop/reference/"),
(
"prn",
"http://www.wikidata.org/prop/reference/value-normalized/",
),
("prv", "http://www.wikidata.org/prop/reference/value/"),
("psv", "http://www.wikidata.org/prop/statement/value/"),
("ps", "http://www.wikidata.org/prop/statement/"),
(
"psn",
"http://www.wikidata.org/prop/statement/value-normalized/",
),
("wd", "http://www.wikidata.org/entity/"),
("wdata", "http://www.wikidata.org/wiki/Special:EntityData/"),
("wdno", "http://www.wikidata.org/prop/novalue/"),
("wdref", "http://www.wikidata.org/reference/"),
("wds", "http://www.wikidata.org/entity/statement/"),
("wdt", "http://www.wikidata.org/prop/direct/"),
("wdtn", "http://www.wikidata.org/prop/direct-normalized/"),
("wdv", "http://www.wikidata.org/value/"),
("wikibase", "http://wikiba.se/ontology#"),
]))
.unwrap()
.without_default_colors()
.with_hyperlink(true)
}
pub fn without_colors(mut self) -> Self {
self.qualify_localname_color = None;
self.qualify_prefix_color = None;
self.qualify_semicolon_color = None;
self
}
pub fn without_default_colors(mut self) -> Self {
self.qualify_localname_color = Some(Color::Black);
self.qualify_prefix_color = Some(Color::Blue);
self.qualify_semicolon_color = Some(Color::Red);
self
}
pub fn with_hyperlink(mut self, hyperlink: bool) -> Self {
self.hyperlink = hyperlink;
self
}
pub fn merge(&mut self, other: PrefixMap) -> Result<(), PrefixMapError> {
for (alias, iri) in other.iter() {
self.insert(alias, iri)?
}
Ok(())
}
}
impl fmt::Display for PrefixMap {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (alias, iri) in self.map.iter() {
writeln!(f, "prefix {}: <{}>", &alias, &iri)?
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn split_ex_name() {
assert_eq!(split("ex:name"), Some(("ex", "name")))
}
#[test]
fn prefix_map1() {
let mut pm = PrefixMap::new();
let binding = IriS::from_str("http://example.org/").unwrap();
pm.insert("ex", &binding).unwrap();
let expected = IriS::from_str("http://example.org/name").unwrap();
assert_eq!(pm.resolve("ex:name").unwrap(), expected);
}
#[test]
fn prefixmap_display() {
let mut pm = PrefixMap::new();
let ex_iri = IriS::from_str("http://example.org/").unwrap();
pm.insert("ex", &ex_iri).unwrap();
let ex_rdf = IriS::from_str("http://www.w3.org/1999/02/22-rdf-syntax-ns#").unwrap();
pm.insert("rdf", &ex_rdf).unwrap();
assert_eq!(
pm.to_string(),
"prefix ex: <http://example.org/>\nprefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n"
);
}
#[test]
fn prefixmap_resolve() {
let mut pm = PrefixMap::new();
let ex_iri = IriS::from_str("http://example.org/").unwrap();
pm.insert("ex", &ex_iri).unwrap();
assert_eq!(
pm.resolve("ex:pepe").unwrap(),
IriS::from_str("http://example.org/pepe").unwrap()
);
}
#[test]
fn prefixmap_resolve_xsd() {
let mut pm = PrefixMap::new();
let ex_iri = IriS::from_str("http://www.w3.org/2001/XMLSchema#").unwrap();
pm.insert("xsd", &ex_iri).unwrap();
assert_eq!(
pm.resolve_prefix_local("xsd", "string").unwrap(),
IriS::from_str("http://www.w3.org/2001/XMLSchema#string").unwrap()
);
}
#[test]
fn qualify() {
let mut pm = PrefixMap::new();
pm.insert("", &IriS::from_str("http://example.org/").unwrap())
.unwrap();
pm.insert(
"shapes",
&IriS::from_str("http://example.org/shapes/").unwrap(),
)
.unwrap();
assert_eq!(
pm.qualify(&IriS::from_str("http://example.org/alice").unwrap()),
":alice"
);
assert_eq!(
pm.qualify(&IriS::from_str("http://example.org/shapes/User").unwrap()),
"shapes:User"
);
}
}