/
book.rs
170 lines (149 loc) · 5.43 KB
/
book.rs
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
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Basic data structures for representing a book.
use std::old_io::BufferedReader;
use std::iter;
use std::iter::AdditiveIterator;
pub struct BookItem {
pub title: String,
pub path: Path,
pub path_to_root: Path,
pub children: Vec<BookItem>,
}
pub struct Book {
pub chapters: Vec<BookItem>,
}
/// A depth-first iterator over a book.
pub struct BookItems<'a> {
cur_items: &'a [BookItem],
cur_idx: usize,
stack: Vec<(&'a [BookItem], usize)>,
}
impl<'a> Iterator for BookItems<'a> {
type Item = (String, &'a BookItem);
fn next(&mut self) -> Option<(String, &'a BookItem)> {
loop {
if self.cur_idx >= self.cur_items.len() {
match self.stack.pop() {
None => return None,
Some((parent_items, parent_idx)) => {
self.cur_items = parent_items;
self.cur_idx = parent_idx + 1;
}
}
} else {
let cur = self.cur_items.get(self.cur_idx).unwrap();
let mut section = "".to_string();
for &(_, idx) in &self.stack {
section.push_str(&(idx + 1).to_string()[..]);
section.push('.');
}
section.push_str(&(self.cur_idx + 1).to_string()[..]);
section.push('.');
self.stack.push((self.cur_items, self.cur_idx));
self.cur_items = &cur.children[..];
self.cur_idx = 0;
return Some((section, cur))
}
}
}
}
impl Book {
pub fn iter(&self) -> BookItems {
BookItems {
cur_items: &self.chapters[..],
cur_idx: 0,
stack: Vec::new(),
}
}
}
/// Construct a book by parsing a summary (markdown table of contents).
pub fn parse_summary<R: Reader>(input: R, src: &Path) -> Result<Book, Vec<String>> {
fn collapse(stack: &mut Vec<BookItem>,
top_items: &mut Vec<BookItem>,
to_level: usize) {
loop {
if stack.len() < to_level { return }
if stack.len() == 1 {
top_items.push(stack.pop().unwrap());
return;
}
let tip = stack.pop().unwrap();
let last = stack.len() - 1;
stack[last].children.push(tip);
}
}
let mut top_items = vec!();
let mut stack = vec!();
let mut errors = vec!();
// always include the introduction
top_items.push(BookItem {
title: "Introduction".to_string(),
path: Path::new("README.md"),
path_to_root: Path::new("."),
children: vec!(),
});
for line_result in BufferedReader::new(input).lines() {
let line = match line_result {
Ok(line) => line,
Err(err) => {
errors.push(err.desc.to_string()); // FIXME: include detail
return Err(errors);
}
};
let star_idx = match line.find("*") { Some(i) => i, None => continue };
let start_bracket = star_idx + line[star_idx..].find("[").unwrap();
let end_bracket = start_bracket + line[start_bracket..].find("](").unwrap();
let start_paren = end_bracket + 1;
let end_paren = start_paren + line[start_paren..].find(")").unwrap();
let given_path = &line[start_paren + 1 .. end_paren];
let title = line[start_bracket + 1..end_bracket].to_string();
let indent = &line[..star_idx];
let path_from_root = match src.join(given_path).path_relative_from(src) {
Some(p) => p,
None => {
errors.push(format!("paths in SUMMARY.md must be relative, \
but path '{}' for section '{}' is not.",
given_path, title));
Path::new("")
}
};
let path_to_root = Path::new(iter::repeat("../")
.take(path_from_root.components().count() - 1)
.collect::<String>());
let item = BookItem {
title: title,
path: path_from_root,
path_to_root: path_to_root,
children: vec!(),
};
let level = indent.chars().map(|c| -> usize {
match c {
' ' => 1,
'\t' => 4,
_ => unreachable!()
}
}).sum() / 4 + 1;
if level > stack.len() + 1 {
errors.push(format!("section '{}' is indented too deeply; \
found {}, expected {} or less",
item.title, level, stack.len() + 1));
} else if level <= stack.len() {
collapse(&mut stack, &mut top_items, level);
}
stack.push(item)
}
if errors.is_empty() {
collapse(&mut stack, &mut top_items, 1);
Ok(Book { chapters: top_items })
} else {
Err(errors)
}
}