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 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
/*!
Hayagriva provides a YAML-backed format and data model for various
bibliography items as well as a CSL processor formatting both in-text citations and
reference lists based on these literature databases.
The crate is intended to assist scholarly writing and reference management
and can be used both through a CLI and an API.
Below, there is an example of how to parse a YAML database and get a Modern
Language Association-style citation.
# Supported styles
Hayagriva supports all styles provided in the
[official Citation Style Language repository](https://github.com/citation-style-language/styles),
currently over 2,600. You must provide your own style file, which can be
obtained there.
# Usage
```rust
use hayagriva::io::from_yaml_str;
let yaml = r#"
crazy-rich:
type: Book
title: Crazy Rich Asians
author: Kwan, Kevin
date: 2014
publisher: Anchor Books
location: New York, NY, US
"#;
// Parse a bibliography
let bib = from_yaml_str(yaml).unwrap();
assert_eq!(bib.get("crazy-rich").unwrap().date().unwrap().year, 2014);
// Format the reference
use std::fs;
use hayagriva::{
BibliographyDriver, BibliographyRequest, BufWriteFormat,
CitationItem, CitationRequest,
};
use hayagriva::citationberg::{LocaleFile, IndependentStyle};
let en_locale = fs::read_to_string("tests/data/locales-en-US.xml").unwrap();
let locales = [LocaleFile::from_xml(&en_locale).unwrap().into()];
let style = fs::read_to_string("tests/data/art-history.csl").unwrap();
let style = IndependentStyle::from_xml(&style).unwrap();
let mut driver = BibliographyDriver::new();
for entry in bib.iter() {
let items = vec![CitationItem::with_entry(entry)];
driver.citation(CitationRequest::from_items(items, &style, &locales));
}
let result = driver.finish(BibliographyRequest {
style: &style,
locale: None,
locale_files: &locales,
});
for cite in result.citations {
println!("{}", cite.citation.to_string())
}
```
To format entries, you need to wrap them in a [`CitationRequest`]. Each of these
can reference multiple entries in their respective [`CitationItem`]s.
Use these with a [`BibliographyDriver`] to obtain formatted citations and bibliographies.
If the default features are enabled, Hayagriva supports BibTeX and BibLaTeX
bibliographies. You can use [`io::from_biblatex_str`] to parse such
bibliographies.
Should you need more manual control, the library's native `Entry` struct
also offers an implementation of the `From<&biblatex::Entry>`-Trait. You will
need to depend on the [biblatex](https://docs.rs/biblatex/latest/biblatex/)
crate to obtain its `Entry`. Therefore, you could also use your BibLaTeX
content like this:
```ignore
use hayagriva::Entry;
let converted: Entry = your_biblatex_entry.into();
```
If you do not need BibLaTeX compatibility, you can use Hayagriva without the
default features by writing this in your `Cargo.toml`:
```toml
[dependencies]
hayagriva = { version = "0.2", default-features = false }
```
# Selectors
Hayagriva uses a custom selector language that enables you to filter
bibliographies by type of media. For more information about selectors, refer
to the [selectors.md
file](https://github.com/typst/hayagriva/blob/main/docs/selectors.md). While
you can parse user-defined selectors using the function `Selector::parse`,
you may instead want to use the selector macro to avoid the run time cost of
parsing a selector when working with constant selectors.
```rust
use hayagriva::select;
use hayagriva::io::from_yaml_str;
let yaml = r#"
quantized-vortex:
type: Article
author: Gross, E. P.
title: Structure of a Quantized Vortex in Boson Systems
date: 1961-05
page-range: 454-477
serial-number:
doi: 10.1007/BF02731494
parent:
issue: 3
volume: 20
title: Il Nuovo Cimento
"#;
let entries = from_yaml_str(yaml).unwrap();
let journal = select!((Article["date"]) > ("journal":Periodical));
assert!(journal.matches(entries.nth(0).unwrap()));
```
There are two ways to check if a selector matches an entry.
You should use [`Selector::matches`] if you just want to know if an item
matches a selector and [`Selector::apply`] to continue to work with the data from
parents of a matching entry. Keep in mind that the latter function will
return `Some` even if no sub-entry was bound / if the hash map is empty.
*/
#![warn(missing_docs)]
#![allow(clippy::comparison_chain)]
#[macro_use]
mod selectors;
#[cfg(feature = "biblatex")]
mod interop;
mod csl;
pub mod io;
pub mod lang;
pub mod types;
mod util;
use std::collections::BTreeMap;
#[cfg(feature = "archive")]
pub use crate::csl::archive;
pub use citationberg;
pub use csl::{
standalone_citation, BibliographyDriver, BibliographyRequest, Brackets,
BufWriteFormat, CitationItem, CitationRequest, CitePurpose, Elem, ElemChild,
ElemChildren, ElemMeta, Formatted, Formatting, LocatorPayload, Rendered,
RenderedBibliography, RenderedCitation, SpecificLocator,
};
pub use selectors::{Selector, SelectorError};
use indexmap::IndexMap;
use paste::paste;
use serde::{de::Visitor, Deserialize, Serialize};
use types::*;
use unic_langid::LanguageIdentifier;
use util::{
deserialize_one_or_many_opt, serialize_one_or_many, serialize_one_or_many_opt,
OneOrMany,
};
/// A collection of bibliographic entries.
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
pub struct Library(IndexMap<String, Entry>);
impl Library {
/// Construct a new, empty bibliography library.
pub fn new() -> Self {
Self(IndexMap::new())
}
/// Add an entry to the library.
pub fn push(&mut self, entry: &Entry) {
self.0.insert(entry.key.clone(), entry.clone());
}
/// Retrieve an entry from the library.
pub fn get(&self, key: &str) -> Option<&Entry> {
self.0.get(key)
}
/// Get an iterator over the entries in the library.
pub fn iter(&self) -> impl Iterator<Item = &Entry> {
self.0.values()
}
/// Get an iterator over the keys in the library.
pub fn keys(&self) -> impl Iterator<Item = &str> {
self.0.keys().map(|k| k.as_str())
}
/// Remove an entry from the library.
pub fn remove(&mut self, key: &str) -> Option<Entry> {
self.0.shift_remove(key)
}
/// Get the length of the library.
pub fn len(&self) -> usize {
self.0.len()
}
/// Check whether the library is empty.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Get the nth entry in the library.
pub fn nth(&self, n: usize) -> Option<&Entry> {
self.0.get_index(n).map(|(_, v)| v)
}
}
impl<'a> IntoIterator for &'a Library {
type Item = &'a Entry;
type IntoIter = indexmap::map::Values<'a, String, Entry>;
fn into_iter(self) -> Self::IntoIter {
self.0.values()
}
}
impl IntoIterator for Library {
type Item = Entry;
type IntoIter = std::iter::Map<
indexmap::map::IntoIter<String, Entry>,
fn((String, Entry)) -> Entry,
>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter().map(|(_, v)| v)
}
}
impl FromIterator<Entry> for Library {
fn from_iter<T: IntoIterator<Item = Entry>>(iter: T) -> Self {
Self(iter.into_iter().map(|e| (e.key().to_string(), e)).collect())
}
}
macro_rules! entry {
($(
$(#[doc = $doc:literal])*
$(#[serde $serde:tt])*
$s:literal => $i:ident : $t:ty
$(| $d:ty)? $(,)?
),*) => {
// Build the struct and make it serializable.
/// A citable item in a bibliography.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Hash)]
pub struct Entry {
/// The key of the entry.
#[serde(skip)]
key: String,
/// The type of the item.
#[serde(rename = "type")]
entry_type: EntryType,
$(
$(#[doc = $doc])*
$(#[serde $serde])*
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = $s)]
$i: Option<$t>,
)*
/// Item in which the item was published / to which it is strongly
/// associated to.
#[serde(serialize_with = "serialize_one_or_many")]
#[serde(skip_serializing_if = "Vec::is_empty")]
#[serde(rename = "parent")]
parents: Vec<Entry>,
}
impl Entry {
/// Get the key of the entry.
pub fn key(&self) -> &str {
&self.key
}
/// Construct a new, empty entry.
pub fn new(key: &str, entry_type: EntryType) -> Self {
Self {
key: key.to_owned(),
entry_type,
$(
$i: None,
)*
parents: Vec::new(),
}
}
/// Check whether the entry has some key.
pub fn has(&self, key: &str) -> bool {
match key {
$(
$s => self.$i.is_some(),
)*
_ => false,
}
}
}
/// Getters.
impl Entry {
/// Get the type of the entry.
pub fn entry_type(&self) -> &EntryType {
&self.entry_type
}
/// Get the parents of the entry.
pub fn parents(&self) -> &[Entry] {
&self.parents
}
$(
entry!(@get $(#[doc = $doc])* $s => $i : $t $(| $d)?);
)*
}
/// Setters.
impl Entry {
/// Set the parents of the entry.
pub fn set_parents(&mut self, parents: Vec<Entry>) {
self.parents = parents;
}
$(
entry!(@set $s => $i : $t);
)*
}
/// The library deserialization also handles entries.
///
/// Entries do not implement [`Deserialize`] because they have a data
/// dependency on their key (stored in the parent map) and their
/// children for default types.
impl<'de> Deserialize<'de> for Library {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct MyVisitor;
#[derive(Deserialize)]
struct NakedEntry {
#[serde(rename = "type")]
entry_type: Option<EntryType>,
#[serde(default)]
#[serde(rename = "parent")]
parents: OneOrMany<NakedEntry>,
$(
$(#[serde $serde])*
#[serde(rename = $s)]
#[serde(default)]
$i: Option<$t>,
)*
}
impl NakedEntry {
/// Convert into a full entry using the child entry type
/// (if any) and the key.
fn into_entry<E>(
self,
key: &str,
child_entry_type: Option<EntryType>,
) -> Result<Entry, E>
where E: serde::de::Error
{
let entry_type = self.entry_type
.or_else(|| child_entry_type.map(|e| e.default_parent()))
.ok_or_else(|| E::custom("no entry type"))?;
let parents: Result<Vec<_>, _> = self.parents
.into_iter()
.map(|p| p.into_entry(key, Some(entry_type)))
.collect();
Ok(Entry {
key: key.to_owned(),
entry_type,
parents: parents?,
$(
$i: self.$i,
)*
})
}
}
impl<'de> Visitor<'de> for MyVisitor {
type Value = Library;
fn expecting(&self, formatter: &mut std::fmt::Formatter)
-> std::fmt::Result
{
formatter.write_str(
"a map between cite keys and entries"
)
}
fn visit_map<A>(self, mut map: A)
-> Result<Self::Value, A::Error>
where
A: serde::de::MapAccess<'de>,
{
let mut entries = Vec::with_capacity(
map.size_hint().unwrap_or(0).min(128)
);
while let Some(key) = map.next_key::<String>()? {
if entries.iter().any(|(k, _)| k == &key) {
return Err(serde::de::Error::custom(format!(
"duplicate key {}",
key
)));
}
let entry: NakedEntry = map.next_value()?;
entries.push((key, entry));
}
let entries: Result<IndexMap<_, _>, A::Error> =
entries.into_iter().map(|(k, v)| {
v.into_entry(&k, None).map(|e| (k, e))
}).collect();
Ok(Library(entries?))
}
}
deserializer.deserialize_map(MyVisitor)
}
}
};
(@match
$s:literal => $i:ident,
$naked:ident, $map:ident $(,)?
) => {
$naked.$i = Some($map.next_value()?)
};
// All items with a serde attribute are expected to be collections.
(@match
$(#[serde $serde:tt])+
$s:literal => $i:ident,
$naked:ident, $map:ident $(,)?
) => {
let one_or_many: OneOrMany = $map.next_value()?;
$naked.$i = Some(one_or_many.into());
};
// Getter macro for deref types
(@get $(#[$docs:meta])+ $s:literal => $i:ident : $t:ty | $d:ty $(,)?) => {
$(#[$docs])+
pub fn $i(&self) -> Option<&$d> {
self.$i.as_deref()
}
};
// Getter macro for regular types.
(@get $(#[$docs:meta])+ $s:literal => $i:ident : $t:ty $(,)?) => {
$(#[$docs])+
pub fn $i(&self) -> Option<&$t> {
self.$i.as_ref()
}
};
// Setter for all types.
(@set $s:literal => $i:ident : $t:ty $(,)?) => {
paste! {
#[doc = "Set the `" $s "` field."]
pub fn [<set_ $i>](&mut self, $i: $t) {
self.$i = Some($i);
}
}
};
}
entry! {
/// Title of the item.
"title" => title: FormatString,
/// Persons primarily responsible for creating the item.
#[serde(serialize_with = "serialize_one_or_many_opt")]
#[serde(deserialize_with = "deserialize_one_or_many_opt")]
"author" => authors: Vec<Person> | [Person],
/// Date at which the item was published.
"date" => date: Date,
/// Persons responsible for selecting and revising the content of the item.
#[serde(serialize_with = "serialize_one_or_many_opt")]
#[serde(deserialize_with = "deserialize_one_or_many_opt")]
"editor" => editors: Vec<Person> | [Person],
/// Persons involved in the production of the item that are not authors or editors.
#[serde(serialize_with = "serialize_one_or_many_opt")]
#[serde(deserialize_with = "deserialize_one_or_many_opt")]
"affiliated" => affiliated: Vec<PersonsWithRoles> | [PersonsWithRoles],
/// Publisher of the item.
"publisher" => publisher: FormatString,
/// Physical location at which the item was published or created.
"location" => location: FormatString,
/// Organization at/for which the item was created.
"organization" => organization: FormatString,
/// For an item whose parent has multiple issues, indicates the position in
/// the issue sequence. Also used to indicate the episode number for TV.
"issue" => issue: MaybeTyped<Numeric>,
/// For an item whose parent has multiple volumes/parts/seasons ... of which
/// this item is one.
"volume" => volume: MaybeTyped<Numeric>,
/// Total number of volumes/parts/seasons ... this item consists of.
"volume-total" => volume_total: Numeric,
/// Published version of an item.
"edition" => edition: MaybeTyped<Numeric>,
/// The range of pages within the parent this item occupies
"page-range" => page_range: MaybeTyped<Numeric>,
/// The total number of pages the item has.
"page-total" => page_total: Numeric,
/// The time range within the parent this item starts and ends at.
"time-range" => time_range: MaybeTyped<DurationRange>,
/// The total runtime of the item.
"runtime" => runtime: MaybeTyped<Duration>,
/// Canonical public URL of the item, can have access date.
"url" => url: QualifiedUrl,
/// Any serial number or version describing the item that is not appropriate
/// for the fields doi, edition, isbn or issn (may be assigned by the author
/// of the item; especially useful for preprint archives).
#[serde(alias = "serial")]
"serial-number" => serial_number: SerialNumber,
/// The language of the item.
"language" => language: LanguageIdentifier,
/// Name of the institution/collection where the item is kept.
"archive" => archive: FormatString,
/// Physical location of the institution/collection where the item is kept.
"archive-location" => archive_location: FormatString,
/// The call number of the item in the institution/collection.
"call-number" => call_number: FormatString,
/// Additional description to be appended in the bibliographic entry.
"note" => note: FormatString,
/// Abstract of the item (e.g. the abstract of a journal article).
"abstract" => abstract_: FormatString,
/// Short markup, decoration, or annotation to the item (e.g., to indicate
/// items included in a review);
///
/// For descriptive text (e.g., in an annotated bibliography), use `note`
/// instead.
"annote" => annote: FormatString,
/// Type, class, or subtype of the item (e.g. “Doctoral dissertation” for
/// a PhD thesis; “NIH Publication” for an NIH technical report);
/// Do not use for topical descriptions or categories (e.g. “adventure” for an adventure movie).
"genre" => genre: FormatString,
}
impl Entry {
/// Get and parse the `affiliated` field and only return persons of a given
/// [role](PersonRole).
pub(crate) fn affiliated_with_role(&self, role: PersonRole) -> Vec<&Person> {
self.affiliated
.iter()
.flatten()
.filter_map(
|PersonsWithRoles { names, role: r }| {
if r == &role {
Some(names)
} else {
None
}
},
)
.flatten()
.collect()
}
/// Get the unconverted value of a certain field from this entry or any of
/// its parents.
pub fn map<'a, F, T>(&'a self, mut f: F) -> Option<T>
where
F: FnMut(&'a Self) -> Option<T>,
{
if let Some(value) = f(self) {
Some(value)
} else {
self.map_parents(f)
}
}
/// Get the unconverted value of a certain field from the parents only by BFS.
pub fn map_parents<'a, F, T>(&'a self, mut f: F) -> Option<T>
where
F: FnMut(&'a Self) -> Option<T>,
{
let mut path: Vec<usize> = vec![0];
let up = |path: &mut Vec<usize>| {
path.pop();
if let Some(last) = path.last_mut() {
*last += 1;
}
};
'outer: loop {
// Index parents with the items in path. If, at any level, the index
// exceeds the number of parents, increment the index at the
// previous level. If no other level remains, return.
let Some(first_path) = path.first() else {
return None;
};
if self.parents.len() <= *first_path {
return None;
}
let mut item = &self.parents[*first_path];
for i in 1..path.len() {
if path[i] >= item.parents.len() {
up(&mut path);
continue 'outer;
}
item = &item.parents[path[i]];
}
if let Some(first_path) = path.first_mut() {
*first_path += 1;
}
if let Some(value) = f(item) {
return Some(value);
}
}
}
/// Apply a selector and return a bound parent entry or self.
pub fn bound_select(&self, selector: &Selector, binding: &str) -> Option<&Entry> {
selector.apply(self).and_then(|map| map.get(binding).copied())
}
/// Will recursively get a date off either the entry or any of its ancestors.
pub fn date_any(&self) -> Option<&Date> {
self.map(|e| e.date.as_ref())
}
/// Will recursively get an URL off either the entry or any of its ancestors.
pub fn url_any(&self) -> Option<&QualifiedUrl> {
self.map(|e| e.url.as_ref())
}
/// Retrieve a keyed serial number.
pub fn keyed_serial_number(&self, key: &str) -> Option<&str> {
self.serial_number
.as_ref()
.and_then(|s| s.0.get(key).map(|s| s.as_str()))
}
/// Set a keyed serial number.
pub fn set_keyed_serial_number(&mut self, key: &str, value: String) {
if let Some(serials) = &mut self.serial_number {
serials.0.insert(key.to_owned(), value);
} else {
let mut map = BTreeMap::new();
map.insert(key.to_owned(), value);
self.serial_number = Some(SerialNumber(map));
}
}
/// The Digital Object Identifier of the item.
pub fn doi(&self) -> Option<&str> {
self.keyed_serial_number("doi")
}
/// Set the `doi` field.
pub fn set_doi(&mut self, doi: String) {
self.set_keyed_serial_number("doi", doi);
}
/// International Standard Book Number (ISBN), prefer ISBN-13.
pub fn isbn(&self) -> Option<&str> {
self.keyed_serial_number("isbn")
}
/// Set the `isbn` field.
pub fn set_isbn(&mut self, isbn: String) {
self.set_keyed_serial_number("isbn", isbn);
}
/// International Standard Serial Number (ISSN).
pub fn issn(&self) -> Option<&str> {
self.keyed_serial_number("issn")
}
/// Set the `issn` field.
pub fn set_issn(&mut self, issn: String) {
self.set_keyed_serial_number("issn", issn);
}
/// PubMed Identifier (PMID).
pub fn pmid(&self) -> Option<&str> {
self.keyed_serial_number("pmid")
}
/// Set the `pmid` field.
pub fn set_pmid(&mut self, pmid: String) {
self.set_keyed_serial_number("pmid", pmid);
}
/// PubMed Central Identifier (PMCID).
pub fn pmcid(&self) -> Option<&str> {
self.keyed_serial_number("pmcid")
}
/// Set the `pmcid` field.
pub fn set_pmcid(&mut self, pmcid: String) {
self.set_keyed_serial_number("pmcid", pmcid);
}
/// ArXiv identifier.
pub fn arxiv(&self) -> Option<&str> {
self.keyed_serial_number("arxiv")
}
/// Set the `arxiv` field.
pub fn set_arxiv(&mut self, arxiv: String) {
self.set_keyed_serial_number("arxiv", arxiv);
}
/// Get the container of an entry like CSL defines it.
pub(crate) fn get_container(&self) -> Option<&Self> {
let retrieve_container = |possible: &[EntryType]| {
for possibility in possible {
if let Some(container) =
self.parents.iter().find(|e| e.entry_type == *possibility)
{
return Some(container);
}
}
None
};
match &self.entry_type {
EntryType::Article => retrieve_container(&[
EntryType::Book,
// Proceedings must come before Conference.
// Because @inproceedings will result in a Artical entry with a Proceedings and a
// Conference parent. But only the Proceedings has the correct title.
EntryType::Proceedings,
EntryType::Conference,
EntryType::Periodical,
EntryType::Newspaper,
EntryType::Blog,
EntryType::Reference,
EntryType::Web,
]),
EntryType::Anthos => retrieve_container(&[
EntryType::Book,
EntryType::Anthology,
EntryType::Reference,
EntryType::Report,
]),
EntryType::Chapter => retrieve_container(&[
EntryType::Book,
EntryType::Anthology,
EntryType::Reference,
EntryType::Report,
]),
EntryType::Report => {
retrieve_container(&[EntryType::Book, EntryType::Anthology])
}
EntryType::Web => retrieve_container(&[EntryType::Web]),
EntryType::Scene => retrieve_container(&[
EntryType::Audio,
EntryType::Video,
EntryType::Performance,
EntryType::Artwork,
]),
EntryType::Case => retrieve_container(&[
EntryType::Book,
EntryType::Anthology,
EntryType::Reference,
EntryType::Report,
]),
EntryType::Post => {
retrieve_container(&[EntryType::Thread, EntryType::Blog, EntryType::Web])
}
EntryType::Thread => {
retrieve_container(&[EntryType::Thread, EntryType::Web, EntryType::Blog])
}
_ => None,
}
}
/// Get the non-partial parent of the entry.
pub(crate) fn get_full(&self) -> &Self {
let mut parent = self.parents().first();
let mut entry = self;
while select!(Chapter | Scene).matches(entry) && entry.title().is_none() {
if let Some(p) = parent {
entry = p;
parent = entry.parents().first();
} else {
break;
}
}
entry
}
/// Get the collection of an entry like CSL defines it.
pub(crate) fn get_collection(&self) -> Option<&Self> {
match &self.entry_type {
EntryType::Anthology
| EntryType::Newspaper
| EntryType::Performance
| EntryType::Periodical
| EntryType::Proceedings
| EntryType::Book
| EntryType::Reference
| EntryType::Exhibition => self.parents.iter().find(|e| {
e.entry_type == self.entry_type || e.entry_type == EntryType::Anthology
}),
_ => self.parents.iter().find_map(|e| e.get_collection()),
}
}
/// Search a parent by DFS.
pub(crate) fn dfs_parent(&self, kind: EntryType) -> Option<&Self> {
if self.entry_type == kind {
return Some(self);
}
for parent in &self.parents {
if let Some(entry) = parent.dfs_parent(kind) {
return Some(entry);
}
}
None
}
/// Get the original entry.
pub(crate) fn get_original(&self) -> Option<&Self> {
self.dfs_parent(EntryType::Original)
}
}
#[cfg(feature = "biblatex")]
impl Entry {
/// Adds a parent to the current entry. The parent
/// list will be created if there is none.
pub(crate) fn add_parent(&mut self, entry: Self) {
self.parents.push(entry);
}
/// Adds affiliated persons. The list will be created if there is none.
pub(crate) fn add_affiliated_persons(
&mut self,
new_persons: (Vec<Person>, PersonRole),
) {
let obj = PersonsWithRoles { names: new_persons.0, role: new_persons.1 };
if let Some(affiliated) = &mut self.affiliated {
affiliated.push(obj);
} else {
self.affiliated = Some(vec![obj]);
}
}
pub(crate) fn parents_mut(&mut self) -> &mut [Self] {
&mut self.parents
}
}
#[cfg(test)]
mod tests {
use std::fs;
use super::*;
use crate::io::from_yaml_str;
macro_rules! select_all {
($select:expr, $entries:tt, [$($key:expr),* $(,)*] $(,)*) => {
let keys = [$($key,)*];
let selector = Selector::parse($select).unwrap();
for entry in $entries.iter() {
let res = selector.apply(entry);
if keys.contains(&entry.key.as_str()) {
if res.is_none() {
panic!("Key {} not found in results", entry.key);
}
} else {
if res.is_some() {
panic!("Key {} found in results", entry.key);
}
}
}
}
}
macro_rules! select {
($select:expr, $entries:tt >> $entry_key:expr, [$($key:expr),* $(,)*] $(,)*) => {
let keys = vec![ $( $key , )* ];
let entry = $entries.iter().filter_map(|i| if i.key == $entry_key {Some(i)} else {None}).next().unwrap();
let selector = Selector::parse($select).unwrap();
let res = selector.apply(entry).unwrap();
if !keys.into_iter().all(|k| res.get(k).is_some()) {
panic!("Results do not contain binding");
}
}
}
#[test]
fn selectors() {
let contents = fs::read_to_string("tests/data/basic.yml").unwrap();
let entries = from_yaml_str(&contents).unwrap();
select_all!("article > proceedings", entries, ["zygos"]);
select_all!(
"article > (periodical | newspaper)",
entries,
["omarova-libra", "kinetics", "house", "swedish",]
);
select_all!(
"(chapter | anthos) > (anthology | book)",
entries,
["harry", "gedanken"]
);
select_all!(
"*[url]",
entries,
[
"omarova-libra",
"science-e-issue",
"oiseau",
"georgia",
"really-habitable",
"electronic-music",
"mattermost",
"worth",
"wrong",
"un-hdr",
"audio-descriptions",
"camb",
"logician",
"dns-encryption",
"overleaf",
"editors",
]
);
select_all!(
"!(*[url] | (* > *[url]))",
entries,
[
"zygos",
"harry",
"terminator-2",
"interior",
"wire",
"kinetics",
"house",
"plaque",
"renaissance",
"gedanken",
"donne",
"roe-wade",
"foia",
"drill",
"swedish",
"latex-users",
"barb",
]
);
}
#[test]
fn selector_bindings() {
let contents = fs::read_to_string("tests/data/basic.yml").unwrap();
let entries = from_yaml_str(&contents).unwrap();
select!(
"a:article > (b:conference & c:(video|blog|web))",
entries >> "wwdc-network",
["a", "b", "c"]
);
}
}