Skip to content
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
27 changes: 25 additions & 2 deletions crates/mdbook-html/src/html_handlebars/hbs_renderer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ use mdbook_core::utils::fs;
use mdbook_renderer::{RenderContext, Renderer};
use serde_json::json;
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::iter::{repeat, zip};
use std::path::{Component, Path, PathBuf};
use tracing::error;
use tracing::{debug, info, trace, warn};

Expand Down Expand Up @@ -119,8 +120,30 @@ impl HtmlHandlebars {
debug!("Render template");
let rendered = ctx.handlebars.render("index", &ctx.data)?;

// Calculate an output path that's contained in the specified destination
// This is required to be able to reference files in the parent directory
// without putting the HTML files there
let out_path = ctx.destination.join(
&filepath
.parent()
.context("filepath points to a directory")?,
);
fs::create_dir_all(&out_path).context("could not create output directories")?;
let fixed_path: PathBuf = zip(
ctx.destination
.components()
// padding destination because it's always shorter
.chain(repeat(Component::CurDir)),
std::fs::canonicalize(&out_path)?.components(),
)
.skip_while(|(out, canonicalized)| out == canonicalized)
.map(|(_, canonicalized)| canonicalized)
.collect();
let out_path = ctx
.destination
.join(fixed_path)
.join(filepath.file_name().context("filepath points to parent")?);
// Write to file
let out_path = ctx.destination.join(filepath);
fs::write(&out_path, rendered)?;

if prev_ch.is_none() {
Expand Down
15 changes: 15 additions & 0 deletions tests/testsuite/rendering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -304,3 +304,18 @@ HTML tags must be closed before exiting a markdown element.
str![[r##"<h3 id="option"><a class="header" href="#option">Option<t></t></a></h3>"##]],
);
}

#[test]
fn including_files_from_parent_directories_works() {
let mut test =
BookTest::from_dir("rendering/including_files_from_parent_directories_works/parent");
test.check_main_file(
"book/index.html",
str![[r##"<h1 id="test"><a class="header" href="#test">Test!</a></h1>"##]],
);

assert!(
!std::fs::exists(test.dir.join("../test.html")).unwrap(),
"test.html was rendered outside build directory"
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[test](../test.md)
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Test!