use crate::app_dirs::AppDirs;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
pub const MAX_RECENTS: usize = 10;
const RECENT_FILE: &str = "recent.json";
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct RecentLocation(String);
impl RecentLocation {
#[must_use]
pub fn new(token: impl Into<String>) -> Self {
Self(token.into())
}
#[must_use]
pub fn from_path(path: &Path) -> Option<Self> {
canonicalize(path)
.into_os_string()
.into_string()
.ok()
.map(Self)
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn to_path(&self) -> PathBuf {
PathBuf::from(&self.0)
}
}
pub fn record_location(dirs: &AppDirs, location: RecentLocation) {
if let Some(file) = dirs.config_file(RECENT_FILE) {
record_in(&file, location);
}
}
#[must_use]
pub fn locations(dirs: &AppDirs) -> Vec<RecentLocation> {
dirs.config_file(RECENT_FILE)
.map(|file| read_raw(&file))
.unwrap_or_default()
}
pub fn record(dirs: &AppDirs, path: impl AsRef<Path>) {
match RecentLocation::from_path(path.as_ref()) {
Some(location) => record_location(dirs, location),
None => eprintln!(
"ledgeline: not remembering {} in recents: the path is not valid UTF-8",
path.as_ref().display()
),
}
}
#[must_use]
pub fn list(dirs: &AppDirs) -> Vec<PathBuf> {
dirs.config_file(RECENT_FILE)
.map(|file| list_in(&file))
.unwrap_or_default()
}
#[must_use]
pub fn most_recent(dirs: &AppDirs) -> Option<PathBuf> {
dirs.config_file(RECENT_FILE)
.and_then(|file| usable_entries(&file).next())
}
#[cfg(feature = "gui")]
#[must_use]
pub fn display_label(path: &Path) -> String {
label_under(path, dirs::home_dir().as_deref())
}
#[cfg(feature = "gui")]
fn label_under(path: &Path, home: Option<&Path>) -> String {
let path = dunce::simplified(path);
if let Some(home) = home
&& let Ok(relative) = path.strip_prefix(dunce::simplified(home))
{
return format!("~/{}", relative.display());
}
path.display().to_string()
}
fn canonicalize(path: &Path) -> PathBuf {
std::fs::canonicalize(path)
.or_else(|_| std::path::absolute(path))
.unwrap_or_else(|_| path.to_path_buf())
}
enum Stored {
Missing,
Entries(Vec<RecentLocation>),
Corrupt,
}
fn record_in(file: &Path, entry: RecentLocation) {
let existing = match read_stored(file) {
Stored::Entries(entries) => entries,
Stored::Missing => Vec::new(),
Stored::Corrupt => {
set_corrupt_aside(file);
Vec::new()
}
};
let entries: Vec<RecentLocation> = std::iter::once(entry.clone())
.chain(existing.into_iter().filter(|old| old != &entry))
.take(MAX_RECENTS)
.collect();
write_raw(file, &entries);
}
fn list_in(file: &Path) -> Vec<PathBuf> {
usable_entries(file).collect()
}
fn usable_entries(file: &Path) -> impl Iterator<Item = PathBuf> {
read_raw(file)
.into_iter()
.map(|location| location.to_path())
.filter(|path| is_regular_file(path))
}
fn is_regular_file(path: &Path) -> bool {
std::fs::metadata(path).is_ok_and(|meta| meta.is_file())
}
fn read_raw(file: &Path) -> Vec<RecentLocation> {
match read_stored(file) {
Stored::Entries(entries) => entries,
Stored::Missing | Stored::Corrupt => Vec::new(),
}
}
fn read_stored(file: &Path) -> Stored {
let Ok(text) = std::fs::read_to_string(file) else {
return if file.exists() {
Stored::Corrupt
} else {
Stored::Missing
};
};
serde_json::from_str::<Vec<RecentLocation>>(&text).map_or(Stored::Corrupt, Stored::Entries)
}
fn set_corrupt_aside(file: &Path) {
let aside = file.with_extension("json.corrupt");
match ledgeline_core::pinned::rename_replacing(file, &aside) {
Ok(()) => eprintln!(
"ledgeline: recents file {} was unreadable; kept a copy at {} and started a new list",
file.display(),
aside.display()
),
Err(error) => eprintln!(
"ledgeline: could not set aside unreadable recents {}: {error}",
file.display()
),
}
}
fn write_raw(file: &Path, entries: &[RecentLocation]) {
if let Some(parent) = file.parent()
&& let Err(error) = std::fs::create_dir_all(parent)
{
eprintln!(
"ledgeline: could not create config dir {}: {error}",
parent.display()
);
return;
}
match serde_json::to_string_pretty(entries) {
Ok(json) => {
if let Err(error) = ledgeline_core::edit::atomic_write(file, json.as_bytes()) {
eprintln!(
"ledgeline: could not write recents {}: {error}",
file.display()
);
}
}
Err(error) => eprintln!("ledgeline: could not serialize recents: {error}"),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use tempfile::TempDir;
#[cfg(feature = "gui")]
#[test]
fn labels_collapse_the_home_directory() {
let home = Path::new("/Users/me");
assert_eq!(
label_under(Path::new("/Users/me/books/main.journal"), Some(home)),
"~/books/main.journal"
);
assert_eq!(
label_under(Path::new("/srv/books/main.journal"), Some(home)),
"/srv/books/main.journal"
);
assert_eq!(label_under(Path::new("/a.journal"), None), "/a.journal");
}
#[cfg(all(feature = "gui", windows))]
#[test]
fn verbatim_entries_collapse_against_a_plain_home() {
let home = Path::new(r"C:\Users\me");
assert_eq!(
label_under(Path::new(r"\\?\C:\Users\me\books\main.journal"), Some(home)),
r"~/books\main.journal"
);
assert_eq!(
label_under(Path::new(r"\\?\D:\books\main.journal"), Some(home)),
r"D:\books\main.journal"
);
}
fn loc(path: &Path) -> RecentLocation {
RecentLocation::from_path(path).expect("UTF-8 test path")
}
fn raw_paths(store: &Path) -> Vec<PathBuf> {
read_raw(store)
.iter()
.map(RecentLocation::to_path)
.collect()
}
fn write_paths(store: &Path, paths: &[PathBuf]) {
let entries: Vec<RecentLocation> = paths
.iter()
.map(|p| RecentLocation::new(p.to_str().expect("UTF-8")))
.collect();
write_raw(store, &entries);
}
fn touch(dir: &Path, name: &str) -> PathBuf {
let path = dir.join(name);
fs::write(&path, "").expect("write temp journal");
path
}
#[test]
fn record_moves_to_front_and_dedupes() {
let dir = TempDir::new().expect("temp dir");
let store = dir.path().join("recent.json");
let a = touch(dir.path(), "a.journal");
let b = touch(dir.path(), "b.journal");
let c = touch(dir.path(), "c.journal");
record_in(&store, loc(&a));
record_in(&store, loc(&b));
record_in(&store, loc(&c));
assert_eq!(
raw_paths(&store),
vec![canonicalize(&c), canonicalize(&b), canonicalize(&a)]
);
record_in(&store, loc(&a));
assert_eq!(
raw_paths(&store),
vec![canonicalize(&a), canonicalize(&c), canonicalize(&b)]
);
record_in(&store, loc(&dir.path().join("./b.journal")));
let entries = raw_paths(&store);
assert_eq!(entries.first(), Some(&canonicalize(&b)));
assert_eq!(
entries.iter().filter(|p| **p == canonicalize(&b)).count(),
1,
"the same file must appear only once"
);
}
#[test]
fn record_caps_at_max() {
let dir = TempDir::new().expect("temp dir");
let store = dir.path().join("recent.json");
let total = MAX_RECENTS + 3;
let paths: Vec<PathBuf> = (0..total)
.map(|i| touch(dir.path(), &format!("j{i}.journal")))
.collect();
for path in &paths {
record_in(&store, loc(path));
}
let entries = raw_paths(&store);
assert_eq!(entries.len(), MAX_RECENTS, "capped at MAX_RECENTS");
assert_eq!(entries.first(), Some(&canonicalize(paths.last().unwrap())));
assert!(
!entries.contains(&canonicalize(&paths[0])),
"the oldest entry is evicted once the cap is exceeded"
);
}
#[test]
fn list_skips_missing_paths() {
let dir = TempDir::new().expect("temp dir");
let store = dir.path().join("recent.json");
let present = touch(dir.path(), "present.journal");
let missing = dir.path().join("gone.journal");
write_paths(
&store,
&[canonicalize(&present), missing, canonicalize(&present)],
);
assert_eq!(list_in(&store), vec![canonicalize(&present); 2]);
}
#[test]
fn missing_or_corrupt_store_reads_empty() {
let dir = TempDir::new().expect("temp dir");
let store = dir.path().join("recent.json");
assert!(raw_paths(&store).is_empty());
fs::write(&store, "{ not valid json ]").expect("write garbage");
assert!(raw_paths(&store).is_empty());
}
#[test]
fn list_skips_entries_that_are_not_regular_files() {
let dir = TempDir::new().expect("temp dir");
let store = dir.path().join("recent.json");
let journal = touch(dir.path(), "real.journal");
let subdir = dir.path().join("a-directory");
fs::create_dir(&subdir).expect("create dir");
write_paths(&store, &[canonicalize(&subdir), canonicalize(&journal)]);
assert!(subdir.exists(), "the decoy really is present on disk");
assert_eq!(
list_in(&store),
vec![canonicalize(&journal)],
"a directory must not be offered as a recent journal"
);
assert_eq!(
usable_entries(&store).next(),
Some(canonicalize(&journal)),
"most_recent's lazy filter must skip past it too"
);
}
#[test]
fn a_corrupt_store_is_preserved_rather_than_erased() {
let dir = TempDir::new().expect("temp dir");
let store = dir.path().join("recent.json");
let journal = touch(dir.path(), "j.journal");
fs::write(&store, "{ not valid json ]").expect("write garbage");
record_in(&store, loc(&journal));
let aside = store.with_extension("json.corrupt");
assert_eq!(
fs::read_to_string(&aside).expect("the unreadable bytes are kept"),
"{ not valid json ]"
);
assert_eq!(
raw_paths(&store),
vec![canonicalize(&journal)],
"and the store recovers rather than staying broken"
);
}
#[test]
fn a_missing_store_is_not_treated_as_corrupt() {
let dir = TempDir::new().expect("temp dir");
let store = dir.path().join("recent.json");
let journal = touch(dir.path(), "j.journal");
record_in(&store, loc(&journal));
assert!(!store.with_extension("json.corrupt").exists());
assert_eq!(raw_paths(&store), vec![canonicalize(&journal)]);
}
#[test]
fn the_store_is_written_atomically_and_owner_only() {
let dir = TempDir::new().expect("temp dir");
let store = dir.path().join("recent.json");
let journal = touch(dir.path(), "j.journal");
record_in(&store, loc(&journal));
let leftovers: Vec<PathBuf> = fs::read_dir(dir.path())
.expect("read config dir")
.filter_map(|entry| entry.ok().map(|e| e.path()))
.filter(|p| p.to_string_lossy().contains(".ledgeline-"))
.collect();
assert!(
leftovers.is_empty(),
"temp files left behind: {leftovers:?}"
);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = fs::metadata(&store).expect("stat").permissions().mode() & 0o777;
assert_eq!(
mode & !0o600,
0,
"a freshly created recents store must not be wider than 0600, got {mode:o}"
);
}
}
#[test]
fn record_creates_missing_config_dir() {
let dir = TempDir::new().expect("temp dir");
let store = dir.path().join("nested").join("deeper").join("recent.json");
let journal = touch(dir.path(), "j.journal");
record_in(&store, loc(&journal));
assert_eq!(raw_paths(&store), vec![canonicalize(&journal)]);
}
#[test]
fn the_file_format_is_the_path_array_it_always_was() {
let dir = TempDir::new().expect("temp dir");
let store = dir.path().join("recent.json");
let journal = touch(dir.path(), "old.journal");
let canonical = canonicalize(&journal);
let legacy = serde_json::to_string_pretty(&vec![canonical.clone()]).expect("json");
fs::write(&store, &legacy).expect("write legacy store");
assert_eq!(list_in(&store), vec![canonical.clone()]);
let other = touch(dir.path(), "new.journal");
record_in(&store, loc(&other));
let reread: Vec<PathBuf> =
serde_json::from_str(&fs::read_to_string(&store).expect("read")).expect("old shape");
assert_eq!(reread, vec![canonicalize(&other), canonical]);
}
#[test]
fn an_opaque_token_round_trips_and_is_not_a_usable_path() {
let dir = TempDir::new().expect("temp dir");
let store = dir.path().join("recent.json");
let bookmark = RecentLocation::new("bookmark:6F1C-77A2");
record_in(&store, bookmark.clone());
record_in(&store, RecentLocation::new("bookmark:other"));
record_in(&store, bookmark.clone());
assert_eq!(
read_raw(&store),
vec![bookmark, RecentLocation::new("bookmark:other")]
);
assert!(list_in(&store).is_empty(), "a bookmark id is not a file");
}
#[test]
fn the_store_lives_in_the_injected_config_dir() {
let dir = TempDir::new().expect("temp dir");
let dirs = AppDirs::under(dir.path());
let journal = touch(dir.path(), "j.journal");
record(&dirs, &journal);
assert!(dir.path().join("config").join("recent.json").is_file());
assert_eq!(most_recent(&dirs), Some(canonicalize(&journal)));
assert_eq!(locations(&dirs), vec![loc(&journal)]);
let no_config = AppDirs {
config_dir: None,
..AppDirs::under(dir.path())
};
record(&no_config, &journal);
assert!(list(&no_config).is_empty());
}
}