debian_control/lossy/
control.rs

1use crate::fields::Priority;
2use crate::lossy::relations::Relations;
3use deb822_fast::{FromDeb822, ToDeb822};
4use deb822_fast::{FromDeb822Paragraph, ToDeb822Paragraph};
5
6fn deserialize_yesno(s: &str) -> Result<bool, String> {
7    match s {
8        "yes" => Ok(true),
9        "no" => Ok(false),
10        _ => Err(format!("invalid value for yesno: {}", s)),
11    }
12}
13
14fn serialize_yesno(b: &bool) -> String {
15    if *b {
16        "yes".to_string()
17    } else {
18        "no".to_string()
19    }
20}
21
22/// The source package.
23#[derive(FromDeb822, ToDeb822, Default, Clone, PartialEq)]
24pub struct Source {
25    #[deb822(field = "Source")]
26    /// The name of the source package.
27    pub name: String,
28    #[deb822(field = "Build-Depends")]
29    /// The packages that this package depends on during build.
30    pub build_depends: Option<Relations>,
31    #[deb822(field = "Build-Depends-Indep")]
32    /// The packages that this package depends on during build.
33    pub build_depends_indep: Option<Relations>,
34    #[deb822(field = "Build-Depends-Arch")]
35    /// The packages that this package depends on during build.
36    pub build_depends_arch: Option<Relations>,
37    #[deb822(field = "Build-Conflicts")]
38    /// The packages that this package conflicts with during build.
39    pub build_conflicts: Option<Relations>,
40    #[deb822(field = "Build-Conflicts-Indep")]
41    /// The packages that this package conflicts with during build.
42    pub build_conflicts_indep: Option<Relations>,
43    #[deb822(field = "Build-Conflicts-Arch")]
44    /// The packages that this package conflicts with during build.
45    pub build_conflicts_arch: Option<Relations>,
46    #[deb822(field = "Standards-Version")]
47    /// The version of the Debian Policy Manual that the package complies with.
48    pub standards_version: Option<String>,
49    #[deb822(field = "Homepage")]
50    /// The homepage of the package.
51    pub homepage: Option<url::Url>,
52    #[deb822(field = "Section")]
53    /// The section of the package.
54    pub section: Option<String>,
55    #[deb822(field = "Priority")]
56    /// The priority of the package.
57    pub priority: Option<Priority>,
58    #[deb822(field = "Maintainer")]
59    /// The maintainer of the package.
60    pub maintainer: Option<String>,
61    #[deb822(field = "Uploaders")]
62    /// The uploaders of the package.
63    pub uploaders: Option<String>,
64    #[deb822(field = "Architecture")]
65    /// The architecture the package is built for.
66    pub architecture: Option<String>,
67    #[deb822(field = "Rules-Requires-Root", deserialize_with = deserialize_yesno, serialize_with = serialize_yesno)]
68    /// Whether the package's build rules require root.
69    pub rules_requires_root: Option<bool>,
70    #[deb822(field = "Testsuite")]
71    /// The name of the test suite.
72    pub testsuite: Option<String>,
73    #[deb822(field = "Vcs-Git")]
74    /// The URL of the Git repository.
75    pub vcs_git: Option<crate::vcs::ParsedVcs>,
76    #[deb822(field = "Vcs-Browser")]
77    /// The URL to the web interface of the VCS.
78    pub vcs_browser: Option<url::Url>,
79}
80
81impl std::fmt::Display for Source {
82    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
83        let para: deb822_fast::Paragraph = self.to_paragraph();
84        write!(f, "{}", para)?;
85        Ok(())
86    }
87}
88
89/// A binary package.
90#[derive(FromDeb822, ToDeb822, Default, Clone, PartialEq)]
91pub struct Binary {
92    #[deb822(field = "Package")]
93    /// The name of the package.
94    pub name: String,
95    #[deb822(field = "Depends")]
96    /// The packages that this package depends on.
97    pub depends: Option<Relations>,
98    #[deb822(field = "Recommends")]
99    /// The packages that this package recommends.
100    pub recommends: Option<Relations>,
101    #[deb822(field = "Suggests")]
102    /// The packages that this package suggests.
103    pub suggests: Option<Relations>,
104    #[deb822(field = "Enhances")]
105    /// The packages that this package enhances.
106    pub enhances: Option<Relations>,
107    #[deb822(field = "Pre-Depends")]
108    /// The packages that this package depends on before it is installed.
109    pub pre_depends: Option<Relations>,
110    #[deb822(field = "Breaks")]
111    /// The packages that this package breaks.
112    pub breaks: Option<Relations>,
113    #[deb822(field = "Conflicts")]
114    /// The packages that this package conflicts with.
115    pub conflicts: Option<Relations>,
116    #[deb822(field = "Replaces")]
117    /// The packages that this package replaces.
118    pub replaces: Option<Relations>,
119    #[deb822(field = "Provides")]
120    /// The packages that this package provides.
121    pub provides: Option<Relations>,
122    #[deb822(field = "Built-Using")]
123    /// The packages that this package is built using.
124    pub built_using: Option<Relations>,
125    #[deb822(field = "Architecture")]
126    /// The architecture the package is built for.
127    pub architecture: Option<String>,
128    #[deb822(field = "Section")]
129    /// The section of the package.
130    pub section: Option<String>,
131    #[deb822(field = "Priority")]
132    /// The priority of the package.
133    pub priority: Option<Priority>,
134    #[deb822(field = "Multi-Arch")]
135    /// The multi-arch field.
136    pub multi_arch: Option<crate::fields::MultiArch>,
137    #[deb822(field = "Essential", deserialize_with = deserialize_yesno, serialize_with = serialize_yesno)]
138    /// Whether the package is essential.
139    pub essential: Option<bool>,
140    #[deb822(field = "Description")]
141    /// The description of the package. The first line is the short description, and the rest is the long description.
142    pub description: Option<String>,
143}
144
145impl std::fmt::Display for Binary {
146    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
147        let para: deb822_fast::Paragraph = self.to_paragraph();
148        write!(f, "{}", para)?;
149        Ok(())
150    }
151}
152
153/// A control file.
154#[derive(Clone, PartialEq)]
155pub struct Control {
156    /// The source package.
157    pub source: Source,
158    /// The binary packages.
159    pub binaries: Vec<Binary>,
160}
161
162impl std::fmt::Display for Control {
163    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
164        write!(f, "{}", self.source)?;
165        for binary in &self.binaries {
166            f.write_str("\n")?;
167            write!(f, "{}", binary)?;
168        }
169        Ok(())
170    }
171}
172
173impl std::str::FromStr for Control {
174    type Err = String;
175
176    fn from_str(s: &str) -> Result<Self, Self::Err> {
177        let deb822: deb822_fast::Deb822 = s.parse().map_err(|e| format!("parse error: {}", e))?;
178
179        let mut source: Option<Source> = None;
180        let mut binaries: Vec<Binary> = Vec::new();
181
182        for para in deb822.iter() {
183            if para.get("Package").is_some() {
184                let binary: Binary = Binary::from_paragraph(para)?;
185                binaries.push(binary);
186            } else if para.get("Source").is_some() {
187                if source.is_some() {
188                    return Err("more than one source paragraph".to_string());
189                }
190                source = Some(Source::from_paragraph(para)?);
191            } else {
192                return Err("paragraph without Source or Package field".to_string());
193            }
194        }
195
196        Ok(Control {
197            source: source.ok_or_else(|| "no source paragraph".to_string())?,
198            binaries,
199        })
200    }
201}
202
203impl Default for Control {
204    fn default() -> Self {
205        Self::new()
206    }
207}
208
209impl Control {
210    /// Create a new control file.
211    pub fn new() -> Self {
212        Self {
213            source: Source::default(),
214            binaries: Vec::new(),
215        }
216    }
217
218    /// Add a new binary package to the control file.
219    pub fn add_binary(&mut self, name: &str) -> &mut Binary {
220        let binary = Binary {
221            name: name.to_string(),
222            ..Default::default()
223        };
224        self.binaries.push(binary);
225        self.binaries.last_mut().unwrap()
226    }
227}
228
229#[cfg(test)]
230mod tests {
231    use super::*;
232    use crate::relations::VersionConstraint;
233    #[test]
234    fn test_parse() {
235        let control: Control = r#"Source: foo
236Section: libs
237Priority: optional
238Build-Depends: bar (>= 1.0.0), baz (>= 1.0.0)
239Homepage: https://example.com
240
241"#
242        .parse()
243        .unwrap();
244        let source = &control.source;
245
246        assert_eq!(source.name, "foo".to_owned());
247        assert_eq!(source.section, Some("libs".to_owned()));
248        assert_eq!(source.priority, Some(super::Priority::Optional));
249        assert_eq!(
250            source.homepage,
251            Some("https://example.com".parse().unwrap())
252        );
253        let bd = source.build_depends.as_ref().unwrap();
254        let mut entries = bd.iter().collect::<Vec<_>>();
255        assert_eq!(entries.len(), 2);
256        let rel = entries[0].pop().unwrap();
257        assert_eq!(rel.name, "bar");
258        assert_eq!(
259            rel.version,
260            Some((
261                VersionConstraint::GreaterThanEqual,
262                "1.0.0".parse().unwrap()
263            ))
264        );
265        let rel = entries[1].pop().unwrap();
266        assert_eq!(rel.name, "baz");
267        assert_eq!(
268            rel.version,
269            Some((
270                VersionConstraint::GreaterThanEqual,
271                "1.0.0".parse().unwrap()
272            ))
273        );
274    }
275
276    #[test]
277    fn test_description() {
278        let control: Control = r#"Source: foo
279
280Package: foo
281Description: this is the short description
282 And the longer one
283 .
284 is on the next lines
285"#
286        .parse()
287        .unwrap();
288        let binary = &control.binaries[0];
289        assert_eq!(
290            binary.description,
291            Some(
292                "this is the short description\nAnd the longer one\n.\nis on the next lines"
293                    .to_owned()
294            )
295        );
296    }
297}