capsule_library/library/
open.rs1use std::path::Path;
2
3use capsule_core::sidecar::library_version::CURRENT_LIBRARY_VERSION;
4
5use crate::db::{DatabaseDriver, MigrationError};
6use crate::library::error::LibraryError;
7use crate::library::library::Library;
8use crate::library::lock;
9use crate::library::scrub::startup_scrub;
10use crate::sidecar_io::{read_library_config, read_library_version, write_library_config};
11
12pub fn open_library(root: &Path) -> Result<Library, LibraryError> {
17 let version_path = root.join(".library/version.cbor");
19 let version = read_library_version(&version_path)
20 .map_err(|e| LibraryError::CorruptVersion(e.to_string()))?;
21
22 if version.version != CURRENT_LIBRARY_VERSION {
23 return Err(LibraryError::VersionMismatch {
24 found: version.version,
25 expected: CURRENT_LIBRARY_VERSION,
26 });
27 }
28
29 lock::try_acquire(root)?;
31
32 let db_path = root.join("index/library.sqlite");
35 let db = DatabaseDriver::open_typed(&db_path).map_err(|e| {
36 let _ = lock::release(root);
37 match e {
38 MigrationError::CatalogTooNew { found, supported } => {
39 LibraryError::CatalogTooNew { found, supported }
40 }
41 other => LibraryError::Db(other.into()),
42 }
43 })?;
44
45 let config_path = root.join(".library/config.cbor");
47 let mut config = read_library_config(&config_path).map_err(|e| {
48 let _ = lock::release(root);
49 LibraryError::Cbor(e.to_string())
50 })?;
51
52 startup_scrub(root, &mut config).inspect_err(|_e| {
54 let _ = lock::release(root);
55 })?;
56
57 config.last_opened_at = now_secs();
59 write_library_config(&config_path, &config).map_err(|e| {
60 let _ = lock::release(root);
61 LibraryError::Cbor(e.to_string())
62 })?;
63
64 Ok(Library::new(root.to_path_buf(), db, config))
65}
66
67fn now_secs() -> i64 {
68 std::time::SystemTime::now()
69 .duration_since(std::time::UNIX_EPOCH)
70 .unwrap_or_default()
71 .as_secs() as i64
72}
73
74#[cfg(test)]
75mod tests;