Skip to main content

alpm_pkginfo/
schema.rs

1//! Schemas for PKGINFO data.
2
3use std::{
4    collections::HashMap,
5    fmt::{Display, Formatter},
6    fs::File,
7    path::{Path, PathBuf},
8    str::FromStr,
9};
10
11use alpm_common::FileFormatSchema;
12use alpm_parsers::custom_ini::parser::Item;
13use alpm_types::{SchemaVersion, semver_version::Version};
14use fluent_i18n::t;
15
16use crate::Error;
17
18/// An enum tracking all available [PKGINFO] schemas.
19///
20/// The schema of a PKGINFO refers to its available fields in a specific version.
21///
22/// [PKGINFO]: https://alpm.archlinux.page/specifications/PKGINFO.5.html
23#[derive(Clone, Debug, Eq, PartialEq)]
24pub enum PackageInfoSchema {
25    /// Schema for the [PKGINFOv1] file format.
26    ///
27    /// [PKGINFOv1]: https://alpm.archlinux.page/specifications/PKGINFOv1.5.html
28    V1(SchemaVersion),
29    /// Schema for the [PKGINFOv2] file format.
30    ///
31    /// [PKGINFOv2]: https://alpm.archlinux.page/specifications/PKGINFOv2.5.html
32    V2(SchemaVersion),
33}
34
35impl AsRef<SchemaVersion> for PackageInfoSchema {
36    /// Returns a reference to the targeted [`SchemaVersion`].
37    fn as_ref(&self) -> &SchemaVersion {
38        match self {
39            PackageInfoSchema::V1(v) | PackageInfoSchema::V2(v) => v,
40        }
41    }
42}
43
44impl FileFormatSchema for PackageInfoSchema {
45    type Err = Error;
46
47    /// Derives a [`PackageInfoSchema`] from a PKGINFO file.
48    ///
49    /// Opens the `file` and defers to [`PackageInfoSchema::derive_from_reader`].
50    ///
51    /// # Errors
52    ///
53    /// Returns an error if
54    /// - opening `file` for reading fails
55    /// - or deriving a [`PackageInfoSchema`] from the contents of `file` fails.
56    fn derive_from_file(file: impl AsRef<Path>) -> Result<Self, Error>
57    where
58        Self: Sized,
59    {
60        let file = file.as_ref();
61        Self::derive_from_reader(File::open(file).map_err(|source| Error::IoPath {
62            path: PathBuf::from(file),
63            context: t!("error-io-derive-schema-from-pkginfo"),
64            source,
65        })?)
66    }
67
68    /// Derives a [`PackageInfoSchema`] from PKGINFO data in a `reader`.
69    ///
70    /// Reads the `reader` to string and defers to [`PackageInfoSchema::derive_from_str`].
71    ///
72    /// # Errors
73    ///
74    /// Returns an error if
75    /// - reading a [`String`] from `reader` fails
76    /// - or deriving a [`PackageInfoSchema`] from the contents of `reader` fails.
77    fn derive_from_reader(reader: impl std::io::Read) -> Result<Self, Error>
78    where
79        Self: Sized,
80    {
81        let mut buf = String::new();
82        let mut reader = reader;
83        reader
84            .read_to_string(&mut buf)
85            .map_err(|source| Error::IoRead {
86                context: t!("error-io-derive-schema-from-pkginfo"),
87                source,
88            })?;
89        Self::derive_from_str(&buf)
90    }
91
92    /// Derives a [`PackageInfoSchema`] from a string slice containing PKGINFO data.
93    ///
94    /// Since the PKGINFO format does not carry any version information, this function looks for the
95    /// first `xdata` field (if any) to determine whether the input may be [PKGINFOv2].
96    /// If no `xdata` field is found, [PKGINFOv1] is assumed.
97    ///
98    /// # Examples
99    ///
100    /// ```
101    /// use alpm_common::FileFormatSchema;
102    /// use alpm_pkginfo::PackageInfoSchema;
103    /// use alpm_types::{SchemaVersion, semver_version::Version};
104    ///
105    /// # fn main() -> Result<(), alpm_pkginfo::Error> {
106    /// let pkginfo_v2 = r#"
107    /// pkgname = example
108    /// pkgbase = example
109    /// pkgver = 1:1.0.0-1
110    /// pkgdesc = A project that does something
111    /// url = https://example.org/
112    /// builddate = 1729181726
113    /// packager = John Doe <john@example.org>
114    /// size = 181849963
115    /// arch = any
116    /// xdata = pkgtype=pkg
117    /// "#;
118    /// assert_eq!(
119    ///     PackageInfoSchema::V2(SchemaVersion::new(Version::new(2, 0, 0))),
120    ///     PackageInfoSchema::derive_from_str(pkginfo_v2)?
121    /// );
122    ///
123    /// let pkginfo_v1 = r#"
124    /// pkgname = example
125    /// pkgbase = example
126    /// pkgver = 1:1.0.0-1
127    /// pkgdesc = A project that does something
128    /// url = https://example.org/
129    /// builddate = 1729181726
130    /// packager = John Doe <john@example.org>
131    /// size = 181849963
132    /// arch = any
133    /// "#;
134    /// assert_eq!(
135    ///     PackageInfoSchema::V1(SchemaVersion::new(Version::new(1, 0, 0))),
136    ///     PackageInfoSchema::derive_from_str(pkginfo_v1)?
137    /// );
138    /// # Ok(())
139    /// # }
140    /// ```
141    ///
142    /// # Errors
143    ///
144    /// Returns an error if
145    /// - the first `xdata` keyword is assigned an empty string,
146    /// - or the first `xdata` keyword does not assign "pkgtype".
147    ///
148    /// [PKGINFOv1]: https://alpm.archlinux.page/specifications/PKGINFOv1.5.html
149    /// [PKGINFOv2]: https://alpm.archlinux.page/specifications/PKGINFOv2.5.html
150    fn derive_from_str(s: &str) -> Result<PackageInfoSchema, Error> {
151        // Deserialize the file into a simple map, so we can take a look at whether there is a
152        // `xdata` string that indicates PKGINFOv2.
153        let raw: HashMap<String, Item> = alpm_parsers::custom_ini::from_str(s)?;
154        let value = match raw.get("xdata") {
155            Some(Item::Value(value)) => Some(value),
156            Some(Item::List(values)) => {
157                if !values.is_empty() {
158                    values.iter().next()
159                } else {
160                    return Err(Error::ExtraDataEmpty);
161                }
162            }
163            None => return Ok(Self::V1(SchemaVersion::new(Version::new(1, 0, 0)))),
164        };
165
166        if let Some(value) = value {
167            if value.starts_with("pkgtype") {
168                Ok(Self::V2(SchemaVersion::new(Version::new(2, 0, 0))))
169            } else {
170                Err(Error::FirstExtraDataNotPkgType)
171            }
172        } else {
173            Err(Error::ExtraDataEmpty)
174        }
175    }
176}
177
178impl Default for PackageInfoSchema {
179    /// Returns the default [`PackageInfoSchema`] variant ([`PackageInfoSchema::V2`]).
180    fn default() -> Self {
181        Self::V2(SchemaVersion::new(Version::new(2, 0, 0)))
182    }
183}
184
185impl FromStr for PackageInfoSchema {
186    type Err = Error;
187
188    /// Creates a [`PackageInfoSchema`] from string slice `s`.
189    ///
190    /// Relies on [`SchemaVersion::from_str`] to create a corresponding [`PackageInfoSchema`] from
191    /// `s`.
192    ///
193    /// # Errors
194    ///
195    /// Returns an error if
196    /// - no [`SchemaVersion`] can be created from `s`,
197    /// - or the conversion from [`SchemaVersion`] to [`PackageInfoSchema`] fails.
198    fn from_str(s: &str) -> Result<PackageInfoSchema, Self::Err> {
199        match SchemaVersion::from_str(s) {
200            Ok(version) => Self::try_from(version),
201            Err(_) => Err(Error::UnsupportedSchemaVersion(s.to_string())),
202        }
203    }
204}
205
206impl TryFrom<SchemaVersion> for PackageInfoSchema {
207    type Error = Error;
208
209    /// Converts a [`SchemaVersion`] to a [`PackageInfoSchema`].
210    ///
211    /// # Errors
212    ///
213    /// Returns an error if the [`SchemaVersion`]'s inner [`Version`] does not provide a major
214    /// version that corresponds to a [`PackageInfoSchema`] variant.
215    fn try_from(value: SchemaVersion) -> Result<Self, Self::Error> {
216        match value.as_ref().major {
217            1 => Ok(PackageInfoSchema::V1(value)),
218            2 => Ok(PackageInfoSchema::V2(value)),
219            _ => Err(Error::UnsupportedSchemaVersion(value.to_string())),
220        }
221    }
222}
223
224impl Display for PackageInfoSchema {
225    fn fmt(&self, fmt: &mut Formatter) -> std::fmt::Result {
226        write!(
227            fmt,
228            "{}",
229            match self {
230                PackageInfoSchema::V1(version) | PackageInfoSchema::V2(version) =>
231                    version.as_ref().major,
232            }
233        )
234    }
235}