Skip to content

feat(mdbook): improve mdbook generics behaviour and fix broken links #319

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

Merged
merged 8 commits into from
Feb 23, 2025
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -25,22 +25,18 @@ impl<'a> MarkdownArgumentVisitor<'a> {

impl ArgumentVisitor for MarkdownArgumentVisitor<'_> {
fn visit_lad_type_id(&mut self, type_id: &ladfile::LadTypeId) {
let mut buffer = String::new();

// Write identifier<Generic1TypeIdentifier, Generic2TypeIdentifier>
buffer.push_str(&self.ladfile.get_type_identifier(type_id));
self.buffer.text(self.ladfile.get_type_identifier(type_id));
if let Some(generics) = self.ladfile.get_type_generics(type_id) {
buffer.push('<');
self.buffer.text('<');
for (i, generic) in generics.iter().enumerate() {
self.visit_lad_type_id(&generic.type_id);
if i > 0 {
buffer.push_str(", ");
self.buffer.text(", ");
}
buffer.push_str(&self.ladfile.get_type_identifier(&generic.type_id));
}
buffer.push('>');
self.buffer.text('>');
}

self.buffer.text(buffer);
}

fn walk_option(&mut self, inner: &ladfile::LadArgumentKind) {
Expand Down
130 changes: 89 additions & 41 deletions crates/lad_backends/mdbook_lad_preprocessor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#![allow(missing_docs)]

use mdbook::{errors::Error, preprocess::Preprocessor};
use sections::Section;
mod argument_visitor;
mod markdown;
mod sections;
Expand All @@ -10,6 +11,46 @@ const LAD_EXTENSION: &str = "lad.json";

pub struct LADPreprocessor;

impl LADPreprocessor {
/// Checks if a chapter is a LAD file.
fn is_lad_file(chapter: &mdbook::book::Chapter) -> bool {
chapter
.source_path
.as_ref()
.and_then(|a| a.file_name())
.map(|s| s.to_string_lossy().ends_with(LAD_EXTENSION))
.unwrap_or(false)
}

/// Process a chapter that is a LAD file.
///
/// `parent` is the optional parent chapter reference,
/// and `chapter_index` is the index of the chapter among its siblings.
fn process_lad_chapter(
chapter: &mdbook::book::Chapter,
parent: Option<&mdbook::book::Chapter>,
chapter_index: usize,
) -> Result<mdbook::book::Chapter, Error> {
let chapter_title = chapter.name.trim_end_matches(".lad.json").to_owned();
let ladfile = ladfile::parse_lad_file(&chapter.content)
.map_err(|e| Error::new(e).context("Failed to parse LAD file"))?;
log::debug!(
"Parsed LAD file: {}",
serde_json::to_string_pretty(&ladfile).unwrap_or_default()
);
let new_chapter = Section::Summary {
ladfile: &ladfile,
title: Some(chapter_title),
}
.into_chapter(parent, chapter_index);
log::debug!(
"New chapter: {}",
serde_json::to_string_pretty(&new_chapter).unwrap_or_default()
);
Ok(new_chapter)
}
}

impl Preprocessor for LADPreprocessor {
fn name(&self) -> &str {
"lad-preprocessor"
Expand All @@ -20,62 +61,69 @@ impl Preprocessor for LADPreprocessor {
_ctx: &mdbook::preprocess::PreprocessorContext,
mut book: mdbook::book::Book,
) -> mdbook::errors::Result<mdbook::book::Book> {
let mut errors = Vec::default();
let mut errors = Vec::new();

// first replace children in parents
book.for_each_mut(|item| {
if let mdbook::BookItem::Chapter(chapter) = item {
let is_lad_chapter = chapter
.source_path
.as_ref()
.and_then(|a| a.file_name())
.is_some_and(|a| a.to_string_lossy().ends_with(LAD_EXTENSION));
if let mdbook::BookItem::Chapter(parent) = item {
// First, collect the indices and new chapters for LAD file chapters.
let replacements: Vec<(usize, mdbook::book::Chapter)> = parent
.sub_items
.iter()
.enumerate()
.filter_map(|(idx, item)| {
if let mdbook::BookItem::Chapter(chapter) = item {
if LADPreprocessor::is_lad_file(chapter) {
match LADPreprocessor::process_lad_chapter(
chapter,
Some(parent),
idx,
) {
Ok(new_chapter) => return Some((idx, new_chapter)),
Err(e) => {
errors.push(e);
return None;
}
}
}
}
None
})
.collect();

// Then, apply the replacements.
for (idx, new_chapter) in replacements {
if let mdbook::BookItem::Chapter(chapter) = &mut parent.sub_items[idx] {
*chapter = new_chapter;
}
}
}
});

if !is_lad_chapter {
log::debug!("Skipping non-LAD chapter: {:?}", chapter.source_path);
log::trace!(
"Non-LAD chapter: {}",
serde_json::to_string_pretty(&chapter).unwrap_or_default()
);
// then try match items themselves
book.for_each_mut(|item| {
if let mdbook::BookItem::Chapter(chapter) = item {
if !LADPreprocessor::is_lad_file(chapter) {
return;
}

let chapter_title = chapter.name.clone();

let lad = match ladfile::parse_lad_file(&chapter.content) {
Ok(lad) => lad,
let new_chapter = match LADPreprocessor::process_lad_chapter(chapter, None, 0) {
Ok(new_chapter) => new_chapter,
Err(e) => {
log::debug!("Failed to parse LAD file: {:?}", e);
errors.push(Error::new(e).context("Failed to parse LAD file"));
errors.push(e);
return;
}
};

log::debug!(
"Parsed LAD file: {}",
serde_json::to_string_pretty(&lad).unwrap_or_default()
);

let sections = sections::lad_file_to_sections(&lad, Some(chapter_title));

let new_chapter = sections::section_to_chapter(
sections,
Some(chapter),
chapter.parent_names.clone(),
chapter.number.clone(),
None,
None,
);

// serialize chapter to json
log::debug!(
"New chapter: {}",
serde_json::to_string_pretty(&new_chapter).unwrap_or_default()
);

*chapter = new_chapter;
}
});

log::debug!(
"Book after LAD processing: {}",
serde_json::to_string_pretty(&book).unwrap_or_default()
);

if !errors.is_empty() {
// return on first error
for error in errors {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::borrow::Cow;

/// Takes the first n characters from the markdown, without splitting any formatting
/// Takes the first n characters from the markdown, without splitting any formatting.
pub(crate) fn markdown_substring(markdown: &str, length: usize) -> &str {
if markdown.len() <= length {
return markdown;
Expand Down
Loading
Loading