kaeru 0.1.9

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
//! Notes on disk: one JSON file per note in kaeru's state folder, the `.cwd`
//! file that a shell keeps its folder in, the lock that lets only one tab ask
//! about waiting tabs, the plan of the tabs being reopened, and the log of the
//! commands that print nothing.

use std::fs::{self, File, OpenOptions, TryLockError};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use anyhow::{Context, Result};

use crate::engine::config::Config;
use crate::engine::note::Note;
use crate::engine::rules::{self, Facts, SingleWindowClose, TabState, TerminalShape};
use crate::engine::tabs::Seen;
use crate::procs::{self, ProcessTable};

/// The environment variable that moves the state folder, and with it the
/// config file, for tests and for trying kaeru without touching the real
/// notes.
pub const STATE_DIR_VAR: &str = "KAERU_STATE_DIR";

/// How large the log may grow, in bytes, before it starts over.
const LOG_LIMIT: u64 = 256 * 1024;

/// How long a plan of reopened tabs counts, after which a tab that opens
/// isn't one of them.
const PLAN_LIFETIME: std::time::Duration = std::time::Duration::from_secs(120);

/// A tab that the picker reopens: its place in the order they come back,
/// how many come back, and its folder.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Reopening {
    pub number: usize,
    pub total: usize,
    pub cwd: String,
}

/// kaeru's state folder, and its config file.
pub struct Store {
    dir: PathBuf,
    config: PathBuf,
}

/// A note, and the file it was read from.
#[derive(Debug, Clone)]
pub struct StoredNote {
    pub path: PathBuf,
    pub note: Note,
}

/// A note, and what it means now.
#[derive(Debug, Clone)]
pub struct Reviewed {
    pub stored: StoredNote,
    pub state: TabState,
}

impl Store {
    /// Returns the state folder: the one in `KAERU_STATE_DIR` when that is
    /// set, or else the OS's usual place for app state. The config file is
    /// in the OS's usual place for app config, or in the state folder when
    /// `KAERU_STATE_DIR` is set.
    ///
    /// # Errors
    ///
    /// Fails when the OS has no such place, or the folder can't be created.
    pub fn open() -> Result<Store> {
        if let Some(dir) = std::env::var_os(STATE_DIR_VAR) {
            return Store::at(PathBuf::from(dir));
        }
        let mut store =
            Store::at(default_dir().context("this system has no folder for app state")?)?;
        if let Some(config) = dirs::config_dir() {
            store.config = config.join("kaeru").join("config.toml");
        }
        Ok(store)
    }

    /// Returns the store in `dir`, with its config file there too, creating
    /// the folders it needs.
    ///
    /// # Errors
    ///
    /// Fails when the folders can't be created.
    pub fn at(dir: PathBuf) -> Result<Store> {
        let notes = dir.join("notes");
        fs::create_dir_all(&notes).with_context(|| format!("can't create {}", notes.display()))?;
        let config = dir.join("config.toml");
        Ok(Store { dir, config })
    }

    /// Returns the user's options from the config file, or the defaults when
    /// there is no file. A file that can't be read is logged, and the
    /// defaults are used.
    pub fn config(&self) -> Config {
        let Ok(text) = fs::read_to_string(&self.config) else {
            return Config::default();
        };
        toml::from_str(&text).unwrap_or_else(|error| {
            self.log(&format!("can't read {}: {error}", self.config.display()));
            Config::default()
        })
    }

    /// Saves the user's options to the config file.
    ///
    /// # Errors
    ///
    /// Fails when the file can't be written.
    pub fn save_config(&self, config: &Config) -> Result<()> {
        if let Some(folder) = self.config.parent() {
            fs::create_dir_all(folder)?;
        }
        fs::write(&self.config, toml::to_string(config)?)
            .with_context(|| format!("can't write {}", self.config.display()))
    }

    /// Returns the note in one file, as it is on disk now.
    ///
    /// # Errors
    ///
    /// Fails when the file is gone or can't be read.
    pub fn read(&self, path: &Path) -> Result<Note> {
        read_note(path)
    }

    /// Returns every note, oldest process first. A file that can't be read
    /// is skipped and logged.
    pub fn notes(&self) -> Vec<StoredNote> {
        let Ok(entries) = fs::read_dir(self.notes_dir()) else {
            return Vec::new();
        };
        let mut notes: Vec<StoredNote> = entries
            .filter_map(|entry| entry.ok().map(|entry| entry.path()))
            .filter(|path| {
                path.extension()
                    .is_some_and(|extension| extension == "json")
            })
            .filter_map(|path| match read_note(&path) {
                Ok(note) => Some(StoredNote { path, note }),
                Err(error) => {
                    self.log(&format!("skipped {}: {error:#}", path.display()));
                    None
                }
            })
            .collect();
        notes.sort_by_key(|stored| stored.note.process().started_ms);
        notes
    }

    /// Returns the path that a note is saved at.
    pub fn path_of(&self, note: &Note) -> PathBuf {
        self.notes_dir().join(file_name(note))
    }

    /// Writes a note, replacing an earlier one for the same process. The note
    /// goes to a temporary file that is then renamed, to avoid half-written
    /// notes after a crash.
    ///
    /// # Errors
    ///
    /// Fails when the file can't be written.
    pub fn save(&self, note: &Note) -> Result<PathBuf> {
        let path = self.path_of(note);
        let temp = path.with_extension(format!("json.{}.tmp", std::process::id()));
        fs::write(&temp, serde_json::to_vec_pretty(note)?)
            .with_context(|| format!("can't write {}", temp.display()))?;
        if let Err(error) = fs::rename(&temp, &path) {
            let _ = fs::remove_file(&temp);
            return Err(error).with_context(|| format!("can't write {}", path.display()));
        }
        Ok(path)
    }

    /// Deletes a note, and the `.cwd` file of a shell note.
    pub fn remove(&self, stored: &StoredNote) {
        let _ = fs::remove_file(&stored.path);
        let _ = fs::remove_file(cwd_file(&stored.path));
    }

    /// Returns the state folder.
    pub fn dir(&self) -> &Path {
        &self.dir
    }

    /// Deletes everything kaeru keeps: the notes, the lock, the log and the
    /// config file, and then the state folder if nothing else is in it. Only
    /// kaeru's own files are deleted, even when `KAERU_STATE_DIR` points to a
    /// folder that holds other files too.
    ///
    /// # Errors
    ///
    /// Fails when the notes folder can't be deleted.
    pub fn delete_all(&self) -> Result<()> {
        let notes = self.notes_dir();
        if notes.exists() {
            fs::remove_dir_all(&notes)
                .with_context(|| format!("can't delete {}", notes.display()))?;
        }
        for file in [self.dir.join("lock"), self.log_path(), self.config.clone()] {
            let _ = fs::remove_file(file);
        }
        let _ = fs::remove_dir(&self.dir);
        if let Some(folder) = self.config.parent() {
            let _ = fs::remove_dir(folder);
        }
        Ok(())
    }

    /// Takes the lock that lets only one tab ask about waiting tabs, or
    /// returns `None` when another process holds it. The lock is released
    /// when the returned file is dropped, or when the process ends.
    ///
    /// # Errors
    ///
    /// Fails when the lock file can't be opened.
    pub fn try_lock(&self) -> Result<Option<File>> {
        let path = self.dir.join("lock");
        let file = OpenOptions::new()
            .create(true)
            .truncate(false)
            .write(true)
            .open(&path)
            .with_context(|| format!("can't open {}", path.display()))?;
        match file.try_lock() {
            Ok(()) => Ok(Some(file)),
            Err(TryLockError::WouldBlock) => Ok(None),
            Err(TryLockError::Error(error)) => {
                Err(error).with_context(|| format!("can't lock {}", path.display()))
            }
        }
    }

    /// Writes the plan of the tabs that the picker is about to reopen, so
    /// that each of them can say how far the reopening has come once it
    /// opens. The terminal shows each new tab as it opens, so the picker's
    /// own tab, which says the same, is out of sight.
    ///
    /// # Errors
    ///
    /// Fails when the plan can't be written.
    pub fn plan_reopening(&self, tabs: &[Reopening]) -> Result<()> {
        let path = self.dir.join("reopening");
        fs::write(&path, plan_text(tabs)).with_context(|| format!("can't write {}", path.display()))
    }

    /// Takes the tab in folder `cwd` out of the plan of reopened tabs, and
    /// returns it, or the first tab in the plan when no tab has that folder.
    /// Nothing comes back when there is no plan, or when it is too old.
    pub fn take_reopening(&self, cwd: &str) -> Option<Reopening> {
        let path = self.dir.join("reopening");
        let fresh = fs::metadata(&path)
            .and_then(|metadata| metadata.modified())
            .ok()
            .and_then(|modified| modified.elapsed().ok())
            .is_some_and(|age| age < PLAN_LIFETIME);
        if !fresh {
            let _ = fs::remove_file(&path);
            return None;
        }
        let mut tabs = parse_plan(&fs::read_to_string(&path).ok()?);
        let index = plan_place(&tabs, cwd)?;
        let tab = tabs.remove(index);
        let _ = if tabs.is_empty() {
            fs::remove_file(&path)
        } else {
            fs::write(&path, plan_text(&tabs))
        };
        Some(tab)
    }

    /// Returns the path of the log.
    pub fn log_path(&self) -> PathBuf {
        self.dir.join("kaeru.log")
    }

    /// Appends a line to the log. The commands that a shell or an agent runs
    /// print nothing, so their problems go here, for `kaeru doctor` to
    /// show. The log starts over when it grows past 256 KB.
    pub fn log(&self, message: &str) {
        let path = self.log_path();
        if fs::metadata(&path).is_ok_and(|metadata| metadata.len() > LOG_LIMIT) {
            let _ = fs::remove_file(&path);
        }
        let seconds = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_or(0, |since| since.as_secs());
        if let Ok(mut file) = OpenOptions::new().create(true).append(true).open(&path) {
            let _ = writeln!(file, "{seconds} [{}] {message}", std::process::id());
        }
    }

    /// Returns the folder that the notes are in.
    fn notes_dir(&self) -> PathBuf {
        self.dir.join("notes")
    }
}

/// Returns a note's file name: its kind, process id and start time, which
/// together are unique.
pub fn file_name(note: &Note) -> String {
    let kind = match note {
        Note::Shell(_) => "shell",
        Note::Agent(_) => "agent",
    };
    let process = note.process();
    format!("{kind}-{}-{}.json", process.pid, process.started_ms)
}

/// Returns the path of the `.cwd` file that belongs to a note file.
pub fn cwd_file(note_path: &Path) -> PathBuf {
    note_path.with_extension("cwd")
}

/// Returns a folder as Windows writes it when it is a Windows path with
/// forward slashes, as Git Bash's `pwd -W` prints it, such as `C:/code`.
/// Other paths come back as they are.
fn windows_path(path: &str) -> String {
    let bytes = path.as_bytes();
    let drive = bytes.len() >= 3 && bytes[0].is_ascii_alphabetic() && &bytes[1..3] == b":/";
    if drive {
        path.replace('/', "\\")
    } else {
        path.to_string()
    }
}

/// Returns what kaeru last saw of a note's tab: the folder its shell wrote to
/// the `.cwd` file, or else the folder the note records, and when the shell
/// last showed its prompt, which is when the `.cwd` file last changed,
/// because the snippet touches it at every prompt.
pub fn last_seen(stored: &StoredNote) -> Seen {
    let recorded = match &stored.note {
        Note::Shell(note) => &note.cwd,
        Note::Agent(note) => &note.cwd,
    };
    let file = cwd_file(&stored.path);
    let cwd = fs::read_to_string(&file)
        .ok()
        .map(|text| windows_path(text.trim()))
        .filter(|text| !text.is_empty())
        .unwrap_or_else(|| recorded.clone());
    let prompt_ms = fs::metadata(&file)
        .and_then(|metadata| metadata.modified())
        .ok()
        .and_then(|modified| modified.duration_since(UNIX_EPOCH).ok())
        .and_then(|since| u64::try_from(since.as_millis()).ok());
    Seen { cwd, prompt_ms }
}

/// Returns what every note means now, and deletes the notes of closed tabs,
/// as docs/architecture.md describes under Housekeeping.
pub fn review(
    store: &Store,
    table: &dyn ProcessTable,
    session: &str,
    single_window_close: SingleWindowClose,
) -> Vec<Reviewed> {
    let mut kept = Vec::new();
    for stored in store.notes() {
        let terminal = stored.note.terminal();
        let facts = Facts {
            program: procs::liveness(table, stored.note.process()),
            terminal: terminal.map(|terminal| procs::liveness(table, &terminal.process)),
            shape: terminal.map_or(TerminalShape::SingleWindow, |terminal| terminal.shape),
            same_session: stored.note.session() == session,
            single_window_close,
        };
        let state = rules::decide(&facts);
        if state == TabState::Closed {
            store.remove(&stored);
        } else {
            kept.push(Reviewed { stored, state });
        }
    }
    kept
}

/// Reads one note file.
fn read_note(path: &Path) -> Result<Note> {
    Ok(serde_json::from_str(&fs::read_to_string(path)?)?)
}

/// Returns the OS's usual folder for kaeru's state.
fn default_dir() -> Option<PathBuf> {
    #[cfg(target_os = "linux")]
    let base = dirs::state_dir();
    #[cfg(not(target_os = "linux"))]
    let base = dirs::data_local_dir();
    base.map(|dir| dir.join("kaeru"))
}

/// Returns the text of a plan of reopened tabs: one tab per line, with its
/// number, the total and its folder, separated by tabs.
fn plan_text(tabs: &[Reopening]) -> String {
    tabs.iter()
        .map(|tab| format!("{}\t{}\t{}\n", tab.number, tab.total, tab.cwd))
        .collect()
}

/// Returns the tabs of a plan's text. Lines that don't read are left out.
fn parse_plan(text: &str) -> Vec<Reopening> {
    text.lines()
        .filter_map(|line| {
            let mut parts = line.splitn(3, '\t');
            Some(Reopening {
                number: parts.next()?.parse().ok()?,
                total: parts.next()?.parse().ok()?,
                cwd: parts.next()?.to_string(),
            })
        })
        .collect()
}

/// Returns the place in the plan of the tab in folder `cwd`, or of the first
/// tab when none has that folder. Folders are compared without case and with
/// either slash, as Windows paths are.
fn plan_place(tabs: &[Reopening], cwd: &str) -> Option<usize> {
    let same = |a: &str, b: &str| {
        let plain = |path: &str| path.replace('\\', "/").trim_end_matches('/').to_lowercase();
        plain(a) == plain(b)
    };
    tabs.iter()
        .position(|tab| same(&tab.cwd, cwd))
        .or_else(|| (!tabs.is_empty()).then_some(0))
}

#[cfg(test)]
mod tests {

    #[test]
    fn a_plan_of_reopened_tabs_reads_back() {
        let tabs = vec![
            Reopening {
                number: 1,
                total: 2,
                cwd: r"C:\Users\demo\code\api-server".into(),
            },
            Reopening {
                number: 2,
                total: 2,
                cwd: "/home/demo/code/web ui".into(),
            },
        ];
        assert_eq!(parse_plan(&plan_text(&tabs)), tabs);
        assert_eq!(plan_place(&tabs, "c:/users/demo/code/api-server/"), Some(0));
        assert_eq!(plan_place(&tabs, "/home/demo/code/web ui"), Some(1));
        assert_eq!(plan_place(&tabs, "/somewhere/else"), Some(0));
        assert_eq!(plan_place(&[], "/home/demo"), None);
    }

    #[test]
    fn a_reopened_tab_takes_its_place_in_the_plan_once() {
        let (_dir, store) = temp_store();
        let tab = |number: usize, cwd: &str| Reopening {
            number,
            total: 2,
            cwd: cwd.into(),
        };
        store
            .plan_reopening(&[tab(1, "/home/demo/a"), tab(2, "/home/demo/b")])
            .unwrap();
        assert_eq!(
            store.take_reopening("/home/demo/b"),
            Some(tab(2, "/home/demo/b"))
        );
        assert_eq!(
            store.take_reopening("/home/demo/b"),
            Some(tab(1, "/home/demo/a"))
        );
        assert_eq!(store.take_reopening("/home/demo/b"), None);
    }
    use super::*;
    use crate::engine::note::{ProcessRef, ShellNote, TerminalRef};

    #[test]
    fn a_folder_from_git_bash_becomes_a_windows_path() {
        assert_eq!(windows_path("C:/Users/demo/code"), r"C:\Users\demo\code");
        assert_eq!(windows_path("d:/"), r"d:\");
        assert_eq!(windows_path(r"C:\Users\demo"), r"C:\Users\demo");
        assert_eq!(windows_path("/home/demo/code"), "/home/demo/code");
    }
    use crate::procs::fake::FakeTable;

    fn temp_store() -> (tempfile::TempDir, Store) {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::at(dir.path().to_path_buf()).unwrap();
        (dir, store)
    }

    fn shell(pid: u32, started_ms: u64, terminal: Option<(u32, u64)>) -> Note {
        Note::Shell(ShellNote {
            process: ProcessRef { pid, started_ms },
            shell: "powershell".into(),
            cwd: r"C:\Users\demo\code\api-server".into(),
            terminal: terminal.map(|(pid, started_ms)| TerminalRef {
                adapter: "windows-terminal".into(),
                process: ProcessRef { pid, started_ms },
                shape: TerminalShape::Tabs,
                tab_id: None,
                profile: None,
                exe: None,
            }),
            session: "win-1".into(),
            offered: false,
            adopted_ms: None,
        })
    }

    #[test]
    fn a_saved_note_reads_back() {
        let (_dir, store) = temp_store();
        let note = shell(10, 1_000, None);
        let path = store.save(&note).unwrap();
        assert!(path.ends_with("shell-10-1000.json"));
        let notes = store.notes();
        assert_eq!(notes.len(), 1);
        assert_eq!(notes[0].note, note);
    }

    #[test]
    fn saving_the_same_process_again_replaces_its_note() {
        let (_dir, store) = temp_store();
        store.save(&shell(10, 1_000, None)).unwrap();
        store.save(&shell(10, 1_000, Some((1, 500)))).unwrap();
        let notes = store.notes();
        assert_eq!(notes.len(), 1);
        assert!(notes[0].note.terminal().is_some());
    }

    #[test]
    fn removing_a_note_also_removes_its_cwd_file() {
        let (_dir, store) = temp_store();
        let path = store.save(&shell(10, 1_000, None)).unwrap();
        fs::write(cwd_file(&path), "D:\\work").unwrap();
        store.remove(&store.notes()[0]);
        assert!(!path.exists());
        assert!(!cwd_file(&path).exists());
    }

    #[test]
    fn an_unreadable_note_is_skipped_and_logged() {
        let (dir, store) = temp_store();
        fs::write(dir.path().join("notes").join("shell-1-1.json"), "not json").unwrap();
        assert!(store.notes().is_empty());
        let log = fs::read_to_string(store.log_path()).unwrap();
        assert!(log.contains("skipped"));
    }

    #[test]
    fn the_last_folder_comes_from_the_cwd_file() {
        let (_dir, store) = temp_store();
        let path = store.save(&shell(10, 1_000, None)).unwrap();
        let stored = store.notes().remove(0);
        assert_eq!(last_seen(&stored).cwd, r"C:\Users\demo\code\api-server");
        fs::write(cwd_file(&path), "D:\\work\\프로젝트\r\n").unwrap();
        assert_eq!(last_seen(&stored).cwd, "D:\\work\\프로젝트");
    }

    #[test]
    fn only_one_holder_gets_the_lock() {
        let (_dir, store) = temp_store();
        let first = store.try_lock().unwrap();
        assert!(first.is_some());
        assert!(store.try_lock().unwrap().is_none());
        drop(first);
        // A test that starts a program at this moment gives it a copy of the
        // lock file until the program runs, so the lock can take a moment
        // to be free.
        let taken = (0..100).any(|_| {
            let taken = store.try_lock().unwrap().is_some();
            if !taken {
                std::thread::sleep(std::time::Duration::from_millis(10));
            }
            taken
        });
        assert!(taken);
    }

    #[test]
    fn review_deletes_closed_tabs_and_keeps_the_rest() {
        let (_dir, store) = temp_store();
        let open = store.save(&shell(10, 1_000, Some((1, 500)))).unwrap();
        let closed = store.save(&shell(20, 2_000, Some((1, 500)))).unwrap();
        let waiting = store.save(&shell(30, 3_000, Some((2, 600)))).unwrap();
        let table = FakeTable::new(&[
            (10, Some(1), "powershell.exe", Some(1_000)),
            (1, None, "WindowsTerminal.exe", Some(500)),
        ]);
        let reviewed = review(&store, &table, "win-1", SingleWindowClose::Forget);
        let states: Vec<(&Path, TabState)> = reviewed
            .iter()
            .map(|reviewed| (reviewed.stored.path.as_path(), reviewed.state))
            .collect();
        assert_eq!(
            states,
            [
                (open.as_path(), TabState::Open),
                (waiting.as_path(), TabState::Waiting)
            ]
        );
        assert!(!closed.exists());
    }

    #[test]
    fn options_are_saved_and_read_back() {
        let (_dir, store) = temp_store();
        assert_eq!(store.config(), Config::default(), "no file yet");
        let config = Config {
            offer_shells: false,
            ..Config::default()
        };
        store.save_config(&config).unwrap();
        assert_eq!(store.config(), config);
    }

    #[test]
    fn a_broken_config_file_gives_the_defaults_and_is_logged() {
        let (dir, store) = temp_store();
        fs::write(dir.path().join("config.toml"), "offer-shells = maybe").unwrap();
        assert_eq!(store.config(), Config::default());
        let log = fs::read_to_string(store.log_path()).unwrap();
        assert!(log.contains("config.toml"));
    }
}