novel_cli/cmd/
check.rs

1use std::{
2    fs,
3    ops::Range,
4    path::{Path, PathBuf},
5};
6
7use clap::Args;
8use color_eyre::eyre::{self, Result};
9use fluent_templates::Loader;
10use hashbrown::HashSet;
11use novel_api::Timing;
12use pulldown_cmark::{Event, HeadingLevel, Options, Parser, Tag, TagEnd, TextMergeWithOffset};
13
14use crate::{
15    utils::{self, CurrentDir, Lang},
16    LANG_ID, LOCALES,
17};
18
19#[must_use]
20#[derive(Args)]
21#[command(arg_required_else_help = true,
22    about = LOCALES.lookup(&LANG_ID, "check_command"))]
23pub struct Check {
24    #[arg(help = LOCALES.lookup(&LANG_ID, "file_path"))]
25    pub file_path: PathBuf,
26
27    #[arg(long, default_value_t = false,
28        help = LOCALES.lookup(&LANG_ID, "basic_check"))]
29    pub basic_check: bool,
30
31    #[arg(long, default_value_t = false,
32        help = LOCALES.lookup(&LANG_ID, "word_count"))]
33    pub word_count: bool,
34}
35
36pub fn execute(config: Check) -> Result<()> {
37    let mut timing = Timing::new();
38
39    let input_file_path;
40    let input_file_parent_path;
41
42    if utils::is_markdown_or_txt_file(&config.file_path)? {
43        input_file_path = dunce::canonicalize(&config.file_path)?;
44        input_file_parent_path = input_file_path.parent().unwrap().to_path_buf();
45    } else if let Ok(Some(path)) =
46        utils::try_get_markdown_or_txt_file_name_in_dir(&config.file_path)
47    {
48        input_file_path = path;
49        input_file_parent_path = dunce::canonicalize(&config.file_path)?;
50    } else {
51        eyre::bail!("Invalid input path: `{}`", config.file_path.display());
52    }
53    tracing::info!("Input file path: `{}`", input_file_path.display());
54
55    let current_dir = CurrentDir::new(input_file_parent_path)?;
56
57    let bytes = fs::read(&input_file_path)?;
58    let markdown = simdutf8::basic::from_utf8(&bytes)?;
59    let mut parser = TextMergeWithOffset::new(
60        Parser::new_ext(markdown, Options::ENABLE_YAML_STYLE_METADATA_BLOCKS).into_offset_iter(),
61    );
62
63    let lang = check_metadata(&mut parser)?;
64
65    let max_width = (utils::terminal_size().0 / 2) as usize;
66    let mut char_set = HashSet::new();
67    let mut in_paragraph = false;
68    let mut word_count = 0;
69    parser.for_each(|(event, range)| match event {
70        Event::Start(tag) => match tag {
71            Tag::Heading { level, .. } => {
72                let title = markdown[range].trim_start_matches('#').trim();
73
74                if level == HeadingLevel::H1 {
75                    if !check_volume_title(title, lang) {
76                        println_msg(format!("Irregular volume title format: `{title}`"));
77                    }
78                } else if level == HeadingLevel::H2 {
79                    if !check_chapter_title(title, lang) {
80                        println_msg(format!("Irregular chapter title format: `{title}`"));
81                    }
82                } else {
83                    println_msg(format!(
84                        "Irregular heading level: `{level:?}`, content: `{title}`"
85                    ));
86                }
87            }
88            Tag::Image { dest_url, .. } => {
89                let image_path = Path::new(dest_url.as_ref());
90
91                if !image_path.is_file() {
92                    println_msg(format!("Image `{}` does not exist", image_path.display()));
93                }
94            }
95            Tag::Paragraph => {
96                in_paragraph = true;
97            }
98            Tag::BlockQuote(_)
99            | Tag::CodeBlock(_)
100            | Tag::List(_)
101            | Tag::Item
102            | Tag::FootnoteDefinition(_)
103            | Tag::Table(_)
104            | Tag::TableHead
105            | Tag::TableRow
106            | Tag::TableCell
107            | Tag::Emphasis
108            | Tag::Strong
109            | Tag::Strikethrough
110            | Tag::Link { .. }
111            | Tag::HtmlBlock
112            | Tag::MetadataBlock(_)
113            | Tag::DefinitionList
114            | Tag::DefinitionListTitle
115            | Tag::DefinitionListDefinition => {
116                if !config.basic_check {
117                    let content = console::truncate_str(markdown[range].trim(), max_width, "...");
118
119                    println_msg(format!(
120                        "Markdown tag that should not appear: `{tag:?}`, content: `{content}`"
121                    ));
122                }
123            }
124        },
125        Event::Text(text) => {
126            if !config.basic_check {
127                for c in text.chars() {
128                    if !utils::is_cjk(c)
129                        && !utils::is_punctuation(c)
130                        && !c.is_ascii_alphanumeric()
131                        && c != ' '
132                    {
133                        if char_set.contains(&c) {
134                            continue;
135                        } else {
136                            char_set.insert(c);
137
138                            println_msg(format!(
139                                "Irregular char: `{}`, at `{}`",
140                                c,
141                                console::truncate_str(
142                                    markdown[range.clone()].trim(),
143                                    max_width,
144                                    "..."
145                                )
146                            ));
147                        }
148                    }
149                }
150            }
151
152            if config.word_count {
153                for c in text.chars() {
154                    if utils::is_cjk(c) {
155                        word_count += 1;
156                    }
157                }
158            }
159        }
160        Event::End(tag) => {
161            if let TagEnd::Paragraph = tag {
162                in_paragraph = false;
163            }
164        }
165        Event::HardBreak
166        | Event::Code(_)
167        | Event::Html(_)
168        | Event::FootnoteReference(_)
169        | Event::SoftBreak
170        | Event::Rule
171        | Event::TaskListMarker(_)
172        | Event::InlineHtml(_)
173        | Event::InlineMath(_)
174        | Event::DisplayMath(_) => {
175            if !config.basic_check {
176                let content = console::truncate_str(markdown[range].trim(), max_width, "...");
177
178                println_msg(format!(
179                    "Markdown event that should not appear: `{event:?}`, content: `{content}`"
180                ));
181            }
182        }
183    });
184
185    if config.word_count {
186        println!("Total number of words: {word_count}");
187    }
188
189    current_dir.restore()?;
190
191    tracing::debug!("Time spent on `check`: {}", timing.elapsed()?);
192
193    Ok(())
194}
195
196fn check_metadata<'a, T>(parser: &mut TextMergeWithOffset<'a, T>) -> Result<Lang>
197where
198    T: Iterator<Item = (Event<'a>, Range<usize>)>,
199{
200    let metadata = utils::get_metadata(parser)?;
201
202    eyre::ensure!(
203        metadata.cover_image_is_ok(),
204        "Cover image does not exist: `{}`",
205        metadata.cover_image.unwrap().display()
206    );
207
208    Ok(metadata.lang)
209}
210
211fn println_msg(msg: String) {
212    println!("{} {}", utils::emoji("⚠️"), msg);
213}
214
215macro_rules! regex {
216    ($re:literal $(,)?) => {{
217        static RE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
218        RE.get_or_init(|| regex::Regex::new($re).unwrap())
219    }};
220}
221
222#[must_use]
223fn check_chapter_title<T>(title: T, lang: Lang) -> bool
224where
225    T: AsRef<str>,
226{
227    let title = title.as_ref();
228
229    match lang {
230        Lang::ZhHant => {
231            let regex = regex!(r"第([零一二三四五六七八九十百千]|[0-9]){1,7}[章話] .+");
232            regex.is_match(title.as_ref())
233        }
234        Lang::ZhHans => {
235            let regex = regex!(r"第([零一二三四五六七八九十百千]|[0-9]){1,7}[章话] .+");
236            regex.is_match(title.as_ref())
237        }
238    }
239}
240
241#[must_use]
242fn check_volume_title<T>(title: T, lang: Lang) -> bool
243where
244    T: AsRef<str>,
245{
246    let title = title.as_ref();
247
248    match lang {
249        Lang::ZhHant => {
250            let regex = regex!(r"第([一二三四五六七八九十]|[0-9]){1,3}卷 .+");
251            regex.is_match(title) || title == "簡介"
252        }
253        Lang::ZhHans => {
254            let regex = regex!(r"第([一二三四五六七八九十]|[0-9]){1,3}卷 .+");
255            regex.is_match(title) || title == "简介"
256        }
257    }
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263
264    #[test]
265    fn check_chapter_title_test() {
266        assert!(check_chapter_title("第一章 被俘虏的开始", Lang::ZhHans));
267        assert!(check_chapter_title(
268            "第一百三十二章 标标标标标标标标标",
269            Lang::ZhHans
270        ));
271        assert!(check_chapter_title("第123章 标题标标标标", Lang::ZhHans));
272        assert!(!check_chapter_title("第一章 ", Lang::ZhHans));
273        assert!(!check_chapter_title("第1二3话", Lang::ZhHans));
274        assert!(!check_chapter_title("第123话标题", Lang::ZhHans));
275        assert!(!check_chapter_title("123话 标题", Lang::ZhHans));
276    }
277
278    #[test]
279    fn check_volume_title_test() {
280        assert!(check_volume_title(
281            "第三十二卷 标标标标标标标标标",
282            Lang::ZhHans
283        ));
284        assert!(!check_volume_title("第123话 标题标标标标", Lang::ZhHans));
285        assert!(!check_volume_title("第1卷 ", Lang::ZhHans));
286    }
287}