Skip to content

Commit

Permalink
change type of citation_locales to HashMap<Locale, PathBuf>
Browse files Browse the repository at this point in the history
  • Loading branch information
Elena Krippner committed Nov 30, 2023
1 parent d4b003f commit be42212
Show file tree
Hide file tree
Showing 6 changed files with 92 additions and 25 deletions.
45 changes: 45 additions & 0 deletions commons/src/config/locale.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,51 @@ pub mod serde {
}
}
}

pub mod hashmap {
use super::*;
use std::collections::HashMap;
use std::path::PathBuf;

pub fn serialize<S>(locales_map: &HashMap<Locale, PathBuf>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut res = String::new();

for entry in locales_map.iter() {
res.push_str(" ");
res.push_str(&entry.0.to_string());
res.push_str(": ");
res.push_str(&entry.1.to_str().expect("couldn't convert PathBuf to String"));
res.push('\n');
}

res.pop();

serializer.serialize_str(&res)
}

// The signature of a deserialize_with function must follow the pattern:
//
// fn deserialize<'de, D>(D) -> Result<T, D::Error>
// where
// D: Deserializer<'de>
//
// although it may also be generic over the output types T.
pub fn deserialize<'de, D>(deserializer: D) -> Result<HashMap<Locale, PathBuf>, D::Error>
where
D: Deserializer<'de>,
{
let s = HashMap::<String, String>::deserialize(deserializer)?;
let mut result: HashMap<Locale, PathBuf> = HashMap::new();

for entry in s {
result.insert(entry.0.parse().expect("Parsing the locale failed"), PathBuf::from(entry.1));
}
Ok(result)
}
}
}

pub mod clap {
Expand Down
19 changes: 19 additions & 0 deletions commons/src/config/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::{collections::HashSet, path::PathBuf};
use std::collections::HashMap;

use clap::{Args, Parser};
use logid::err;
Expand All @@ -7,6 +8,7 @@ use serde::{Deserialize, Serialize};
use self::{log_id::ConfigErr, output::Output, preamble::Preamble};

pub use icu_locid;
use icu_locid::Locale;

pub mod locale;
pub mod log_id;
Expand Down Expand Up @@ -115,6 +117,23 @@ where
Ok(HashSet::from_iter(entries?))
}

pub fn parse_to_locale_pathbuf_hashset(s: &str) -> Result<HashMap<Locale, PathBuf>, clap::Error>
{
if s.is_empty() {
return Ok(HashMap::new());
}

let mut result: HashMap<Locale, PathBuf> = HashMap::new();
let entries = s.split('\n');
for entry in entries {
let split_entry: Vec<String> = entry.split(':').map(|e| e.to_string()).collect();
let locale: Locale = split_entry[0].trim().parse().expect("Parsing the locale failed");
let path: PathBuf = PathBuf::from(split_entry[1].trim());
result.insert(locale, path);
}
Ok(result)
}

// Define extension trait
pub(crate) trait ReplaceIfNone<T> {
fn replace_none(&mut self, other: Option<T>);
Expand Down
10 changes: 5 additions & 5 deletions commons/src/config/preamble.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ use std::{
use clap::Args;
use icu_locid::Locale;
use logid::err;
use serde::{Deserialize, Serialize};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use super::{locale, log_id::ConfigErr, parse_to_hashset, ConfigFns, ReplaceIfNone};
use super::{locale, log_id::ConfigErr, parse_to_hashset, ConfigFns, ReplaceIfNone, parse_to_locale_pathbuf_hashset};

#[derive(Args, Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Preamble {
Expand Down Expand Up @@ -108,9 +108,9 @@ pub struct Citedata {
#[serde(default)]
pub references: HashSet<PathBuf>,
/// Optional files containing locale information to render citations.
#[arg(long, value_parser = parse_to_hashset::<PathBuf>, required = false, default_value = "")]
#[serde(default)]
pub citation_locales: HashSet<PathBuf>,
#[arg(long, value_parser = parse_to_locale_pathbuf_hashset, required = false, default_value = "")]
#[serde(with = "locale::serde::hashmap", default)]
pub citation_locales: HashMap<Locale, PathBuf>,
}

impl ConfigFns for Citedata {
Expand Down
31 changes: 16 additions & 15 deletions render/src/html/citeproc/csl_files.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::collections::HashSet;
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use unimarkup_commons::config::icu_locid::Locale;
macro_rules! csl_files {
($($name:ident, $path:literal)|+) => {
$(
Expand All @@ -22,20 +23,8 @@ csl_files!(
CSL_ZH_CN_LOCALE, "../../../csl_locales/locales-zh-CN.xml"
);

pub fn get_locale_string(paths: HashSet<PathBuf>) -> String {
let mut default_string = "en-US".to_string();
let mut default_string_set = false;
for path in paths {
if path.is_file() {
return fs::read_to_string(path.into_os_string()).expect("Reading the locale file failed");
}
if !default_string_set {
default_string = path.to_str().expect("Converting the path to a string failed").to_string();
default_string_set = true;

}
}
return match default_string.as_str() {
fn get_cached_locale_string(locale: Locale) -> String {
return match locale.to_string().as_str() {
"de-DE" => CSL_DE_DE_LOCALE.to_string(),
"ar" => CSL_AR_LOCALE.to_string(),
"de-AT" => CSL_DE_AT_LOCALE.to_string(),
Expand All @@ -49,6 +38,18 @@ pub fn get_locale_string(paths: HashSet<PathBuf>) -> String {
};
}

pub fn get_locale_string(doc_locale: Locale, paths: HashMap<Locale, PathBuf>) -> String {
match paths.get(&doc_locale) {
Some(path) => {
if path.is_file() {
return fs::read_to_string(path.clone().into_os_string()).unwrap_or(get_cached_locale_string(doc_locale));
}
},
None => return get_cached_locale_string(doc_locale)
};
get_cached_locale_string(doc_locale)
}

csl_files!(
AMERICAN_MEDICAL_ASSOCIATION, "../../../csl_styles/american-medical-association.csl" |
APA, "../../../csl_styles/apa.csl" |
Expand Down
7 changes: 4 additions & 3 deletions render/src/html/citeproc/mod.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
mod csl_files;

use std::collections::HashSet;
use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::PathBuf;

use rustyscript::{json_args, import, ModuleWrapper, serde_json};
use unimarkup_commons::config::icu_locid::Locale;
use crate::csl_json::csl_types::{CslData, CslItem};
use crate::html::citeproc::csl_files::{get_locale_string, get_style_string};

Expand All @@ -23,9 +24,9 @@ impl CiteprocWrapper {
// returns the citation strings to be placed inline in the same order as the citation_ids
// the CitationItems have to have the same order that they should appear in the output, because this considers
// disambiguation and short forms of citations if the same entry was cited before
pub fn get_citation_strings(&mut self, citation_paths: &HashSet<PathBuf>, citation_locales: HashSet<PathBuf>, style_id: PathBuf, citation_id_vectors: &Vec<Vec<String>>, for_pagedjs: bool) -> Vec<String> {
pub fn get_citation_strings(&mut self, citation_paths: &HashSet<PathBuf>, doc_locale: Locale, citation_locales: HashMap<Locale, PathBuf>, style_id: PathBuf, citation_id_vectors: &Vec<Vec<String>>, for_pagedjs: bool) -> Vec<String> {
let citation_text = get_csl_string(citation_paths);
let locale = get_locale_string(citation_locales);
let locale = get_locale_string(doc_locale, citation_locales);
let style = get_style_string(style_id);

self.module.call::<()>("initProcessor", json_args!(citation_text, locale, style)).expect("call of initProcessor failed");
Expand Down
5 changes: 3 additions & 2 deletions render/src/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,10 @@ impl<'a> Context<'a> {

let for_pagedjs = false;
let style = doc.config.preamble.cite.style.clone().unwrap_or(PathBuf::from(String::from("ieee")));
let mut citation_locales = doc.config.preamble.cite.citation_locales.clone();
citation_locales.insert(PathBuf::from(String::from(doc.config.preamble.i18n.lang.clone().unwrap_or(locale!("en")).to_string())));
let doc_locale = doc.config.preamble.i18n.lang.clone().unwrap_or(locale!("en-US"));
let citation_locales = doc.config.preamble.cite.citation_locales.clone();
let rendered_citations = citeproc.get_citation_strings(&doc.config.preamble.cite.references,
doc_locale,
citation_locales,
style,
&doc.citations, for_pagedjs);
Expand Down

0 comments on commit be42212

Please sign in to comment.