Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Drinks - DRY Links Proof of Concept #2332

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/book/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ impl BookBuilder {

self.write_book_toml()?;

self.write_drinks_txt()?;

match MDBook::load(&self.root) {
Ok(book) => Ok(book),
Err(e) => {
Expand All @@ -108,6 +110,18 @@ impl BookBuilder {
Ok(())
}

fn write_drinks_txt(&self) -> Result<()> {
debug!("Writing drinks.txt");
let drinks_txt = self.root.join("drinks.txt");
let entry = "hello: https://world.org";

File::create(drinks_txt)
.with_context(|| "Couldn't create drinks.txt")?
.write_all(&entry.as_bytes())
.with_context(|| "Unable to write entry to drinks.txt")?;
Ok(())
}

fn copy_across_theme(&self) -> Result<()> {
debug!("Copying theme");

Expand Down
13 changes: 8 additions & 5 deletions src/book/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ use topological_sort::TopologicalSort;

use crate::errors::*;
use crate::preprocess::{
CmdPreprocessor, IndexPreprocessor, LinkPreprocessor, Preprocessor, PreprocessorContext,
CmdPreprocessor, DrinkPreprocessor, IndexPreprocessor, LinkPreprocessor, Preprocessor,
PreprocessorContext,
};
use crate::renderer::{CmdRenderer, HtmlHandlebars, MarkdownRenderer, RenderContext, Renderer};
use crate::utils;
Expand Down Expand Up @@ -432,7 +433,7 @@ fn determine_renderers(config: &Config) -> Vec<Box<dyn Renderer>> {
renderers
}

const DEFAULT_PREPROCESSORS: &[&str] = &["links", "index"];
const DEFAULT_PREPROCESSORS: &[&str] = &["drinks", "links", "index"];

fn is_default_preprocessor(pre: &dyn Preprocessor) -> bool {
let name = pre.name();
Expand Down Expand Up @@ -533,6 +534,7 @@ fn determine_preprocessors(config: &Config) -> Result<Vec<Box<dyn Preprocessor>>
names.sort();
for name in names {
let preprocessor: Box<dyn Preprocessor> = match name.as_str() {
"drinks" => Box::new(DrinkPreprocessor::new()),
"links" => Box::new(LinkPreprocessor::new()),
"index" => Box::new(IndexPreprocessor::new()),
_ => {
Expand Down Expand Up @@ -660,9 +662,10 @@ mod tests {
let got = determine_preprocessors(&cfg);

assert!(got.is_ok());
assert_eq!(got.as_ref().unwrap().len(), 2);
assert_eq!(got.as_ref().unwrap()[0].name(), "index");
assert_eq!(got.as_ref().unwrap()[1].name(), "links");
assert_eq!(got.as_ref().unwrap().len(), 3);
assert_eq!(got.as_ref().unwrap()[0].name(), "drinks");
assert_eq!(got.as_ref().unwrap()[1].name(), "index");
assert_eq!(got.as_ref().unwrap()[2].name(), "links");
}

#[test]
Expand Down
83 changes: 83 additions & 0 deletions src/preprocess/drinks.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
use crate::errors::*;

use super::{Preprocessor, PreprocessorContext};
use crate::book::{Book, BookItem, Chapter};
use once_cell::sync::Lazy;
use regex::{Captures, Regex};
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader};

const SPLITTER: char = ':';

type Dict = HashMap<String, String>;

/// DRY Links - A preprocessor for using centralized links collection:
///
/// - `{{# drink}}` - Insert link from the collection
#[derive(Default)]
pub struct DrinkPreprocessor;

impl DrinkPreprocessor {
pub(crate) const NAME: &'static str = "drinks";

/// Create a new `DrinkPreprocessor`.
pub fn new() -> Self {
DrinkPreprocessor
}

fn replace_drinks(&self, chapter: &mut Chapter, dict: &Dict) -> Result<String, Error> {
static RE: Lazy<Regex> = Lazy::new(|| {
Regex::new(
r"(?x) # insignificant whitespace mode
\{\{\s* # link opening parens and whitespace
\#(drink) # drink marker
\s+ # separating whitespace
(?<drink>[A-z0-9_-]+) # drink name
\}\} # link closing parens",
)
.unwrap()
});

static NODRINK: Lazy<String> = Lazy::new(|| "deadbeef".to_string());

let res = RE.replace_all(&chapter.content, |caps: &Captures<'_>| {
dict.get(&caps["drink"]).unwrap_or(&NODRINK)
});
Ok(res.to_string())
}
}

impl Preprocessor for DrinkPreprocessor {
fn name(&self) -> &str {
Self::NAME
}

fn run(&self, ctx: &PreprocessorContext, mut book: Book) -> Result<Book> {
let path = ctx.root.join("drinks.txt");

if !path.exists() {
return Ok(book);
}

let reader = BufReader::new(File::open(path).expect("Cannot open drinks dictionary"));
let drinks: Dict = reader
.lines()
.filter_map(|l| {
l.expect("Cannot read line in drinks dictionary")
.split_once(SPLITTER)
.map(|(name, value)| (name.trim().to_owned(), value.trim().to_owned()))
})
.collect::<HashMap<_, _>>();

book.for_each_mut(|section: &mut BookItem| {
if let BookItem::Chapter(ref mut ch) = *section {
ch.content = self
.replace_drinks(ch, &drinks)
.expect("Error converting drinks into links for chapter");
}
});

Ok(book)
}
}
2 changes: 2 additions & 0 deletions src/preprocess/mod.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
//! Book preprocessing.

pub use self::cmd::CmdPreprocessor;
pub use self::drinks::DrinkPreprocessor;
pub use self::index::IndexPreprocessor;
pub use self::links::LinkPreprocessor;

mod cmd;
mod drinks;
mod index;
mod links;

Expand Down
Loading