Skip to main content

ledgeline_shell/
recents.rs

1//! Recently-opened journals: a tiny persistent list so the CLI can default to
2//! the last journal you used and the desktop GUI can offer a File → "Open
3//! Recent" submenu.
4//!
5//! # What an entry is: an opaque [`RecentLocation`]
6//!
7//! The store holds TOKENS, not paths. On the desktop a token is the journal's
8//! canonical absolute path, and the path-shaped helpers here ([`record`],
9//! [`list`], [`most_recent`]) read and write it that way. A sandboxed host
10//! cannot reopen a file from a path at all — iOS hands back access only through
11//! a security-scoped bookmark — so there a token is whatever id the host keeps
12//! its bookmark under, written and read with [`record_location`] /
13//! [`locations`] and resolved by the host itself.
14//!
15//! The file format did not change to make room for that: it is still a JSON
16//! array of strings, most-recent-first, so a `recent.json` written before
17//! tokens existed (an array of path strings) loads unchanged, and one written
18//! now loads in an older build.
19//!
20//! The list lives in `recent.json` under the injected
21//! [`AppDirs::config_dir`] (on the desktop `$LEDGELINE_CONFIG_DIR` or
22//! `dirs::config_dir()/ledgeline`), deduplicated on the token (for a path, the
23//! *canonicalized* path) and capped at [`MAX_RECENTS`]. The store is
24//! intentionally forgiving: a missing file reads back as an empty list and a
25//! write failure is logged but never fatal, so nothing here can break startup.
26//!
27//! # Why this file is security-relevant
28//! [`most_recent`] chooses the journal `ledgeline` opens — and then *writes* —
29//! when invoked with no arguments, so whatever can write `recent.json` chooses
30//! that file. Three properties follow:
31//!
32//! - Entries are checked to be **regular files** ([`is_regular_file`]), not
33//!   merely to exist. `exists()` is also true for a directory, a device node or a
34//!   FIFO, and a FIFO planted here would hang the app at startup instead of
35//!   failing cleanly.
36//! - The store is written **atomically and owner-only** via
37//!   [`ledgeline_core::edit::atomic_write`], so a crash mid-write cannot leave a
38//!   truncated `recent.json`, and a fresh store is not group- or world-writable.
39//! - A store that is present but **unreadable is moved aside, never silently
40//!   replaced** ([`record_in`]), so a parse failure cannot erase the user's
41//!   history beyond recovery.
42
43use crate::app_dirs::AppDirs;
44use serde::{Deserialize, Serialize};
45use std::path::{Path, PathBuf};
46
47/// Maximum number of entries retained on disk (the GUI shows a shorter slice).
48pub const MAX_RECENTS: usize = 10;
49/// File name of the recents store within the config directory.
50const RECENT_FILE: &str = "recent.json";
51
52/// One remembered journal, as an opaque token.
53///
54/// On the desktop the token is a canonical absolute path
55/// ([`from_path`](Self::from_path) / [`to_path`](Self::to_path)); on iOS it is
56/// the id of a security-scoped bookmark the host stores and resolves. The store
57/// never interprets it beyond equality. Serialized as a bare JSON string, which
58/// is what keeps the file format identical to the path-only one before it.
59#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
60#[serde(transparent)]
61pub struct RecentLocation(String);
62
63impl RecentLocation {
64    /// Wrap a host-chosen token (a bookmark id) as-is.
65    #[must_use]
66    pub fn new(token: impl Into<String>) -> Self {
67        Self(token.into())
68    }
69
70    /// The desktop token for `path`: canonicalized to an absolute path for a
71    /// stable dedup key, falling back to a plain absolute path (then the input)
72    /// if the file cannot be resolved.
73    ///
74    /// `None` for a path that is not valid UTF-8, which a JSON string cannot
75    /// hold. (Before tokens such a path made the whole store fail to
76    /// serialize; now it is simply not remembered.)
77    #[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    /// The token as stored.
87    #[must_use]
88    pub fn as_str(&self) -> &str {
89        &self.0
90    }
91
92    /// The desktop reading of the token: the path it names. Meaningless for a
93    /// bookmark id, which a host resolves itself.
94    #[must_use]
95    pub fn to_path(&self) -> PathBuf {
96        PathBuf::from(&self.0)
97    }
98}
99
100/// Record `location` as the most-recently-opened journal: move it to the front
101/// (deduplicating an earlier copy) and cap the list. Best-effort — any I/O
102/// error is logged, never propagated.
103pub 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/// Every stored token, most-recent-first, unfiltered: a host whose tokens are
110/// not paths decides for itself which ones still resolve.
111#[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
118/// Record the journal at `path` (the desktop form of [`record_location`]):
119/// canonicalize it so another spelling of the same file dedupes to one entry.
120pub 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/// The recently-opened journals that still exist on disk, most-recent-first.
131#[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/// The most-recently-opened journal that is still a usable file, if any (the
139/// CLI's default when no journal is given).
140///
141/// Filtering is lazy, so this stats only as far as the first usable entry rather
142/// than all [`MAX_RECENTS`] of them — one `stat` on the startup path instead of
143/// ten, which matters when a stale entry points at an unresponsive network mount.
144#[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/// A concise, human-readable label for a recent-journal menu entry: the path with
151/// the user's home directory collapsed to `~` when applicable.
152///
153/// The home directory is read here for DISPLAY only — it decides no location,
154/// so it is not part of [`AppDirs`].
155#[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/// [`display_label`] with the home directory passed in, for tests.
162///
163/// Both sides go through `dunce::simplified` first: a recent entry is
164/// canonicalized, which on Windows spells it `\\?\C:\Users\…`, while the home
165/// directory is plain `C:\Users\…` — and `strip_prefix` compares prefix
166/// components, so the two would never match and every label would show the
167/// verbatim form. Elsewhere `simplified` is the identity.
168#[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
179/// Canonicalize to an absolute path for stable dedup keys, falling back to a
180/// plain absolute path (then the input) if the file cannot be resolved.
181fn 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
187/// What the store at a given path currently holds.
188enum Stored {
189    /// No file there — an empty list, and nothing to preserve.
190    Missing,
191    /// A well-formed list (possibly empty).
192    Entries(Vec<RecentLocation>),
193    /// Present, but unreadable or not a JSON array of strings. Distinguished
194    /// from [`Missing`](Self::Missing) precisely so it is never silently
195    /// overwritten.
196    Corrupt,
197}
198
199/// Move `entry` to the front of the store at `file`, deduped and capped.
200///
201/// If the existing store is unreadable it is moved aside rather than overwritten:
202/// reading a corrupt file as "no history" and then writing a fresh one-entry list
203/// over it would destroy a history we had merely failed to *parse*.
204fn 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
220/// Read the store at `file`, keeping only entries that are usable journals.
221fn list_in(file: &Path) -> Vec<PathBuf> {
222    usable_entries(file).collect()
223}
224
225/// The stored entries, read as paths, that are usable journals — filtered
226/// **lazily** so a caller that needs only the first ([`most_recent`]) does not
227/// stat the whole list.
228fn 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
235/// Whether `path` is something that can actually be opened as a journal.
236///
237/// `Path::exists` was not enough: it is equally true for a directory, a device
238/// node, a unix socket, or a FIFO — and since [`most_recent`] picks the file the
239/// app opens with no arguments, a FIFO here would block startup forever rather
240/// than fail. Symlinks are followed, so a symlinked journal still qualifies.
241///
242/// Known residual cost, unchanged by this fix: this is a blocking `stat`, so an
243/// entry on an unresponsive network mount can still stall startup. Bounding that
244/// needs a watchdog thread, which is more machinery than a recents list warrants;
245/// [`most_recent`]'s laziness reduces the exposure to the first entry only.
246fn is_regular_file(path: &Path) -> bool {
247    std::fs::metadata(path).is_ok_and(|meta| meta.is_file())
248}
249
250/// Read the raw stored list, treating anything unreadable as empty. Callers that
251/// need to tell "missing" from "corrupt" use [`read_stored`].
252fn 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
259/// Classify the store at `file`.
260fn read_stored(file: &Path) -> Stored {
261    let Ok(text) = std::fs::read_to_string(file) else {
262        // Absent, unreadable, or not UTF-8. Only a genuine absence is safe to
263        // treat as "no history"; anything else is content we failed to read.
264        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
273/// Rename an unreadable store to `recent.json.corrupt` so its bytes survive for
274/// recovery and the next write starts from a clean file.
275fn 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
290/// Persist `entries` as pretty JSON, creating the config directory if needed.
291///
292/// Written through [`ledgeline_core::edit::atomic_write`] (temp file, `fsync`,
293/// `rename`) rather than `fs::write`, so a crash or a full disk mid-write leaves
294/// the previous store intact instead of a truncated file that would read back as
295/// corrupt. A store created here is owner-only. Any failure is logged and
296/// swallowed so a write error can never abort the app.
297fn 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    /// A canonical (verbatim) recent entry still collapses against a plain
342    /// home directory, and is shown without the `\\?\` prefix.
343    #[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    /// The desktop token for `path`.
358    fn loc(path: &Path) -> RecentLocation {
359        RecentLocation::from_path(path).expect("UTF-8 test path")
360    }
361
362    /// The stored tokens, read back as paths.
363    fn raw_paths(store: &Path) -> Vec<PathBuf> {
364        read_raw(store)
365            .iter()
366            .map(RecentLocation::to_path)
367            .collect()
368    }
369
370    /// Write raw path entries, as an older build (or a hand edit) would.
371    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    /// Create an empty file at `dir/name` and return its path (so `canonicalize`
380    /// during `record_in` resolves an existing file).
381    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        // Most-recent-first.
399        assert_eq!(
400            raw_paths(&store),
401            vec![canonicalize(&c), canonicalize(&b), canonicalize(&a)]
402        );
403
404        // Re-recording an older entry moves it to the front without duplicating.
405        record_in(&store, loc(&a));
406        assert_eq!(
407            raw_paths(&store),
408            vec![canonicalize(&a), canonicalize(&c), canonicalize(&b)]
409        );
410
411        // A different spelling of the same file dedupes to one canonical entry.
412        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        // The last-recorded is at the front; the oldest few were dropped.
437        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"); // never created
450
451        write_paths(
452            &store,
453            &[canonicalize(&present), missing, canonicalize(&present)],
454        );
455        // `list_in` keeps only entries that still exist on disk.
456        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        // Missing file.
464        assert!(raw_paths(&store).is_empty());
465        // Corrupt / non-array content.
466        fs::write(&store, "{ not valid json ]").expect("write garbage");
467        assert!(raw_paths(&store).is_empty());
468    }
469
470    /// SEC-10 / DL-6: entries must be regular FILES. `exists()` is also true for
471    /// a directory, and for a FIFO — which `most_recent()` would hand to the
472    /// journal reader, hanging startup instead of failing.
473    #[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    /// The corrupt-store path must not erase history beyond recovery: the bytes
497    /// are moved aside so they can be recovered by hand.
498    #[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    /// An absent store is NOT corrupt — recording into a fresh config dir must
520    /// not leave a stray `.corrupt` file behind.
521    #[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    /// `write_raw` goes through the hardened atomic write, so the store lands
534    /// complete and owner-only, and no temp file is left in the config dir.
535    #[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        // Nested, not-yet-existing directory: `write_raw` must create it.
569        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    /// A `recent.json` written before tokens existed — an array of absolute
576    /// path strings — must load unchanged, and a store written now must still
577    /// be that shape so an older build can read it.
578    #[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    /// A host token that is not a path (an iOS bookmark id) round-trips and
597    /// dedupes like any other, and is never offered as a desktop path.
598    #[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    /// The public entry points read the injected config dir, not the
615    /// environment.
616    #[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}