bazaar 3.5.3

Rust implementation of the Bazaar formats and protocols
Documentation
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
use crate::revision::Revision;
use crate::serializer::{Error, RevisionSerializer};
use crate::RevisionId;
use bendy::decoding::Object;
use bendy::encoding::Encoder;
use std::io::BufRead;
use std::io::Read;

pub struct BEncodeRevisionSerializer1;

impl RevisionSerializer for BEncodeRevisionSerializer1 {
    fn format_name(&self) -> &'static str {
        "10"
    }

    fn squashes_xml_invalid_characters(&self) -> bool {
        false
    }

    fn write_revision_to_string(&self, rev: &Revision) -> std::result::Result<Vec<u8>, Error> {
        let mut e = Encoder::new();
        e.emit_list(|e| {
            e.emit_list(|e| {
                e.emit_bytes(b"format")?;
                e.emit_int(10)?;
                Ok(())
            })?;
            if let Some(committer) = rev.committer.as_ref() {
                e.emit_list(|e| {
                    e.emit_bytes(b"committer")?;
                    e.emit_bytes(committer.as_bytes())?;
                    Ok(())
                })?;
            }
            if let Some(timezone) = rev.timezone {
                e.emit_list(|e| {
                    e.emit_bytes(b"timezone")?;
                    e.emit_int(timezone)?;
                    Ok(())
                })?;
            }
            e.emit_list(|e| {
                e.emit_bytes(b"properties")?;
                e.emit_dict(|mut e| {
                    let mut keys = rev.properties.keys().collect::<Vec<&String>>();
                    keys.sort_by_key(|k| k.as_bytes());
                    for k in keys {
                        let v = rev.properties.get(k).unwrap();
                        e.emit_pair_with(k.as_bytes(), |e| {
                            e.emit_bytes(v)?;
                            Ok(())
                        })?;
                    }
                    Ok(())
                })?;
                Ok(())
            })?;
            e.emit_list(|e| {
                e.emit_bytes(b"timestamp")?;
                e.emit_bytes(format!("{:.3}", rev.timestamp).as_bytes())?;
                Ok(())
            })?;
            e.emit_list(|e| {
                e.emit_bytes(b"revision-id")?;
                e.emit_bytes(rev.revision_id.0.as_slice())?;
                Ok(())
            })?;
            e.emit_list(|e| {
                e.emit_bytes(b"parent-ids")?;
                e.emit_list(|e| {
                    for p in rev.parent_ids.iter() {
                        e.emit_bytes(p.0.as_slice())?;
                    }
                    Ok(())
                })?;
                Ok(())
            })?;
            if let Some(inventory_sha1) = rev.inventory_sha1.as_ref() {
                e.emit_list(|e| {
                    e.emit_bytes(b"inventory-sha1")?;
                    e.emit_bytes(inventory_sha1.as_slice())?;
                    Ok(())
                })?;
            }
            e.emit_list(|e| {
                e.emit_bytes(b"message")?;
                e.emit_bytes(rev.message.as_bytes())?;
                Ok(())
            })?;
            Ok(())
        })
        .map_err(|e| Error::EncodeError(format!("failed to encode revision: {}", e)))?;
        e.get_output()
            .map_err(|e| Error::EncodeError(format!("failed to encode revision: {}", e)))
    }

    fn write_revision_to_lines(
        &self,
        rev: &Revision,
    ) -> Box<dyn Iterator<Item = Result<Vec<u8>, Error>>> {
        let buf = self.write_revision_to_string(rev);

        if let Err(e) = buf {
            return Box::new(std::iter::once(Err(e)));
        }

        let buf = buf.unwrap();

        let mut cursor = std::io::Cursor::new(buf);

        Box::new(std::iter::from_fn(move || {
            let mut buf = Vec::new();
            if let Err(e) = cursor.read_until(b'\n', &mut buf) {
                return Some(Err(Error::EncodeError(format!(
                    "failed to encode revision: {}",
                    e
                ))));
            }
            if buf.is_empty() {
                None
            } else {
                Some(Ok(buf))
            }
        }))
    }

    fn read_revision_from_string(&self, text: &[u8]) -> std::result::Result<Revision, Error> {
        let mut decoder = bendy::decoding::Decoder::new(text);
        let mut d = if let Some(Object::List(d)) = decoder
            .next_object()
            .map_err(|e| Error::DecodeError(format!("failed to decode bencode: {}", e)))?
        {
            d
        } else {
            return Err(Error::DecodeError("expected dict".to_string()));
        };
        let mut timestamp = None;
        let mut timezone = None;
        let mut committer = None;
        let mut properties = None;
        let mut message = None;
        let mut parent_ids = None;
        let mut revision_id = None;
        let mut inventory_sha1 = None;
        while let Some(entry) = d
            .next_object()
            .map_err(|e| Error::DecodeError(format!("failed to decode bencode: {}", e)))?
        {
            let mut tuple =
                entry.list_or_else(|_| Err(Error::DecodeError("expected tuple".to_string())))?;
            let key = tuple
                .next_object()
                .map_err(|e| Error::DecodeError(format!("expected tuple with key: {}", e)))?
                .ok_or_else(|| Error::DecodeError("expected tuple with key".to_string()))?
                .bytes_or_else(|_| {
                    Err(Error::DecodeError("expected tuple with key".to_string()))
                })?;
            let value = tuple
                .next_object()
                .map_err(|e| Error::DecodeError(format!("expected tuple with value: {}", e)))?
                .ok_or_else(|| Error::DecodeError("expected tuple with value".to_string()))?;
            match key {
                b"format" => {
                    if value
                        .integer_or(Err(Error::DecodeError("invalid format".to_string())))?
                        .parse::<u64>()
                        .map_err(|e| Error::DecodeError(format!("invalid format: {}", e)))?
                        != 10
                    {
                        return Err(Error::DecodeError("invalid format".to_string()));
                    }
                }
                b"timezone" => {
                    timezone = Some(
                        value
                            .integer_or(Err(Error::DecodeError("invalid timezone".to_string())))?
                            .parse()
                            .map_err(|e| Error::DecodeError(format!("invalid timezone: {}", e)))?,
                    );
                }
                b"timestamp" => {
                    timestamp = Some(
                        String::from_utf8(
                            value
                                .bytes_or(Err(Error::DecodeError("invalid timestamp".to_string())))?
                                .to_vec(),
                        )
                        .map_err(|e| Error::DecodeError(format!("invalid timestamp: {}", e)))?
                        .parse::<f64>()
                        .map_err(|e| Error::DecodeError(format!("invalid timestamp: {}", e)))?,
                    );
                }
                b"committer" => {
                    committer = Some(
                        String::from_utf8(
                            value
                                .bytes_or(Err(Error::DecodeError("invalid committer".to_string())))?
                                .to_vec(),
                        )
                        .map_err(|e| Error::DecodeError(format!("invalid committer: {}", e)))?,
                    );
                }
                b"parent-ids" => {
                    let mut ps =
                        value.list_or(Err(Error::DecodeError("invalid parent_ids".to_string())))?;
                    let mut gs = Vec::new();
                    while let Some(o) = ps.next_object().map_err(|e| {
                        Error::DecodeError(format!("failed to decode bencode: {}", e))
                    })? {
                        let p = RevisionId::from(
                            o.bytes_or(Err(Error::DecodeError("invalid parent_id".to_string())))?,
                        );
                        gs.push(p);
                    }
                    parent_ids = Some(gs);
                }
                b"revision-id" => {
                    revision_id = Some(RevisionId::from(
                        value
                            .bytes_or(Err(Error::DecodeError("invalid revision_id".to_string())))?,
                    ));
                }
                b"inventory-sha1" => {
                    inventory_sha1 = Some(
                        value
                            .bytes_or(Err(Error::DecodeError(
                                "invalid inventory_sha1".to_string(),
                            )))?
                            .to_vec(),
                    );
                }
                b"properties" => {
                    properties =
                        Some(
                            value
                                .dictionary_or_else(|_| {
                                    Err(Error::DecodeError("invalid properties".to_string()))
                                })
                                .map(|mut d| {
                                    let mut ps = std::collections::HashMap::new();
                                    while let Some((k, v)) = d.next_pair().map_err(|e| {
                                        Error::DecodeError(format!(
                                            "failed to decode bencode: {}",
                                            e
                                        ))
                                    })? {
                                        let v = v
                                            .bytes_or(Err(Error::DecodeError(format!(
                                                "invalid property {}",
                                                String::from_utf8_lossy(k)
                                            ))))?
                                            .to_vec();
                                        let k = String::from_utf8(k.to_vec()).map_err(|e| {
                                            Error::DecodeError(format!(
                                                "invalid property {}: {}",
                                                String::from_utf8_lossy(k),
                                                e
                                            ))
                                        })?;
                                        ps.insert(k, v);
                                    }
                                    Ok::<
                                        std::collections::HashMap<std::string::String, Vec<u8>>,
                                        Error,
                                    >(ps)
                                })??,
                        );
                }
                b"message" => {
                    message = Some(
                        String::from_utf8(
                            value
                                .bytes_or(Err(Error::DecodeError("invalid message".to_string())))?
                                .to_vec(),
                        )
                        .map_err(|e| Error::DecodeError(format!("invalid message: {}", e)))?,
                    );
                }
                _ => {
                    return Err(Error::DecodeError(format!(
                        "unknown key {}",
                        String::from_utf8_lossy(key)
                    )));
                }
            }
            if tuple
                .next_object()
                .map_err(|e| Error::DecodeError(format!("expected tuple: {}", e)))?
                .is_some()
            {
                return Err(Error::DecodeError("extra item in tuple".to_string()));
            }
        }

        Ok(Revision::new(
            revision_id.ok_or(Error::DecodeError("missing revision_id".to_string()))?,
            parent_ids.ok_or(Error::DecodeError("missing parent_ids".to_string()))?,
            committer,
            message.ok_or(Error::DecodeError("missing message".to_string()))?,
            properties.ok_or(Error::DecodeError("missing properties".to_string()))?,
            inventory_sha1,
            timestamp.ok_or(Error::DecodeError("missing timestamp".to_string()))?,
            timezone,
        ))
    }

    fn read_revision(&self, f: &mut dyn Read) -> std::result::Result<Revision, Error> {
        let mut buf = Vec::new();
        f.read_to_end(&mut buf).map_err(Error::IOError)?;
        self.read_revision_from_string(&buf)
    }
}

#[allow(dead_code)]
const BENCODE_REVISION_SERIALIZER_V1: BEncodeRevisionSerializer1 = BEncodeRevisionSerializer1 {};

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

    const WORKING_REVISION_BENCODE1: &[u8] = b"l\
l6:formati10ee\
l9:committer54:Canonical.com Patch Queue Manager <pqm@pqm.ubuntu.com>e\
l8:timezonei3600ee\
l10:propertiesd11:branch-nick6:+trunkee\
l9:timestamp14:1242300770.844e\
l11:revision-id50:pqm@pqm.ubuntu.com-20090514113250-jntkkpminfn3e0tze\
l10:parent-ids\
l\
50:pqm@pqm.ubuntu.com-20090514104039-kggemn7lrretzpvc\
48:jelmer@samba.org-20090510012654-jp9ufxquekaokbeo\
ee\
l14:inventory-sha140:4a2c7fb50e077699242cf6eb16a61779c7b680a7e\
l7:message35:(Jelmer) Move dpush to InterBranch.e\
e";

    const WORKING_REVISION_BENCODE1_NO_TIMEZONE: &[u8] = b"l\
l6:formati10ee\
l9:committer54:Canonical.com Patch Queue Manager <pqm@pqm.ubuntu.com>e\
l9:timestamp14:1242300770.844e\
l10:propertiesd11:branch-nick6:+trunkee\
l11:revision-id50:pqm@pqm.ubuntu.com-20090514113250-jntkkpminfn3e0tze\
l10:parent-ids\
l\
50:pqm@pqm.ubuntu.com-20090514104039-kggemn7lrretzpvc\
48:jelmer@samba.org-20090510012654-jp9ufxquekaokbeo\
ee\
l14:inventory-sha140:4a2c7fb50e077699242cf6eb16a61779c7b680a7e\
l7:message35:(Jelmer) Move dpush to InterBranch.e\
e";

    fn ser() -> BEncodeRevisionSerializer1 {
        BEncodeRevisionSerializer1
    }

    #[test]
    fn test_unpack_revision() {
        let rev = ser()
            .read_revision_from_string(WORKING_REVISION_BENCODE1)
            .unwrap();
        assert_eq!(
            rev.committer.as_deref(),
            Some("Canonical.com Patch Queue Manager <pqm@pqm.ubuntu.com>")
        );
        assert_eq!(
            rev.inventory_sha1.as_deref(),
            Some(b"4a2c7fb50e077699242cf6eb16a61779c7b680a7".as_slice())
        );
        assert_eq!(
            rev.parent_ids,
            vec![
                RevisionId::from(b"pqm@pqm.ubuntu.com-20090514104039-kggemn7lrretzpvc".to_vec()),
                RevisionId::from(b"jelmer@samba.org-20090510012654-jp9ufxquekaokbeo".to_vec()),
            ]
        );
        assert_eq!(rev.message, "(Jelmer) Move dpush to InterBranch.");
        assert_eq!(
            rev.revision_id,
            RevisionId::from(b"pqm@pqm.ubuntu.com-20090514113250-jntkkpminfn3e0tz".to_vec())
        );
        assert_eq!(rev.properties.get("branch-nick").unwrap(), b"+trunk");
        assert_eq!(rev.timezone, Some(3600));
    }

    #[test]
    fn test_written_form_matches() {
        let s = ser();
        let rev = s
            .read_revision_from_string(WORKING_REVISION_BENCODE1)
            .unwrap();
        let as_bytes = s.write_revision_to_string(&rev).unwrap();
        assert_eq!(as_bytes, WORKING_REVISION_BENCODE1);
    }

    #[test]
    fn test_unpack_revision_no_timezone() {
        let rev = ser()
            .read_revision_from_string(WORKING_REVISION_BENCODE1_NO_TIMEZONE)
            .unwrap();
        assert_eq!(rev.timezone, None);
    }

    fn assert_round_trips(rev: &Revision) {
        let s = ser();
        let bytes = s.write_revision_to_string(rev).unwrap();
        let round_tripped = s.read_revision_from_string(&bytes).unwrap();
        assert_eq!(&round_tripped, rev);
    }

    #[test]
    fn test_roundtrips_non_ascii() {
        let mut props: HashMap<String, Vec<u8>> = HashMap::new();
        // keep properties empty to match Python test
        props.clear();
        let rev = Revision::new(
            RevisionId::from(b"revid1".to_vec()),
            vec![],
            Some("Erik B\u{e5}gfors".to_string()),
            "\n\u{e5}me".to_string(),
            props,
            Some(b"4a2c7fb50e077699242cf6eb16a61779c7b680a7".to_vec()),
            1242385452.0,
            Some(3600),
        );
        assert_round_trips(&rev);
    }

    #[test]
    fn test_roundtrips_xml_invalid_chars() {
        let rev = Revision::new(
            RevisionId::from(b"revid1".to_vec()),
            vec![],
            Some("Erik B\u{e5}gfors".to_string()),
            "\t\u{e000}".to_string(),
            HashMap::new(),
            Some(b"4a2c7fb50e077699242cf6eb16a61779c7b680a7".to_vec()),
            1242385452.0,
            Some(3600),
        );
        assert_round_trips(&rev);
    }
}