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)]
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)]
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.
154pub struct Control {
155    /// The source package.
156    pub source: Source,
157    /// The binary packages.
158    pub binaries: Vec<Binary>,
159}
160
161impl std::fmt::Display for Control {
162    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
163        write!(f, "{}", self.source)?;
164        for binary in &self.binaries {
165            f.write_str("\n")?;
166            write!(f, "{}", binary)?;
167        }
168        Ok(())
169    }
170}
171
172impl std::str::FromStr for Control {
173    type Err = String;
174
175    fn from_str(s: &str) -> Result<Self, Self::Err> {
176        let deb822: deb822_fast::Deb822 = s.parse().map_err(|e| format!("parse error: {}", e))?;
177
178        let mut source: Option<Source> = None;
179        let mut binaries: Vec<Binary> = Vec::new();
180
181        for para in deb822.iter() {
182            if para.get("Package").is_some() {
183                let binary: Binary = Binary::from_paragraph(para)?;
184                binaries.push(binary);
185            } else if para.get("Source").is_some() {
186                if source.is_some() {
187                    return Err("more than one source paragraph".to_string());
188                }
189                source = Some(Source::from_paragraph(para)?);
190            } else {
191                return Err("paragraph without Source or Package field".to_string());
192            }
193        }
194
195        Ok(Control {
196            source: source.ok_or_else(|| "no source paragraph".to_string())?,
197            binaries,
198        })
199    }
200}
201
202impl Default for Control {
203    fn default() -> Self {
204        Self::new()
205    }
206}
207
208impl Control {
209    /// Create a new control file.
210    pub fn new() -> Self {
211        Self {
212            source: Source::default(),
213            binaries: Vec::new(),
214        }
215    }
216
217    /// Add a new binary package to the control file.
218    pub fn add_binary(&mut self, name: &str) -> &mut Binary {
219        let binary = Binary {
220            name: name.to_string(),
221            ..Default::default()
222        };
223        self.binaries.push(binary);
224        self.binaries.last_mut().unwrap()
225    }
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231    use crate::relations::VersionConstraint;
232    #[test]
233    fn test_parse() {
234        let control: Control = r#"Source: foo
235Section: libs
236Priority: optional
237Build-Depends: bar (>= 1.0.0), baz (>= 1.0.0)
238Homepage: https://example.com
239
240"#
241        .parse()
242        .unwrap();
243        let source = &control.source;
244
245        assert_eq!(source.name, "foo".to_owned());
246        assert_eq!(source.section, Some("libs".to_owned()));
247        assert_eq!(source.priority, Some(super::Priority::Optional));
248        assert_eq!(
249            source.homepage,
250            Some("https://example.com".parse().unwrap())
251        );
252        let bd = source.build_depends.as_ref().unwrap();
253        let mut entries = bd.iter().collect::<Vec<_>>();
254        assert_eq!(entries.len(), 2);
255        let rel = entries[0].pop().unwrap();
256        assert_eq!(rel.name, "bar");
257        assert_eq!(
258            rel.version,
259            Some((
260                VersionConstraint::GreaterThanEqual,
261                "1.0.0".parse().unwrap()
262            ))
263        );
264        let rel = entries[1].pop().unwrap();
265        assert_eq!(rel.name, "baz");
266        assert_eq!(
267            rel.version,
268            Some((
269                VersionConstraint::GreaterThanEqual,
270                "1.0.0".parse().unwrap()
271            ))
272        );
273    }
274
275    #[test]
276    fn test_description() {
277        let control: Control = r#"Source: foo
278
279Package: foo
280Description: this is the short description
281 And the longer one
282 .
283 is on the next lines
284"#
285        .parse()
286        .unwrap();
287        let binary = &control.binaries[0];
288        assert_eq!(
289            binary.description,
290            Some(
291                "this is the short description\nAnd the longer one\n.\nis on the next lines"
292                    .to_owned()
293            )
294        );
295    }
296}