Skip to content

Commit

Permalink
Name instead of number book chapter files (#2372)
Browse files Browse the repository at this point in the history
  • Loading branch information
casey authored Sep 17, 2024
1 parent ab7105a commit b60fa42
Showing 1 changed file with 21 additions and 9 deletions.
30 changes: 21 additions & 9 deletions crates/generate-book/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
use {
pulldown_cmark::{CowStr, Event, HeadingLevel, Options, Parser, Tag},
pulldown_cmark_to_cmark::cmark,
std::{collections::BTreeMap, error::Error, fmt::Write, fs, ops::Deref},
std::{
collections::{BTreeMap, BTreeSet},
error::Error,
fmt::Write,
fs,
ops::Deref,
},
};

type Result<T = ()> = std::result::Result<T, Box<dyn Error>>;
Expand Down Expand Up @@ -62,8 +68,8 @@ impl<'a> Chapter<'a> {
.collect()
}

fn number(&self) -> usize {
self.index + 1
fn filename(&self) -> String {
slug(&self.title())
}

fn markdown(&self) -> Result<String> {
Expand All @@ -82,7 +88,7 @@ fn slug(s: &str) -> String {
match c {
'A'..='Z' => slug.extend(c.to_lowercase()),
' ' => slug.push('-'),
'?' | '.' | '?' => {}
'?' | '.' | '?' | '’' => {}
_ => slug.push(c),
}
}
Expand Down Expand Up @@ -135,9 +141,9 @@ fn main() -> Result {
.collect::<String>();
let slug = slug(&title);
let link = if let HeadingLevel::H1 | HeadingLevel::H2 | HeadingLevel::H3 = level {
format!("chapter_{}.html", chapter.number())
format!("{}.html", chapter.filename())
} else {
format!("chapter_{}.html#{}", chapter.number(), slug)
format!("{}.html#{}", chapter.filename(), slug)
};
links.insert(slug, link);
current = None;
Expand All @@ -163,8 +169,13 @@ fn main() -> Result {

let mut summary = String::new();

let mut filenames = BTreeSet::new();

for chapter in chapters {
let path = format!("{}/chapter_{}.md", src, chapter.number());
let filename = chapter.filename();
assert!(!filenames.contains(&filename));

let path = format!("{src}/{filename}.md");
fs::write(path, chapter.markdown()?)?;
let indent = match chapter.level {
HeadingLevel::H1 => 0,
Expand All @@ -176,11 +187,12 @@ fn main() -> Result {
};
writeln!(
summary,
"{}- [{}](chapter_{}.md)",
"{}- [{}]({filename}.md)",
" ".repeat(indent * 4),
chapter.title(),
chapter.number()
)?;

filenames.insert(filename);
}

fs::write(format!("{src}/SUMMARY.md"), summary).unwrap();
Expand Down

0 comments on commit b60fa42

Please sign in to comment.