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

Feature/links preprocessor #2103

Closed
wants to merge 107 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
107 commits
Select commit Hold shift + click to select a range
6f53f5a
added ability to clone preprocessors
blandger Nov 5, 2020
4da0928
added logging
blandger Nov 14, 2020
25e7316
added conditional execution
blandger Nov 16, 2020
e32d44b
little info on run
blandger Nov 21, 2020
b0f2ce0
added book version
blandger Nov 24, 2020
da29794
removed DEBUG, added book 'version' field, updated unit tests
blandger Nov 25, 2020
f28f601
added comments
blandger Nov 25, 2020
50e4874
Merge remote-tracking branch 'upstream/master'
blandger Dec 2, 2020
b243d8b
Merge remote-tracking branch 'upstream/master'
blandger Jan 5, 2021
81c9e36
Merge remote-tracking branch 'upstream/master'
blandger Jan 26, 2021
09f1312
Merge remote-tracking branch 'upstream/master'
blandger Feb 15, 2021
6ac4f97
Merge remote-tracking branch 'upstream/master'
blandger Feb 27, 2021
379425d
Merge remote-tracking branch 'upstream/master'
blandger Apr 26, 2021
81a6691
Merge remote-tracking branch 'upstream/master'
blandger Apr 26, 2021
93e6987
After Merge remote-tracking branch 'upstream/master' # Conflicts: # …
blandger Apr 26, 2021
93b59d4
Merge remote-tracking branch 'upstream/master'
blandger May 2, 2021
b082410
Merge remote-tracking branch 'upstream/master'
blandger May 4, 2021
0960c8a
Merge branch 'rust-lang:master' into master
blandger May 10, 2021
cfaac37
Merge branch 'rust-lang:master' into master
blandger May 11, 2021
2ab85da
Merge branch 'rust-lang:master' into master
blandger May 21, 2021
ad141b6
Add useful messages when command line preprocessor fails
apatniv May 8, 2021
b1ae768
Apply max width to video as well as images
ISSOtm May 23, 2021
9e3651c
use semver to validate version
joshrotenberg Apr 26, 2021
e85c23c
add semver v0.11.0 for example
joshrotenberg Apr 26, 2021
eff809e
report book.toml parse errors
joshrotenberg May 19, 2021
d0b5bcb
Update src/config.rs
joshrotenberg May 24, 2021
5acd6ff
update build and rust config change
joshrotenberg May 24, 2021
399d7ad
Mention missing file creation in build/watch/serve's docs (#1548)
ISSOtm May 25, 2021
6b5eb9d
restructure guide configuration section
joshrotenberg May 24, 2021
861ac26
use panic::set_hook to exit
joshrotenberg May 28, 2021
c5ae5fd
book: use non_exhaustive attribute for struct Book
xrmx May 30, 2021
22ea514
book: simplify is_draft_chapter
xrmx May 30, 2021
bc3406c
renderer: remove redundant clone in CmdRenderer
xrmx May 30, 2021
904a14e
clippy: PathBuf to Path
joshrotenberg Jun 1, 2021
ffed4e4
use book_config.src for edit path
joshrotenberg May 28, 2021
417a152
Update to 0.4.9
ehuss Jun 2, 2021
256fb23
Fix typo in documentation
tfidfwastaken Jun 5, 2021
5983e56
update handlebars to 4.0
sunng87 May 26, 2021
508cd3c
bump msrv to 1.45 as handlebars 4.0 requires
sunng87 May 28, 2021
9a2181e
doc clarification on markdown list markers
joshrotenberg Jun 5, 2021
b75912b
Revert "book: use non_exhaustive attribute for struct Book"
joshrotenberg Jun 8, 2021
24ea4ab
Remove chapter_begin id from print output.
ehuss May 22, 2021
876c07d
Update to 0.4.10
ehuss Jun 8, 2021
5dea52a
Fix inconsistent between bash version and rust version of the sample
tuyen-at-work Jun 19, 2021
8f1f735
Update renderers.md
fritsstegmann Jul 4, 2021
2329881
clarify the library path documentation
joshrotenberg Jun 25, 2021
bb241b1
fix link
joshrotenberg Jun 25, 2021
6b5fe97
first pass at 2021 support
joshrotenberg Jul 4, 2021
a434845
add edition2021 as an option
joshrotenberg Jul 4, 2021
f2a3bf3
remove debugging
joshrotenberg Jul 5, 2021
3bb7da5
Add ability to generate shell completions via clap
alexmaco Jan 4, 2021
03e6302
MyPaths are not required and fail
xyl012 Jun 11, 2021
315d912
Add comments to edit in case of custom book path
xyl012 Jul 4, 2021
c73df40
Update continuous-integration.md
xyl012 Jul 4, 2021
1f98b7f
add init flags
joshrotenberg Jun 1, 2021
83d8768
drop short flags
joshrotenberg Jul 4, 2021
2f767ab
ignore now takes a value
joshrotenberg Jul 4, 2021
2849fd0
format
joshrotenberg Jul 4, 2021
47e7dce
Update CLI docs for flag name change.
ehuss Jul 6, 2021
0a64073
feat(playground): show "No output" on playgrounds that print nothing
notriddle Jul 7, 2021
55ffcf9
Support space as seperator between language and additional class in c…
tuyen-at-work Feb 21, 2021
79ecade
Update mod.rs
tuyen-at-work Feb 21, 2021
36cc9f6
Split lang on tab to be consistent with rustdoc and GitHub.
ehuss Jul 10, 2021
55a90c0
Merge remote-tracking branch 'upstream/master'
blandger Sep 26, 2021
74560c7
Merge branch 'rust-lang:master' into master
blandger Dec 25, 2021
73dc4ff
Merge branch 'rust-lang:master' into master
blandger Jan 1, 2022
957d6f9
Merge branch 'rust-lang:master' into master
blandger Jan 21, 2022
76f300a
Merge branch 'rust-lang:master' into master
blandger Feb 17, 2022
fb548f8
Merge branch 'rust-lang:master' into master
blandger Jun 21, 2022
3d76a7d
Merge remote-tracking branch 'upstream/master'
blandger Dec 23, 2022
0376053
Merge remote-tracking branch 'upstream/master'
blandger Dec 25, 2022
dc4dba8
added use macros
blandger Dec 25, 2022
9746789
synched with upstream
blandger Dec 25, 2022
8477c66
Merge branch 'rust-lang:master' into master
blandger Jan 18, 2023
e8b8861
Merge branch 'master' into feature/links_preprocessor
blandger Jan 18, 2023
713fc03
Merge branch 'rust-lang:master' into master
blandger Feb 19, 2023
3b0ad70
Merge branch 'rust-lang:master' into master
blandger Mar 5, 2023
29375e9
Merge remote-tracking branch 'origin/master'
blandger Apr 16, 2023
4f01e38
Merge branch 'master' into feature/links_preprocessor
blandger Apr 16, 2023
4ced46f
import clean up
blandger Apr 16, 2023
3dbe972
sparse registry
blandger Apr 16, 2023
e465990
version was lost, added back
blandger Apr 16, 2023
b3f0d14
restored functionality
blandger Apr 17, 2023
592bb92
RESTORED ! one chapter processing functionality
blandger Apr 17, 2023
4a4126a
version bump to 0.4.28
blandger Apr 17, 2023
81fd18c
Merge remote-tracking branch 'origin/master'
blandger May 22, 2023
ae05d60
version bump to 0.4.29
blandger May 22, 2023
b3f2d98
minor log
blandger May 25, 2023
2c7324a
Merge remote-tracking branch 'origin/master'
blandger May 29, 2023
2b12ee6
Merge branch 'master' into feature/links_preprocessor
blandger May 29, 2023
d848fa8
Merge remote-tracking branch 'origin/master'
blandger Jun 20, 2023
0e91901
Merge branch 'master' into feature/links_preprocessor
blandger Jun 20, 2023
27f536d
minor compiler version update
blandger Jun 20, 2023
8fafdda
sparse is not needed anymore
blandger Jun 20, 2023
b451ce6
rust bump to 1.70.0
blandger Jun 21, 2023
a3dfc84
rust fmt fixes
blandger Jun 21, 2023
91e3408
Merge remote-tracking branch 'origin/master'
blandger Jul 2, 2023
7e5accc
Merge branch 'master' into feature/links_preprocessor
blandger Jul 2, 2023
94c6036
Merge remote-tracking branch 'origin/master'
blandger Jul 17, 2023
e473ec0
Merge remote-tracking branch 'origin/master'
blandger Jul 24, 2023
5b9c593
merged master, bump 0.4.32
blandger Jul 24, 2023
364f32d
Merge remote-tracking branch 'origin/master'
blandger Aug 4, 2023
7780533
Merge branch 'master' into feature/links_preprocessor
blandger Aug 4, 2023
4a5d2a3
Merge remote-tracking branch 'origin/master'
blandger Aug 7, 2023
2a7110f
Merge branch 'master' into feature/links_preprocessor
blandger Aug 7, 2023
7e438ed
Merge remote-tracking branch 'origin/master'
blandger Sep 30, 2023
8e6bfa8
merged master, bump 0.4.35
blandger Oct 8, 2023
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
2 changes: 1 addition & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ jobs:
- build: msrv
os: ubuntu-20.04
# sync MSRV with docs: guide/src/guide/installation.md and Cargo.toml
rust: 1.66.0
rust: 1.71.0
steps:
- uses: actions/checkout@v3
- name: Install Rust
Expand Down
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ license = "MPL-2.0"
readme = "README.md"
repository = "https://github.com/rust-lang/mdBook"
description = "Creates a book from markdown files"
rust-version = "1.66"
rust-version = "1.71"

[dependencies]
anyhow = "1.0.71"
Expand Down
1 change: 1 addition & 0 deletions examples/nop-preprocessor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ mod nop_lib {
use super::*;

/// A no-op preprocessor.
#[derive(Clone)]
pub struct Nop;

impl Nop {
Expand Down
6 changes: 6 additions & 0 deletions src/book/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,11 @@ impl MDBook {
.unwrap_or_default()
.theme_dir(&self.root)
}

/// Clone registered boxed preprocessors Vec
pub fn clone_preprocessors(&self) -> Vec<Box<dyn Preprocessor>> {
self.preprocessors.clone()
}
}

/// Look at the `Config` and try to figure out what renderers to use.
Expand Down Expand Up @@ -846,6 +851,7 @@ mod tests {
assert!(should_run);
}

#[derive(Default, Clone)]
struct BoolPreprocessor(bool);
impl Preprocessor for BoolPreprocessor {
fn name(&self) -> &str {
Expand Down
5 changes: 5 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,8 @@ pub struct BookConfig {
/// The direction of text in the book: Left-to-right (LTR) or Right-to-left (RTL).
/// When not specified, the text direction is derived from [`BookConfig::language`].
pub text_direction: Option<TextDirection>,
/// The book version.
pub version: Option<String>,
}

impl Default for BookConfig {
Expand All @@ -426,6 +428,7 @@ impl Default for BookConfig {
multilingual: false,
language: Some(String::from("en")),
text_direction: None,
version: Some(String::from("0.0.1")),
}
}
}
Expand Down Expand Up @@ -789,6 +792,7 @@ mod tests {
multilingual = true
src = "source"
language = "ja"
version = "0.0.1"

[build]
build-dir = "outputs"
Expand Down Expand Up @@ -829,6 +833,7 @@ mod tests {
src: PathBuf::from("source"),
language: Some(String::from("ja")),
text_direction: None,
version: Some(String::from("0.0.1")),
};
let build_should_be = BuildConfig {
build_dir: PathBuf::from("outputs"),
Expand Down
2 changes: 1 addition & 1 deletion src/preprocess/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use once_cell::sync::Lazy;

/// A preprocessor for converting file name `README.md` to `index.md` since
/// `README.md` is the de facto index file in markdown-based documentation.
#[derive(Default)]
#[derive(Default, Clone)]
pub struct IndexPreprocessor;

impl IndexPreprocessor {
Expand Down
83 changes: 73 additions & 10 deletions src/preprocess/links.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ use std::ops::{Bound, Range, RangeBounds, RangeFrom, RangeFull, RangeTo};
use std::path::{Path, PathBuf};

use super::{Preprocessor, PreprocessorContext};
use crate::book::{Book, BookItem};
use log::{error, warn};
use crate::book::{Book, BookItem, Chapter};
use log::{error, trace, warn};
use once_cell::sync::Lazy;

const ESCAPE_CHAR: char = '\\';
Expand All @@ -26,7 +26,7 @@ const MAX_LINK_NESTED_DEPTH: usize = 10;
/// block and provides them to Rustdoc for testing.
/// - `{{# playground}}` - Insert runnable Rust files
/// - `{{# title}}` - Override \<title\> of a webpage.
#[derive(Default)]
#[derive(Default, Clone)]
pub struct LinkPreprocessor;

impl LinkPreprocessor {
Expand Down Expand Up @@ -55,8 +55,15 @@ impl Preprocessor for LinkPreprocessor {
.expect("All book items have a parent");

let mut chapter_title = ch.name.clone();
let content =
replace_all(&ch.content, base, chapter_path, 0, &mut chapter_title);
// run normal link replacement by all content with 'dashed' lines inside present
let content = replace_all(
&ch.content,
base,
chapter_path,
0,
&mut chapter_title,
false,
);
ch.content = content;
if chapter_title != ch.name {
ctx.chapter_titles
Expand All @@ -69,6 +76,34 @@ impl Preprocessor for LinkPreprocessor {

Ok(book)
}

/// Pre-process one chapter's content by supplied preprocessor
fn preprocess_chapter(&self, ctx: &PreprocessorContext, chapter: &mut Chapter) -> Result<()> {
if let Some(ref chapter_path) = chapter.path {
let src_dir = ctx.root.join(&ctx.config.book.src);
trace!("src_dir = {:?}", &src_dir.display());
let base = chapter_path
.parent()
.map(|dir| src_dir.join(dir))
.expect("All book items have a parent");

trace!("base = {:?}", &base.display());
let mut chapter_title = chapter.name.clone();
// replace link {{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs:print}}
// by lined content with removing # dashed lines
let updated_content = replace_all(
&chapter.content.clone(),
base,
chapter_path,
0,
&mut chapter_title,
true,
);
trace!("updated_content = {:?}", updated_content.len());
chapter.content = updated_content;
}
Ok(())
}
}

fn replace_all<P1, P2>(
Expand All @@ -77,6 +112,7 @@ fn replace_all<P1, P2>(
source: P2,
depth: usize,
chapter_title: &mut String,
cutoff_commented_lines: bool,
) -> String
where
P1: AsRef<Path>,
Expand All @@ -93,7 +129,7 @@ where
for link in find_links(s) {
replaced.push_str(&s[previous_end_index..link.start_index]);

match link.render_with_path(path, chapter_title) {
match link.render_with_path(path, chapter_title, cutoff_commented_lines) {
Ok(new_content) => {
if depth < MAX_LINK_NESTED_DEPTH {
if let Some(rel_path) = link.link_type.relative_path(path) {
Expand All @@ -103,6 +139,7 @@ where
source,
depth + 1,
chapter_title,
cutoff_commented_lines,
));
} else {
replaced.push_str(&new_content);
Expand Down Expand Up @@ -323,6 +360,7 @@ impl<'a> Link<'a> {
&self,
base: P,
chapter_title: &mut String,
cutoff_commented_lines: bool,
) -> Result<String> {
let base = base.as_ref();
match self.link_type {
Expand Down Expand Up @@ -350,10 +388,10 @@ impl<'a> Link<'a> {
fs::read_to_string(&target)
.map(|s| match range_or_anchor {
RangeOrAnchor::Range(range) => {
take_rustdoc_include_lines(&s, range.clone())
take_rustdoc_include_lines(&s, range.clone(), cutoff_commented_lines)
}
RangeOrAnchor::Anchor(anchor) => {
take_rustdoc_include_anchored_lines(&s, anchor)
take_rustdoc_include_anchored_lines(&s, anchor, cutoff_commented_lines)
}
})
.with_context(|| {
Expand Down Expand Up @@ -444,7 +482,29 @@ mod tests {
{{#include file.rs}} << an escaped link!
```";
let mut chapter_title = "test_replace_all_escaped".to_owned();
assert_eq!(replace_all(start, "", "", 0, &mut chapter_title), end);
assert_eq!(
replace_all(start, "", "", 0, &mut chapter_title, false),
end
);
}

#[test]
fn test_replace_all_escaped_with_cutoff() {
let start = r"
Some text over here.
```hbs
\{{#include file.rs}} << an escaped link!
```";
let end = r"
Some text over here.
```hbs
{{#include file.rs}} << an escaped link!
```";
let mut chapter_title = "test_replace_all_escaped_with_cutoff".to_owned();
assert_eq!(
replace_all(start, "", "", 0, &mut chapter_title, false),
end
);
}

#[test]
Expand All @@ -456,7 +516,10 @@ mod tests {
# My Chapter
";
let mut chapter_title = "test_set_chapter_title".to_owned();
assert_eq!(replace_all(start, "", "", 0, &mut chapter_title), end);
assert_eq!(
replace_all(start, "", "", 0, &mut chapter_title, false),
end
);
assert_eq!(chapter_title, "My Title");
}

Expand Down
34 changes: 31 additions & 3 deletions src/preprocess/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ mod cmd;
mod index;
mod links;

use crate::book::Book;
use crate::book::{Book, Chapter};
use crate::config::Config;
use crate::errors::*;

Expand Down Expand Up @@ -37,7 +37,7 @@ pub struct PreprocessorContext {

impl PreprocessorContext {
/// Create a new `PreprocessorContext`.
pub(crate) fn new(root: PathBuf, config: Config, renderer: String) -> Self {
pub fn new(root: PathBuf, config: Config, renderer: String) -> Self {
PreprocessorContext {
root,
config,
Expand All @@ -51,14 +51,23 @@ impl PreprocessorContext {

/// An operation which is run immediately after loading a book into memory and
/// before it gets rendered.
pub trait Preprocessor {
pub trait Preprocessor: PreprocessorClone {
/// Get the `Preprocessor`'s name.
fn name(&self) -> &str;

/// Run this `Preprocessor`, allowing it to update the book before it is
/// given to a renderer.
fn run(&self, ctx: &PreprocessorContext, book: Book) -> Result<Book>;

/// Pre-Process only one mutable chapter using context and supplied pre-processor
fn preprocess_chapter(&self, ctx: &PreprocessorContext, chapter: &mut Chapter) -> Result<()> {
println!(
"preprocess chapter: '{}' by ctx = {}",
chapter.name, ctx.renderer
);
Ok(())
}

/// A hint to `MDBook` whether this preprocessor is compatible with a
/// particular renderer.
///
Expand All @@ -67,3 +76,22 @@ pub trait Preprocessor {
true
}
}

/// That is the code to have ability to clone vec[Preprocessor]
/// We use for cloning vector of preprocessors and reuse inside 'mdbook-epub'
pub trait PreprocessorClone {
/// clone one boxed preprocessor
fn clone_preprocessor(&self) -> Box<dyn Preprocessor>;
}

impl<T: 'static + Preprocessor + Clone> PreprocessorClone for T {
fn clone_preprocessor(&self) -> Box<dyn Preprocessor> {
Box::new(self.clone())
}
}

impl Clone for Box<dyn Preprocessor> {
fn clone(&self) -> Box<dyn Preprocessor> {
self.clone_preprocessor()
}
}
Loading