Skip to content

Commit

Permalink
add more context to errors returned from Renderer::render()
Browse files Browse the repository at this point in the history
  • Loading branch information
max-heller committed Nov 26, 2023
1 parent 7137008 commit b26a969
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 9 deletions.
20 changes: 14 additions & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,10 @@ impl mdbook::Renderer for Renderer {
.with_context(|| format!("Unable to deserialize {}", Self::CONFIG_KEY))?
.ok_or(anyhow!("No {} table found", Self::CONFIG_KEY))?;

let source_dir = ctx.source_dir().canonicalize()?;
let source_dir = ctx.source_dir();
let source_dir = source_dir
.canonicalize()
.with_context(|| format!("Unable to canonicalize path: {}", source_dir.display()))?;

for (name, profile) in cfg.profiles {
let destination = ctx.destination.join(name);
Expand All @@ -159,26 +162,31 @@ impl mdbook::Renderer for Renderer {
destination.join("src").into(),
profile.preprocessor_options(),
);
let mut preprocessed = preprocessor.preprocess()?;
let mut preprocessed = preprocessor
.preprocess()
.context("Failed to preprocess book source")?;

// Initialize renderer
let mut renderer = PandocRenderer::new(profile, &ctx.root, destination.into());

// Add preprocessed book chapters to renderer
renderer.current_dir(preprocessed.output_dir());
for input in &mut preprocessed {
renderer.input(input?);
renderer.input(input.context("Failed to preprocess input file")?);
}

if let Some(logfile) = &self.logfile {
renderer.stderr(logfile.try_clone()?);
renderer.stderr(logfile.try_clone().context("Failed to clone logfile")?);
}

// Render final output
renderer.render()?;
renderer
.render()
.context("Failed to render preprocessed source")?;

if !cfg.keep_preprocessed {
fs::remove_dir_all(preprocessed.output_dir())?;
fs::remove_dir_all(preprocessed.output_dir())
.context("Failed to clear preprocessed source files")?;
}
}

Expand Down
13 changes: 10 additions & 3 deletions src/preprocess.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,17 @@ impl<'a> Preprocessor<'a> {
}

pub fn preprocess(self) -> anyhow::Result<PreprocessedFiles<'a>> {
if self.destination.try_exists()? {
fs::remove_dir_all(&self.destination)?;
let dest_error = || {
format!(
"Unable to clear destination directory {}",
self.destination.display()
)
};
if self.destination.try_exists().with_context(dest_error)? {
fs::remove_dir_all(&self.destination).with_context(dest_error)?;
}
fs::create_dir_all(&self.destination)?;
fs::create_dir_all(&self.destination).with_context(dest_error)?;

Ok(PreprocessedFiles {
items: self.book.iter(),
preprocessor: self,
Expand Down

0 comments on commit b26a969

Please sign in to comment.