Skip to content

Commit

Permalink
run cargo fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
Elena Krippner committed Dec 4, 2023
1 parent 8002276 commit 3e1b519
Show file tree
Hide file tree
Showing 9 changed files with 181 additions and 107 deletions.
25 changes: 18 additions & 7 deletions commons/src/config/locale.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,17 +105,25 @@ pub mod serde {
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,
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_str(
entry
.1
.to_str()
.expect("couldn't convert PathBuf to String"),
);
res.push('\n');
}

Expand All @@ -132,14 +140,17 @@ pub mod serde {
//
// 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>,
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));
result.insert(
entry.0.parse().expect("Parsing the locale failed"),
PathBuf::from(entry.1),
);
}
Ok(result)
}
Expand Down
16 changes: 9 additions & 7 deletions commons/src/config/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::{collections::HashSet, path::PathBuf};
use std::collections::HashMap;
use std::{collections::HashSet, path::PathBuf};

use clap::{Args, Parser};
use logid::err;
Expand Down Expand Up @@ -117,17 +117,19 @@ 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());
}
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 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);
}
Expand Down
5 changes: 4 additions & 1 deletion commons/src/config/preamble.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ use icu_locid::Locale;
use logid::err;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

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

#[derive(Args, Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Preamble {
Expand Down
40 changes: 21 additions & 19 deletions render/src/html/citeproc/csl_files.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use crate::log_id::GeneralWarning;
use logid::log;
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use logid::log;
use unimarkup_commons::config::icu_locid::Locale;
use crate::log_id::GeneralWarning;
macro_rules! csl_files {
($($name:ident, $path:literal)|+) => {
$(
Expand All @@ -14,15 +14,16 @@ macro_rules! csl_files {
}

csl_files!(
CSL_DE_DE_LOCALE, "../../../csl_locales/locales-de-DE.xml" |
CSL_AR_LOCALE, "../../../csl_locales/locales-ar.xml" |
CSL_DE_AT_LOCALE, "../../../csl_locales/locales-de-AT.xml" |
CSL_EN_GB_LOCALE, "../../../csl_locales/locales-en-GB.xml" |
CSL_EN_US_LOCALE, "../../../csl_locales/locales-en-US.xml" |
CSL_ES_ES_LOCALE, "../../../csl_locales/locales-es-ES.xml" |
CSL_FR_FR_LOCALE, "../../../csl_locales/locales-fr-FR.xml" |
CSL_HI_IN_LOCALE, "../../../csl_locales/locales-hi-IN.xml" |
CSL_ZH_CN_LOCALE, "../../../csl_locales/locales-zh-CN.xml"
CSL_DE_DE_LOCALE,
"../../../csl_locales/locales-de-DE.xml" | CSL_AR_LOCALE,
"../../../csl_locales/locales-ar.xml" | CSL_DE_AT_LOCALE,
"../../../csl_locales/locales-de-AT.xml" | CSL_EN_GB_LOCALE,
"../../../csl_locales/locales-en-GB.xml" | CSL_EN_US_LOCALE,
"../../../csl_locales/locales-en-US.xml" | CSL_ES_ES_LOCALE,
"../../../csl_locales/locales-es-ES.xml" | CSL_FR_FR_LOCALE,
"../../../csl_locales/locales-fr-FR.xml" | CSL_HI_IN_LOCALE,
"../../../csl_locales/locales-hi-IN.xml" | CSL_ZH_CN_LOCALE,
"../../../csl_locales/locales-zh-CN.xml"
);

fn get_cached_locale_string(locale: Locale) -> &'static str {
Expand Down Expand Up @@ -56,14 +57,15 @@ pub fn get_locale_string(doc_locale: Locale, paths: HashMap<Locale, PathBuf>) ->
}

csl_files!(
AMERICAN_MEDICAL_ASSOCIATION, "../../../csl_styles/american-medical-association.csl" |
APA, "../../../csl_styles/apa.csl" |
BLUEBOOK_INLINE, "../../../csl_styles/bluebook-inline.csl" |
CHICAGO_FULLNOTE_BIBLIOGRAPHY, "../../../csl_styles/chicago-fullnote-bibliography.csl" |
COUNCIL_OF_SCIENCE_EDITORS, "../../../csl_styles/council-of-science-editors.csl" |
HARVARD_CITE_THEM_RIGHT, "../../../csl_styles/harvard-cite-them-right.csl" |
IEEE, "../../../csl_styles/ieee.csl" |
TURABIAN_AUTHOR_DATE, "../../../csl_styles/turabian-author-date.csl"
AMERICAN_MEDICAL_ASSOCIATION,
"../../../csl_styles/american-medical-association.csl" | APA,
"../../../csl_styles/apa.csl" | BLUEBOOK_INLINE,
"../../../csl_styles/bluebook-inline.csl" | CHICAGO_FULLNOTE_BIBLIOGRAPHY,
"../../../csl_styles/chicago-fullnote-bibliography.csl" | COUNCIL_OF_SCIENCE_EDITORS,
"../../../csl_styles/council-of-science-editors.csl" | HARVARD_CITE_THEM_RIGHT,
"../../../csl_styles/harvard-cite-them-right.csl" | IEEE,
"../../../csl_styles/ieee.csl" | TURABIAN_AUTHOR_DATE,
"../../../csl_styles/turabian-author-date.csl"
);

pub fn get_style_string(path: PathBuf) -> String {
Expand Down
62 changes: 38 additions & 24 deletions render/src/html/citeproc/mod.rs
Original file line number Diff line number Diff line change
@@ -1,72 +1,86 @@
mod csl_files;

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

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};
use crate::log_id::{CiteError, GeneralWarning};
use rustyscript::{import, json_args, serde_json, ModuleWrapper};
use unimarkup_commons::config::icu_locid::Locale;

pub struct CiteprocWrapper {
module: ModuleWrapper,
}

impl CiteprocWrapper {

pub fn new() -> Result<CiteprocWrapper, CiteError> {
return match import("render/src/html/citeproc/js/citeproc_adapter.js") {
Ok(module) => Ok(CiteprocWrapper {
module
}),
Err(err) => Err(CiteError::ModuleImportError)
match import("render/src/html/citeproc/js/citeproc_adapter.js") {
Ok(module) => Ok(CiteprocWrapper { module }),
Err(_err) => Err(CiteError::ModuleImportError),
}
}

// 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>, doc_locale: Locale,
citation_locales: HashMap<Locale, PathBuf>, style_id: PathBuf,
citation_id_vectors: &Vec<Vec<String>>, for_pagedjs: bool) -> Result<Vec<String>, CiteError> {
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,
) -> Result<Vec<String>, CiteError> {
let citation_text = get_csl_string(citation_paths);
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))
self.module
.call::<()>("initProcessor", json_args!(citation_text, locale, style))
.map_err(|_| CiteError::ProcessorInitializationError)?;


self.module.call("getCitationStrings", json_args!(serde_json::to_string(citation_id_vectors).unwrap(), for_pagedjs))
self.module
.call(
"getCitationStrings",
json_args!(
serde_json::to_string(citation_id_vectors).unwrap(),
for_pagedjs
),
)
.map_err(|_| CiteError::CitationError)
}

pub fn get_footnotes(&mut self) -> Result<String, CiteError> {
let has_footnotes = self.module.call("hasFootnotes", json_args!())
let has_footnotes = self
.module
.call("hasFootnotes", json_args!())
.map_err(|_| CiteError::CheckForFootnotesError)?;
return if has_footnotes {
self.module.call("getFootnotesString", json_args!())
if has_footnotes {
self.module
.call("getFootnotesString", json_args!())
.map_err(|_| CiteError::GetFootnotesError)
} else {
Ok("".to_string())
}
}

pub fn get_bibliography(&mut self) -> Result<String, CiteError> {
self.module.call("getBibliography", json_args!())
self.module
.call("getBibliography", json_args!())
.map_err(|_| CiteError::GetBibliographyError)
}
}

fn get_csl_string(references: &HashSet<PathBuf>)-> String {
fn get_csl_string(references: &HashSet<PathBuf>) -> String {
let mut citation_items: Vec<CslItem> = vec![];
for reference in references {
if let Ok(citation_string) = fs::read_to_string(reference.clone().into_os_string()) {
let mut citation_data: CslData = serde_json::from_str::<CslData>(&citation_string)
.unwrap();
let mut citation_data: CslData =
serde_json::from_str::<CslData>(&citation_string).unwrap();
citation_items.append(&mut citation_data.items);
} else {
log!(
Expand All @@ -76,7 +90,7 @@ fn get_csl_string(references: &HashSet<PathBuf>)-> String {
}
}
let csl_data = CslData {
items: citation_items
items: citation_items,
};
return serde_json::ser::to_string_pretty(&csl_data).unwrap();
serde_json::ser::to_string_pretty(&csl_data).unwrap()
}
2 changes: 1 addition & 1 deletion render/src/html/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ use crate::render::OutputFormat;

use self::tag::HtmlTag;

pub(crate) mod citeproc;
pub mod highlight;
pub mod render;
pub mod tag;
pub(crate) mod citeproc;

#[derive(Debug, Default)]
pub struct HtmlAttribute {
Expand Down
47 changes: 23 additions & 24 deletions render/src/html/render.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use unimarkup_commons::config::icu_locid::locale;
use crate::log_id::RenderError;
use unimarkup_commons::lexer::{span::Span, symbol::SymbolKind, token::TokenKind};
use unimarkup_inline::element::{
base::{EscapedNewline, EscapedPlain, EscapedWhitespace, Newline, Plain},
Expand All @@ -10,7 +10,6 @@ use unimarkup_inline::element::{
InlineElement,
};
use unimarkup_parser::elements::indents::{BulletList, BulletListEntry};
use crate::log_id::RenderError;

use crate::render::{Context, OutputFormat, Renderer};

Expand Down Expand Up @@ -189,26 +188,25 @@ impl Renderer<Html> for HtmlRenderer {

fn render_bibliography(
&mut self,
context: &Context
context: &Context,
) -> Result<Html, crate::log_id::RenderError> {
let mut elements: Vec<HtmlElement> = vec![];
let bibliography_string: String;
if context.get_lang() == locale!("de-DE") || context.get_lang() == locale!("de-AT") {
bibliography_string = "Literaturverzeichnis".to_string();
} else if context.get_lang() == locale!("en-US") || context.get_lang() == locale!("en-GB") {
bibliography_string = "Bibliography".to_string();
let bibliography_string = if context.get_lang().id.language
== unimarkup_commons::config::icu_locid::subtags::language!("de")
{
"Literaturverzeichnis"
} else {
bibliography_string = "Bibliography".to_string();
}
"Bibliography"
};
elements.push(HtmlElement {
tag: HtmlTag::H1,
attributes: HtmlAttributes::default(),
content: Some(bibliography_string)
content: Some(bibliography_string.to_string()),
});
elements.push(HtmlElement {
tag: HtmlTag::PlainContent,
attributes: HtmlAttributes::default(),
content: Some(context.bibliography.clone())
content: Some(context.bibliography.clone()),
});
let body = HtmlBody::from(elements);
let html = Html::with_body(body);
Expand All @@ -218,22 +216,23 @@ impl Renderer<Html> for HtmlRenderer {
fn render_footnotes(&mut self, context: &Context) -> Result<Html, RenderError> {
let footnotes = context.footnotes.clone();
if !footnotes.is_empty() {
let mut elements: Vec<HtmlElement> = vec![];
elements.push(HtmlElement {
tag: HtmlTag::PlainContent,
attributes: HtmlAttributes::default(),
content: Some("<hr style=\"width: 25%; margin-left: 0\">".to_string())
});
elements.push(HtmlElement {
tag: HtmlTag::PlainContent,
attributes: HtmlAttributes::default(),
content: Some(footnotes)
});
let elements: Vec<HtmlElement> = vec![
HtmlElement {
tag: HtmlTag::PlainContent,
attributes: HtmlAttributes::default(),
content: Some("<hr style=\"width: 25%; margin-left: 0\">".to_string()),
},
HtmlElement {
tag: HtmlTag::PlainContent,
attributes: HtmlAttributes::default(),
content: Some(footnotes),
},
];
let body = HtmlBody::from(elements);
let html = Html::with_body(body);
Ok(html)
} else {
return Ok(Html::default());
Ok(Html::default())
}
}

Expand Down
2 changes: 1 addition & 1 deletion render/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
//!
//! It also provides syntax highlighting functionality.
mod csl_json;
pub mod html;
pub mod log_id;
pub mod render;
mod csl_json;
Loading

0 comments on commit 3e1b519

Please sign in to comment.