1
1
mirror of https://github.com/casey/just.git synced 2024-11-22 10:26:26 +03:00

Name instead of number book chapter files (#2372)

This commit is contained in:
Casey Rodarmor 2024-09-17 16:55:52 +08:00 committed by GitHub
parent ab7105afce
commit b60fa4263c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1,7 +1,13 @@
use { use {
pulldown_cmark::{CowStr, Event, HeadingLevel, Options, Parser, Tag}, pulldown_cmark::{CowStr, Event, HeadingLevel, Options, Parser, Tag},
pulldown_cmark_to_cmark::cmark, 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>>; type Result<T = ()> = std::result::Result<T, Box<dyn Error>>;
@ -62,8 +68,8 @@ impl<'a> Chapter<'a> {
.collect() .collect()
} }
fn number(&self) -> usize { fn filename(&self) -> String {
self.index + 1 slug(&self.title())
} }
fn markdown(&self) -> Result<String> { fn markdown(&self) -> Result<String> {
@ -82,7 +88,7 @@ fn slug(s: &str) -> String {
match c { match c {
'A'..='Z' => slug.extend(c.to_lowercase()), 'A'..='Z' => slug.extend(c.to_lowercase()),
' ' => slug.push('-'), ' ' => slug.push('-'),
'?' | '.' | '' => {} '?' | '.' | '' | '' => {}
_ => slug.push(c), _ => slug.push(c),
} }
} }
@ -135,9 +141,9 @@ fn main() -> Result {
.collect::<String>(); .collect::<String>();
let slug = slug(&title); let slug = slug(&title);
let link = if let HeadingLevel::H1 | HeadingLevel::H2 | HeadingLevel::H3 = level { let link = if let HeadingLevel::H1 | HeadingLevel::H2 | HeadingLevel::H3 = level {
format!("chapter_{}.html", chapter.number()) format!("{}.html", chapter.filename())
} else { } else {
format!("chapter_{}.html#{}", chapter.number(), slug) format!("{}.html#{}", chapter.filename(), slug)
}; };
links.insert(slug, link); links.insert(slug, link);
current = None; current = None;
@ -163,8 +169,13 @@ fn main() -> Result {
let mut summary = String::new(); let mut summary = String::new();
let mut filenames = BTreeSet::new();
for chapter in chapters { 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()?)?; fs::write(path, chapter.markdown()?)?;
let indent = match chapter.level { let indent = match chapter.level {
HeadingLevel::H1 => 0, HeadingLevel::H1 => 0,
@ -176,11 +187,12 @@ fn main() -> Result {
}; };
writeln!( writeln!(
summary, summary,
"{}- [{}](chapter_{}.md)", "{}- [{}]({filename}.md)",
" ".repeat(indent * 4), " ".repeat(indent * 4),
chapter.title(), chapter.title(),
chapter.number()
)?; )?;
filenames.insert(filename);
} }
fs::write(format!("{src}/SUMMARY.md"), summary).unwrap(); fs::write(format!("{src}/SUMMARY.md"), summary).unwrap();