guidebook 0.1.73

HonKit/GitBook compatible static book generator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
use anyhow::Result;
use pulldown_cmark::{Event, Parser, Tag, TagEnd};
use std::fs;
use std::path::Path;

#[derive(Debug, Clone)]
pub struct Summary {
    /// Title from # heading in SUMMARY.md (kept for compatibility)
    #[allow(dead_code)]
    pub title: Option<String>,
    pub items: Vec<SummaryItem>,
}

#[derive(Debug, Clone)]
pub enum SummaryItem {
    /// A chapter with a link
    Link {
        title: String,
        path: Option<String>,
        children: Vec<SummaryItem>,
    },
    /// A separator (horizontal rule)
    Separator,
    /// A part header (unlinked heading)
    PartTitle(String),
}

impl Summary {
    pub fn parse(book_dir: &Path) -> Result<Self> {
        let summary_path = book_dir.join("SUMMARY.md");
        let content = fs::read_to_string(&summary_path)?;
        parse_summary(&content)
    }
}

/// Parse SUMMARY.md content into a Summary structure
/// Uses pulldown-cmark to parse Markdown structure (like HonKit)
pub fn parse_summary(content: &str) -> Result<Summary> {
    let mut title = None;
    let mut items = Vec::new();
    let parser = Parser::new(content);

    // State tracking
    let mut in_list_stack: Vec<Vec<SummaryItem>> = Vec::new(); // Stack of list items at each depth
    let mut current_link: Option<(String, Option<String>)> = None; // (title, path)
    let mut current_text = String::new();
    let mut in_heading = false;
    let mut heading_level = 0;
    let mut pending_item_text = String::new(); // Text for plain items (no link)

    for event in parser {
        match event {
            // Heading (# Title, ## Part, ### Part)
            Event::Start(Tag::Heading { level, .. }) => {
                in_heading = true;
                heading_level = level as usize;
                current_text.clear();
            }
            Event::End(TagEnd::Heading(_)) => {
                in_heading = false;
                let text = current_text.trim().to_string();
                if heading_level == 1 {
                    // # Title
                    title = Some(text);
                } else if heading_level == 2 || heading_level == 3 {
                    // ## Part or ### Part
                    items.push(SummaryItem::PartTitle(text));
                }
                current_text.clear();
            }

            // List start/end
            Event::Start(Tag::List(_)) => {
                // Before starting nested list, flush any pending link from parent item
                if !in_list_stack.is_empty() {
                    if let Some((link_title, link_path)) = current_link.take() {
                        if let Some(current_list) = in_list_stack.last_mut() {
                            current_list.push(SummaryItem::Link {
                                title: link_title,
                                path: link_path,
                                children: Vec::new(),
                            });
                        }
                    } else if !pending_item_text.is_empty() {
                        // Plain text item
                        if let Some(current_list) = in_list_stack.last_mut() {
                            current_list.push(SummaryItem::Link {
                                title: pending_item_text.trim().to_string(),
                                path: None,
                                children: Vec::new(),
                            });
                        }
                        pending_item_text.clear();
                    }
                }
                in_list_stack.push(Vec::new());
            }
            Event::End(TagEnd::List(_)) => {
                if let Some(completed_items) = in_list_stack.pop() {
                    if in_list_stack.is_empty() {
                        // Top-level list completed, add to items
                        items.extend(completed_items);
                    } else {
                        // Nested list completed, attach as children to last item in parent
                        if let Some(parent_list) = in_list_stack.last_mut() {
                            if let Some(SummaryItem::Link { children, .. }) = parent_list.last_mut()
                            {
                                *children = completed_items;
                            }
                        }
                    }
                }
            }

            // List item
            Event::Start(Tag::Item) => {
                current_link = None;
                current_text.clear();
                pending_item_text.clear();
            }
            Event::End(TagEnd::Item) => {
                // Only add item here if it wasn't already added when nested list started
                if let Some(current_list) = in_list_stack.last_mut() {
                    if let Some((link_title, link_path)) = current_link.take() {
                        current_list.push(SummaryItem::Link {
                            title: link_title,
                            path: link_path,
                            children: Vec::new(),
                        });
                    } else if !pending_item_text.is_empty() {
                        // Plain text item (no link)
                        current_list.push(SummaryItem::Link {
                            title: pending_item_text.trim().to_string(),
                            path: None,
                            children: Vec::new(),
                        });
                    }
                }
                current_text.clear();
                pending_item_text.clear();
            }

            // Link — the FIRST link in a list item wins; additional links in
            // the same item are ignored (previously a second link silently
            // overwrote the first, dropping its navigation entry entirely)
            Event::Start(Tag::Link { dest_url, .. }) if current_link.is_none() => {
                current_text.clear();
                let path = dest_url.to_string();
                let path = if path.is_empty() || path == "#" {
                    None
                } else {
                    // Normalize path: remove leading ./ (but keep / for root-relative paths)
                    Some(path.trim_start_matches("./").to_string())
                };
                current_link = Some((String::new(), path));
            }
            Event::End(TagEnd::Link) => {
                if let Some((ref mut link_title, _)) = current_link {
                    // Only the first link's text becomes the title
                    if link_title.is_empty() {
                        *link_title = current_text.trim().to_string();
                    }
                }
                current_text.clear();
            }

            // Horizontal rule (separator)
            Event::Rule => {
                items.push(SummaryItem::Separator);
            }

            // Text content
            Event::Text(text) => {
                if in_heading {
                    current_text.push_str(&text);
                } else if !in_list_stack.is_empty() {
                    current_text.push_str(&text);
                    // Also track for plain items (text outside links)
                    if current_link.is_none() {
                        pending_item_text.push_str(&text);
                    }
                }
            }
            Event::Code(code) => {
                if in_heading {
                    current_text.push_str(&code);
                } else if !in_list_stack.is_empty() {
                    current_text.push_str(&code);
                    if current_link.is_none() {
                        pending_item_text.push_str(&code);
                    }
                }
            }

            _ => {}
        }
    }

    Ok(Summary { title, items })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_simple_summary() {
        let content = r#"# Summary

* [Introduction](README.md)
* [Chapter 1](chapter1.md)
    * [Section 1.1](chapter1/section1.md)
    * [Section 1.2](chapter1/section2.md)
* [Chapter 2](chapter2.md)
"#;

        let summary = parse_summary(content).unwrap();
        assert_eq!(summary.title, Some("Summary".to_string()));
        assert_eq!(summary.items.len(), 3);
    }

    #[test]
    fn test_parse_nested_summary() {
        let content = r#"# Summary

* [表紙](README.md)
* 顧客画面
    * ポートフォリオ
        * [TOP](Customer/AssetStatus/PortfolioTop.md)
        * [国内株式現物](./Customer/AssetStatus/PortfolioStock.md)
"#;

        let summary = parse_summary(content).unwrap();
        assert_eq!(summary.items.len(), 2);

        // Verify children structure
        if let SummaryItem::Link {
            title, children, ..
        } = &summary.items[1]
        {
            assert_eq!(title, "顧客画面");
            assert_eq!(
                children.len(),
                1,
                "顧客画面 should have 1 child (ポートフォリオ)"
            );

            if let SummaryItem::Link {
                title: child_title,
                children: grandchildren,
                ..
            } = &children[0]
            {
                assert_eq!(child_title, "ポートフォリオ");
                assert_eq!(
                    grandchildren.len(),
                    2,
                    "ポートフォリオ should have 2 children (TOP, 国内株式現物)"
                );
            } else {
                panic!("Expected Link for ポートフォリオ");
            }
        } else {
            panic!("Expected Link for 顧客画面");
        }
    }

    #[test]
    fn test_parse_2space_indent() {
        // Test 2-space indentation (like kcsta-trade-bff)
        let content = r#"# Summary

* [Introduction](README.md)
* [Chapter 1](chapter1.md)
  * [Section 1.1](chapter1/section1.md)
  * [Section 1.2](chapter1/section2.md)
    * [Subsection 1.2.1](chapter1/section2/sub1.md)
* [Chapter 2](chapter2.md)
"#;

        let summary = parse_summary(content).unwrap();
        assert_eq!(summary.items.len(), 3, "Should have 3 top-level items");

        // Verify Chapter 1 has 2 children
        if let SummaryItem::Link {
            title, children, ..
        } = &summary.items[1]
        {
            assert_eq!(title, "Chapter 1");
            assert_eq!(children.len(), 2, "Chapter 1 should have 2 children");

            // Verify Section 1.2 has 1 child (Subsection 1.2.1)
            if let SummaryItem::Link {
                title: sec_title,
                children: sec_children,
                ..
            } = &children[1]
            {
                assert_eq!(sec_title, "Section 1.2");
                assert_eq!(sec_children.len(), 1, "Section 1.2 should have 1 child");
            } else {
                panic!("Expected Link for Section 1.2");
            }
        } else {
            panic!("Expected Link for Chapter 1");
        }
    }

    #[test]
    fn test_parse_4space_indent() {
        // Test 4-space indentation (traditional)
        let content = r#"# Summary

* [Introduction](README.md)
* [Chapter 1](chapter1.md)
    * [Section 1.1](chapter1/section1.md)
    * [Section 1.2](chapter1/section2.md)
        * [Subsection 1.2.1](chapter1/section2/sub1.md)
* [Chapter 2](chapter2.md)
"#;

        let summary = parse_summary(content).unwrap();
        assert_eq!(summary.items.len(), 3, "Should have 3 top-level items");

        // Verify Chapter 1 has 2 children
        if let SummaryItem::Link {
            title, children, ..
        } = &summary.items[1]
        {
            assert_eq!(title, "Chapter 1");
            assert_eq!(children.len(), 2, "Chapter 1 should have 2 children");

            // Verify Section 1.2 has 1 child (Subsection 1.2.1)
            if let SummaryItem::Link {
                title: sec_title,
                children: sec_children,
                ..
            } = &children[1]
            {
                assert_eq!(sec_title, "Section 1.2");
                assert_eq!(sec_children.len(), 1, "Section 1.2 should have 1 child");
            } else {
                panic!("Expected Link for Section 1.2");
            }
        } else {
            panic!("Expected Link for Chapter 1");
        }
    }

    #[test]
    fn test_parse_mixed_indent() {
        // Test mixed indentation (2 and 4 spaces in same file)
        // With pulldown-cmark, this should work correctly
        let content = r#"# Summary

* [Item 1](item1.md)
  * [Item 1.1](item1-1.md)
* [Item 2](item2.md)
    * [Item 2.1](item2-1.md)
"#;

        let summary = parse_summary(content).unwrap();
        assert_eq!(summary.items.len(), 2, "Should have 2 top-level items");

        // Verify Item 1 has 1 child
        if let SummaryItem::Link {
            title, children, ..
        } = &summary.items[0]
        {
            assert_eq!(title, "Item 1");
            assert_eq!(children.len(), 1, "Item 1 should have 1 child");
        } else {
            panic!("Expected Link for Item 1");
        }

        // Verify Item 2 has 1 child
        if let SummaryItem::Link {
            title, children, ..
        } = &summary.items[1]
        {
            assert_eq!(title, "Item 2");
            assert_eq!(children.len(), 1, "Item 2 should have 1 child");
        } else {
            panic!("Expected Link for Item 2");
        }
    }

    #[test]
    fn test_parse_tab_indent() {
        // Test tab indentation
        let content =
            "# Summary\n\n* [Item 1](item1.md)\n\t* [Item 1.1](item1-1.md)\n* [Item 2](item2.md)\n";

        let summary = parse_summary(content).unwrap();
        assert_eq!(summary.items.len(), 2, "Should have 2 top-level items");

        if let SummaryItem::Link {
            title, children, ..
        } = &summary.items[0]
        {
            assert_eq!(title, "Item 1");
            assert_eq!(
                children.len(),
                1,
                "Item 1 should have 1 child (tab-indented)"
            );
        } else {
            panic!("Expected Link for Item 1");
        }
    }

    #[test]
    fn test_parse_absolute_paths() {
        // Test absolute paths (leading /) - preserved for root-relative handling
        let content = r#"# Summary

* [Relative](chapter1.md)
* [With Dot Slash](./chapter2.md)
* [Absolute](/chapter3.md)
* [Absolute Nested](/dir/chapter4.md)
"#;

        let summary = parse_summary(content).unwrap();
        assert_eq!(summary.items.len(), 4);

        // Verify paths are normalized (./ removed, but / preserved for root-relative paths)
        if let SummaryItem::Link { path, .. } = &summary.items[0] {
            assert_eq!(path.as_deref(), Some("chapter1.md"));
        }
        if let SummaryItem::Link { path, .. } = &summary.items[1] {
            assert_eq!(path.as_deref(), Some("chapter2.md"), "./ should be removed");
        }
        if let SummaryItem::Link { path, .. } = &summary.items[2] {
            assert_eq!(
                path.as_deref(),
                Some("/chapter3.md"),
                "Leading / should be preserved for root-relative paths"
            );
        }
        if let SummaryItem::Link { path, .. } = &summary.items[3] {
            assert_eq!(
                path.as_deref(),
                Some("/dir/chapter4.md"),
                "Leading / should be preserved for root-relative paths"
            );
        }
    }

    // ── Fuzz-like edge case tests ──

    #[test]
    fn test_fuzz_empty_input() {
        let result = parse_summary("");
        assert!(result.is_ok());
    }

    #[test]
    fn test_fuzz_only_whitespace() {
        let result = parse_summary("   \n\n\t\t\n   ");
        assert!(result.is_ok());
    }

    #[test]
    fn test_fuzz_only_heading() {
        let result = parse_summary("# Summary");
        assert!(result.is_ok());
    }

    #[test]
    fn test_fuzz_broken_links() {
        let inputs = vec![
            "* []()",
            "* [title]()",
            "* [](path.md)",
            "* [broken",
            "* broken](link.md)",
            "* [link](path with spaces.md)",
            "* [](javascript:alert(1))",
            "* [🎉](emoji.md)",
        ];
        for input in inputs {
            let result = parse_summary(input);
            assert!(result.is_ok(), "Should not panic on: {}", input);
        }
    }

    #[test]
    fn test_fuzz_deep_nesting() {
        let mut content = String::from("# Summary\n");
        for i in 0..20 {
            let indent = "  ".repeat(i);
            content.push_str(&format!("{}* [Level {}](l{}.md)\n", indent, i, i));
        }
        let result = parse_summary(&content);
        assert!(result.is_ok());
    }

    #[test]
    fn test_fuzz_null_bytes() {
        let content = "# Summary\n* [Test\0](file\0.md)\n";
        let result = parse_summary(content);
        assert!(result.is_ok());
    }

    #[test]
    fn test_fuzz_very_long_line() {
        let long_title = "A".repeat(10000);
        let content = format!("* [{}](test.md)\n", long_title);
        let result = parse_summary(&content);
        assert!(result.is_ok());
    }

    #[test]
    fn test_first_link_wins_with_two_links_in_item() {
        // Regression: a second link in the same item overwrote the first,
        // silently dropping its navigation entry
        let content = "# Summary\n\n* [Old](old.md) → [New](new.md)\n";
        let summary = parse_summary(content).unwrap();
        let links: Vec<(String, Option<String>)> = summary
            .items
            .iter()
            .filter_map(|i| match i {
                SummaryItem::Link { title, path, .. } => Some((title.clone(), path.clone())),
                _ => None,
            })
            .collect();
        assert_eq!(links.len(), 1);
        assert_eq!(links[0].0, "Old");
        assert_eq!(links[0].1.as_deref(), Some("old.md"));
    }

    #[test]
    fn test_trailing_text_after_link_does_not_break_title() {
        let content = "# Summary\n\n* [Page](page.md) (draft)\n";
        let summary = parse_summary(content).unwrap();
        match &summary.items[0] {
            SummaryItem::Link { title, path, .. } => {
                assert_eq!(title, "Page");
                assert_eq!(path.as_deref(), Some("page.md"));
            }
            other => panic!("unexpected item: {:?}", other),
        }
    }
}