From 6aec427e4585ad3f213c1e8d62df8c4e3ed5dbcc Mon Sep 17 00:00:00 2001 From: Gambhiro Date: Sat, 12 Oct 2019 18:45:19 +0100 Subject: [PATCH] rustfmt --- src/app.rs | 110 +++++++++++------------- src/dict_word.rs | 34 ++++++-- src/ebook.rs | 199 +++++++++++++++++++++++++++++-------------- src/error.rs | 2 +- src/helpers.rs | 15 +++- src/letter_groups.rs | 21 ++--- src/main.rs | 35 +++++--- src/pali.rs | 10 ++- 8 files changed, 267 insertions(+), 159 deletions(-) diff --git a/src/app.rs b/src/app.rs index f7b8f17..769c8d2 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1,17 +1,19 @@ use std::default::Default; use std::error::Error; use std::fs; -use std::process::Command; use std::path::{Path, PathBuf}; +use std::process::Command; +use chrono::prelude::*; use regex::Regex; use walkdir::WalkDir; -use chrono::prelude::*; -use crate::ebook::{Ebook, EbookMetadata, EbookFormat, DICTIONARY_METADATA_SEP, DICTIONARY_WORD_ENTRIES_SEP}; use crate::dict_word::{DictWord, DictWordHeader}; -use crate::helpers::{is_hidden, ensure_parent, ensure_parent_all}; +use crate::ebook::{ + Ebook, EbookFormat, EbookMetadata, DICTIONARY_METADATA_SEP, DICTIONARY_WORD_ENTRIES_SEP, +}; use crate::error::ToolError; +use crate::helpers::{ensure_parent, ensure_parent_all, is_hidden}; pub struct AppStartParams { pub ebook_format: EbookFormat, @@ -47,7 +49,6 @@ pub enum ZipWith { impl Default for AppStartParams { fn default() -> Self { - // Zip cli tool is not usually available on Windows, so we zip with lib there. // // lise-henry/epub-builder notes that zipping epub with the lib sometimes gave her errors @@ -149,7 +150,11 @@ fn look_for_kindlegen() -> Option { // Try if it is available from the system PATH. let output = if cfg!(target_os = "windows") { - match Command::new("cmd").arg("/C").arg("where kindlegen.exe").output() { + match Command::new("cmd") + .arg("/C") + .arg("where kindlegen.exe") + .output() + { Ok(o) => o, Err(e) => { warn!("🔥 Failed to find KindleGen: {:?}", e); @@ -183,12 +188,7 @@ pub fn process_cli_args(matches: clap::ArgMatches) -> Result() - { + if let Ok(x) = sub_matches.value_of("json_path").unwrap().parse::() { let path = PathBuf::from(&x); if path.exists() { params.json_path = Some(path); @@ -215,9 +215,7 @@ pub fn process_cli_args(matches: clap::ArgMatches) -> Result Result() + .unwrap() + .parse::() { let s = x.trim().to_lowercase(); if s == "epub" { @@ -267,10 +263,11 @@ pub fn process_cli_args(matches: clap::ArgMatches) -> Result Result() + .unwrap() + .parse::() { let path = PathBuf::from(&x); if path.exists() { @@ -292,11 +289,7 @@ pub fn process_cli_args(matches: clap::ArgMatches) -> Result() - { + if let Ok(x) = sub_matches.value_of("title").unwrap().parse::() { params.title = Some(x); } } @@ -304,8 +297,8 @@ pub fn process_cli_args(matches: clap::ArgMatches) -> Result() + .unwrap() + .parse::() { params.dict_label = Some(x); } @@ -314,8 +307,8 @@ pub fn process_cli_args(matches: clap::ArgMatches) -> Result() + .unwrap() + .parse::() { let list_path = PathBuf::from(&x); let s = match fs::read_to_string(&list_path) { @@ -323,7 +316,7 @@ pub fn process_cli_args(matches: clap::ArgMatches) -> Result { let msg = format!("🔥 Can't read path. {:?}", e); return Err(Box::new(ToolError::Exit(msg))); - }, + } }; let s = s.trim(); @@ -351,11 +344,11 @@ pub fn process_cli_args(matches: clap::ArgMatches) -> Result { let p = dir.join(PathBuf::from(filename).with_extension("epub")); params.output_path = Some(ensure_parent(&p)); - }, + } EbookFormat::Mobi => { let p = dir.join(PathBuf::from(filename).with_extension("mobi")); params.output_path = Some(ensure_parent(&p)); - }, + } } } } @@ -363,8 +356,8 @@ pub fn process_cli_args(matches: clap::ArgMatches) -> Result() + .unwrap() + .parse::() { params.mobi_compression = x; } @@ -378,8 +371,8 @@ pub fn process_cli_args(matches: clap::ArgMatches) -> Result() + .unwrap() + .parse::() { let path = PathBuf::from(&x); if path.exists() { @@ -462,10 +455,12 @@ pub fn process_nyanatiloka_entries( dict_label: &Option, ebook: &mut Ebook, ) { - let nyanatiloka_root = &nyanatiloka_root.as_ref().expect("nyanatiloka_root is missing."); + let nyanatiloka_root = &nyanatiloka_root + .as_ref() + .expect("nyanatiloka_root is missing."); let dict_label = &dict_label.as_ref().expect("dict_label is missing."); - info!{"=== Begin processing {:?} ===", nyanatiloka_root}; + info! {"=== Begin processing {:?} ===", nyanatiloka_root}; #[derive(Deserialize)] struct Entry { @@ -503,10 +498,7 @@ pub fn process_nyanatiloka_entries( word = cap[1].to_string(); } - entries.push(Entry { - word, - text, - }); + entries.push(Entry { word, text }); } for e in entries.iter() { @@ -525,12 +517,10 @@ pub fn process_nyanatiloka_entries( } } - pub fn process_markdown_list( markdown_paths: Vec, - ebook: &mut Ebook -) -> Result<(), Box> -{ + ebook: &mut Ebook, +) -> Result<(), Box> { for p in markdown_paths.iter() { process_markdown(p, ebook)?; } @@ -538,11 +528,7 @@ pub fn process_markdown_list( Ok(()) } -pub fn process_markdown( - markdown_path: &PathBuf, - ebook: &mut Ebook -) -> Result<(), Box> -{ +pub fn process_markdown(markdown_path: &PathBuf, ebook: &mut Ebook) -> Result<(), Box> { info! {"=== Begin processing {:?} ===", markdown_path}; let s = fs::read_to_string(markdown_path).unwrap(); @@ -551,11 +537,15 @@ pub fn process_markdown( let parts: Vec<&str> = s.split(DICTIONARY_WORD_ENTRIES_SEP).collect(); if parts.len() != 2 { - let msg = "Bad Markdown input. Can't separate the Dictionary header and DictWord entries.".to_string(); + let msg = "Bad Markdown input. Can't separate the Dictionary header and DictWord entries." + .to_string(); return Err(Box::new(ToolError::Exit(msg))); } - let a = parts.get(0).unwrap().to_string() + let a = parts + .get(0) + .unwrap() + .to_string() .replace(DICTIONARY_METADATA_SEP, "") .replace("``` toml", "") .replace("```", ""); @@ -563,7 +553,10 @@ pub fn process_markdown( let mut meta: EbookMetadata = match toml::from_str(&a) { Ok(x) => x, Err(e) => { - let msg = format!("🔥 Can't serialize from TOML String: {:?}\nError: {:?}", &a, e); + let msg = format!( + "🔥 Can't serialize from TOML String: {:?}\nError: {:?}", + &a, e + ); return Err(Box::new(ToolError::Exit(msg))); } }; @@ -574,7 +567,7 @@ pub fn process_markdown( EbookFormat::Epub => { meta.is_epub = true; meta.is_mobi = false; - }, + } EbookFormat::Mobi => { meta.is_epub = false; meta.is_mobi = true; @@ -602,7 +595,7 @@ pub fn process_markdown( Err(e) => { let msg = format!("{:?}", e); return Err(Box::new(ToolError::Exit(msg))); - }, + } } } @@ -628,4 +621,3 @@ fn html_to_plain(html: &str) -> String { plain } */ - diff --git a/src/dict_word.rs b/src/dict_word.rs index 2a7969a..aabd371 100644 --- a/src/dict_word.rs +++ b/src/dict_word.rs @@ -1,6 +1,6 @@ +use regex::Regex; use std::default::Default; use std::error::Error; -use regex::Regex; use crate::error::ToolError; @@ -26,7 +26,11 @@ impl DictWord { pub fn as_markdown_and_toml_string(&self) -> String { let header = toml::to_string(&self.word_header).unwrap(); - format!("``` toml\n{}\n```\n\n{}", &header.trim(), &self.definition_md.trim()) + format!( + "``` toml\n{}\n```\n\n{}", + &header.trim(), + &self.definition_md.trim() + ) } pub fn from_markdown(s: &str) -> Result> { @@ -37,7 +41,10 @@ impl DictWord { let word_header: DictWordHeader = match toml::from_str(toml) { Ok(x) => x, Err(e) => { - let msg = format!("🔥 Can't serialize from TOML String: {:?}\nError: {:?}", &toml, e); + let msg = format!( + "🔥 Can't serialize from TOML String: {:?}\nError: {:?}", + &toml, e + ); return Err(Box::new(ToolError::Exit(msg))); } }; @@ -85,12 +92,18 @@ impl DictWord { // See... with markdown link // (see *[abbha](/define/abbha)*) -> (see abbha) let re_see_markdown_links = Regex::new(r"\(see \*\[([^\]]+)\]\([^\)]+\)\**\)").unwrap(); - summary = re_see_markdown_links.replace_all(&summary, "(see $1)").trim().to_string(); + summary = re_see_markdown_links + .replace_all(&summary, "(see $1)") + .trim() + .to_string(); // markdown links // [abbha](/define/abbha) -> abbha let re_markdown_links = Regex::new(r"\[([^\]]+)\]\([^\)]+\)").unwrap(); - summary = re_markdown_links.replace_all(&summary, "$1").trim().to_string(); + summary = re_markdown_links + .replace_all(&summary, "$1") + .trim() + .to_string(); // remaining markdown markup: *, [] let re_markdown = Regex::new(r"[\*\[\]]").unwrap(); @@ -109,7 +122,10 @@ impl DictWord { // grammar abbr., with- or without dot, with- or without parens let re_abbr_one = Regex::new(r"^\(*(d|f|m|ṃ|n|r|s|t)\.*\)*\.*\b").unwrap(); let re_abbr_two = Regex::new(r"^\(*(ac|fn|id|mf|pl|pp|pr|sg|si)\.*\)*\.*\b").unwrap(); - let re_abbr_three = Regex::new(r"^\(*(abl|acc|act|adv|aor|dat|fpp|fut|gen|inc|ind|inf|loc|mfn|neg|opt)\.*\)*\.*\b").unwrap(); + let re_abbr_three = Regex::new( + r"^\(*(abl|acc|act|adv|aor|dat|fpp|fut|gen|inc|ind|inf|loc|mfn|neg|opt)\.*\)*\.*\b", + ) + .unwrap(); let re_abbr_four = Regex::new(r"^\(*(caus|part|pass|pron)\.*\)*\.*\b").unwrap(); let re_abbr_more = Regex::new(r"^\(*(absol|abstr|accus|compar|desid|feminine|impers|instr|masculine|neuter|plural|singular)\.*\)*\.*\b").unwrap(); @@ -209,7 +225,10 @@ impl DictWord { if !summary.is_empty() { let sum_length = 50; if summary.char_indices().count() > sum_length { - let (char_idx, _char) = summary.char_indices().nth(sum_length).ok_or("Bad char index")?; + let (char_idx, _char) = summary + .char_indices() + .nth(sum_length) + .ok_or("Bad char index")?; summary = summary[..char_idx].trim().to_string(); } @@ -244,4 +263,3 @@ impl Default for DictWordHeader { } } } - diff --git a/src/ebook.rs b/src/ebook.rs index fd6d257..998b637 100644 --- a/src/ebook.rs +++ b/src/ebook.rs @@ -1,19 +1,19 @@ use std::error::Error; -use std::process::Command; use std::fs::{self, File}; use std::io::{self, Write}; +use std::process::Command; use std::collections::BTreeMap; use std::path::PathBuf; -use walkdir::WalkDir; use handlebars::{self, Handlebars}; +use walkdir::WalkDir; -use crate::dict_word::{DictWord, DictWordHeader}; -use crate::letter_groups::LetterGroups; -use crate::helpers::{md2html, markdown_helper, is_hidden}; use crate::app::{AppStartParams, ZipWith}; +use crate::dict_word::{DictWord, DictWordHeader}; use crate::error::ToolError; +use crate::helpers::{is_hidden, markdown_helper, md2html}; +use crate::letter_groups::LetterGroups; pub const DICTIONARY_METADATA_SEP: &str = "--- DICTIONARY METADATA ---"; pub const DICTIONARY_WORD_ENTRIES_SEP: &str = "--- DICTIONARY WORD ENTRIES ---"; @@ -58,7 +58,7 @@ pub struct EbookMetadata { #[derive(Serialize, Deserialize, Copy, Clone)] pub enum EbookFormat { Epub, - Mobi + Mobi, } #[derive(Serialize, Deserialize)] @@ -80,59 +80,101 @@ impl Ebook { // Can't loop because the arg of include_str! must be a string literal. let k = "content-page.xhtml".to_string(); - afs.insert(k.clone(), include_str!("../assets/content-page.xhtml").to_string()); + afs.insert( + k.clone(), + include_str!("../assets/content-page.xhtml").to_string(), + ); reg_tmpl(&mut h, &k, &afs); let k = "about.md".to_string(); - afs.insert(k.clone(), include_str!("../assets/OEBPS/about.md").to_string()); + afs.insert( + k.clone(), + include_str!("../assets/OEBPS/about.md").to_string(), + ); reg_tmpl(&mut h, &k, &afs); let k = "copyright.md".to_string(); - afs.insert(k.clone(), include_str!("../assets/OEBPS/copyright.md").to_string()); + afs.insert( + k.clone(), + include_str!("../assets/OEBPS/copyright.md").to_string(), + ); reg_tmpl(&mut h, &k, &afs); let k = "entries-epub.xhtml".to_string(); - afs.insert(k.clone(), include_str!("../assets/OEBPS/entries-epub.xhtml").to_string()); + afs.insert( + k.clone(), + include_str!("../assets/OEBPS/entries-epub.xhtml").to_string(), + ); reg_tmpl(&mut h, &k, &afs); let k = "entries-mobi.xhtml".to_string(); - afs.insert(k.clone(), include_str!("../assets/OEBPS/entries-mobi.xhtml").to_string()); + afs.insert( + k.clone(), + include_str!("../assets/OEBPS/entries-mobi.xhtml").to_string(), + ); reg_tmpl(&mut h, &k, &afs); let k = "htmltoc.xhtml".to_string(); - afs.insert(k.clone(), include_str!("../assets/OEBPS/htmltoc.xhtml").to_string()); + afs.insert( + k.clone(), + include_str!("../assets/OEBPS/htmltoc.xhtml").to_string(), + ); reg_tmpl(&mut h, &k, &afs); let k = "toc.ncx".to_string(); - afs.insert(k.clone(), include_str!("../assets/OEBPS/toc.ncx").to_string()); + afs.insert( + k.clone(), + include_str!("../assets/OEBPS/toc.ncx").to_string(), + ); reg_tmpl(&mut h, &k, &afs); let k = "package.opf".to_string(); - afs.insert(k.clone(), include_str!("../assets/OEBPS/package.opf").to_string()); + afs.insert( + k.clone(), + include_str!("../assets/OEBPS/package.opf").to_string(), + ); reg_tmpl(&mut h, &k, &afs); let k = "cover.xhtml".to_string(); - afs.insert(k.clone(), include_str!("../assets/OEBPS/cover.xhtml").to_string()); + afs.insert( + k.clone(), + include_str!("../assets/OEBPS/cover.xhtml").to_string(), + ); reg_tmpl(&mut h, &k, &afs); let k = "titlepage.xhtml".to_string(); - afs.insert(k.clone(), include_str!("../assets/OEBPS/titlepage.xhtml").to_string()); + afs.insert( + k.clone(), + include_str!("../assets/OEBPS/titlepage.xhtml").to_string(), + ); reg_tmpl(&mut h, &k, &afs); - afb.insert("cover.jpg".to_string(), include_bytes!("../assets/OEBPS/cover.jpg").to_vec()); + afb.insert( + "cover.jpg".to_string(), + include_bytes!("../assets/OEBPS/cover.jpg").to_vec(), + ); - afb.insert("style.css".to_string(), include_bytes!("../assets/OEBPS/style.css").to_vec()); + afb.insert( + "style.css".to_string(), + include_bytes!("../assets/OEBPS/style.css").to_vec(), + ); - afb.insert("container.xml".to_string(), include_bytes!("../assets/META-INF/container.xml").to_vec()); + afb.insert( + "container.xml".to_string(), + include_bytes!("../assets/META-INF/container.xml").to_vec(), + ); - afb.insert("com.apple.ibooks.display-options.xml".to_string(), include_bytes!("../assets/META-INF/com.apple.ibooks.display-options.xml").to_vec()); + afb.insert( + "com.apple.ibooks.display-options.xml".to_string(), + include_bytes!("../assets/META-INF/com.apple.ibooks.display-options.xml").to_vec(), + ); let mut meta = EbookMetadata::default(); match ebook_format { EbookFormat::Epub => { meta.is_epub = true; meta.is_mobi = false; - }, + } EbookFormat::Mobi => { meta.is_epub = false; meta.is_mobi = true; @@ -156,10 +198,16 @@ impl Ebook { } pub fn add_word(&mut self, new_word: DictWord) { - let w_key = format!("{} {}", new_word.word_header.word, new_word.word_header.dict_label); + let w_key = format!( + "{} {}", + new_word.word_header.word, new_word.word_header.dict_label + ); if self.dict_words.contains_key(&w_key) { - warn!("Double word: '{}'. Entries should be unique for word within one dictionary.", &w_key); + warn!( + "Double word: '{}'. Entries should be unique for word within one dictionary.", + &w_key + ); let ww = DictWord { word_header: DictWordHeader { @@ -169,15 +217,17 @@ impl Ebook { grammar: new_word.word_header.grammar, inflections: new_word.word_header.inflections, }, - definition_md: new_word.definition_md + definition_md: new_word.definition_md, }; let ww_key = format!("{} double", &w_key); self.dict_words.insert(ww_key, ww); - } else { let w = self.dict_words.insert(w_key.clone(), new_word); if w.is_some() { - error!("Unhandled double word '{}', new value replacing the old.", w_key); + error!( + "Unhandled double word '{}', new value replacing the old.", + w_key + ); } } } @@ -243,7 +293,7 @@ impl Ebook { } else { p.to_path_buf() } - }, + } None => PathBuf::from("."), }; let build_base_dir = match parent.canonicalize() { @@ -251,15 +301,18 @@ impl Ebook { Err(e) => { let msg = format!("Can't canonicalize: {:?}\nError: {:?}", parent, e); return Err(Box::new(ToolError::Exit(msg))); - }, + } }; if !build_base_dir.exists() { match fs::create_dir(&build_base_dir) { - Ok(_) => {}, + Ok(_) => {} Err(e) => { - let msg = format!("Can't create directory: {:?}\nError: {:?}", build_base_dir, e); + let msg = format!( + "Can't create directory: {:?}\nError: {:?}", + build_base_dir, e + ); return Err(Box::new(ToolError::Exit(msg))); - }, + } }; } self.build_base_dir = Some(build_base_dir.clone()); @@ -298,7 +351,6 @@ impl Ebook { }; for (order_idx, group) in groups.groups.values_mut().enumerate() { - if order_idx == 0 { group.title = self.meta.title.clone(); } @@ -320,11 +372,10 @@ impl Ebook { // entries-00.xhtml, entries-01.xhtml and so on. let group_file_name = format!("entries-{:02}.xhtml", order_idx); - self.entries_manifest.push( - EntriesManifest { - id: format!("item_entries_{:02}", order_idx), - href: group_file_name.clone(), - }); + self.entries_manifest.push(EntriesManifest { + id: format!("item_entries_{:02}", order_idx), + href: group_file_name.clone(), + }); let dir = self.oebps_dir.as_ref().ok_or("missing oebps_dir")?; let mut file = File::create(dir.join(group_file_name))?; @@ -506,7 +557,10 @@ impl Ebook { let dir = self.oebps_dir.as_ref().ok_or("missing oebps_dir")?; for filename in ["cover.jpg", "style.css"].iter() { - let file_content = self.asset_files_byte.get(&filename.to_string()).ok_or("missing get key")?; + let file_content = self + .asset_files_byte + .get(&filename.to_string()) + .ok_or("missing get key")?; let mut file = File::create(dir.join(filename))?; file.write_all(file_content)?; } @@ -529,7 +583,10 @@ impl Ebook { let dir = self.meta_inf_dir.as_ref().ok_or("missing meta_inf_dir")?; for filename in ["container.xml", "com.apple.ibooks.display-options.xml"].iter() { - let file_content = self.asset_files_byte.get(&filename.to_string()).ok_or("missing get key")?; + let file_content = self + .asset_files_byte + .get(&filename.to_string()) + .ok_or("missing get key")?; let mut file = File::create(dir.join(filename))?; file.write_all(file_content)?; } @@ -561,7 +618,10 @@ impl Ebook { fn zip_with_shell(&self) -> Result<(), Box> { info!("zip_with_shell()"); - let d = self.build_base_dir.as_ref().ok_or("missing build_base_dir")?; + let d = self + .build_base_dir + .as_ref() + .ok_or("missing build_base_dir")?; let dir: &str = d.to_str().unwrap(); let n = self.output_path.file_name().ok_or("mising file_name")?; let epub_name: &str = n.to_str().unwrap(); @@ -597,7 +657,8 @@ impl Ebook { // mimetype file first, not compressed { - let o = zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Stored); + let o = zip::write::FileOptions::default() + .compression_method(zip::CompressionMethod::Stored); zip.start_file("mimetype", o)?; zip.write_all(b"application/epub+zip")?; } @@ -611,7 +672,11 @@ impl Ebook { let o = zip::write::FileOptions::default(); zip.start_file("META-INF/com.apple.ibooks.display-options.xml", o)?; - zip.write_all(self.asset_files_byte.get("com.apple.ibooks.display-options.xml").unwrap())?; + zip.write_all( + self.asset_files_byte + .get("com.apple.ibooks.display-options.xml") + .unwrap(), + )?; zip.start_file("META-INF/container.xml", o)?; zip.write_all(self.asset_files_byte.get("container.xml").unwrap())?; @@ -666,7 +731,11 @@ impl Ebook { } } - pub fn run_kindlegen(&self, kindlegen_path: &PathBuf, mobi_compression: usize) -> Result<(), Box> { + pub fn run_kindlegen( + &self, + kindlegen_path: &PathBuf, + mobi_compression: usize, + ) -> Result<(), Box> { info!("run_kindlegen()"); let oebps_dir = self.oebps_dir.as_ref().ok_or("missing oebps_dir")?; @@ -679,37 +748,39 @@ impl Ebook { } let output = if cfg!(target_os = "windows") { - match Command::new("cmd").arg("/C") + match Command::new("cmd") + .arg("/C") .arg(kindlegen_path) .arg(opf_path) .arg(format!("-c{}", mobi_compression)) .arg("-dont_append_source") .arg("-o") .arg(output_file_name) - .output() { - Ok(o) => o, - Err(e) => { - let msg = format!("🔥 Failed to run KindleGen: {:?}", e); - return Err(Box::new(ToolError::Exit(msg))); - } + .output() + { + Ok(o) => o, + Err(e) => { + let msg = format!("🔥 Failed to run KindleGen: {:?}", e); + return Err(Box::new(ToolError::Exit(msg))); } + } } else { // sh expects a command string after -c. - let cmd_string = format!("{} \"{}\" -c{} -dont_append_source -o \"{}\"", + let cmd_string = format!( + "{} \"{}\" -c{} -dont_append_source -o \"{}\"", kindlegen_path.to_str().unwrap(), opf_path.to_str().unwrap(), mobi_compression, - output_file_name.to_str().unwrap()); - - match Command::new("sh").arg("-c") - .arg(cmd_string) - .output() { - Ok(o) => o, - Err(e) => { - let msg = format!("🔥 Failed to run KindleGen: {:?}", e); - return Err(Box::new(ToolError::Exit(msg))); - } + output_file_name.to_str().unwrap() + ); + + match Command::new("sh").arg("-c").arg(cmd_string).output() { + Ok(o) => o, + Err(e) => { + let msg = format!("🔥 Failed to run KindleGen: {:?}", e); + return Err(Box::new(ToolError::Exit(msg))); } + } }; io::stdout().write_all(&output.stdout)?; @@ -752,7 +823,10 @@ impl Ebook { self.write_oebps_files()?; if !app_params.dont_run_kindlegen { - let kindlegen_path = &app_params.kindlegen_path.as_ref().ok_or("kindlegen_path is missing.")?; + let kindlegen_path = &app_params + .kindlegen_path + .as_ref() + .ok_or("kindlegen_path is missing.")?; self.run_kindlegen(&kindlegen_path, app_params.mobi_compression)?; } } @@ -790,4 +864,3 @@ impl Default for EbookMetadata { } } } - diff --git a/src/error.rs b/src/error.rs index 62918ec..0a8bb33 100644 --- a/src/error.rs +++ b/src/error.rs @@ -2,7 +2,7 @@ use std::error::Error; use std::{error, fmt}; pub enum ToolError { - Exit(String) + Exit(String), } impl fmt::Display for ToolError { diff --git a/src/helpers.rs b/src/helpers.rs index 2003962..bbb17d1 100644 --- a/src/helpers.rs +++ b/src/helpers.rs @@ -1,16 +1,22 @@ -use std::path::PathBuf; use std::error::Error; +use std::path::PathBuf; use std::process::exit; use std::thread::sleep; use std::time::Duration; +use handlebars::{Context, Handlebars, Helper, HelperResult, JsonRender, Output, RenderContext}; use regex::Regex; use walkdir::DirEntry; -use handlebars::{Handlebars, RenderContext, Helper, Context, JsonRender, HelperResult, Output}; use comrak::{markdown_to_html, ComrakOptions}; -pub fn markdown_helper(h: &Helper, _: &Handlebars, _: &Context, _rc: &mut RenderContext, out: &mut dyn Output) -> HelperResult { +pub fn markdown_helper( + h: &Helper, + _: &Handlebars, + _: &Context, + _rc: &mut RenderContext, + out: &mut dyn Output, +) -> HelperResult { let param = h.param(0).unwrap(); let html = md2html(param.value().render().as_ref()); out.write(&html)?; @@ -29,7 +35,8 @@ pub fn md2html(markdown: &str) -> String { } pub fn is_hidden(entry: &DirEntry) -> bool { - entry.file_name() + entry + .file_name() .to_str() .map(|s| s.starts_with('.')) .unwrap_or(false) diff --git a/src/letter_groups.rs b/src/letter_groups.rs index fcca422..06314d9 100644 --- a/src/letter_groups.rs +++ b/src/letter_groups.rs @@ -32,17 +32,19 @@ impl LetterGroups { } }; - groups.entry(key).or_insert(LetterGroup { - title: "".to_string(), - group_letter: first_letter, - letter_index: key, - dict_words: vec![i.clone()], - }).dict_words.push(i.clone()); - } - - LetterGroups { groups + .entry(key) + .or_insert(LetterGroup { + title: "".to_string(), + group_letter: first_letter, + letter_index: key, + dict_words: vec![i.clone()], + }) + .dict_words + .push(i.clone()); } + + LetterGroups { groups } } pub fn len(&self) -> usize { @@ -54,4 +56,3 @@ impl LetterGroups { k.is_empty() } } - diff --git a/src/main.rs b/src/main.rs index 7fa495c..af87237 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,8 +7,8 @@ extern crate serde_derive; extern crate serde_json; extern crate toml; -extern crate zip; extern crate html2md; +extern crate zip; #[macro_use] extern crate log; @@ -18,18 +18,18 @@ extern crate kankyo; extern crate clap; extern crate chrono; -extern crate handlebars; extern crate comrak; +extern crate handlebars; use clap::App; pub mod app; -pub mod ebook; pub mod dict_word; -pub mod letter_groups; -pub mod pali; +pub mod ebook; pub mod error; pub mod helpers; +pub mod letter_groups; +pub mod pali; use std::process::exit; @@ -75,12 +75,18 @@ fn main() { } RunCommand::SuttaCentralJsonToMarkdown => { - let p = &app_params.markdown_paths.expect("markdown_path is missing."); + let p = &app_params + .markdown_paths + .expect("markdown_path is missing."); let output_markdown_path = p.get(0).unwrap().to_path_buf(); let mut ebook = Ebook::new(app_params.ebook_format, &output_markdown_path); - app::process_suttacentral_json(&app_params.json_path, &app_params.dict_label, &mut ebook); + app::process_suttacentral_json( + &app_params.json_path, + &app_params.dict_label, + &mut ebook, + ); for (_key, word) in ebook.dict_words.iter_mut() { ok_or_exit(app_params.used_first_arg, word.clean_summary()); @@ -92,12 +98,18 @@ fn main() { } RunCommand::NyanatilokaToMarkdown => { - let p = &app_params.markdown_paths.expect("markdown_path is missing."); + let p = &app_params + .markdown_paths + .expect("markdown_path is missing."); let output_markdown_path = p.get(0).unwrap().to_path_buf(); let mut ebook = Ebook::new(app_params.ebook_format, &output_markdown_path); - app::process_nyanatiloka_entries(&app_params.nyanatiloka_root, &app_params.dict_label, &mut ebook); + app::process_nyanatiloka_entries( + &app_params.nyanatiloka_root, + &app_params.dict_label, + &mut ebook, + ); for (_key, word) in ebook.dict_words.iter_mut() { ok_or_exit(app_params.used_first_arg, word.clean_summary()); @@ -117,7 +129,10 @@ fn main() { let p = paths.expect("markdown_paths is missing."); let markdown_paths = p.to_vec(); - ok_or_exit(app_params.used_first_arg, app::process_markdown_list(markdown_paths, &mut ebook)); + ok_or_exit( + app_params.used_first_arg, + app::process_markdown_list(markdown_paths, &mut ebook), + ); info!("Added words: {}", ebook.len()); diff --git a/src/pali.rs b/src/pali.rs index 86a9ffa..dbad8f7 100644 --- a/src/pali.rs +++ b/src/pali.rs @@ -24,7 +24,10 @@ const ROMANIZED_PALI_ALPHABET: &str = "a ā b bh c ch d dh ḍ ḍh e f g gh h i const RPA_DOUBLES_FIRST: &str = "bh ch dh ḍh gh jh kh ph th ṭh a ā b c d ḍ e f g h i ī j k l ḷ m ṃ n ṅ ṇ ñ o p q r s t ṭ u ū v w x y z"; pub fn romanized_pali_letter_index(word: &str) -> usize { - let alphabet: Vec = ROMANIZED_PALI_ALPHABET.split(' ').map(String::from).collect(); + let alphabet: Vec = ROMANIZED_PALI_ALPHABET + .split(' ') + .map(String::from) + .collect(); let word_clean = word.trim().to_lowercase(); match first_letter(&word_clean) { @@ -32,7 +35,7 @@ pub fn romanized_pali_letter_index(word: &str) -> usize { Ok(x) => x, Err(_) => alphabet.len(), }, - None => alphabet.len() + None => alphabet.len(), } } @@ -42,10 +45,9 @@ pub fn first_letter(word: &str) -> Option { for i in doubles_first.iter() { if word_clean.starts_with(*i) { - return Some(String::from(*i)) + return Some(String::from(*i)); } } None } -