1use std::{
2 fs,
3 path::{Path, PathBuf},
4};
5
6use chrono::Local;
7use doing_config::Config;
8use doing_error::Result;
9use doing_taskpaper::{Document, io as taskpaper_io};
10
11pub fn backup_prefix(source: &Path) -> String {
17 let stem = source.file_name().and_then(|n| n.to_str()).unwrap_or("unknown");
18 let canonical = source
19 .canonicalize()
20 .or_else(|_| {
21 source
22 .parent()
23 .and_then(|p| p.canonicalize().ok())
24 .map(|p| p.join(source.file_name().unwrap_or_default()))
25 .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, ""))
26 })
27 .unwrap_or_else(|_| source.to_path_buf());
28
29 let hash = fnv1a_hash(canonical.to_string_lossy().as_bytes());
30
31 format!("{stem}_{hash:016x}_")
32}
33
34pub fn create_backup(source: &Path, backup_dir: &Path) -> Result<PathBuf> {
39 fs::create_dir_all(backup_dir)?;
40
41 let prefix = backup_prefix(source);
42 let timestamp = Local::now().format("%Y%m%d_%H%M%S_%6f");
43 let backup_name = format!("{prefix}{timestamp}.bak");
44 let backup_path = backup_dir.join(backup_name);
45
46 fs::copy(source, &backup_path)?;
47 Ok(backup_path)
48}
49
50pub fn list_backups(source: &Path, backup_dir: &Path) -> Result<Vec<PathBuf>> {
52 list_files_with_ext(source, backup_dir, ".bak")
53}
54
55pub fn list_undone(source: &Path, backup_dir: &Path) -> Result<Vec<PathBuf>> {
57 list_files_with_ext(source, backup_dir, ".undone")
58}
59
60pub fn prune_backups(source: &Path, backup_dir: &Path, history_size: u32) -> Result<()> {
66 let mut backups = list_backups(source, backup_dir)?;
67 if backups.len() <= history_size as usize {
68 return Ok(());
69 }
70
71 for old in backups.drain(history_size as usize..) {
72 fs::remove_file(old)?;
73 }
74
75 Ok(())
76}
77
78pub fn write_with_backup(doc: &Document, path: &Path, config: &Config) -> Result<()> {
85 if path.exists() {
86 create_backup(path, &config.backup_dir)?;
87 prune_backups(path, &config.backup_dir, config.history_size)?;
88 }
89
90 let mut doc = doc.clone();
91 doc.sort_entries(config.doing_file_sort == doing_config::SortOrder::Desc);
92 taskpaper_io::write_file(&doc, path)
93}
94
95fn fnv1a_hash(bytes: &[u8]) -> u64 {
97 const FNV_OFFSET: u64 = 0xcbf29ce484222325;
98 const FNV_PRIME: u64 = 0x00000100000001B3;
99
100 let mut hash = FNV_OFFSET;
101 for &byte in bytes {
102 hash ^= byte as u64;
103 hash = hash.wrapping_mul(FNV_PRIME);
104 }
105 hash
106}
107
108fn list_files_with_ext(source: &Path, backup_dir: &Path, ext: &str) -> Result<Vec<PathBuf>> {
109 if !backup_dir.exists() {
110 return Ok(Vec::new());
111 }
112
113 let prefix = backup_prefix(source);
114 let mut backups: Vec<PathBuf> = fs::read_dir(backup_dir)?
115 .filter_map(|entry| entry.ok())
116 .map(|entry| entry.path())
117 .filter(|path| {
118 path
119 .file_name()
120 .and_then(|n| n.to_str())
121 .map(|n| n.starts_with(&prefix) && n.ends_with(ext))
122 .unwrap_or(false)
123 })
124 .collect();
125
126 backups.sort_by(|a, b| b.cmp(a));
127 Ok(backups)
128}
129
130#[cfg(test)]
131mod test {
132 use doing_config::SortOrder;
133 use doing_taskpaper::{Entry, Note, Section, Tags};
134
135 use super::*;
136
137 fn sample_doc() -> Document {
138 let mut doc = Document::new();
139 let mut section = Section::new("Currently");
140 section.add_entry(Entry::new(
141 chrono::Local::now(),
142 "Test task",
143 Tags::new(),
144 Note::new(),
145 "Currently",
146 None::<String>,
147 ));
148 doc.add_section(section);
149 doc
150 }
151
152 mod fnv1a_hash {
153 use pretty_assertions::assert_eq;
154
155 use super::super::fnv1a_hash;
156
157 #[test]
158 fn it_produces_known_output_for_known_input() {
159 let hash = fnv1a_hash(b"hello");
161
162 assert_eq!(hash, 0xa430d84680aabd0b);
163 }
164 }
165
166 mod backup_prefix {
167 use pretty_assertions::assert_eq;
168
169 use super::*;
170
171 #[test]
172 fn it_produces_deterministic_hash() {
173 let dir = tempfile::tempdir().unwrap();
174 let source = dir.path().join("test.md");
175 fs::write(&source, "").unwrap();
176
177 let prefix1 = backup_prefix(&source);
178 let prefix2 = backup_prefix(&source);
179
180 assert_eq!(prefix1, prefix2);
181 }
182 }
183
184 mod create_backup {
185 use pretty_assertions::assert_eq;
186
187 use super::*;
188
189 #[test]
190 fn it_copies_file_to_backup_dir() {
191 let dir = tempfile::tempdir().unwrap();
192 let source = dir.path().join("test.md");
193 let backup_dir = dir.path().join("backups");
194 fs::write(&source, "content").unwrap();
195
196 let backup = create_backup(&source, &backup_dir).unwrap();
197
198 assert!(backup.exists());
199 assert_eq!(fs::read_to_string(&backup).unwrap(), "content");
200 }
201
202 #[test]
203 fn it_creates_backup_dir_if_missing() {
204 let dir = tempfile::tempdir().unwrap();
205 let source = dir.path().join("test.md");
206 let backup_dir = dir.path().join("nested/backups");
207 fs::write(&source, "content").unwrap();
208
209 create_backup(&source, &backup_dir).unwrap();
210
211 assert!(backup_dir.exists());
212 }
213
214 #[test]
215 fn it_uses_timestamped_bak_filename() {
216 let dir = tempfile::tempdir().unwrap();
217 let source = dir.path().join("doing.md");
218 let backup_dir = dir.path().join("backups");
219 fs::write(&source, "content").unwrap();
220
221 let backup = create_backup(&source, &backup_dir).unwrap();
222 let name = backup.file_name().unwrap().to_str().unwrap();
223 let prefix = backup_prefix(&source);
224
225 assert!(name.starts_with(&prefix));
226 assert!(name.ends_with(".bak"));
227 }
228 }
229
230 mod list_backups {
231 use pretty_assertions::assert_eq;
232
233 use super::*;
234
235 #[test]
236 fn it_isolates_backups_by_source_path() {
237 let dir = tempfile::tempdir().unwrap();
238 let backup_dir = dir.path().join("backups");
239 fs::create_dir_all(&backup_dir).unwrap();
240
241 let dir_a = dir.path().join("a");
242 let dir_b = dir.path().join("b");
243 fs::create_dir_all(&dir_a).unwrap();
244 fs::create_dir_all(&dir_b).unwrap();
245
246 let source_a = dir_a.join("doing.md");
247 let source_b = dir_b.join("doing.md");
248 fs::write(&source_a, "content a").unwrap();
249 fs::write(&source_b, "content b").unwrap();
250
251 create_backup(&source_a, &backup_dir).unwrap();
252 create_backup(&source_b, &backup_dir).unwrap();
253
254 let backups_a = list_backups(&source_a, &backup_dir).unwrap();
255 let backups_b = list_backups(&source_b, &backup_dir).unwrap();
256
257 assert_eq!(backups_a.len(), 1);
258 assert_eq!(backups_b.len(), 1);
259 assert_eq!(fs::read_to_string(&backups_a[0]).unwrap(), "content a");
260 assert_eq!(fs::read_to_string(&backups_b[0]).unwrap(), "content b");
261 }
262 }
263
264 mod prune_backups {
265 use super::*;
266
267 #[test]
268 fn it_does_nothing_when_under_limit() {
269 let dir = tempfile::tempdir().unwrap();
270 let source = dir.path().join("test.md");
271 let backup_dir = dir.path().join("backups");
272 fs::create_dir_all(&backup_dir).unwrap();
273 fs::write(&source, "").unwrap();
274
275 let prefix = backup_prefix(&source);
276 fs::write(backup_dir.join(format!("{prefix}20240101_000001.bak")), "").unwrap();
277
278 prune_backups(&source, &backup_dir, 5).unwrap();
279
280 let remaining = list_backups(&source, &backup_dir).unwrap();
281 assert_eq!(remaining.len(), 1);
282 }
283
284 #[test]
285 fn it_keeps_only_history_size_newest_backups() {
286 let dir = tempfile::tempdir().unwrap();
287 let source = dir.path().join("test.md");
288 let backup_dir = dir.path().join("backups");
289 fs::create_dir_all(&backup_dir).unwrap();
290 fs::write(&source, "").unwrap();
291
292 let prefix = backup_prefix(&source);
293 for i in 1..=5 {
294 let name = format!("{prefix}20240101_{:06}.bak", i);
295 fs::write(backup_dir.join(name), "").unwrap();
296 }
297
298 prune_backups(&source, &backup_dir, 2).unwrap();
299
300 let remaining = list_backups(&source, &backup_dir).unwrap();
301 assert_eq!(remaining.len(), 2);
302 }
303 }
304
305 mod write_with_backup {
306 use pretty_assertions::assert_eq;
307
308 use super::*;
309
310 #[test]
311 fn it_creates_backup_before_writing() {
312 let dir = tempfile::tempdir().unwrap();
313 let path = dir.path().join("test.md");
314 let backup_dir = dir.path().join("backups");
315 fs::write(&path, "old content\n").unwrap();
316
317 let mut config = Config::default();
318 config.backup_dir = backup_dir.clone();
319 config.doing_file_sort = SortOrder::Asc;
320
321 write_with_backup(&sample_doc(), &path, &config).unwrap();
322
323 let backups = list_backups(&path, &backup_dir).unwrap();
324 assert_eq!(backups.len(), 1);
325 assert_eq!(fs::read_to_string(&backups[0]).unwrap(), "old content\n");
326 }
327
328 #[test]
329 fn it_skips_backup_for_new_file() {
330 let dir = tempfile::tempdir().unwrap();
331 let path = dir.path().join("test.md");
332 let backup_dir = dir.path().join("backups");
333
334 let mut config = Config::default();
335 config.backup_dir = backup_dir.clone();
336 config.doing_file_sort = SortOrder::Asc;
337
338 write_with_backup(&sample_doc(), &path, &config).unwrap();
339
340 assert!(path.exists());
341 assert!(!backup_dir.exists());
342 }
343
344 #[test]
345 fn it_writes_document_content() {
346 let dir = tempfile::tempdir().unwrap();
347 let path = dir.path().join("test.md");
348
349 let mut config = Config::default();
350 config.backup_dir = dir.path().join("backups");
351 config.doing_file_sort = SortOrder::Asc;
352
353 write_with_backup(&sample_doc(), &path, &config).unwrap();
354
355 let content = fs::read_to_string(&path).unwrap();
356 assert!(content.contains("Currently:"));
357 assert!(content.contains("Test task"));
358 }
359 }
360}