link_cli/transactions/
journal_file.rs1use std::fs::{File, OpenOptions};
17use std::io::{Read, Write};
18use std::path::{Path, PathBuf};
19
20use crate::error::LinkError;
21use crate::named_types::NamedTypesDecorator;
22
23use super::log::{FileTransitionLog, TransitionLogStore};
24
25const ENTRY_PREFIX: &[u8] = b"__transactions:";
27
28pub fn make_transitions_log_filename<P: AsRef<Path>>(database_filename: P) -> PathBuf {
30 sibling(database_filename.as_ref(), "transitions.log")
31}
32
33pub fn make_legacy_transitions_filename<P: AsRef<Path>>(database_filename: P) -> PathBuf {
36 sibling(database_filename.as_ref(), "transitions.links")
37}
38
39fn sibling(path: &Path, suffix: &str) -> PathBuf {
40 let stem = path
41 .file_stem()
42 .and_then(|s| s.to_str())
43 .unwrap_or_default();
44 let name = format!("{stem}.{suffix}");
45 match path.parent() {
46 Some(parent) if !parent.as_os_str().is_empty() => parent.join(name),
47 _ => PathBuf::from(name),
48 }
49}
50
51pub fn open_transitions_journal(
55 database: &Path,
56 explicit: Option<&Path>,
57 trace: bool,
58) -> Result<FileTransitionLog, LinkError> {
59 let path = match explicit {
60 Some(path) => {
61 if is_links_journal(path)? {
62 import_links_journal(path, path, trace)?;
63 }
64 path.to_path_buf()
65 }
66 None => {
67 let path = make_transitions_log_filename(database);
68 let legacy = make_legacy_transitions_filename(database);
69 if legacy.exists() {
70 import_links_journal(&legacy, &path, trace)?;
71 }
72 path
73 }
74 };
75 FileTransitionLog::open(path)
76}
77
78pub fn is_links_journal(path: &Path) -> Result<bool, LinkError> {
81 let mut head = Vec::with_capacity(ENTRY_PREFIX.len());
82 match File::open(path) {
83 Ok(file) => {
84 file.take(ENTRY_PREFIX.len() as u64)
85 .read_to_end(&mut head)?;
86 }
87 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
88 Err(error) => return Err(error.into()),
89 }
90 Ok(!head.is_empty() && !ENTRY_PREFIX.starts_with(&head))
91}
92
93pub fn import_links_journal(legacy: &Path, target: &Path, trace: bool) -> Result<bool, LinkError> {
100 let names = NamedTypesDecorator::make_names_database_filename(legacy);
101 let entries = {
102 let mut store = NamedTypesDecorator::with_names_database_path(legacy, &names, false)
103 .map_err(|error| LinkError::StorageError(format!("{error:#}")))?
104 .with_indexed_lookups();
105 store.read_log_entries()?
106 };
107 let in_place = legacy == target;
108 if !in_place && target.exists() {
109 let mut existing = FileTransitionLog::open(target)?;
110 let present: std::collections::HashSet<String> =
111 existing.read_log_entries()?.into_iter().collect();
112 if entries.iter().all(|entry| present.contains(entry)) {
113 remove_legacy(legacy, &names)?;
114 } else if trace {
115 crate::diagnostics::stderr!(
116 "[Transactions] Kept legacy journal {}: {} already exists.",
117 legacy.display(),
118 target.display()
119 );
120 }
121 return Ok(false);
122 }
123 let mut temporary = target.as_os_str().to_os_string();
124 temporary.push(".import");
125 let temporary = PathBuf::from(temporary);
126 {
127 let mut file = OpenOptions::new()
128 .write(true)
129 .create(true)
130 .truncate(true)
131 .open(&temporary)?;
132 for entry in &entries {
133 writeln!(file, "{entry}")?;
134 }
135 file.sync_all()?;
136 }
137 std::fs::rename(&temporary, target)?;
138 if !in_place {
139 remove_legacy(legacy, &names)?;
140 } else {
141 remove_if_exists(&names)?;
142 }
143 FileTransitionLog::open(target)?; if trace {
145 crate::diagnostics::stderr!(
146 "[Transactions] Imported {} entries from legacy journal {} into {}.",
147 entries.len(),
148 legacy.display(),
149 target.display()
150 );
151 }
152 Ok(true)
153}
154
155fn remove_legacy(legacy: &Path, names: &Path) -> Result<(), LinkError> {
156 remove_if_exists(legacy)?;
157 remove_if_exists(names)
158}
159
160fn remove_if_exists(path: &Path) -> Result<(), LinkError> {
161 match std::fs::remove_file(path) {
162 Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error.into()),
163 _ => Ok(()),
164 }
165}