Skip to content

Adding LinksPreprocessor for SUMMARY.md #2172

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

Open
wants to merge 2 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
12 changes: 6 additions & 6 deletions src/book/book.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use std::path::{Path, PathBuf};
use super::summary::{parse_summary, Link, SectionNumber, Summary, SummaryItem};
use crate::config::BuildConfig;
use crate::errors::*;
use crate::preprocess::SummaryPreprocessor;
use crate::utils::bracket_escape;
use log::debug;
use serde::{Deserialize, Serialize};
Expand All @@ -21,7 +22,9 @@ pub fn load_book<P: AsRef<Path>>(src_dir: P, cfg: &BuildConfig) -> Result<Book>
.with_context(|| format!("Couldn't open SUMMARY.md in {:?} directory", src_dir))?
.read_to_string(&mut summary_content)?;

let summary = parse_summary(&summary_content)
let preprocessed_summary_content = SummaryPreprocessor::resolve(src_dir, &summary_content);

let summary = parse_summary(&preprocessed_summary_content)
.with_context(|| format!("Summary parsing failed for file={:?}", summary_md))?;

if cfg.create_missing {
Expand Down Expand Up @@ -75,10 +78,10 @@ fn create_missing(src_dir: &Path, summary: &Summary) -> Result<()> {
/// [`iter()`]: #method.iter
/// [`for_each_mut()`]: #method.for_each_mut
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Book {
/// The sections in this book.
pub sections: Vec<BookItem>,
__non_exhaustive: (),
}

impl Book {
Expand Down Expand Up @@ -226,10 +229,7 @@ pub(crate) fn load_book_from_disk<P: AsRef<Path>>(summary: &Summary, src_dir: P)
chapters.push(chapter);
}

Ok(Book {
sections: chapters,
__non_exhaustive: (),
})
Ok(Book { sections: chapters })
}

fn load_summary_item<P: AsRef<Path> + Clone>(
Expand Down
2 changes: 1 addition & 1 deletion src/book/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -839,7 +839,7 @@ mod tests {
.and_then(Value::as_str)
.unwrap();
assert_eq!(html, "html");
let html_renderer = HtmlHandlebars::default();
let html_renderer = HtmlHandlebars;
let pre = LinkPreprocessor::new();

let should_run = preprocessor_should_run(&pre, &html_renderer, &cfg);
Expand Down
4 changes: 1 addition & 3 deletions src/book/summary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -566,9 +566,7 @@ fn get_last_link(links: &mut [SummaryItem]) -> Result<(usize, &mut Link)> {
links
.iter_mut()
.enumerate()
.filter_map(|(i, item)| item.maybe_link_mut().map(|l| (i, l)))
.rev()
.next()
.filter_map(|(i, item)| item.maybe_link_mut().map(|l| (i, l))).next_back()
.ok_or_else(||
anyhow::anyhow!("Unable to get last link because the list of SummaryItems doesn't contain any Links")
)
Expand Down
10 changes: 1 addition & 9 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -646,21 +646,13 @@ impl Default for Playground {
}

/// Configuration for tweaking how the the HTML renderer handles code blocks.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "kebab-case")]
pub struct Code {
/// A prefix string to hide lines per language (one or more chars).
pub hidelines: HashMap<String, String>,
}

impl Default for Code {
fn default() -> Code {
Code {
hidelines: HashMap::new(),
}
}
}

/// Configuration of the search functionality of the HTML renderer.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "kebab-case")]
Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ fn main() {
fn create_clap_command() -> Command {
let app = Command::new(crate_name!())
.about(crate_description!())
.author("Mathieu David <[email protected]>")
.author("Mathieu David <[email protected]> and edited by Mauro Gentile <[email protected]>")
.version(VERSION)
.propagate_version(true)
.arg_required_else_help(true)
Expand Down
2 changes: 1 addition & 1 deletion src/preprocess/links.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ impl Preprocessor for LinkPreprocessor {
}
}

fn replace_all<P1, P2>(
pub(crate) fn replace_all<P1, P2>(
s: &str,
path: P1,
source: P2,
Expand Down
2 changes: 2 additions & 0 deletions src/preprocess/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@
pub use self::cmd::CmdPreprocessor;
pub use self::index::IndexPreprocessor;
pub use self::links::LinkPreprocessor;
pub use self::summary::SummaryPreprocessor;

mod cmd;
mod index;
mod links;
mod summary;

use crate::book::Book;
use crate::config::Config;
Expand Down
13 changes: 13 additions & 0 deletions src/preprocess/summary.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
use std::path::Path;

/// A preprocessor dedicated just to the summary to resolve links
#[derive(Default)]
pub struct SummaryPreprocessor;

impl SummaryPreprocessor {
/// Preprocess Summary to resolve links.
pub fn resolve(src_dir: &Path, content: &str) -> String {
let mut title = String::from("SUMMARY.md");
super::links::replace_all(content, src_dir, src_dir, 0, &mut title)
}
}
2 changes: 1 addition & 1 deletion src/renderer/html_handlebars/hbs_renderer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -823,7 +823,7 @@ fn build_header_links(html: &str) -> String {

// Ignore .menu-title because now it's getting detected by the regex.
if let Some(classes) = caps.get(3) {
for class in classes.as_str().split(" ") {
for class in classes.as_str().split(' ') {
if IGNORE_CLASS.contains(&class) {
return caps[0].to_string();
}
Expand Down
14 changes: 6 additions & 8 deletions src/utils/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,12 @@ pub fn create_file(path: &Path) -> Result<File> {

/// Removes all the content of a directory but not the directory itself
pub fn remove_dir_content(dir: &Path) -> Result<()> {
for item in fs::read_dir(dir)? {
if let Ok(item) = item {
let item = item.path();
if item.is_dir() {
fs::remove_dir_all(item)?;
} else {
fs::remove_file(item)?;
}
for item in (fs::read_dir(dir)?).flatten() {
let item = item.path();
if item.is_dir() {
fs::remove_dir_all(item)?;
} else {
fs::remove_file(item)?;
}
}
Ok(())
Expand Down
4 changes: 2 additions & 2 deletions tests/custom_preprocessors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ fn example_supports_whatever() {

let got = cmd.supports_renderer("whatever");

assert_eq!(got, true);
assert!(got);
}

#[test]
Expand All @@ -26,7 +26,7 @@ fn example_doesnt_support_not_supported() {

let got = cmd.supports_renderer("not-supported");

assert_eq!(got, false);
assert!(!got);
}

#[test]
Expand Down
2 changes: 1 addition & 1 deletion tests/rendered_output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -966,5 +966,5 @@ fn custom_header_attributes() {
r##"<h2 id="heading-with-classes" class="class1 class2"><a class="header" href="#heading-with-classes">Heading with classes</a></h2>"##,
r##"<h2 id="both" class="class1 class2"><a class="header" href="#both">Heading with id and classes</a></h2>"##,
];
assert_contains_strings(&contents, summary_strings);
assert_contains_strings(contents, summary_strings);
}