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
use std::fmt;
use link::Link;
use util::BubbleResult;
use yaml::*;
#[derive(Debug, Clone)]
pub struct Person {
pub name: String,
pub email: Option<String>,
pub photo: Option<String>,
pub key: Option<Key>,
pub nicknames: Vec<String>,
pub also: Vec<Link>,
}
#[derive(Debug, Clone)]
pub struct Key {
pub url: String,
pub fingerprint: String,
}
impl Key {
pub fn from_yaml(key: Yaml) -> Result<Self, &'static str> {
match key {
Yaml::Hash(mut key) => {
Ok(Key {
url: match key.remove(&URL) {
Some(Yaml::String(url)) => url,
Some(..) => return Err("key url must be a string"),
None => return Err("key url missing"),
},
fingerprint: match key.remove(&FINGERPRINT) {
Some(Yaml::String(fprint)) => fprint,
Some(..) => return Err("key fingerprint must be a string"),
None => return Err("key fingerprint missing"),
},
})
}
_ => Err("if specified, key must be a hash"),
}
}
}
impl fmt::Display for Person {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.name)?;
if let Some(ref email) = self.email {
write!(f, " <{}>", email)?;
}
Ok(())
}
}
impl Person {
pub fn from_yaml(person: Yaml) -> Result<Self, &'static str> {
Ok(match person {
Yaml::Hash(mut person) => {
Person {
name: match person.remove(&NAME) {
Some(Yaml::String(name)) => name,
None => return Err("missing name"),
_ => return Err("name must be a string"),
},
photo: match person.remove(&PHOTO) {
Some(Yaml::String(photo)) => Some(photo),
None => None,
_ => return Err("if specified, photo must be a string"),
},
email: match person.remove(&EMAIL) {
Some(Yaml::String(email)) => Some(email),
None => None,
_ => return Err("if specified, email must be a string"),
},
nicknames: match person.remove(&NICKNAMES) {
Some(Yaml::String(nick)) => vec![nick],
Some(Yaml::Array(nicks)) => {
nicks.into_iter()
.map(|nick| match nick {
Yaml::String(nick) => Ok(nick),
_ => Err("nicknames must be strings"),
})
.collect::<Result<_, _>>()?
}
Some(..) => return Err("invalid nicknames value"),
None => vec![],
},
also: person.remove(&ALSO)
.map(Link::many_from_yaml)
.bubble_result()?
.unwrap_or_else(Vec::new),
key: person.remove(&KEY).map(Key::from_yaml).bubble_result()?,
}
}
Yaml::String(name) => {
Person {
name: name,
email: None,
key: None,
also: Vec::new(),
photo: None,
nicknames: Vec::new(),
}
}
_ => return Err("invalid person"),
})
}
}