1use crate::app_dirs::AppDirs;
44use serde::{Deserialize, Serialize};
45use std::path::{Path, PathBuf};
46
47pub const MAX_RECENTS: usize = 10;
49const RECENT_FILE: &str = "recent.json";
51
52#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
60#[serde(transparent)]
61pub struct RecentLocation(String);
62
63impl RecentLocation {
64 #[must_use]
66 pub fn new(token: impl Into<String>) -> Self {
67 Self(token.into())
68 }
69
70 #[must_use]
78 pub fn from_path(path: &Path) -> Option<Self> {
79 canonicalize(path)
80 .into_os_string()
81 .into_string()
82 .ok()
83 .map(Self)
84 }
85
86 #[must_use]
88 pub fn as_str(&self) -> &str {
89 &self.0
90 }
91
92 #[must_use]
95 pub fn to_path(&self) -> PathBuf {
96 PathBuf::from(&self.0)
97 }
98}
99
100pub fn record_location(dirs: &AppDirs, location: RecentLocation) {
104 if let Some(file) = dirs.config_file(RECENT_FILE) {
105 record_in(&file, location);
106 }
107}
108
109#[must_use]
112pub fn locations(dirs: &AppDirs) -> Vec<RecentLocation> {
113 dirs.config_file(RECENT_FILE)
114 .map(|file| read_raw(&file))
115 .unwrap_or_default()
116}
117
118pub fn record(dirs: &AppDirs, path: impl AsRef<Path>) {
121 match RecentLocation::from_path(path.as_ref()) {
122 Some(location) => record_location(dirs, location),
123 None => eprintln!(
124 "ledgeline: not remembering {} in recents: the path is not valid UTF-8",
125 path.as_ref().display()
126 ),
127 }
128}
129
130#[must_use]
132pub fn list(dirs: &AppDirs) -> Vec<PathBuf> {
133 dirs.config_file(RECENT_FILE)
134 .map(|file| list_in(&file))
135 .unwrap_or_default()
136}
137
138#[must_use]
145pub fn most_recent(dirs: &AppDirs) -> Option<PathBuf> {
146 dirs.config_file(RECENT_FILE)
147 .and_then(|file| usable_entries(&file).next())
148}
149
150#[cfg(feature = "gui")]
156#[must_use]
157pub fn display_label(path: &Path) -> String {
158 label_under(path, dirs::home_dir().as_deref())
159}
160
161#[cfg(feature = "gui")]
169fn label_under(path: &Path, home: Option<&Path>) -> String {
170 let path = dunce::simplified(path);
171 if let Some(home) = home
172 && let Ok(relative) = path.strip_prefix(dunce::simplified(home))
173 {
174 return format!("~/{}", relative.display());
175 }
176 path.display().to_string()
177}
178
179fn canonicalize(path: &Path) -> PathBuf {
182 std::fs::canonicalize(path)
183 .or_else(|_| std::path::absolute(path))
184 .unwrap_or_else(|_| path.to_path_buf())
185}
186
187enum Stored {
189 Missing,
191 Entries(Vec<RecentLocation>),
193 Corrupt,
197}
198
199fn record_in(file: &Path, entry: RecentLocation) {
205 let existing = match read_stored(file) {
206 Stored::Entries(entries) => entries,
207 Stored::Missing => Vec::new(),
208 Stored::Corrupt => {
209 set_corrupt_aside(file);
210 Vec::new()
211 }
212 };
213 let entries: Vec<RecentLocation> = std::iter::once(entry.clone())
214 .chain(existing.into_iter().filter(|old| old != &entry))
215 .take(MAX_RECENTS)
216 .collect();
217 write_raw(file, &entries);
218}
219
220fn list_in(file: &Path) -> Vec<PathBuf> {
222 usable_entries(file).collect()
223}
224
225fn usable_entries(file: &Path) -> impl Iterator<Item = PathBuf> {
229 read_raw(file)
230 .into_iter()
231 .map(|location| location.to_path())
232 .filter(|path| is_regular_file(path))
233}
234
235fn is_regular_file(path: &Path) -> bool {
247 std::fs::metadata(path).is_ok_and(|meta| meta.is_file())
248}
249
250fn read_raw(file: &Path) -> Vec<RecentLocation> {
253 match read_stored(file) {
254 Stored::Entries(entries) => entries,
255 Stored::Missing | Stored::Corrupt => Vec::new(),
256 }
257}
258
259fn read_stored(file: &Path) -> Stored {
261 let Ok(text) = std::fs::read_to_string(file) else {
262 return if file.exists() {
265 Stored::Corrupt
266 } else {
267 Stored::Missing
268 };
269 };
270 serde_json::from_str::<Vec<RecentLocation>>(&text).map_or(Stored::Corrupt, Stored::Entries)
271}
272
273fn set_corrupt_aside(file: &Path) {
276 let aside = file.with_extension("json.corrupt");
277 match ledgeline_core::pinned::rename_replacing(file, &aside) {
278 Ok(()) => eprintln!(
279 "ledgeline: recents file {} was unreadable; kept a copy at {} and started a new list",
280 file.display(),
281 aside.display()
282 ),
283 Err(error) => eprintln!(
284 "ledgeline: could not set aside unreadable recents {}: {error}",
285 file.display()
286 ),
287 }
288}
289
290fn write_raw(file: &Path, entries: &[RecentLocation]) {
298 if let Some(parent) = file.parent()
299 && let Err(error) = std::fs::create_dir_all(parent)
300 {
301 eprintln!(
302 "ledgeline: could not create config dir {}: {error}",
303 parent.display()
304 );
305 return;
306 }
307 match serde_json::to_string_pretty(entries) {
308 Ok(json) => {
309 if let Err(error) = ledgeline_core::edit::atomic_write(file, json.as_bytes()) {
310 eprintln!(
311 "ledgeline: could not write recents {}: {error}",
312 file.display()
313 );
314 }
315 }
316 Err(error) => eprintln!("ledgeline: could not serialize recents: {error}"),
317 }
318}
319
320#[cfg(test)]
321mod tests {
322 use super::*;
323 use std::fs;
324 use tempfile::TempDir;
325
326 #[cfg(feature = "gui")]
327 #[test]
328 fn labels_collapse_the_home_directory() {
329 let home = Path::new("/Users/me");
330 assert_eq!(
331 label_under(Path::new("/Users/me/books/main.journal"), Some(home)),
332 "~/books/main.journal"
333 );
334 assert_eq!(
335 label_under(Path::new("/srv/books/main.journal"), Some(home)),
336 "/srv/books/main.journal"
337 );
338 assert_eq!(label_under(Path::new("/a.journal"), None), "/a.journal");
339 }
340
341 #[cfg(all(feature = "gui", windows))]
344 #[test]
345 fn verbatim_entries_collapse_against_a_plain_home() {
346 let home = Path::new(r"C:\Users\me");
347 assert_eq!(
348 label_under(Path::new(r"\\?\C:\Users\me\books\main.journal"), Some(home)),
349 r"~/books\main.journal"
350 );
351 assert_eq!(
352 label_under(Path::new(r"\\?\D:\books\main.journal"), Some(home)),
353 r"D:\books\main.journal"
354 );
355 }
356
357 fn loc(path: &Path) -> RecentLocation {
359 RecentLocation::from_path(path).expect("UTF-8 test path")
360 }
361
362 fn raw_paths(store: &Path) -> Vec<PathBuf> {
364 read_raw(store)
365 .iter()
366 .map(RecentLocation::to_path)
367 .collect()
368 }
369
370 fn write_paths(store: &Path, paths: &[PathBuf]) {
372 let entries: Vec<RecentLocation> = paths
373 .iter()
374 .map(|p| RecentLocation::new(p.to_str().expect("UTF-8")))
375 .collect();
376 write_raw(store, &entries);
377 }
378
379 fn touch(dir: &Path, name: &str) -> PathBuf {
382 let path = dir.join(name);
383 fs::write(&path, "").expect("write temp journal");
384 path
385 }
386
387 #[test]
388 fn record_moves_to_front_and_dedupes() {
389 let dir = TempDir::new().expect("temp dir");
390 let store = dir.path().join("recent.json");
391 let a = touch(dir.path(), "a.journal");
392 let b = touch(dir.path(), "b.journal");
393 let c = touch(dir.path(), "c.journal");
394
395 record_in(&store, loc(&a));
396 record_in(&store, loc(&b));
397 record_in(&store, loc(&c));
398 assert_eq!(
400 raw_paths(&store),
401 vec![canonicalize(&c), canonicalize(&b), canonicalize(&a)]
402 );
403
404 record_in(&store, loc(&a));
406 assert_eq!(
407 raw_paths(&store),
408 vec![canonicalize(&a), canonicalize(&c), canonicalize(&b)]
409 );
410
411 record_in(&store, loc(&dir.path().join("./b.journal")));
413 let entries = raw_paths(&store);
414 assert_eq!(entries.first(), Some(&canonicalize(&b)));
415 assert_eq!(
416 entries.iter().filter(|p| **p == canonicalize(&b)).count(),
417 1,
418 "the same file must appear only once"
419 );
420 }
421
422 #[test]
423 fn record_caps_at_max() {
424 let dir = TempDir::new().expect("temp dir");
425 let store = dir.path().join("recent.json");
426 let total = MAX_RECENTS + 3;
427 let paths: Vec<PathBuf> = (0..total)
428 .map(|i| touch(dir.path(), &format!("j{i}.journal")))
429 .collect();
430 for path in &paths {
431 record_in(&store, loc(path));
432 }
433
434 let entries = raw_paths(&store);
435 assert_eq!(entries.len(), MAX_RECENTS, "capped at MAX_RECENTS");
436 assert_eq!(entries.first(), Some(&canonicalize(paths.last().unwrap())));
438 assert!(
439 !entries.contains(&canonicalize(&paths[0])),
440 "the oldest entry is evicted once the cap is exceeded"
441 );
442 }
443
444 #[test]
445 fn list_skips_missing_paths() {
446 let dir = TempDir::new().expect("temp dir");
447 let store = dir.path().join("recent.json");
448 let present = touch(dir.path(), "present.journal");
449 let missing = dir.path().join("gone.journal"); write_paths(
452 &store,
453 &[canonicalize(&present), missing, canonicalize(&present)],
454 );
455 assert_eq!(list_in(&store), vec![canonicalize(&present); 2]);
457 }
458
459 #[test]
460 fn missing_or_corrupt_store_reads_empty() {
461 let dir = TempDir::new().expect("temp dir");
462 let store = dir.path().join("recent.json");
463 assert!(raw_paths(&store).is_empty());
465 fs::write(&store, "{ not valid json ]").expect("write garbage");
467 assert!(raw_paths(&store).is_empty());
468 }
469
470 #[test]
474 fn list_skips_entries_that_are_not_regular_files() {
475 let dir = TempDir::new().expect("temp dir");
476 let store = dir.path().join("recent.json");
477 let journal = touch(dir.path(), "real.journal");
478 let subdir = dir.path().join("a-directory");
479 fs::create_dir(&subdir).expect("create dir");
480
481 write_paths(&store, &[canonicalize(&subdir), canonicalize(&journal)]);
482
483 assert!(subdir.exists(), "the decoy really is present on disk");
484 assert_eq!(
485 list_in(&store),
486 vec![canonicalize(&journal)],
487 "a directory must not be offered as a recent journal"
488 );
489 assert_eq!(
490 usable_entries(&store).next(),
491 Some(canonicalize(&journal)),
492 "most_recent's lazy filter must skip past it too"
493 );
494 }
495
496 #[test]
499 fn a_corrupt_store_is_preserved_rather_than_erased() {
500 let dir = TempDir::new().expect("temp dir");
501 let store = dir.path().join("recent.json");
502 let journal = touch(dir.path(), "j.journal");
503 fs::write(&store, "{ not valid json ]").expect("write garbage");
504
505 record_in(&store, loc(&journal));
506
507 let aside = store.with_extension("json.corrupt");
508 assert_eq!(
509 fs::read_to_string(&aside).expect("the unreadable bytes are kept"),
510 "{ not valid json ]"
511 );
512 assert_eq!(
513 raw_paths(&store),
514 vec![canonicalize(&journal)],
515 "and the store recovers rather than staying broken"
516 );
517 }
518
519 #[test]
522 fn a_missing_store_is_not_treated_as_corrupt() {
523 let dir = TempDir::new().expect("temp dir");
524 let store = dir.path().join("recent.json");
525 let journal = touch(dir.path(), "j.journal");
526
527 record_in(&store, loc(&journal));
528
529 assert!(!store.with_extension("json.corrupt").exists());
530 assert_eq!(raw_paths(&store), vec![canonicalize(&journal)]);
531 }
532
533 #[test]
536 fn the_store_is_written_atomically_and_owner_only() {
537 let dir = TempDir::new().expect("temp dir");
538 let store = dir.path().join("recent.json");
539 let journal = touch(dir.path(), "j.journal");
540
541 record_in(&store, loc(&journal));
542
543 let leftovers: Vec<PathBuf> = fs::read_dir(dir.path())
544 .expect("read config dir")
545 .filter_map(|entry| entry.ok().map(|e| e.path()))
546 .filter(|p| p.to_string_lossy().contains(".ledgeline-"))
547 .collect();
548 assert!(
549 leftovers.is_empty(),
550 "temp files left behind: {leftovers:?}"
551 );
552
553 #[cfg(unix)]
554 {
555 use std::os::unix::fs::PermissionsExt;
556 let mode = fs::metadata(&store).expect("stat").permissions().mode() & 0o777;
557 assert_eq!(
558 mode & !0o600,
559 0,
560 "a freshly created recents store must not be wider than 0600, got {mode:o}"
561 );
562 }
563 }
564
565 #[test]
566 fn record_creates_missing_config_dir() {
567 let dir = TempDir::new().expect("temp dir");
568 let store = dir.path().join("nested").join("deeper").join("recent.json");
570 let journal = touch(dir.path(), "j.journal");
571 record_in(&store, loc(&journal));
572 assert_eq!(raw_paths(&store), vec![canonicalize(&journal)]);
573 }
574
575 #[test]
579 fn the_file_format_is_the_path_array_it_always_was() {
580 let dir = TempDir::new().expect("temp dir");
581 let store = dir.path().join("recent.json");
582 let journal = touch(dir.path(), "old.journal");
583 let canonical = canonicalize(&journal);
584 let legacy = serde_json::to_string_pretty(&vec![canonical.clone()]).expect("json");
585 fs::write(&store, &legacy).expect("write legacy store");
586
587 assert_eq!(list_in(&store), vec![canonical.clone()]);
588
589 let other = touch(dir.path(), "new.journal");
590 record_in(&store, loc(&other));
591 let reread: Vec<PathBuf> =
592 serde_json::from_str(&fs::read_to_string(&store).expect("read")).expect("old shape");
593 assert_eq!(reread, vec![canonicalize(&other), canonical]);
594 }
595
596 #[test]
599 fn an_opaque_token_round_trips_and_is_not_a_usable_path() {
600 let dir = TempDir::new().expect("temp dir");
601 let store = dir.path().join("recent.json");
602 let bookmark = RecentLocation::new("bookmark:6F1C-77A2");
603 record_in(&store, bookmark.clone());
604 record_in(&store, RecentLocation::new("bookmark:other"));
605 record_in(&store, bookmark.clone());
606
607 assert_eq!(
608 read_raw(&store),
609 vec![bookmark, RecentLocation::new("bookmark:other")]
610 );
611 assert!(list_in(&store).is_empty(), "a bookmark id is not a file");
612 }
613
614 #[test]
617 fn the_store_lives_in_the_injected_config_dir() {
618 let dir = TempDir::new().expect("temp dir");
619 let dirs = AppDirs::under(dir.path());
620 let journal = touch(dir.path(), "j.journal");
621 record(&dirs, &journal);
622 assert!(dir.path().join("config").join("recent.json").is_file());
623 assert_eq!(most_recent(&dirs), Some(canonicalize(&journal)));
624 assert_eq!(locations(&dirs), vec![loc(&journal)]);
625
626 let no_config = AppDirs {
627 config_dir: None,
628 ..AppDirs::under(dir.path())
629 };
630 record(&no_config, &journal);
631 assert!(list(&no_config).is_empty());
632 }
633}