alpm_db/files/schema.rs
1//! Schema definition for the [alpm-db-files] format.
2//!
3//! [alpm-db-files]: https://alpm.archlinux.page/specifications/alpm-db-files.5.html
4
5use std::{fs::File, io::Read, path::Path};
6
7use alpm_common::FileFormatSchema;
8use alpm_types::{SchemaVersion, semver_version::Version};
9use fluent_i18n::t;
10
11use crate::files::{Error, v1::FilesSection};
12
13/// A schema for the [alpm-db-files] format.
14///
15/// [alpm-db-files]: https://alpm.archlinux.page/specifications/alpm-db-files.5.html
16#[derive(Clone, Debug, Eq, PartialEq)]
17pub enum DbFilesSchema {
18 /// Version 1 of the [alpm-db-files] specification.
19 ///
20 /// [alpm-db-files]: https://alpm.archlinux.page/specifications/alpm-db-files.5.html
21 V1(SchemaVersion),
22}
23
24impl AsRef<SchemaVersion> for DbFilesSchema {
25 /// Returns a reference to the targeted [`SchemaVersion`].
26 fn as_ref(&self) -> &SchemaVersion {
27 match self {
28 DbFilesSchema::V1(v) => v,
29 }
30 }
31}
32
33impl FileFormatSchema for DbFilesSchema {
34 type Err = crate::Error;
35
36 /// Creates a new [`DbFilesSchema`] from a file [`Path`].
37 ///
38 /// # Note
39 ///
40 /// Delegates to [`Self::derive_from_reader`] after opening `file` for reading.
41 ///
42 /// # Errors
43 ///
44 /// Returns an error if
45 ///
46 /// - `file` cannot be opened for reading,
47 /// - or [`Self::derive_from_reader`] fails.
48 ///
49 /// # Examples
50 ///
51 /// ```
52 /// use std::io::Write;
53 ///
54 /// use alpm_common::FileFormatSchema;
55 /// use alpm_db::files::DbFilesSchema;
56 /// use tempfile::NamedTempFile;
57 ///
58 /// # fn main() -> testresult::TestResult {
59 /// let data = r#"%FILES%
60 /// usr/
61 /// usr/bin/
62 /// usr/bin/foo
63 /// "#;
64 /// let mut temp_file = NamedTempFile::new()?;
65 /// write!(temp_file, "{data}");
66 /// let schema = DbFilesSchema::derive_from_file(temp_file.path())?;
67 /// matches!(schema, DbFilesSchema::V1(_));
68 ///
69 /// // Empty inputs may also be considered as a schema
70 /// let mut temp_file = NamedTempFile::new()?;
71 /// let schema = DbFilesSchema::derive_from_file(temp_file.path())?;
72 /// matches!(schema, DbFilesSchema::V1(_));
73 /// # Ok(())
74 /// # }
75 /// ```
76 fn derive_from_file(file: impl AsRef<Path>) -> Result<Self, Self::Err>
77 where
78 Self: Sized,
79 {
80 let file = file.as_ref();
81 Self::derive_from_reader(File::open(file).map_err(|source| crate::Error::IoPath {
82 path: file.to_path_buf(),
83 context: t!("error-io-path-context-deriving-schema-version-from-alpm-db-files-file"),
84 source,
85 })?)
86 }
87
88 /// Creates a new [`DbFilesSchema`] from a [`Read`] implementation.
89 ///
90 /// # Note
91 ///
92 /// Delegates to [`Self::derive_from_str`] after reading the `reader` to string.
93 ///
94 /// # Errors
95 ///
96 /// Returns an error if
97 ///
98 /// - `reader` cannot be read to string,
99 /// - or [`Self::derive_from_str`] fails.
100 ///
101 /// # Examples
102 ///
103 /// ```
104 /// use std::io::{Seek, SeekFrom, Write};
105 ///
106 /// use alpm_common::FileFormatSchema;
107 /// use alpm_db::files::DbFilesSchema;
108 /// use tempfile::tempfile;
109 ///
110 /// # fn main() -> testresult::TestResult {
111 /// let data = r#"%FILES%
112 /// usr/
113 /// usr/bin/
114 /// usr/bin/foo
115 /// "#;
116 /// let mut temp_file = tempfile()?;
117 /// write!(temp_file, "{data}");
118 /// temp_file.seek(SeekFrom::Start(0))?;
119 ///
120 /// let schema = DbFilesSchema::derive_from_reader(temp_file)?;
121 /// matches!(schema, DbFilesSchema::V1(_));
122 ///
123 /// // Empty inputs may also be considered as a schema
124 /// let mut temp_file = tempfile()?;
125 /// let schema = DbFilesSchema::derive_from_reader(temp_file)?;
126 /// matches!(schema, DbFilesSchema::V1(_));
127 /// # Ok(())
128 /// # }
129 /// ```
130 fn derive_from_reader(mut reader: impl Read) -> Result<Self, Self::Err>
131 where
132 Self: Sized,
133 {
134 let mut buf = String::new();
135 reader
136 .read_to_string(&mut buf)
137 .map_err(|source| crate::Error::Io {
138 context: t!("error-io-context-deriving-a-schema-version-from-alpm-db-files-data"),
139 source,
140 })?;
141 Self::derive_from_str(&buf)
142 }
143
144 /// Creates a new [`DbFilesSchema`] from a string slice.
145 ///
146 /// # Errors
147 ///
148 /// Returns an error if
149 ///
150 /// - a [`DbFilesSchema`] cannot be derived from `s`,
151 /// - or a [`DbFilesV1`][`crate::files::DbFilesV1`] cannot be created from `s`.
152 ///
153 /// # Examples
154 ///
155 /// ```
156 /// use alpm_common::FileFormatSchema;
157 /// use alpm_db::files::DbFilesSchema;
158 ///
159 /// # fn main() -> Result<(), alpm_db::Error> {
160 /// let data = r#"%FILES%
161 /// usr/
162 /// usr/bin/
163 /// usr/bin/foo
164 /// "#;
165 /// let schema = DbFilesSchema::derive_from_str(data)?;
166 /// matches!(schema, DbFilesSchema::V1(_));
167 ///
168 /// // Empty inputs may also be considered as a schema
169 /// let data = "";
170 /// let schema = DbFilesSchema::derive_from_str(data)?;
171 /// matches!(schema, DbFilesSchema::V1(_));
172 /// # Ok(())
173 /// # }
174 /// ```
175 fn derive_from_str(s: &str) -> Result<Self, Self::Err>
176 where
177 Self: Sized,
178 {
179 // Return an error if there is a first line, but it doesn't contain the expected section
180 // header.
181 if s.lines()
182 .next()
183 .is_some_and(|line| line != FilesSection::SECTION_KEYWORD)
184 {
185 return Err(Error::UnknownSchemaVersion.into());
186 }
187
188 // If there are no lines (empty file) or the first line contains the expected section
189 // header, we can assume to deal with a version 1.
190 Ok(Self::V1(SchemaVersion::new(Version::new(1, 0, 0))))
191 }
192}
193
194impl Default for DbFilesSchema {
195 /// Returns the default schema variant ([`DbFilesSchema::V1`]).
196 fn default() -> Self {
197 Self::V1(SchemaVersion::new(Version::new(1, 0, 0)))
198 }
199}
200
201#[cfg(test)]
202mod tests {
203 use std::io::Write;
204
205 use rstest::rstest;
206 use tempfile::NamedTempFile;
207 use testresult::TestResult;
208
209 use super::*;
210
211 const ALPM_DB_FILES_FULL: &str = r#"%FILES%
212usr/
213usr/bin/
214usr/bin/foo
215"#;
216 const ALPM_DB_FILES_EMPTY: &str = "";
217 const ALPM_REPO_FILES_FULL: &str = r#"%FILES%
218usr/
219usr/bin/
220usr/bin/foo"#;
221 const ALPM_REPO_FILES_EMPTY: &str = "%FILES%";
222
223 /// Ensures that different types of full and empty alpm-db-files files can be parsed from file.
224 #[rstest]
225 #[case::alpm_db_files_full(ALPM_DB_FILES_FULL)]
226 #[case::alpm_db_files_empty(ALPM_DB_FILES_EMPTY)]
227 #[case::alpm_repo_files_full(ALPM_REPO_FILES_FULL)]
228 #[case::alpm_repo_files_full(ALPM_REPO_FILES_EMPTY)]
229 fn files_schema_derive_from_file_succeeds(#[case] data: &str) -> TestResult {
230 let mut temp_file = NamedTempFile::new()?;
231 write!(temp_file, "{data}")?;
232
233 let schema = DbFilesSchema::derive_from_file(temp_file.path())?;
234
235 assert!(matches!(schema, DbFilesSchema::V1(_)));
236
237 Ok(())
238 }
239
240 /// Ensures that different types of full and empty alpm-db-files files can be parsed from file.
241 #[test]
242 fn files_schema_derive_from_file_fails() -> TestResult {
243 let mut temp_file = NamedTempFile::new()?;
244 write!(temp_file, "%WRONG%")?;
245
246 let result = DbFilesSchema::derive_from_file(temp_file.path());
247 match result {
248 Ok(schema) => {
249 panic!(
250 "Expected to fail with an Error::UnknownSchemaVersion but succeeded: {schema:?}"
251 );
252 }
253 Err(crate::Error::DbFiles(Error::UnknownSchemaVersion)) => {}
254 Err(error) => {
255 panic!(
256 "Expected to fail with an Error::UnknownSchemaVersion but got another error instead: {error}"
257 );
258 }
259 }
260
261 Ok(())
262 }
263
264 /// Ensures that [`DbFilesSchema::as_ref`] returns the correct schema version.
265 #[test]
266 fn files_schema_inner() {
267 let schema_version = SchemaVersion::new(Version::new(1, 0, 0));
268 let schema = DbFilesSchema::V1(schema_version.clone());
269 assert_eq!(schema.as_ref(), &schema_version)
270 }
271
272 /// Ensures that [`DbFilesSchema::V1`] is the default.
273 #[test]
274 fn files_schema_default() {
275 assert_eq!(
276 DbFilesSchema::default(),
277 DbFilesSchema::V1(SchemaVersion::new(Version::new(1, 0, 0)))
278 )
279 }
280}