Skip to main content

alpm_db/desc/
file.rs

1use std::{
2    fmt::Display,
3    fs::File,
4    path::{Path, PathBuf},
5    str::FromStr,
6};
7
8use alpm_common::{FileFormatSchema, MetadataFile};
9use alpm_types::{FullVersion, InstalledPackage, Name};
10use fluent_i18n::t;
11
12use crate::{
13    Error,
14    desc::{DbDescFileV1, DbDescFileV2, DbDescSchema},
15};
16
17/// A representation of the [alpm-db-desc] file format.
18///
19/// Tracks all supported schema versions (`v1` and `v2`) of the database description file.
20/// Each variant corresponds to a distinct layout of the format.
21///
22/// [alpm-db-desc]: https://alpm.archlinux.page/specifications/alpm-db-desc.5.html
23#[derive(Clone, Debug, PartialEq, serde::Serialize)]
24#[serde(untagged)]
25pub enum DbDescFile {
26    /// The [alpm-db-descv1] file format.
27    ///
28    /// [alpm-db-descv1]: https://alpm.archlinux.page/specifications/alpm-db-descv1.5.html
29    V1(DbDescFileV1),
30    /// The [alpm-db-descv2] file format.
31    ///
32    /// This revision of the file format, adds the `%XDATA%` section.
33    ///
34    /// [alpm-db-descv2]: https://alpm.archlinux.page/specifications/alpm-db-descv2.5.html
35    V2(DbDescFileV2),
36}
37
38impl DbDescFile {
39    /// Returns an [`InstalledPackage`] for this [alpm-db-desc] file.
40    ///
41    /// [alpm-db-desc]: https://alpm.archlinux.page/specifications/alpm-db-desc.5.html
42    pub fn installed_package(&self) -> InstalledPackage {
43        match self {
44            DbDescFile::V1(DbDescFileV1 {
45                name,
46                version,
47                arch,
48                ..
49            })
50            | DbDescFile::V2(DbDescFileV2 {
51                name,
52                version,
53                arch,
54                ..
55            }) => InstalledPackage::new(name.clone(), version.clone(), arch.clone()),
56        }
57    }
58
59    /// Returns a reference to the [`Name`] for this file.
60    pub fn name(&self) -> &Name {
61        match self {
62            Self::V1(file) => &file.name,
63            Self::V2(file) => &file.name,
64        }
65    }
66
67    /// Returns a reference to the [`FullVersion`] for this file.
68    pub fn version(&self) -> &FullVersion {
69        match self {
70            Self::V1(file) => &file.version,
71            Self::V2(file) => &file.version,
72        }
73    }
74}
75
76impl MetadataFile<DbDescSchema> for DbDescFile {
77    type Err = Error;
78
79    /// Creates a [`DbDescFile`] from a file on disk, optionally validated using a [`DbDescSchema`].
80    ///
81    /// Opens the file and defers to [`DbDescFile::from_reader_with_schema`].
82    ///
83    /// # Examples
84    ///
85    /// ```
86    /// use std::{fs::File, io::Write};
87    ///
88    /// use alpm_common::{FileFormatSchema, MetadataFile};
89    /// use alpm_db::desc::{DbDescFile, DbDescSchema};
90    /// use alpm_types::{SchemaVersion, semver_version::Version};
91    ///
92    /// # fn main() -> testresult::TestResult {
93    /// // Prepare a file with DB desc data (v1)
94    /// let (file, desc_data) = {
95    ///     let desc_data = r#"%NAME%
96    /// foo
97    ///
98    /// %VERSION%
99    /// 1.0.0-1
100    ///
101    /// %BASE%
102    /// foo
103    ///
104    /// %DESC%
105    /// An example package
106    ///
107    /// %URL%
108    /// https://example.org/
109    ///
110    /// %ARCH%
111    /// x86_64
112    ///
113    /// %BUILDDATE%
114    /// 1733737242
115    ///
116    /// %INSTALLDATE%
117    /// 1733737243
118    ///
119    /// %PACKAGER%
120    /// Foobar McFooface <foobar@mcfooface.org>
121    ///
122    /// %SIZE%
123    /// 123
124    ///
125    /// %VALIDATION%
126    /// pgp
127    ///
128    /// "#;
129    ///     let file = tempfile::NamedTempFile::new()?;
130    ///     let mut output = File::create(&file)?;
131    ///     write!(output, "{}", desc_data)?;
132    ///     (file, desc_data)
133    /// };
134    ///
135    /// let db_desc = DbDescFile::from_file_with_schema(
136    ///     file.path(),
137    ///     Some(DbDescSchema::V1(SchemaVersion::new(Version::new(1, 0, 0)))),
138    /// )?;
139    /// assert_eq!(db_desc.to_string(), desc_data);
140    /// # Ok(())
141    /// # }
142    /// ```
143    ///
144    /// # Errors
145    ///
146    /// Returns an error if:
147    ///
148    /// - the file cannot be opened for reading,
149    /// - the contents cannot be parsed into any known [`DbDescFile`] variant,
150    /// - or the provided [`DbDescSchema`] does not match the contents of the file.
151    fn from_file_with_schema(
152        file: impl AsRef<Path>,
153        schema: Option<DbDescSchema>,
154    ) -> Result<Self, Error> {
155        let file = file.as_ref();
156        Self::from_reader_with_schema(
157            File::open(file).map_err(|source| Error::IoPath {
158                path: PathBuf::from(file),
159                context: t!("error-io-path-open-file"),
160                source,
161            })?,
162            schema,
163        )
164    }
165
166    /// Creates a [`DbDescFile`] from any readable stream, optionally validated using a
167    /// [`DbDescSchema`].
168    ///
169    /// Reads the `reader` to a string buffer and defers to [`DbDescFile::from_str_with_schema`].
170    ///
171    /// # Examples
172    ///
173    /// ```
174    /// use std::{fs::File, io::Write};
175    ///
176    /// use alpm_common::MetadataFile;
177    /// use alpm_db::desc::{DbDescFile, DbDescSchema};
178    /// use alpm_types::{SchemaVersion, semver_version::Version};
179    ///
180    /// # fn main() -> testresult::TestResult {
181    /// // Prepare a reader with DB desc data (v2)
182    /// let (reader, desc_data) = {
183    ///     let desc_data = r#"%NAME%
184    /// foo
185    ///
186    /// %VERSION%
187    /// 1.0.0-1
188    ///
189    /// %BASE%
190    /// foo
191    ///
192    /// %DESC%
193    /// An example package
194    ///
195    /// %URL%
196    /// https://example.org/
197    ///
198    /// %ARCH%
199    /// x86_64
200    ///
201    /// %BUILDDATE%
202    /// 1733737242
203    ///
204    /// %INSTALLDATE%
205    /// 1733737243
206    ///
207    /// %PACKAGER%
208    /// Foobar McFooface <foobar@mcfooface.org>
209    ///
210    /// %SIZE%
211    /// 123
212    ///
213    /// %VALIDATION%
214    /// pgp
215    ///
216    /// %XDATA%
217    /// pkgtype=pkg
218    ///
219    /// "#;
220    ///     let file = tempfile::NamedTempFile::new()?;
221    ///     let mut output = File::create(&file)?;
222    ///     write!(output, "{}", desc_data)?;
223    ///     (File::open(&file.path())?, desc_data)
224    /// };
225    ///
226    /// let db_desc = DbDescFile::from_reader_with_schema(
227    ///     reader,
228    ///     Some(DbDescSchema::V2(SchemaVersion::new(Version::new(2, 0, 0)))),
229    /// )?;
230    /// assert_eq!(db_desc.to_string(), desc_data);
231    /// # Ok(())
232    /// # }
233    /// ```
234    ///
235    /// # Errors
236    ///
237    /// Returns an error if:
238    ///
239    /// - the `reader` cannot be read to string,
240    /// - the data cannot be parsed into a known [`DbDescFile`] variant,
241    /// - or the provided [`DbDescSchema`] does not match the parsed content.
242    fn from_reader_with_schema(
243        mut reader: impl std::io::Read,
244        schema: Option<DbDescSchema>,
245    ) -> Result<Self, Error> {
246        let mut buf = String::new();
247        reader
248            .read_to_string(&mut buf)
249            .map_err(|source| Error::Io {
250                context: t!("error-io-read-db-desc-data"),
251                source,
252            })?;
253        Self::from_str_with_schema(&buf, schema)
254    }
255
256    /// Creates a [`DbDescFile`] from a string slice, optionally validated using a [`DbDescSchema`].
257    ///
258    /// If `schema` is [`None`], automatically infers the schema version by inspecting the input
259    /// (`v1` = no `%XDATA%` section, `v2` = has `%XDATA%`).
260    ///
261    /// # Examples
262    ///
263    /// ```
264    /// use alpm_common::MetadataFile;
265    /// use alpm_db::desc::{DbDescFile, DbDescSchema};
266    /// use alpm_types::{SchemaVersion, semver_version::Version};
267    ///
268    /// # fn main() -> testresult::TestResult {
269    /// let v1_data = r#"%NAME%
270    /// foo
271    ///
272    /// %VERSION%
273    /// 1.0.0-1
274    ///
275    /// %BASE%
276    /// foo
277    ///
278    /// %DESC%
279    /// An example package
280    ///
281    /// %URL%
282    /// https://example.org/
283    ///
284    /// %ARCH%
285    /// x86_64
286    ///
287    /// %BUILDDATE%
288    /// 1733737242
289    ///
290    /// %INSTALLDATE%
291    /// 1733737243
292    ///
293    /// %PACKAGER%
294    /// Foobar McFooface <foobar@mcfooface.org>
295    ///
296    /// %SIZE%
297    /// 123
298    ///
299    /// %VALIDATION%
300    /// pgp
301    ///
302    /// "#;
303    ///
304    /// let dbdesc_v1 = DbDescFile::from_str_with_schema(
305    ///     v1_data,
306    ///     Some(DbDescSchema::V1(SchemaVersion::new(Version::new(1, 0, 0)))),
307    /// )?;
308    /// assert_eq!(dbdesc_v1.to_string(), v1_data);
309    ///
310    /// let v2_data = r#"%NAME%
311    /// foo
312    ///
313    /// %VERSION%
314    /// 1.0.0-1
315    ///
316    /// %BASE%
317    /// foo
318    ///
319    /// %DESC%
320    /// An example package
321    ///
322    /// %URL%
323    /// https://example.org/
324    ///
325    /// %ARCH%
326    /// x86_64
327    ///
328    /// %BUILDDATE%
329    /// 1733737242
330    ///
331    /// %INSTALLDATE%
332    /// 1733737243
333    ///
334    /// %PACKAGER%
335    /// Foobar McFooface <foobar@mcfooface.org>
336    ///
337    /// %SIZE%
338    /// 123
339    ///
340    /// %VALIDATION%
341    /// pgp
342    ///
343    /// %XDATA%
344    /// pkgtype=pkg
345    ///
346    /// "#;
347    ///
348    /// let dbdesc_v2 = DbDescFile::from_str_with_schema(
349    ///     v2_data,
350    ///     Some(DbDescSchema::V2(SchemaVersion::new(Version::new(2, 0, 0)))),
351    /// )?;
352    /// assert_eq!(dbdesc_v2.to_string(), v2_data);
353    /// # Ok(())
354    /// # }
355    /// ```
356    ///
357    /// # Errors
358    ///
359    /// Returns an error if:
360    ///
361    /// - the input cannot be parsed into a valid [`DbDescFile`],
362    /// - or the derived or provided schema does not match the detected format.
363    fn from_str_with_schema(s: &str, schema: Option<DbDescSchema>) -> Result<Self, Error> {
364        let schema = match schema {
365            Some(schema) => schema,
366            None => DbDescSchema::derive_from_str(s)?,
367        };
368
369        match schema {
370            DbDescSchema::V1(_) => Ok(DbDescFile::V1(DbDescFileV1::from_str(s)?)),
371            DbDescSchema::V2(_) => Ok(DbDescFile::V2(DbDescFileV2::from_str(s)?)),
372        }
373    }
374}
375
376impl Display for DbDescFile {
377    /// Returns the textual representation of the [`DbDescFile`] in its corresponding
378    /// [alpm-db-desc] format.
379    ///
380    /// [alpm-db-desc]: https://alpm.archlinux.page/specifications/alpm-db-desc.5.html
381    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
382        match self {
383            Self::V1(file) => write!(f, "{file}"),
384            Self::V2(file) => write!(f, "{file}"),
385        }
386    }
387}
388
389impl FromStr for DbDescFile {
390    type Err = Error;
391
392    /// Creates a [`DbDescFile`] from a string slice.
393    ///
394    /// Internally calls [`DbDescFile::from_str_with_schema`] with `schema` set to [`None`].
395    ///
396    /// # Errors
397    ///
398    /// Returns an error if [`DbDescFile::from_str_with_schema`] fails.
399    fn from_str(s: &str) -> Result<Self, Self::Err> {
400        Self::from_str_with_schema(s, None)
401    }
402}