1use std::{
6 fmt::{Display, Formatter},
7 fs::{File, write},
8 io::Read,
9 path::{Path, PathBuf},
10 str::FromStr,
11};
12
13use alpm_common::FileFormatSchema;
14use alpm_types::{SchemaVersion, semver_version::Version};
15use fluent_i18n::t;
16
17use crate::Error;
18
19const VERSION_9: u64 = 9;
21
22#[derive(Clone, Debug, Eq, PartialEq)]
24pub enum DbSchema {
25 V9(SchemaVersion),
27}
28
29impl DbSchema {
30 pub const VERSION_FILE_NAME: &str = "ALPM_DB_VERSION";
34
35 pub(crate) fn write_version_file_to_db_root(
41 &self,
42 base_path: impl AsRef<Path>,
43 ) -> Result<(), Error> {
44 let base_path = base_path.as_ref();
45 let file = base_path.join(Self::VERSION_FILE_NAME);
46 write(&file, format!("{}\n", self.as_ref().as_ref().major)).map_err(|source| {
47 Error::IoPath {
48 path: file,
49 context: t!("error-io-path-write-db-version"),
50 source,
51 }
52 })
53 }
54}
55
56impl AsRef<SchemaVersion> for DbSchema {
57 fn as_ref(&self) -> &SchemaVersion {
58 match self {
59 Self::V9(v) => v,
60 }
61 }
62}
63
64impl Default for DbSchema {
65 fn default() -> Self {
67 Self::V9(SchemaVersion::new(Version::new(VERSION_9, 0, 0)))
68 }
69}
70
71impl Display for DbSchema {
72 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
76 write!(
77 f,
78 "{}",
79 match self {
80 Self::V9(version) => version.as_ref().major,
81 }
82 )
83 }
84}
85
86impl FileFormatSchema for DbSchema {
87 type Err = Error;
88
89 fn derive_from_file(file: impl AsRef<Path>) -> Result<Self, Self::Err>
100 where
101 Self: Sized,
102 {
103 let file = file.as_ref();
104 let mut handle = File::open(file).map_err(|source| Error::IoPath {
105 path: PathBuf::from(file),
106 context: t!("error-io-path-open-read-only"),
107 source,
108 })?;
109 Self::derive_from_reader(&mut handle)
110 }
111
112 fn derive_from_reader(mut reader: impl Read) -> Result<Self, Self::Err>
123 where
124 Self: Sized,
125 {
126 let mut buf = String::new();
127 reader
128 .read_to_string(&mut buf)
129 .map_err(|source| Error::Io {
130 context: t!("error-io-read-db-version"),
131 source,
132 })?;
133 Self::derive_from_str(buf.trim())
134 }
135
136 fn derive_from_str(s: &str) -> Result<Self, Self::Err>
142 where
143 Self: Sized,
144 {
145 Self::from_str(s)
146 }
147}
148
149impl FromStr for DbSchema {
150 type Err = Error;
151
152 fn from_str(s: &str) -> Result<Self, Self::Err> {
158 if s.is_empty() || s != VERSION_9.to_string() {
159 return Err(Error::UnsupportedSchemaVersion(s.to_string()));
160 }
161
162 Ok(Self::V9(SchemaVersion::new(Version::new(VERSION_9, 0, 0))))
163 }
164}
165
166impl TryFrom<SchemaVersion> for DbSchema {
167 type Error = Error;
168
169 fn try_from(value: SchemaVersion) -> Result<Self, Self::Error> {
175 match value.as_ref().major {
176 VERSION_9 => Ok(Self::V9(value)),
177 _ => Err(Error::UnsupportedSchemaVersion(value.to_string())),
178 }
179 }
180}
181
182#[cfg(test)]
183mod tests {
184 use std::{fs::write, io::Cursor, str::FromStr};
185
186 use tempfile::TempDir;
187 use testresult::TestResult;
188
189 use super::*;
190
191 #[test]
193 fn db_schema_from_str_succeeds() -> TestResult {
194 assert_eq!(DbSchema::default(), DbSchema::from_str("9")?);
195 Ok(())
196 }
197
198 #[test]
200 fn db_schema_from_str_fails_on_empty_string() {
201 let Err(Error::UnsupportedSchemaVersion(_)) = DbSchema::from_str("") else {
202 panic!("Expected to fail but succeeded instead");
203 };
204 }
205
206 #[test]
208 fn db_schema_from_str_fails_on_unsupported_version() {
209 let Err(Error::UnsupportedSchemaVersion(_)) = DbSchema::from_str("8") else {
210 panic!("Expected to fail but succeeded instead");
211 };
212 }
213
214 #[test]
216 fn db_schema_derive_from_file() -> TestResult {
217 let test_dir = TempDir::new()?;
218 let version_file_path = test_dir.path().join(DbSchema::VERSION_FILE_NAME);
219 write(&version_file_path, "9\n")?;
220 let schema = DbSchema::derive_from_file(&version_file_path)?;
221 assert_eq!(DbSchema::default(), schema);
222 Ok(())
223 }
224
225 #[test]
227 fn db_schema_derive_from_file_reader_succeeds() -> TestResult {
228 let schema = DbSchema::derive_from_reader(Cursor::new("9\n"))?;
229 assert_eq!(DbSchema::default(), schema);
230 Ok(())
231 }
232}