zenops 0.20.0

Declarative system configuration management for shell config and dotfiles.
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
//! Bridge between [`super::Plan`] and the generic [`crate::picker`] trait.
//!
//! [`pickable_items`] flattens the four per-action lists on a [`Plan`]
//! (`files`, `renamed_files`, `removed_files`, `skipped`) into a parallel
//! pair of vectors: a [`Vec<PendingItem>`] of internal back-references and
//! a [`Vec<PickItem>`] of the user-facing rows. The picker mutates the
//! second; [`apply_picks`] reads the user's choices back through the first
//! to mutate the plan in place.
//!
//! The choice constants live here so a glance at the top of the file is
//! enough to see exactly which actions the picker exposes per row shape,
//! and adding a third option later is a one-line edit instead of a
//! cross-file refactor.

use std::borrow::Cow;

use smol_str::SmolStr;

use crate::output::SkipReason;
use crate::picker::{ChoiceLabel, PickItem};

use super::{Plan, TomlPlan};

/// `import`-side actions a picker row can cycle through. Each row's
/// `PickItem::choices` is a slice of [`ChoiceLabel`]s whose `key` strings
/// match these constants verbatim — [`apply_picks`] dispatches on the
/// key after the picker returns.
pub(super) const CHOICE_IMPORT: &str = "import";
pub(super) const CHOICE_RENAME: &str = "rename";
pub(super) const CHOICE_REMOVE: &str = "remove";
pub(super) const CHOICE_KEEP: &str = "keep";
pub(super) const CHOICE_SKIP: &str = "skip";

const FILE_CHOICES: &[ChoiceLabel] = &[
    ChoiceLabel {
        key: SmolStr::new_static(CHOICE_IMPORT),
        label: SmolStr::new_static("import"),
    },
    ChoiceLabel {
        key: SmolStr::new_static(CHOICE_SKIP),
        label: SmolStr::new_static("skip"),
    },
];

const RENAME_CHOICES: &[ChoiceLabel] = &[
    ChoiceLabel {
        key: SmolStr::new_static(CHOICE_RENAME),
        label: SmolStr::new_static("rename"),
    },
    ChoiceLabel {
        key: SmolStr::new_static(CHOICE_SKIP),
        label: SmolStr::new_static("skip"),
    },
];

const REMOVE_CHOICES: &[ChoiceLabel] = &[
    ChoiceLabel {
        key: SmolStr::new_static(CHOICE_REMOVE),
        label: SmolStr::new_static("remove"),
    },
    ChoiceLabel {
        key: SmolStr::new_static(CHOICE_KEEP),
        label: SmolStr::new_static("keep"),
    },
];

const SKIPPED_CHOICES: &[ChoiceLabel] = &[ChoiceLabel {
    key: SmolStr::new_static(CHOICE_SKIP),
    label: SmolStr::new_static("skip"),
}];

/// Identifies one row in the user-facing picker by its source list on the
/// underlying [`Plan`]. [`apply_picks`] walks these in parallel with the
/// picker's mutated [`PickItem`] vec to mutate the right list when the
/// user picked a non-default action.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct PendingItem {
    pub(super) kind: PendingKind,
    pub(super) index: usize,
}

/// Which list on [`Plan`] a [`PendingItem`] points into.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum PendingKind {
    /// Index into `plan.files` — a new file the picker can `import` or `skip`.
    File,
    /// Index into `plan.renamed_files` — a moved file the picker can
    /// `rename` (in-repo) or `skip`.
    Renamed,
    /// Index into `plan.removed_files` — a file gone from home that the
    /// picker can `remove` from the repo or `keep` (defer cleanup).
    Removed,
    /// Index into `plan.skipped` — a disabled row that exists only to
    /// surface the skipped entry's reason to the user.
    Skipped,
}

/// Flatten `plan` into the parallel `(PendingItem, PickItem)` vecs the
/// picker session needs. Order is stable: files first, then renames,
/// then removes, then skipped — mirroring the same order the
/// `ImportFileAction` event uses in [`super::plan_to_event`].
pub(super) fn pickable_items(plan: &Plan) -> (Vec<PendingItem>, Vec<PickItem<'static>>) {
    let mut pending = Vec::new();
    let mut items = Vec::new();

    for (idx, f) in plan.files.iter().enumerate() {
        pending.push(PendingItem {
            kind: PendingKind::File,
            index: idx,
        });
        items.push(PickItem {
            label: Cow::Owned(super::path_to_forward_slash(&f.rel)),
            note: None,
            choices: FILE_CHOICES,
            choice: 0,
        });
    }
    for (idx, r) in plan.renamed_files.iter().enumerate() {
        pending.push(PendingItem {
            kind: PendingKind::Renamed,
            index: idx,
        });
        items.push(PickItem {
            label: Cow::Owned(format!(
                "{}{}",
                super::path_to_forward_slash(&r.from),
                super::path_to_forward_slash(&r.to),
            )),
            note: Some(Cow::Borrowed("moved in place")),
            choices: RENAME_CHOICES,
            choice: 0,
        });
    }
    for (idx, r) in plan.removed_files.iter().enumerate() {
        pending.push(PendingItem {
            kind: PendingKind::Removed,
            index: idx,
        });
        items.push(PickItem {
            label: Cow::Owned(super::path_to_forward_slash(&r.repo_rel)),
            note: Some(Cow::Borrowed("gone from disk")),
            choices: REMOVE_CHOICES,
            choice: 0,
        });
    }
    for (idx, s) in plan.skipped.iter().enumerate() {
        pending.push(PendingItem {
            kind: PendingKind::Skipped,
            index: idx,
        });
        items.push(PickItem {
            label: Cow::Owned(super::path_to_forward_slash(&s.path)),
            note: Some(Cow::Borrowed(humanise_reason(s.reason))),
            choices: SKIPPED_CHOICES,
            choice: 0,
        });
    }

    (pending, items)
}

/// Map a [`SkipReason`] to the dim note text shown on a picker row. The
/// match is exhaustive: a new reason variant won't compile until it has a
/// note here.
fn humanise_reason(reason: SkipReason) -> &'static str {
    match reason {
        SkipReason::Symlink => "already symlinked",
        SkipReason::Vcs => "vcs directory",
        SkipReason::Other => "not a regular file",
        SkipReason::PresentButNotLinked => "regular file shadows array entry",
        SkipReason::SymlinkElsewhere => "symlink to outside the repo",
    }
}

/// Apply the user's per-row choices back onto `plan`. Walks `pending` and
/// `items` in lockstep; for every row whose chosen key isn't the default
/// (`import` / `rename` / `remove`), drops the row from the corresponding
/// source list and rebuilds the TOML delta accordingly.
///
/// Indices on `PendingItem` are stable through this walk because we
/// process them right-to-left when filtering, so earlier indices remain
/// valid as later ones are dropped.
pub(super) fn apply_picks(plan: &mut Plan, pending: &[PendingItem], items: &[PickItem<'_>]) {
    debug_assert_eq!(pending.len(), items.len());

    let mut drop_files: Vec<usize> = Vec::new();
    let mut drop_renamed: Vec<usize> = Vec::new();
    let mut drop_removed: Vec<usize> = Vec::new();

    for (p, item) in pending.iter().zip(items.iter()) {
        let choice = &item.choices[item.choice];
        match (p.kind, choice.key.as_str()) {
            (PendingKind::File, CHOICE_SKIP) => drop_files.push(p.index),
            (PendingKind::Renamed, CHOICE_SKIP) => drop_renamed.push(p.index),
            (PendingKind::Removed, CHOICE_KEEP) => drop_removed.push(p.index),
            // All other (kind, key) pairs are the row's default action —
            // nothing to do, the plan already represents it.
            _ => {}
        }
    }

    drop_in_place(&mut plan.files, &drop_files);
    drop_in_place(&mut plan.renamed_files, &drop_renamed);
    drop_in_place(&mut plan.removed_files, &drop_removed);

    rebuild_toml_deltas(plan);
}

/// Remove the entries at `indices` (in any order) from `v`. Sorts +
/// dedups internally and walks back-to-front so each surviving index
/// stays valid.
fn drop_in_place<T>(v: &mut Vec<T>, indices: &[usize]) {
    if indices.is_empty() {
        return;
    }
    let mut sorted: Vec<usize> = indices.to_vec();
    sorted.sort_unstable();
    sorted.dedup();
    for idx in sorted.into_iter().rev() {
        v.remove(idx);
    }
}

/// After the per-row lists have been mutated, rebuild each `TomlPlan`
/// variant's symlink deltas from the survivors. Only [`TomlPlan::Reconcile`]
/// and [`TomlPlan::ExtendExisting`] hold deltas; the new-pkg variants
/// ([`TomlPlan::DotConfig`] / [`TomlPlan::Home`]) rebuild their `symlinks`
/// array from `plan.files` directly.
fn rebuild_toml_deltas(plan: &mut Plan) {
    match &mut plan.toml {
        TomlPlan::Reconcile {
            added_symlinks,
            removed_symlinks,
            ..
        } => {
            let mut new_added: Vec<String> = plan
                .files
                .iter()
                .map(|f| super::path_to_forward_slash(&f.repo_rel))
                .collect();
            let mut new_removed: Vec<String> = plan
                .removed_files
                .iter()
                .map(|r| super::path_to_forward_slash(&r.repo_rel))
                .collect();
            for r in &plan.renamed_files {
                new_added.push(super::path_to_forward_slash(&r.to));
                new_removed.push(super::path_to_forward_slash(&r.from));
            }
            *added_symlinks = new_added;
            *removed_symlinks = new_removed;
        }
        TomlPlan::ExtendExisting {
            existing_symlinks,
            added_symlinks,
            ..
        } => {
            // Extend mode always has exactly one PendingItem::File at most.
            // If the user skipped it, plan.files is now empty and the
            // delta empties too — the caller's is_noop check then short-
            // circuits the apply.
            *added_symlinks = plan
                .files
                .iter()
                .map(|f| super::path_to_forward_slash(&f.repo_rel))
                .filter(|s| !existing_symlinks.iter().any(|e| e == s))
                .collect();
        }
        TomlPlan::DotConfig { symlinks, .. } | TomlPlan::Home { symlinks, .. } => {
            *symlinks = plan
                .files
                .iter()
                .map(|f| super::path_to_forward_slash(&f.repo_rel))
                .collect();
        }
    }
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use similar_asserts::assert_eq;
    use smol_str::SmolStr;

    use super::super::{PlannedFile, RemovedFile, RenamedFile, SkippedEntry};
    use super::*;

    fn empty_plan() -> Plan {
        Plan {
            pkg_key: SmolStr::new_static("p"),
            r#type: crate::output::ImportType::DotConfig,
            source: PathBuf::from("/src"),
            source_root: PathBuf::from("/src"),
            repo_dest: PathBuf::from("/repo"),
            repo_rel: "configs/p".into(),
            files: Vec::new(),
            skipped: Vec::new(),
            removed_files: Vec::new(),
            renamed_files: Vec::new(),
            toml: TomlPlan::DotConfig {
                name_override: None,
                symlinks: Vec::new(),
            },
        }
    }

    #[test]
    fn pickable_items_orders_file_then_rename_then_remove_then_skipped() {
        let mut plan = empty_plan();
        plan.files.push(PlannedFile {
            rel: PathBuf::from("a"),
            repo_rel: PathBuf::from("a"),
        });
        plan.renamed_files.push(RenamedFile {
            from: PathBuf::from("old"),
            to: PathBuf::from("new"),
        });
        plan.removed_files.push(RemovedFile {
            repo_rel: PathBuf::from("gone"),
        });
        plan.skipped.push(SkippedEntry {
            path: PathBuf::from(".git"),
            reason: SkipReason::Vcs,
        });

        let (pending, items) = pickable_items(&plan);
        assert_eq!(pending.len(), 4);
        assert_eq!(items.len(), 4);
        assert_eq!(pending[0].kind, PendingKind::File);
        assert_eq!(pending[1].kind, PendingKind::Renamed);
        assert_eq!(pending[2].kind, PendingKind::Removed);
        assert_eq!(pending[3].kind, PendingKind::Skipped);
        assert_eq!(items[0].label, "a");
        assert_eq!(items[1].label, "old → new");
        assert_eq!(items[2].label, "gone");
        assert_eq!(items[3].label, ".git");
        assert_eq!(items[3].note.as_deref(), Some("vcs directory"));
        // Skipped row is disabled (single choice).
        assert_eq!(items[3].choices.len(), 1);
    }

    #[test]
    fn humanise_reason_known_tags() {
        assert_eq!(humanise_reason(SkipReason::Symlink), "already symlinked");
        assert_eq!(humanise_reason(SkipReason::Vcs), "vcs directory");
        assert_eq!(humanise_reason(SkipReason::Other), "not a regular file");
        assert_eq!(
            humanise_reason(SkipReason::PresentButNotLinked),
            "regular file shadows array entry",
        );
        assert_eq!(
            humanise_reason(SkipReason::SymlinkElsewhere),
            "symlink to outside the repo",
        );
    }

    #[test]
    fn apply_picks_skip_on_file_drops_it_from_plan_files() {
        let mut plan = empty_plan();
        plan.files.push(PlannedFile {
            rel: PathBuf::from("keep"),
            repo_rel: PathBuf::from("keep"),
        });
        plan.files.push(PlannedFile {
            rel: PathBuf::from("drop"),
            repo_rel: PathBuf::from("drop"),
        });

        let (pending, mut items) = pickable_items(&plan);
        // Skip the second file.
        items[1].choice = 1;

        apply_picks(&mut plan, &pending, &items);
        assert_eq!(plan.files.len(), 1);
        assert_eq!(plan.files[0].rel, PathBuf::from("keep"));
        match &plan.toml {
            TomlPlan::DotConfig { symlinks, .. } => {
                assert_eq!(symlinks, &vec!["keep".to_string()]);
            }
            other => panic!("unexpected toml plan: {other:?}"),
        }
    }

    #[test]
    fn apply_picks_keep_on_removed_drops_it_from_plan_removed_files() {
        let mut plan = empty_plan();
        plan.toml = TomlPlan::Reconcile {
            config_index: 0,
            existing_symlinks: vec!["a".into(), "b".into()],
            added_symlinks: Vec::new(),
            removed_symlinks: vec!["a".into(), "b".into()],
        };
        plan.removed_files.push(RemovedFile {
            repo_rel: PathBuf::from("a"),
        });
        plan.removed_files.push(RemovedFile {
            repo_rel: PathBuf::from("b"),
        });

        let (pending, mut items) = pickable_items(&plan);
        // Keep `a` (index 0 in removed_files).
        items[0].choice = 1;

        apply_picks(&mut plan, &pending, &items);
        assert_eq!(plan.removed_files.len(), 1);
        assert_eq!(plan.removed_files[0].repo_rel, PathBuf::from("b"));
        match &plan.toml {
            TomlPlan::Reconcile {
                removed_symlinks, ..
            } => {
                assert_eq!(removed_symlinks, &vec!["b".to_string()]);
            }
            other => panic!("unexpected toml plan: {other:?}"),
        }
    }

    #[test]
    fn apply_picks_skip_on_renamed_drops_both_sides_from_deltas() {
        let mut plan = empty_plan();
        plan.toml = TomlPlan::Reconcile {
            config_index: 0,
            existing_symlinks: vec!["old".into()],
            added_symlinks: vec!["new".into()],
            removed_symlinks: vec!["old".into()],
        };
        plan.renamed_files.push(RenamedFile {
            from: PathBuf::from("old"),
            to: PathBuf::from("new"),
        });

        let (pending, mut items) = pickable_items(&plan);
        items[0].choice = 1; // skip the rename

        apply_picks(&mut plan, &pending, &items);
        assert_eq!(plan.renamed_files.len(), 0);
        match &plan.toml {
            TomlPlan::Reconcile {
                added_symlinks,
                removed_symlinks,
                ..
            } => {
                assert!(added_symlinks.is_empty());
                assert!(removed_symlinks.is_empty());
            }
            other => panic!("unexpected toml plan: {other:?}"),
        }
    }

    #[test]
    fn apply_picks_no_changes_leaves_plan_alone() {
        let mut plan = empty_plan();
        plan.files.push(PlannedFile {
            rel: PathBuf::from("a"),
            repo_rel: PathBuf::from("a"),
        });

        let (pending, items) = pickable_items(&plan);
        apply_picks(&mut plan, &pending, &items);
        assert_eq!(plan.files.len(), 1);
    }

    #[test]
    fn drop_in_place_walks_back_to_front_with_dedup() {
        let mut v = vec!['a', 'b', 'c', 'd', 'e'];
        drop_in_place(&mut v, &[1, 3, 1]);
        assert_eq!(v, vec!['a', 'c', 'e']);
    }
}