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
use std::{
borrow::Cow,
io::{BufRead, Write},
};
#[derive(Debug)]
pub enum ControlError {
IoError(std::io::Error),
ParseError(String),
}
impl From<std::io::Error> for ControlError {
fn from(e: std::io::Error) -> Self {
Self::IoError(e)
}
}
impl std::fmt::Display for ControlError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::IoError(inner) => write!(f, "I/O error: {}", inner),
Self::ParseError(msg) => write!(f, "parse error: {}", msg),
}
}
}
impl std::error::Error for ControlError {}
#[derive(Clone, Debug)]
pub enum ControlFieldValue<'a> {
Simple(Cow<'a, str>),
Folded(Cow<'a, str>),
Multiline(Cow<'a, str>),
}
impl<'a> ControlFieldValue<'a> {
pub fn write<W: Write>(&self, writer: &mut W) -> std::io::Result<()> {
let data = match self {
Self::Simple(v) => v,
Self::Folded(v) => v,
Self::Multiline(v) => v,
};
writer.write_all(data.as_bytes())
}
}
impl<'a> From<Cow<'a, str>> for ControlFieldValue<'a> {
fn from(value: Cow<'a, str>) -> Self {
if value.contains('\n') {
if value.starts_with(' ') || value.starts_with('\t') {
ControlFieldValue::Multiline(value)
} else {
ControlFieldValue::Folded(value)
}
} else {
ControlFieldValue::Simple(value)
}
}
}
#[derive(Clone, Debug)]
pub struct ControlField<'a> {
name: Cow<'a, str>,
value: ControlFieldValue<'a>,
}
impl<'a> ControlField<'a> {
pub fn new(name: Cow<'a, str>, value: ControlFieldValue<'a>) -> Self {
Self { name, value }
}
pub fn from_string_value(key: Cow<'a, str>, value: Cow<'a, str>) -> Result<Self, ControlError> {
let value = ControlFieldValue::from(value);
Ok(Self { name: key, value })
}
pub fn write<W: Write>(&self, writer: &mut W) -> std::io::Result<()> {
writer.write_all(self.name.as_bytes())?;
writer.write_all(b": ")?;
self.value.write(writer)?;
writer.write_all(b"\n")
}
}
#[derive(Clone, Debug, Default)]
pub struct ControlParagraph<'a> {
fields: Vec<ControlField<'a>>,
}
impl<'a> ControlParagraph<'a> {
pub fn add_field(&mut self, field: ControlField<'a>) {
self.fields.push(field);
}
pub fn add_field_from_string(
&mut self,
name: Cow<'a, str>,
value: Cow<'a, str>,
) -> Result<(), ControlError> {
self.fields
.push(ControlField::from_string_value(name, value)?);
Ok(())
}
pub fn has_field(&self, name: &str) -> bool {
self.fields.iter().any(|f| f.name == name)
}
pub fn get_field(&self, name: &str) -> Option<&ControlField> {
self.fields.iter().find(|f| f.name == name)
}
pub fn get_field_mut(&mut self, name: &str) -> Option<&'a mut ControlField> {
self.fields.iter_mut().find(|f| f.name == name)
}
pub fn write<W: Write>(&self, writer: &mut W) -> std::io::Result<()> {
for field in &self.fields {
field.write(writer)?;
}
writer.write_all(b"\n")
}
}
#[derive(Clone, Debug, Default)]
pub struct ControlFile<'a> {
paragraphs: Vec<ControlParagraph<'a>>,
}
impl<'a> ControlFile<'a> {
pub fn parse_reader<R: BufRead>(reader: &mut R) -> Result<Self, ControlError> {
let mut paragraphs = Vec::new();
let mut current_paragraph = ControlParagraph::default();
let mut current_field: Option<String> = None;
loop {
let mut line = String::new();
let bytes_read = reader.read_line(&mut line)?;
let is_empty_line = line.trim().is_empty();
let is_indented = line.starts_with(' ') && line.len() > 1;
current_field = match (is_empty_line, current_field, is_indented) {
(_, Some(v), false) => {
let mut parts = v.splitn(2, ':');
let name = parts.next().ok_or_else(|| {
ControlError::ParseError(format!(
"error parsing line '{}'; missing colon",
line
))
})?;
let value = parts
.next()
.ok_or_else(|| {
ControlError::ParseError(format!(
"error parsing field '{}'; could not detect value",
v
))
})?
.trim();
current_paragraph.add_field_from_string(
Cow::Owned(name.to_string()),
Cow::Owned(value.to_string()),
)?;
if is_empty_line {
None
} else {
Some(line)
}
}
(true, _, _) => {
if !current_paragraph.fields.is_empty() {
paragraphs.push(current_paragraph);
current_paragraph = ControlParagraph::default();
}
None
}
(false, None, _) => Some(line),
(false, Some(v), true) => Some(v + &line),
};
if bytes_read == 0 {
break;
}
}
Ok(Self { paragraphs })
}
pub fn parse_str(s: &str) -> Result<Self, ControlError> {
let mut reader = std::io::BufReader::new(s.as_bytes());
Self::parse_reader(&mut reader)
}
pub fn add_paragraph(&mut self, p: ControlParagraph<'a>) {
self.paragraphs.push(p);
}
pub fn paragraphs(&self) -> impl Iterator<Item = &ControlParagraph<'a>> {
self.paragraphs.iter()
}
pub fn write<W: Write>(&self, writer: &mut W) -> std::io::Result<()> {
for p in &self.paragraphs {
p.write(writer)?;
}
Ok(())
}
}
#[derive(Default)]
pub struct SourceControl<'a> {
general: ControlParagraph<'a>,
binaries: Vec<ControlParagraph<'a>>,
}
impl<'a> SourceControl<'a> {
pub fn parse_reader<R: BufRead>(reader: &mut R) -> Result<Self, ControlError> {
let control = ControlFile::parse_reader(reader)?;
let mut paragraphs = control.paragraphs();
let general = paragraphs
.next()
.ok_or_else(|| {
ControlError::ParseError("no general paragraph in source control file".to_string())
})?
.to_owned();
let binaries = paragraphs.map(|x| x.to_owned()).collect();
Ok(Self { general, binaries })
}
pub fn parse_str(s: &str) -> Result<Self, ControlError> {
let mut reader = std::io::BufReader::new(s.as_bytes());
Self::parse_reader(&mut reader)
}
pub fn general_paragraph(&self) -> &ControlParagraph<'a> {
&self.general
}
pub fn binary_paragraphs(&self) -> impl Iterator<Item = &ControlParagraph<'a>> {
self.binaries.iter()
}
}
#[cfg(test)]
mod tests {
use {super::*, anyhow::Result};
#[test]
fn test_parse_system_lists() -> Result<()> {
let paths = glob::glob("/var/lib/apt/lists/*_Packages")?
.chain(glob::glob("/var/lib/apt/lists/*_Sources")?)
.chain(glob::glob("/var/lib/apt/lists/*i18n_Translation-*")?);
for path in paths {
let path = path?;
eprintln!("parsing {}", path.display());
let fh = std::fs::File::open(&path)?;
let mut reader = std::io::BufReader::new(fh);
ControlFile::parse_reader(&mut reader)?;
}
Ok(())
}
}