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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

/*! Source package control files. */

use {
    crate::{
        control::{ControlFile, ControlParagraph},
        error::{DebianError, Result},
    },
    std::io::BufRead,
};

/// Represents a `debian/control` file.
///
/// Specified at <https://www.debian.org/doc/debian-policy/ch-controlfields.html#source-package-control-files-debian-control>.
///
/// The 1st paragraph defines the source package. Subsequent paragraphs define binary packages
/// that the source tree builds.
#[derive(Default)]
pub struct SourcePackageControlFile<'a> {
    general: ControlParagraph<'a>,
    binaries: Vec<ControlParagraph<'a>>,
}

impl<'a> SourcePackageControlFile<'a> {
    /// Construct an instance from an iterable of [ControlParagraph].
    pub fn from_paragraphs(
        mut paragraphs: impl Iterator<Item = ControlParagraph<'a>>,
    ) -> Result<Self> {
        let general = paragraphs.next().ok_or_else(|| {
            DebianError::ControlParseError(
                "no general paragraph in source control file".to_string(),
            )
        })?;

        let binaries = paragraphs.collect::<Vec<_>>();

        Ok(Self { general, binaries })
    }

    /// Construct an instance by parsing a control file from a reader.
    pub fn parse_reader<R: BufRead>(reader: &mut R) -> Result<Self> {
        let control = ControlFile::parse_reader(reader)?;

        Self::from_paragraphs(control.paragraphs().map(|x| x.to_owned()))
    }

    /// Construct an instance by parsing a string.
    pub fn parse_str(s: &str) -> Result<Self> {
        let mut reader = std::io::BufReader::new(s.as_bytes());
        Self::parse_reader(&mut reader)
    }

    /// Obtain a handle on the general paragraph.
    pub fn general_paragraph(&self) -> &ControlParagraph<'a> {
        &self.general
    }

    /// Obtain an iterator over paragraphs defining binaries.
    pub fn binary_paragraphs(&self) -> impl Iterator<Item = &ControlParagraph<'a>> {
        self.binaries.iter()
    }
}