repon 0.30.5

A terminal UI for the outer loop: seeing many git repos at once and acting on many in one gesture
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
//! `state.toml`: the Set being viewed, plus the Selection, the committed Filter and the
//! table's own `RowOrder` persisted per scope, so a quit and relaunch restores each while
//! every git value is recomputed from scratch ([config.md](../../../docs/spec/config.md#state),
//! [0006](../../../docs/adr/0006-no-git-state-cache-session-state-by-name.md)). This module
//! owns the file's shape and its scope key; [`crate::app::App::restore_session_state`] and
//! [`crate::app::App::persist_state`] are the only callers.

use std::{collections::BTreeMap, fs, path::Path};

use color_eyre::eyre::{Result, WrapErr};
use serde::{Deserialize, Serialize};

use crate::sort::RowOrder;

const STATE_FILE: &str = "state.toml";

/// The one top-level key the file reserves for itself, spelled here as well as in
/// [`StateFile`]'s own field because [`StateFile::set_scope`] compares a scope key against it.
const ACTIVE_SET_KEY: &str = "active_set";

/// One scope's whole session state: the Selection as a list of display names, the committed
/// Filter as its own expression string, the table's `RowOrder`, and the two view toggles.
/// Nothing computed from git is ever a field here, because session state is user input and
/// can only be absent, never stale
/// ([0006](../../../docs/adr/0006-no-git-state-cache-session-state-by-name.md)).
/// `sort` is `None` for a scope nothing has ever chosen an order for, which
/// [`crate::app::App::restore_session_state`] reads as [`RowOrder::cold_start`] rather than
/// [`RowOrder::Natural`]
/// ([ADR 0030](../../../docs/adr/0030-the-table-has-an-order-the-user-chooses.md)'s
/// amendment). `show_worktrees` is `None` for a scope nothing has ever toggled Worktrees in,
/// which [`crate::app::App::restore_session_state`] reads the same way `t` never fired: as
/// deferring to `config.toml`'s own `show_worktrees`
/// ([config.md](../../../docs/spec/config.md#state)). `show_ignored` is `None` the same way,
/// and reads as hidden: no config key backs it, so there is nothing underneath to defer to.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct ScopeState {
    #[serde(default)]
    pub(crate) selection: Vec<String>,
    #[serde(default)]
    pub(crate) filter: String,
    #[serde(default)]
    pub(crate) sort: Option<RowOrder>,
    #[serde(default)]
    pub(crate) show_worktrees: Option<bool>,
    #[serde(default)]
    pub(crate) show_ignored: Option<bool>,
}

/// The whole file: the Set last viewed, then a map of scope key to its own [`ScopeState`],
/// so two Sets, or two working directories both running with no config, never restore each
/// other's Selection or Filter. `active_set` sits at the top level rather than in a scope
/// because it is what chooses the scope, and is absent for a run that had no Set to remember
/// (a zero-config one) or for a file written before it was recorded. It is therefore a
/// reserved key ([`ACTIVE_SET_KEY`]), and a Set carrying that name keeps no scope of its own.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct StateFile {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    active_set: Option<String>,
    #[serde(flatten)]
    scopes: BTreeMap<String, ScopeState>,
}

impl StateFile {
    /// `key`'s own state, or a fresh, empty one when nothing has ever been stored for it.
    pub(crate) fn scope(&self, key: &str) -> ScopeState {
        self.scopes.get(key).cloned().unwrap_or_default()
    }

    /// The Set the last session was viewing, or `None` when nothing has ever recorded one.
    /// [`crate::app::reload::resolve_startup_set`] reads it as a rung below `REPON_SET`, and
    /// a name no longer declared falls through there rather than failing.
    pub(crate) fn active_set(&self) -> Option<&str> {
        self.active_set.as_deref()
    }

    /// Records the Set being viewed, replacing whatever the last session left.
    pub(crate) fn set_active_set(&mut self, name: String) {
        self.active_set = Some(name);
    }

    /// Replaces `key`'s own state wholesale, leaving every other scope's entry untouched. A
    /// scope named after [`ACTIVE_SET_KEY`] is dropped rather than written: two entries under
    /// one key is not TOML, so writing it would cost every other scope in the file its own
    /// state on the next load, where dropping it costs one Set its Selection and no more.
    pub(crate) fn set_scope(&mut self, key: String, state: ScopeState) {
        if key == ACTIVE_SET_KEY {
            return;
        }
        self.scopes.insert(key, state);
    }
}

/// Reads `state.toml` from `data_dir`. A missing file, an unreadable one, malformed TOML, and
/// well-formed TOML in the wrong shape are all treated identically to an absent file, with no
/// warning, because deleting it is a supported reset
/// ([0006](../../../docs/adr/0006-no-git-state-cache-session-state-by-name.md)).
pub(crate) fn load(data_dir: &Path) -> StateFile {
    let Ok(text) = fs::read_to_string(data_dir.join(STATE_FILE)) else {
        return StateFile::default();
    };
    toml::from_str(&text).unwrap_or_default()
}

/// Writes `state` to `state.toml` under `data_dir`, creating the directory first if it does
/// not exist yet.
pub(crate) fn save(data_dir: &Path, state: &StateFile) -> Result<()> {
    fs::create_dir_all(data_dir)
        .wrap_err_with(|| format!("could not create {}", data_dir.display()))?;
    let text = toml::to_string_pretty(state).wrap_err("could not encode state.toml")?;
    let path = data_dir.join(STATE_FILE);
    fs::write(&path, text).wrap_err_with(|| format!("could not write {}", path.display()))
}

/// The scope `state.toml` keys session state by: the active Set's name when a config was
/// loaded, or the absolute working directory when running with no config at all, so two
/// contexts that would otherwise both resolve to the implicit `all` Set never restore each
/// other's Selection or Filter
/// ([config.md](../../../docs/spec/config.md#state)'s "so two contexts cannot restore each
/// other's Selection").
pub(crate) fn scope_key(zero_config: bool, cwd: &Path, active_set_name: &str) -> String {
    if zero_config {
        cwd.to_string_lossy().into_owned()
    } else {
        active_set_name.to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_missing_file_loads_as_an_empty_state_file() {
        let dir = tempfile::tempdir().expect("temp dir");
        let file = load(dir.path());
        assert_eq!(file, StateFile::default());
        assert_eq!(file.scope("anything"), ScopeState::default());
    }

    #[test]
    fn save_then_load_round_trips_a_scopes_whole_content() {
        let dir = tempfile::tempdir().expect("temp dir");
        let mut file = StateFile::default();
        file.set_scope(
            "work".to_string(),
            ScopeState {
                selection: vec!["repo-a".to_string(), "repo-b".to_string()],
                filter: "kind:worktree".to_string(),
                sort: None,
                show_worktrees: None,
                show_ignored: None,
            },
        );

        save(dir.path(), &file).expect("save state.toml");
        let reloaded = load(dir.path());

        assert_eq!(
            reloaded.scope("work"),
            ScopeState {
                selection: vec!["repo-a".to_string(), "repo-b".to_string()],
                filter: "kind:worktree".to_string(),
                sort: None,
                show_worktrees: None,
                show_ignored: None,
            }
        );
    }

    /// Criterion 2's own risk: a round trip of one field proves nothing about what else the
    /// file carries. This asserts the whole written file's content is exactly the four
    /// fields a scope owns, so a later field added to the struct (a branch name, a commit
    /// id) would fail this the moment it serialised, not only when some other test happened
    /// to read it back.
    #[test]
    fn the_written_file_holds_only_selection_filter_sort_and_the_two_toggles_nothing_else() {
        let dir = tempfile::tempdir().expect("temp dir");
        let mut file = StateFile::default();
        file.set_scope(
            "work".to_string(),
            ScopeState {
                selection: vec!["repo-a".to_string()],
                filter: "is:dirty".to_string(),
                sort: Some(RowOrder::cold_start()),
                show_worktrees: Some(false),
                show_ignored: Some(true),
            },
        );
        save(dir.path(), &file).expect("save state.toml");

        let text = fs::read_to_string(dir.path().join(STATE_FILE)).expect("read state.toml");
        let parsed: toml::Value = toml::from_str(&text).expect("parse written toml");
        let scope = parsed
            .get("work")
            .expect("the scope table")
            .as_table()
            .expect("scope is a table");
        let mut keys: Vec<&str> = scope.keys().map(String::as_str).collect();
        keys.sort_unstable();
        assert_eq!(
            keys,
            vec![
                "filter",
                "selection",
                "show_ignored",
                "show_worktrees",
                "sort"
            ],
            "a scope must hold exactly `selection`, `filter`, `sort`, `show_worktrees` and \
             `show_ignored`, nothing git computed: {text:?}"
        );
    }

    /// The two `RowOrder` shapes both round-trip: the struct variant carrying a column and a
    /// direction, and the unit variant with neither, so an explicit `Natural` choice
    /// survives a restart rather than reading back as nothing stored
    /// ([ADR 0030](../../../docs/adr/0030-the-table-has-an-order-the-user-chooses.md)'s
    /// amendment).
    #[test]
    fn a_recorded_sort_round_trips_through_state_toml() {
        use crate::sort::{Direction, SortColumn};

        let dir = tempfile::tempdir().expect("temp dir");
        let mut file = StateFile::default();
        file.set_scope(
            "sorted".to_string(),
            ScopeState {
                selection: vec![],
                filter: String::new(),
                sort: Some(RowOrder::By {
                    column: SortColumn::Dirty,
                    direction: Direction::Descending,
                }),
                show_worktrees: None,
                show_ignored: None,
            },
        );
        file.set_scope(
            "natural".to_string(),
            ScopeState {
                selection: vec![],
                filter: String::new(),
                sort: Some(RowOrder::Natural),
                show_worktrees: None,
                show_ignored: None,
            },
        );
        save(dir.path(), &file).expect("save state.toml");

        let reloaded = load(dir.path());
        assert_eq!(
            reloaded.scope("sorted").sort,
            Some(RowOrder::By {
                column: SortColumn::Dirty,
                direction: Direction::Descending,
            })
        );
        assert_eq!(reloaded.scope("natural").sort, Some(RowOrder::Natural));
    }

    /// The worktrees toggle (`Action::ToggleWorktrees`, `t`) round-trips the same way `sort`
    /// does: both booleans a scope can hold survive a save and a reload.
    #[test]
    fn a_recorded_worktrees_toggle_round_trips_through_state_toml() {
        let dir = tempfile::tempdir().expect("temp dir");
        let mut file = StateFile::default();
        file.set_scope(
            "hidden".to_string(),
            ScopeState {
                show_worktrees: Some(false),
                show_ignored: None,
                ..ScopeState::default()
            },
        );
        file.set_scope(
            "shown".to_string(),
            ScopeState {
                show_worktrees: Some(true),
                show_ignored: None,
                ..ScopeState::default()
            },
        );
        save(dir.path(), &file).expect("save state.toml");

        let reloaded = load(dir.path());
        assert_eq!(reloaded.scope("hidden").show_worktrees, Some(false));
        assert_eq!(reloaded.scope("shown").show_worktrees, Some(true));
    }

    /// The ignored toggle (`Action::ToggleIgnored`, `i`) round-trips the way the worktrees
    /// one does, so a scope reopens showing what it was left showing.
    #[test]
    fn a_recorded_ignored_toggle_round_trips_through_state_toml() {
        let dir = tempfile::tempdir().expect("temp dir");
        let mut file = StateFile::default();
        file.set_scope(
            "hidden".to_string(),
            ScopeState {
                show_ignored: Some(false),
                ..ScopeState::default()
            },
        );
        file.set_scope(
            "shown".to_string(),
            ScopeState {
                show_ignored: Some(true),
                ..ScopeState::default()
            },
        );
        save(dir.path(), &file).expect("save state.toml");

        let reloaded = load(dir.path());
        assert_eq!(reloaded.scope("hidden").show_ignored, Some(false));
        assert_eq!(reloaded.scope("shown").show_ignored, Some(true));
    }

    /// A scope nothing has ever toggled ignored rows in loads `show_ignored` as `None`, which
    /// [`crate::app::App::restore_session_state`] reads as hidden: there is no config key
    /// underneath for it to defer to, unlike the worktrees toggle.
    #[test]
    fn a_scope_with_no_show_ignored_key_loads_it_as_none() {
        let dir = tempfile::tempdir().expect("temp dir");
        fs::write(
            dir.path().join(STATE_FILE),
            "[work]\nselection = [\"repo-a\"]\nfilter = \"is:dirty\"\n",
        )
        .expect("write a pre-toggle state.toml");

        let scope = load(dir.path()).scope("work");
        assert_eq!(scope.show_ignored, None);
    }

    /// A scope nothing has ever toggled Worktrees in loads `show_worktrees` as `None`, which
    /// [`crate::app::App::restore_session_state`] reads as "let `config.toml` decide", exactly
    /// as if the toggle had never fired.
    #[test]
    fn a_scope_with_no_show_worktrees_key_loads_it_as_none() {
        let dir = tempfile::tempdir().expect("temp dir");
        fs::write(
            dir.path().join(STATE_FILE),
            "[work]\nselection = [\"repo-a\"]\nfilter = \"is:dirty\"\n",
        )
        .expect("write a pre-toggle state.toml");

        let scope = load(dir.path()).scope("work");
        assert_eq!(scope.show_worktrees, None);
    }

    /// A scope with no `sort` key at all, exactly what an older build's own `state.toml`
    /// looks like, loads with `sort: None` rather than failing the whole scope, `selection`
    /// and `filter` restoring untouched beside it.
    #[test]
    fn a_scope_with_no_sort_key_loads_sort_as_none() {
        let dir = tempfile::tempdir().expect("temp dir");
        fs::write(
            dir.path().join(STATE_FILE),
            "[work]\nselection = [\"repo-a\"]\nfilter = \"is:dirty\"\n",
        )
        .expect("write a pre-sort state.toml");

        let scope = load(dir.path()).scope("work");
        assert_eq!(scope.sort, None);
        assert_eq!(scope.selection, vec!["repo-a"]);
        assert_eq!(scope.filter, "is:dirty");
    }

    /// The Set being viewed is session state like the Selection beside it, and it is the one
    /// piece that cannot live in a scope, because it is what chooses the scope. It round
    /// trips at the top level with every scope's own entry untouched.
    #[test]
    fn the_active_set_round_trips_beside_the_scopes_it_chooses_between() {
        let dir = tempfile::tempdir().expect("temp dir");
        let mut file = StateFile::default();
        file.set_scope(
            "work".to_string(),
            ScopeState {
                selection: vec!["repo-a".to_string()],
                filter: "is:dirty".to_string(),
                sort: None,
                show_worktrees: None,
                show_ignored: None,
            },
        );
        file.set_active_set("work".to_string());
        save(dir.path(), &file).expect("save state.toml");

        let reloaded = load(dir.path());
        assert_eq!(reloaded.active_set(), Some("work"));
        assert_eq!(reloaded.scope("work").selection, vec!["repo-a"]);
        assert_eq!(reloaded.scope("work").filter, "is:dirty");
    }

    /// A Set carrying the reserved key's own name keeps no scope, and every other scope in
    /// the file survives it: writing both a remembered Set and a scope table under the one
    /// key would not be TOML at all, and the whole file would read back empty next launch.
    #[test]
    fn a_scope_named_after_the_reserved_key_never_displaces_the_remembered_set() {
        let dir = tempfile::tempdir().expect("temp dir");
        let mut file = StateFile::default();
        file.set_scope(
            ACTIVE_SET_KEY.to_string(),
            ScopeState {
                selection: vec!["repo-a".to_string()],
                ..ScopeState::default()
            },
        );
        file.set_scope(
            "work".to_string(),
            ScopeState {
                selection: vec!["repo-b".to_string()],
                ..ScopeState::default()
            },
        );
        file.set_active_set(ACTIVE_SET_KEY.to_string());
        save(dir.path(), &file).expect("save state.toml");

        let reloaded = load(dir.path());
        assert_eq!(reloaded.active_set(), Some(ACTIVE_SET_KEY));
        assert_eq!(
            reloaded.scope("work").selection,
            vec!["repo-b"],
            "every other scope must survive a Set named after the reserved key"
        );
    }

    /// A file an older build wrote, and one a run with no Set to remember wrote, are the same
    /// shape: every scope still loads and the remembered Set is simply absent, never a
    /// failure that would take the whole file down with it.
    #[test]
    fn a_file_with_no_remembered_active_set_loads_every_scope_with_none_remembered() {
        let dir = tempfile::tempdir().expect("temp dir");
        fs::write(
            dir.path().join(STATE_FILE),
            "[work]\nselection = [\"repo-a\"]\nfilter = \"is:dirty\"\n",
        )
        .expect("write a state.toml with no remembered Set");

        let file = load(dir.path());
        assert_eq!(file.active_set(), None);
        assert_eq!(file.scope("work").selection, vec!["repo-a"]);
    }

    /// Two Sets never read each other's state: writing `work`'s scope must leave `personal`'s
    /// own entry absent rather than overwritten with `work`'s content.
    #[test]
    fn two_different_set_scopes_do_not_read_each_others_state() {
        let dir = tempfile::tempdir().expect("temp dir");
        let mut file = StateFile::default();
        file.set_scope(
            "work".to_string(),
            ScopeState {
                selection: vec!["repo-a".to_string()],
                filter: "kind:worktree".to_string(),
                sort: None,
                show_worktrees: None,
                show_ignored: None,
            },
        );
        file.set_scope(
            "personal".to_string(),
            ScopeState {
                selection: vec!["dotfiles".to_string()],
                filter: String::new(),
                sort: None,
                show_worktrees: None,
                show_ignored: None,
            },
        );
        save(dir.path(), &file).expect("save state.toml");

        let reloaded = load(dir.path());
        assert_eq!(reloaded.scope("work").selection, vec!["repo-a"]);
        assert_eq!(reloaded.scope("personal").selection, vec!["dotfiles"]);
        assert_ne!(reloaded.scope("work"), reloaded.scope("personal"));
    }

    /// The scope key's Set-name branch: two named Sets get two distinct keys.
    #[test]
    fn scope_key_uses_the_active_sets_name_when_a_config_was_loaded() {
        let key_a = scope_key(false, Path::new("/irrelevant"), "work");
        let key_b = scope_key(false, Path::new("/irrelevant"), "personal");
        assert_eq!(key_a, "work");
        assert_ne!(key_a, key_b);
    }

    /// The scope key's working-directory branch, the one the ticket names as the one that
    /// gets skipped: running with no config keys by `cwd`, not by the Set name (`all` in
    /// every zero-config run), so two different working directories never collide even
    /// though `active_set_name` is identical for both.
    #[test]
    fn scope_key_uses_the_working_directory_when_running_with_no_config() {
        let key_a = scope_key(true, Path::new("/home/paul/dev/one"), "all");
        let key_b = scope_key(true, Path::new("/home/paul/dev/two"), "all");
        assert_ne!(
            key_a, key_b,
            "two different working directories running zero-config must never collide on \
             the Set name they share"
        );
        assert_eq!(key_a, "/home/paul/dev/one");
    }

    /// Malformed TOML must behave exactly like a missing file: no error, no warning, an empty
    /// `StateFile` indistinguishable from `a_missing_file_loads_as_an_empty_state_file`'s own.
    #[test]
    fn malformed_toml_loads_the_same_as_a_missing_file() {
        let dir = tempfile::tempdir().expect("temp dir");
        fs::write(
            dir.path().join(STATE_FILE),
            "this is not = = valid toml [[[\n",
        )
        .expect("write malformed state.toml");

        assert_eq!(load(dir.path()), StateFile::default());
    }

    /// Well-formed TOML in the wrong shape is the second corruption the ticket names
    /// distinctly from malformed syntax: valid TOML, but a scope whose `selection` is a
    /// string rather than an array, so deserialising into `ScopeState` fails even though
    /// parsing the document itself would not. Must reach the same empty-file outcome as both
    /// the malformed and the missing cases.
    #[test]
    fn well_formed_toml_in_the_wrong_shape_loads_the_same_as_a_missing_file() {
        let dir = tempfile::tempdir().expect("temp dir");
        fs::write(
            dir.path().join(STATE_FILE),
            "[work]\nselection = \"repo-a\"\nfilter = \"is:dirty\"\n",
        )
        .expect("write well-formed but wrong-shaped state.toml");

        assert_eq!(load(dir.path()), StateFile::default());
    }

    /// Deleting `state.toml` is a supported reset, not a state a caller must first empty out:
    /// a scope written, then the file removed by hand, loads back to nothing rather than
    /// erroring or resurrecting the old content.
    #[test]
    fn deleting_the_file_by_hand_is_a_supported_reset() {
        let dir = tempfile::tempdir().expect("temp dir");
        let mut file = StateFile::default();
        file.set_scope(
            "work".to_string(),
            ScopeState {
                selection: vec!["repo-a".to_string()],
                filter: "is:dirty".to_string(),
                sort: None,
                show_worktrees: None,
                show_ignored: None,
            },
        );
        save(dir.path(), &file).expect("save state.toml");

        fs::remove_file(dir.path().join(STATE_FILE)).expect("delete state.toml by hand");

        assert_eq!(load(dir.path()), StateFile::default());
    }
}