forked from steveklabnik/rust-by-example
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.rs
More file actions
93 lines (82 loc) · 2.85 KB
/
example.rs
File metadata and controls
93 lines (82 loc) · 2.85 KB
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
use file;
use markdown::Markdown;
use serialize::{Decodable,json};
use std::iter::AdditiveIterator;
#[deriving(Decodable)]
pub struct Example {
children: Option<Vec<Example>>,
id: String,
title: String,
}
impl Example {
pub fn get_list() -> Vec<Example> {
match file::read(&Path::new("examples/structure.json")) {
Err(why) => panic!("{}", why),
Ok(string) => match json::from_str(string.as_slice()) {
Err(_) => panic!("structure.json is not valid json"),
Ok(json) => {
match Decodable::decode(&mut json::Decoder::new(json)) {
Err(_) => panic!("error decoding structure.json"),
Ok(examples) => examples,
}
}
}
}
}
pub fn count(&self) -> uint {
match self.children {
None => 1,
Some(ref children) => 1 + children.iter().map(|c| c.count()).sum(),
}
}
pub fn process(&self,
number: Vec<uint>,
tx: Sender<(Vec<uint>, String)>,
indent: uint,
prefix: String)
{
let id = self.id.as_slice();
let prefix = prefix.as_slice();
let title = self.title.as_slice();
let entry =
match Markdown::process(number.as_slice(), id, title, prefix) {
Ok(_) => {
let md = if prefix.as_slice().is_whitespace() {
format!("{}.md", id)
} else {
format!("{}/{}.md", prefix, id)
};
format!("{}* [{}]({})",
" ".repeat(indent),
title,
md)
},
Err(why) => {
print!("{}: {}\n", id, why);
format!("{}* {}", " ".repeat(indent), title)
},
};
tx.send((number.clone(), entry));
match self.children {
None => {},
Some(ref children) => {
let path = Path::new(format!("stage/{}/{}", prefix, id));
file::mkdir(&path);
for (i, example) in children.iter().enumerate() {
let tx = tx.clone();
let prefix = if prefix.as_slice().is_whitespace() {
format!("{}", id)
} else {
format!("{}/{}", prefix, id)
};
let mut number = number.clone();
number.push(i + 1);
example.process(number,
tx,
indent + 1,
prefix);
}
},
}
}
}