debian_control/lossless/
changes.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
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
//! Changes files

/// Changes file
pub struct Changes(deb822_lossless::Paragraph);

/// Errors that can occur when parsing a Changes file.
#[derive(Debug)]
pub enum ParseError {
    /// An error occurred while parsing a Deb822 file.
    Deb822(deb822_lossless::Error),

    /// No paragraphs were found in the file.
    NoParagraphs,

    /// Multiple paragraphs were found in the file.
    MultipleParagraphs,
}

impl std::fmt::Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::Deb822(e) => write!(f, "{}", e),
            Self::NoParagraphs => write!(f, "no paragraphs found"),
            Self::MultipleParagraphs => write!(f, "multiple paragraphs found"),
        }
    }
}

impl std::error::Error for ParseError {}

impl From<deb822_lossless::Error> for ParseError {
    fn from(e: deb822_lossless::Error) -> Self {
        Self::Deb822(e)
    }
}

/// A file in a source package.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct File {
    /// MD5 checksum of the file.
    pub md5sum: String,
    /// Size of the file in bytes.
    pub size: usize,
    /// Section the file belongs to.
    pub section: String,
    /// Priority of the file.
    pub priority: crate::Priority,
    /// Filename of the file.
    pub filename: String,
}

impl std::fmt::Display for File {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(
            f,
            "{} {} {} {} {}",
            self.md5sum, self.size, self.section, self.priority, self.filename
        )
    }
}

impl std::str::FromStr for File {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut parts = s.split_whitespace();
        let md5sum = parts.next().ok_or(())?;
        let size = parts.next().ok_or(())?.parse().map_err(|_| ())?;
        let section = parts.next().ok_or(())?.to_string();
        let priority = parts.next().ok_or(())?.parse().map_err(|_| ())?;
        let filename = parts.next().ok_or(())?.to_string();
        Ok(Self {
            md5sum: md5sum.to_string(),
            size,
            section,
            priority,
            filename,
        })
    }
}

impl Changes {
    /// Returns the format of the Changes file.
    pub fn format(&self) -> Option<String> {
        self.0.get("Format").map(|s| s.to_string())
    }

    /// Set the format of the Changes file.
    pub fn set_format(&mut self, value: &str) {
        self.0.set("Format", value);
    }

    /// Returns the name of the source package.
    pub fn source(&self) -> Option<String> {
        self.0.get("Source").map(|s| s.to_string())
    }

    /// Returns the list of binary packages generated by the source package.
    pub fn binary(&self) -> Option<Vec<String>> {
        self.0
            .get("Binary")
            .map(|s| s.split_whitespace().map(|s| s.to_string()).collect())
    }

    /// Returns the architecture the source package is intended for.
    pub fn architecture(&self) -> Option<Vec<String>> {
        self.0
            .get("Architecture")
            .map(|s| s.split_whitespace().map(|s| s.to_string()).collect())
    }

    /// Returns the version of the source package.
    pub fn version(&self) -> Option<debversion::Version> {
        self.0.get("Version").map(|s| s.parse().unwrap())
    }

    /// Returns the distribution the source package is intended for.
    pub fn distribution(&self) -> Option<String> {
        self.0.get("Distribution").map(|s| s.to_string())
    }

    /// Returns the urgency of the source package.
    pub fn urgency(&self) -> Option<crate::fields::Urgency> {
        self.0.get("Urgency").map(|s| s.parse().unwrap())
    }

    /// Returns the name and email address of the person who maintains the package.
    pub fn maintainer(&self) -> Option<String> {
        self.0.get("Maintainer").map(|s| s.to_string())
    }

    /// Returns the name and email address of the person who uploaded the package.
    pub fn changed_by(&self) -> Option<String> {
        self.0.get("Changed-By").map(|s| s.to_string())
    }

    /// Returns the description of the source package.
    pub fn description(&self) -> Option<String> {
        self.0.get("Description").map(|s| s.to_string())
    }

    /// Returns the SHA-1 checksums of the files in the source package.
    pub fn checksums_sha1(&self) -> Option<Vec<crate::fields::Sha1Checksum>> {
        self.0
            .get("Checksums-Sha1")
            .map(|s| s.lines().map(|line| line.parse().unwrap()).collect())
    }

    /// Returns the SHA-256 checksums of the files in the source package.
    pub fn checksums_sha256(&self) -> Option<Vec<crate::fields::Sha256Checksum>> {
        self.0
            .get("Checksums-Sha256")
            .map(|s| s.lines().map(|line| line.parse().unwrap()).collect())
    }

    /// Returns the list of files in the source package.
    pub fn files(&self) -> Option<Vec<File>> {
        self.0
            .get("Files")
            .map(|s| s.lines().map(|line| line.parse().unwrap()).collect())
    }

    /// Returns the path to the pool directory for the source package.
    pub fn get_pool_path(&self) -> Option<String> {
        let files = self.files()?;

        let section = &files.first().unwrap().section;

        let section = if let Some((section, _subsection)) = section.split_once('/') {
            section
        } else {
            "main"
        };

        let source = self.source()?;

        let subdir = if source.starts_with("lib") {
            "lib".to_string()
        } else {
            source[..1].to_lowercase()
        };

        Some(format!("pool/{}/{}/{}", section, subdir, source))
    }

    /// Create a new Changes file.
    pub fn new() -> Self {
        let mut slf = Self(deb822_lossless::Paragraph::new());
        slf.set_format("1.8");
        slf
    }

    /// Read a Changes file from a file.
    pub fn from_file<P: AsRef<std::path::Path>>(path: P) -> Result<Self, ParseError> {
        let deb822 = deb822_lossless::Deb822::from_file(path)?;
        let mut paras = deb822.paragraphs();
        let para = match paras.next() {
            Some(para) => para,
            None => return Err(ParseError::NoParagraphs),
        };
        if paras.next().is_some() {
            return Err(ParseError::MultipleParagraphs);
        }
        Ok(Self(para))
    }

    /// Read a Changes file from a file, allowing syntax errors.
    pub fn from_file_relaxed<P: AsRef<std::path::Path>>(
        path: P,
    ) -> Result<(Self, Vec<String>), std::io::Error> {
        let (mut deb822, mut errors) = deb822_lossless::Deb822::from_file_relaxed(path)?;
        let mut paras = deb822.paragraphs();
        let para = match paras.next() {
            Some(para) => para,
            None => deb822.add_paragraph(),
        };
        if paras.next().is_some() {
            errors.push("multiple paragraphs found".to_string());
        }
        Ok((Self(para), errors))
    }

    /// Read a Changes file from a reader.
    pub fn read<R: std::io::Read>(mut r: R) -> Result<Self, ParseError> {
        let deb822 = deb822_lossless::Deb822::read(&mut r)?;
        let mut paras = deb822.paragraphs();
        let para = match paras.next() {
            Some(para) => para,
            None => return Err(ParseError::NoParagraphs),
        };
        if paras.next().is_some() {
            return Err(ParseError::MultipleParagraphs);
        }
        Ok(Self(para))
    }

    /// Read a Changes file from a reader, allowing syntax errors.
    pub fn read_relaxed<R: std::io::Read>(
        mut r: R,
    ) -> Result<(Self, Vec<String>), deb822_lossless::Error> {
        let (mut deb822, mut errors) = deb822_lossless::Deb822::read_relaxed(&mut r)?;
        let mut paras = deb822.paragraphs();
        let para = match paras.next() {
            Some(para) => para,
            None => deb822.add_paragraph(),
        };
        if paras.next().is_some() {
            errors.push("multiple paragraphs found".to_string());
        }
        Ok((Self(para), errors))
    }
}

impl Default for Changes {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(feature = "python-debian")]
impl pyo3::ToPyObject for Changes {
    fn to_object(&self, py: pyo3::Python) -> pyo3::PyObject {
        self.0.to_object(py)
    }
}

#[cfg(feature = "python-debian")]
impl pyo3::FromPyObject<'_> for Changes {
    fn extract_bound(ob: &pyo3::Bound<pyo3::PyAny>) -> pyo3::PyResult<Self> {
        use pyo3::prelude::*;
        Ok(Changes(ob.extract()?))
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn test_new() {
        let changes = super::Changes::new();
        assert_eq!(changes.format(), Some("1.8".to_string()));
    }

    #[test]
    fn test_parse() {
        let changes = r#"Format: 1.8
Date: Fri, 08 Sep 2023 18:23:59 +0100
Source: buildlog-consultant
Binary: python3-buildlog-consultant
Architecture: all
Version: 0.0.34-1
Distribution: unstable
Urgency: medium
Maintainer: Jelmer Vernooij <jelmer@debian.org>
Changed-By: Jelmer Vernooij <jelmer@debian.org>
Description:
 python3-buildlog-consultant - build log parser and analyser
Changes:
 buildlog-consultant (0.0.34-1) UNRELEASED; urgency=medium
 .
   * New upstream release.
   * Update standards version to 4.6.2, no changes needed.
Checksums-Sha1:
 f1657e628254428ad74542e82c253a181894e8d0 17153 buildlog-consultant_0.0.34-1_amd64.buildinfo
 b44493c05d014bcd59180942d0125b20ddf45d03 2550812 python3-buildlog-consultant_0.0.34-1_all.deb
Checksums-Sha256:
 342a5782bf6a4f282d9002f726d2cac9c689c7e0fa7f61a1b0ecbf4da7916bdb 17153 buildlog-consultant_0.0.34-1_amd64.buildinfo
 7f7e5df81ee23fbbe89015edb37e04f4bb40672fa6e9b1afd4fd698e57db78fd 2550812 python3-buildlog-consultant_0.0.34-1_all.deb
Files:
 aa83112b0f8774a573bcf0b7b5cc12cc 17153 python optional buildlog-consultant_0.0.34-1_amd64.buildinfo
 a55858b90fe0ca728c89c1a1132b45c5 2550812 python optional python3-buildlog-consultant_0.0.34-1_all.deb
"#;
        let changes = super::Changes::read(changes.as_bytes()).unwrap();
        assert_eq!(changes.format(), Some("1.8".to_string()));
        assert_eq!(changes.source(), Some("buildlog-consultant".to_string()));
        assert_eq!(
            changes.binary(),
            Some(vec!["python3-buildlog-consultant".to_string()])
        );
        assert_eq!(changes.architecture(), Some(vec!["all".to_string()]));
        assert_eq!(changes.version(), Some("0.0.34-1".parse().unwrap()));
        assert_eq!(changes.distribution(), Some("unstable".to_string()));
        assert_eq!(changes.urgency(), Some(crate::fields::Urgency::Medium));
        assert_eq!(
            changes.maintainer(),
            Some("Jelmer Vernooij <jelmer@debian.org>".to_string())
        );
        assert_eq!(
            changes.changed_by(),
            Some("Jelmer Vernooij <jelmer@debian.org>".to_string())
        );
        assert_eq!(
            changes.description(),
            Some("python3-buildlog-consultant - build log parser and analyser".to_string())
        );
        assert_eq!(
            changes.checksums_sha1(),
            Some(vec![
                "f1657e628254428ad74542e82c253a181894e8d0 17153 buildlog-consultant_0.0.34-1_amd64.buildinfo".parse().unwrap(),
                "b44493c05d014bcd59180942d0125b20ddf45d03 2550812 python3-buildlog-consultant_0.0.34-1_all.deb".parse().unwrap()
            ])
        );
        assert_eq!(
            changes.checksums_sha256(),
            Some(vec![
                "342a5782bf6a4f282d9002f726d2cac9c689c7e0fa7f61a1b0ecbf4da7916bdb 17153 buildlog-consultant_0.0.34-1_amd64.buildinfo"
                    .parse()
                    .unwrap(),
                "7f7e5df81ee23fbbe89015edb37e04f4bb40672fa6e9b1afd4fd698e57db78fd 2550812 python3-buildlog-consultant_0.0.34-1_all.deb"
                    .parse()
                    .unwrap()
            ])
        );
        assert_eq!(
            changes.files(),
            Some(vec![
                "aa83112b0f8774a573bcf0b7b5cc12cc 17153 python optional buildlog-consultant_0.0.34-1_amd64.buildinfo".parse().unwrap(),
                "a55858b90fe0ca728c89c1a1132b45c5 2550812 python optional python3-buildlog-consultant_0.0.34-1_all.deb".parse().unwrap()
            ])
        );

        assert_eq!(
            changes.get_pool_path(),
            Some("pool/main/b/buildlog-consultant".to_string())
        );
    }
}