alpm_db/desc/schema.rs
1//! Schema definition for the [alpm-db-desc] file format.
2//!
3//! [alpm-db-desc]: https://alpm.archlinux.page/specifications/alpm-db-desc.5.html
4
5use std::{
6 fmt::{Display, Formatter},
7 fs::File,
8 path::{Path, PathBuf},
9 str::FromStr,
10};
11
12use alpm_common::FileFormatSchema;
13use alpm_types::{SchemaVersion, semver_version::Version};
14use fluent_i18n::t;
15
16use crate::Error;
17
18/// An enum describing all valid [alpm-db-desc] schemas.
19///
20/// Each variant corresponds to a specific revision of the
21/// specification.
22///
23/// [alpm-db-desc]: https://alpm.archlinux.page/specifications/alpm-db-desc.5.html
24#[derive(Clone, Debug, Eq, PartialEq)]
25pub enum DbDescSchema {
26 /// Schema for the [alpm-db-descv1] file format.
27 ///
28 /// [alpm-db-descv1]: https://alpm.archlinux.page/specifications/alpm-db-descv1.5.html
29 V1(SchemaVersion),
30 /// Schema for the [alpm-db-descv2] file format.
31 ///
32 /// [alpm-db-descv2]: https://alpm.archlinux.page/specifications/alpm-db-descv2.5.html
33 V2(SchemaVersion),
34}
35
36impl AsRef<SchemaVersion> for DbDescSchema {
37 /// Returns a reference to the targeted [`SchemaVersion`].
38 fn as_ref(&self) -> &SchemaVersion {
39 match self {
40 DbDescSchema::V1(v) => v,
41 DbDescSchema::V2(v) => v,
42 }
43 }
44}
45
46impl FileFormatSchema for DbDescSchema {
47 type Err = Error;
48
49 /// Derives a [`DbDescSchema`] from an [alpm-db-desc] file on disk.
50 ///
51 /// Opens the `file` and defers to [`DbDescSchema::derive_from_reader`].
52 ///
53 /// # Errors
54 ///
55 /// Returns an error if:
56 ///
57 /// - the file cannot be opened for reading,
58 /// - or deriving a [`DbDescSchema`] from its contents fails.
59 ///
60 /// [alpm-db-desc]: https://alpm.archlinux.page/specifications/alpm-db-desc.5.html
61 fn derive_from_file(file: impl AsRef<Path>) -> Result<Self, Error>
62 where
63 Self: Sized,
64 {
65 let file = file.as_ref();
66 Self::derive_from_reader(File::open(file).map_err(|source| Error::IoPath {
67 path: PathBuf::from(file),
68 context: t!("error-io-path-schema-file"),
69 source,
70 })?)
71 }
72
73 /// Derives a [`DbDescSchema`] from [alpm-db-desc] data in a reader.
74 ///
75 /// Reads the `reader` to a string and defers to [`DbDescSchema::derive_from_str`].
76 ///
77 /// # Errors
78 ///
79 /// Returns an error if:
80 ///
81 /// - reading from `reader` fails,
82 /// - or deriving a [`DbDescSchema`] from its contents fails.
83 ///
84 /// [alpm-db-desc]: https://alpm.archlinux.page/specifications/alpm-db-desc.5.html
85 fn derive_from_reader(reader: impl std::io::Read) -> Result<Self, Error>
86 where
87 Self: Sized,
88 {
89 let mut buf = String::new();
90 let mut reader = reader;
91 reader
92 .read_to_string(&mut buf)
93 .map_err(|source| Error::IoRead {
94 context: t!("error-io-read-schema-data"),
95 source,
96 })?;
97 Self::derive_from_str(&buf)
98 }
99
100 /// Derives a [`DbDescSchema`] from a string slice containing [alpm-db-desc] data.
101 ///
102 /// The parser uses a simple heuristic:
103 ///
104 /// - v1 → no `%XDATA%` section present
105 /// - v2 → `%XDATA%` section present
106 ///
107 /// This approach avoids relying on explicit version metadata, as the DB desc
108 /// format itself is not self-describing.
109 ///
110 /// # Examples
111 ///
112 /// ```
113 /// use alpm_common::FileFormatSchema;
114 /// use alpm_db::desc::DbDescSchema;
115 /// use alpm_types::{SchemaVersion, semver_version::Version};
116 ///
117 /// # fn main() -> Result<(), alpm_db::Error> {
118 /// let v1_data = r#"%NAME%
119 /// foo
120 ///
121 /// %VERSION%
122 /// 1.0.0-1
123 /// "#;
124 ///
125 /// assert_eq!(
126 /// DbDescSchema::V1(SchemaVersion::new(Version::new(1, 0, 0))),
127 /// DbDescSchema::derive_from_str(v1_data)?
128 /// );
129 ///
130 /// let v2_data = r#"%NAME%
131 /// foo
132 ///
133 /// %VERSION%
134 /// 1.0.0-1
135 ///
136 /// %XDATA%
137 /// pkgtype=pkg
138 /// "#;
139 ///
140 /// assert_eq!(
141 /// DbDescSchema::V2(SchemaVersion::new(Version::new(2, 0, 0))),
142 /// DbDescSchema::derive_from_str(v2_data)?
143 /// );
144 /// # Ok(())
145 /// # }
146 /// ```
147 ///
148 /// # Errors
149 ///
150 /// Returns an error only if internal conversion or string handling fails.
151 ///
152 /// [alpm-db-desc]: https://alpm.archlinux.page/specifications/alpm-db-desc.5.html
153 fn derive_from_str(s: &str) -> Result<DbDescSchema, Error> {
154 // Instead of an explicit "format" key, we use a heuristic:
155 // presence of `%XDATA%` implies version 2.
156 if s.contains("%XDATA%") {
157 Ok(DbDescSchema::V2(SchemaVersion::new(Version::new(2, 0, 0))))
158 } else {
159 Ok(DbDescSchema::V1(SchemaVersion::new(Version::new(1, 0, 0))))
160 }
161 }
162}
163
164impl Default for DbDescSchema {
165 /// Returns the default schema variant ([`DbDescSchema::V2`]).
166 fn default() -> Self {
167 Self::V2(SchemaVersion::new(Version::new(2, 0, 0)))
168 }
169}
170
171impl FromStr for DbDescSchema {
172 type Err = Error;
173
174 /// Parses a [`DbDescSchema`] from a version string.
175 ///
176 /// # Errors
177 ///
178 /// Returns an error if:
179 ///
180 /// - the input string is not a valid version,
181 /// - or the version does not correspond to a known schema variant.
182 fn from_str(s: &str) -> Result<DbDescSchema, Self::Err> {
183 match SchemaVersion::from_str(s) {
184 Ok(version) => Self::try_from(version),
185 Err(_) => Err(Error::UnsupportedSchemaVersion(s.to_string())),
186 }
187 }
188}
189
190impl TryFrom<SchemaVersion> for DbDescSchema {
191 type Error = Error;
192
193 /// Converts a [`SchemaVersion`] into a corresponding [`DbDescSchema`].
194 ///
195 /// # Errors
196 ///
197 /// Returns an error if the major version of `SchemaVersion` does not
198 /// correspond to a known [`DbDescSchema`] variant.
199 fn try_from(value: SchemaVersion) -> Result<Self, Self::Error> {
200 match value.as_ref().major {
201 1 => Ok(DbDescSchema::V1(value)),
202 2 => Ok(DbDescSchema::V2(value)),
203 _ => Err(Error::UnsupportedSchemaVersion(value.to_string())),
204 }
205 }
206}
207
208impl Display for DbDescSchema {
209 fn fmt(&self, fmt: &mut Formatter) -> std::fmt::Result {
210 write!(
211 fmt,
212 "{}",
213 match self {
214 DbDescSchema::V1(version) | DbDescSchema::V2(version) => version.as_ref().major,
215 }
216 )
217 }
218}