dort 0.1.0

Experimental, TUI-first local dotfile manager with guarded recovery
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
//! Pure session-local shell and retained path drafts. No environment or I/O.
use super::app::Tab;
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

// Ordinary metadata viewport only; private Git patch scrolling never calls this.
pub fn scroll_details(scroll: &mut u16, code: KeyCode) -> bool {
    match code {
        KeyCode::Down | KeyCode::PageDown => {
            *scroll = scroll.saturating_add(if code == KeyCode::Down { 1 } else { 2 })
        }
        KeyCode::Up | KeyCode::PageUp => {
            *scroll = scroll.saturating_sub(if code == KeyCode::Up { 1 } else { 2 })
        }
        KeyCode::Home => *scroll = 0,
        _ => return false,
    }
    true
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Form {
    Choose,
    Init,
    Adopt,
    Check,
    KeepId,
    RemoveId,
}

pub struct ProfilePicker {
    pub report: Box<crate::services::CheckReport>,
    pub requested: Vec<String>,
    pub standalone: bool,
    pub selected: usize,
}

pub struct AdoptionDraft {
    pub target: String,
    pub id: String,
    pub source: String,
    // Fields, Review, Choose repository, Create/attach, Discard.
    pub focused: usize,
}
impl AdoptionDraft {
    pub fn new() -> Self {
        Self {
            target: String::new(),
            id: String::new(),
            source: String::new(),
            focused: 0,
        }
    }
    pub fn suggest(&mut self, path: &std::path::Path, home: &std::path::Path) {
        // Discovery supplies validated paths beneath its explicit HOME. Never infer
        // HOME from a basename/common ancestor or consult the process environment.
        let relative = path
            .strip_prefix(home)
            .expect("discovery path beneath HOME");
        self.target = path.to_str().expect("validated candidate path").to_owned();
        let name = relative
            .to_str()
            .expect("validated relative candidate path");
        let id: String = name
            .trim_start_matches('.')
            .chars()
            .map(|c| {
                if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
                    c
                } else {
                    '-'
                }
            })
            .take(128)
            .collect();
        self.id = if id.is_empty() { "file".into() } else { id };
        self.source = std::path::Path::new("files")
            .join(relative)
            .to_str()
            .expect("validated source suggestion")
            .to_owned();
        self.focused = 0;
    }
}
pub enum Overlay {
    Ignored {
        paths: Vec<std::path::PathBuf>,
        selected: usize,
    },
    Actions {
        query: String,
        selected: usize,
        searching: bool,
        entries: Vec<super::palette::Entry>,
    },
    Repositories {
        selected: usize,
    },
    Form(Form),
    Profiles(Box<ProfilePicker>),
    About,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Action {
    Destination(Tab),
    GitRoot,
    GitDefault,
    GitStatus,
    GitUnstaged,
    GitStaged,
    GitRefresh,
    GitPatch,
    Choose,
    Init,
    Discover,
    IgnoreSelected,
    ManageIgnored,
    Adopt,
    AdoptSelected,
    BatchAdopt,
    ApplyMarked,
    KeepMarked,
    RemoveMarked,
    ToggleMark,
    ClearMarks,
    ExpandAll,
    CollapseAll,
    Profiles,
    CheckCurrent,
    CheckStandalone,
    StandaloneProfiles,
    Refresh,
    Apply,
    Keep,
    Remove,
    KeepId,
    RemoveId,
    ClearFilter,
    Inspect,
    Rollback,
    Resume,
    Abandon,
    PreviewOnly,
    Diagnostics,
    About,
    Help,
    Quit,
}
impl Action {
    pub fn label(self) -> &'static str {
        match self {
            Self::Destination(Tab::Overview) => "Overview",
            Self::Destination(Tab::Files) => "Files: managed mappings",
            Self::Destination(Tab::Recovery) => "Recovery: all repositories",
            Self::Destination(Tab::Checks) => "Checks: manifest validation",
            Self::Destination(Tab::Git) => "Git: read-only inspection",
            Self::GitRoot => "Git: choose independent root (session only)",
            Self::GitDefault => "Git: use current file repository root",
            Self::GitStatus => "Git: Status metadata",
            Self::GitUnstaged => "Git: Unstaged summary",
            Self::GitStaged => "Git: Staged summary",
            Self::GitRefresh => "Git: Refresh metadata only",
            Self::GitPatch => "View patch content (Git comparison; may expose secrets)",
            Self::Choose => "Choose repository (session only)",
            Self::Init => "Create/attach local repository",
            Self::Discover => "Discover files (metadata only; no repository needed)",
            Self::IgnoreSelected => {
                "Ignore selected discovery file/folder (persistent local preview)"
            }
            Self::ManageIgnored => "Manage ignored paths / Unignore (local preferences)",
            Self::Adopt => "Adopt a file (editable target / ID / source)",
            Self::AdoptSelected => "Adopt selected eligible file (editable draft)",
            Self::BatchAdopt => "Adopt marked files (combined editable batch)",
            Self::ApplyMarked => "Apply marked mappings (selected batch)",
            Self::KeepMarked => "Keep marked mappings (combined batch)",
            Self::RemoveMarked => "Delete marked links (each exact ID then yes)",
            Self::ToggleMark => "Mark/unmark item or matching group descendants",
            Self::ClearMarks => "Clear marks (current Files inventory)",
            Self::ExpandAll => "Expand all tree groups",
            Self::CollapseAll => "Collapse all tree groups",
            Self::Profiles => "Profiles: temporary repository additions",
            Self::CheckCurrent => "Check current repository manifest",
            Self::CheckStandalone => "Check standalone manifest (no repository needed)",
            Self::StandaloneProfiles => "Profiles for standalone manifest",
            Self::Refresh => "Refresh observations and history",
            Self::Apply => "Preview apply (requires repository)",
            Self::Keep => "Keep local file (select in Files)",
            Self::Remove => "Delete managed link (select in Files)",
            Self::KeepId => "Keep local file: enter exact mapping ID",
            Self::RemoveId => "Delete managed link: enter exact mapping ID",
            Self::ClearFilter => "Clear current display filter (not execution scope)",
            Self::Inspect => "Inspect selected file / transaction / Git entry details",
            Self::Rollback => "Preview rollback (select in Recovery)",
            Self::Resume => "Preview bootstrap resume (select in Recovery)",
            Self::Abandon => "Preview bootstrap abandon (select in Recovery)",
            Self::PreviewOnly => "Toggle preview-only mode",
            Self::Diagnostics => "Diagnostics: host, paths and global write blockers",
            Self::About => "About Dort: version, capabilities and limits",
            Self::Help => "Help: current context and safeguards",
            Self::Quit => "Quit (wait for worker)",
        }
    }
}
pub struct Shell {
    pub overlay: Option<Overlay>,
    pub scroll: u16,
    pub page_rows: std::cell::Cell<u16>,
    pub init_draft: String,
    pub path_focused: usize,
    pub choose_draft: String,
    pub adoption: AdoptionDraft,
    pub return_to_adopt: bool,
    pub manifest_draft: String,
    pub manifest_focused: usize,
    pub check_profiles: Vec<String>,
    pub unmanage_id: String,
    pub unmanage_focused: usize,
}
pub enum Intent {
    Unignore(std::path::PathBuf),
    Action(Action),
    Submit(Form),
    Known(usize),
    Active,
    ApplyProfiles {
        manifest: Option<std::path::PathBuf>,
        requested: Vec<String>,
    },
}
impl Shell {
    pub fn new() -> Self {
        Self {
            overlay: None,
            scroll: 0,
            page_rows: std::cell::Cell::new(1),
            init_draft: String::new(),
            path_focused: 0,
            choose_draft: String::new(),
            adoption: AdoptionDraft::new(),
            return_to_adopt: false,
            manifest_draft: String::new(),
            manifest_focused: 0,
            check_profiles: vec![],
            unmanage_id: String::new(),
            unmanage_focused: 0,
        }
    }
    pub fn open_actions(&mut self, entries: Vec<super::palette::Entry>) {
        self.scroll = 0;
        self.overlay = Some(Overlay::Actions {
            query: String::new(),
            selected: 0,
            searching: true,
            entries,
        });
    }
    /// Page the currently visible inline metadata viewport.
    pub fn page(&mut self, down: bool) {
        let rows = self.page_rows.get().max(1);
        self.scroll = if down {
            self.scroll.saturating_add(rows)
        } else {
            self.scroll.saturating_sub(rows)
        };
    }
    pub fn text_entry(&self) -> bool {
        matches!(
            self.overlay,
            Some(Overlay::Actions {
                searching: true,
                ..
            })
        ) || (matches!(self.overlay, Some(Overlay::Form(Form::Choose | Form::Init)))
            && self.path_focused == 0)
            || (matches!(self.overlay, Some(Overlay::Form(Form::Adopt)))
                && self.adoption.focused < 3)
            || (matches!(self.overlay, Some(Overlay::Form(Form::Check)))
                && self.manifest_focused == 0)
            || (matches!(
                self.overlay,
                Some(Overlay::Form(Form::KeepId | Form::RemoveId))
            ) && self.unmanage_focused == 0)
    }
    pub fn back(&mut self) {
        self.scroll = 0;
        self.overlay = if self.return_to_adopt {
            self.return_to_adopt = false;
            Some(Overlay::Form(Form::Adopt))
        } else {
            None
        };
    }
    pub fn draft(&self, form: Form) -> &str {
        match form {
            Form::Choose => &self.choose_draft,
            Form::Init => &self.init_draft,
            Form::Adopt => &self.adoption.target,
            Form::Check => &self.manifest_draft,
            Form::KeepId | Form::RemoveId => &self.unmanage_id,
        }
    }
    pub fn key(&mut self, key: KeyEvent, known_count: usize) -> Option<Intent> {
        if !matches!(key.code, KeyCode::PageUp | KeyCode::PageDown) {
            self.scroll = 0;
        }
        match self.overlay.as_mut()? {
            Overlay::Ignored { paths, selected } => match key.code {
                KeyCode::Esc => self.overlay = None,
                KeyCode::Down | KeyCode::Char('j') => {
                    *selected = (*selected + 1).min(paths.len().saturating_sub(1))
                }
                KeyCode::Up | KeyCode::Char('k') => *selected = selected.saturating_sub(1),
                KeyCode::PageDown => *selected = (*selected + 8).min(paths.len().saturating_sub(1)),
                KeyCode::PageUp => *selected = selected.saturating_sub(8),
                KeyCode::Home => *selected = 0,
                KeyCode::End => *selected = paths.len().saturating_sub(1),
                KeyCode::Enter => {
                    if let Some(path) = paths.get(*selected) {
                        return Some(Intent::Unignore(path.clone()));
                    }
                }
                _ => (),
            },
            Overlay::About => {
                if matches!(key.code, KeyCode::Esc | KeyCode::Enter | KeyCode::Char('?')) {
                    self.overlay = None;
                }
            }
            Overlay::Profiles(picker) => {
                let count = picker.report.choices.known.len();
                match key.code {
                    KeyCode::Esc => {
                        self.overlay = if picker.standalone {
                            Some(Overlay::Form(Form::Check))
                        } else {
                            None
                        }
                    }
                    KeyCode::Down => picker.selected = (picker.selected + 1).min(count),
                    KeyCode::Up => picker.selected = picker.selected.saturating_sub(1),
                    KeyCode::Enter if picker.selected == count => {
                        return Some(Intent::ApplyProfiles {
                            manifest: picker.standalone.then(|| picker.report.manifest.clone()),
                            requested: picker.requested.clone(),
                        });
                    }
                    KeyCode::Enter | KeyCode::Char(' ') => {
                        if let Some(name) = picker.report.choices.known.iter().nth(picker.selected)
                            && !picker.report.choices.mandatory.contains(name)
                        {
                            if picker.requested.contains(name) {
                                picker.requested.retain(|p| p != name);
                            } else {
                                picker.requested.push(name.clone());
                            }
                        }
                    }
                    _ => (),
                }
            }
            Overlay::Form(Form::KeepId | Form::RemoveId) => {
                let Some(Overlay::Form(form)) = self.overlay else {
                    unreachable!()
                };
                match key.code {
                    KeyCode::Esc => self.overlay = None,
                    KeyCode::Tab | KeyCode::BackTab => {
                        self.unmanage_focused = 1 - self.unmanage_focused;
                        self.scroll = 0;
                    }
                    KeyCode::Enter if self.unmanage_focused == 0 => self.unmanage_focused = 1,
                    KeyCode::Enter => return Some(Intent::Submit(form)),
                    _ if self.unmanage_focused == 0 => edit_text(&mut self.unmanage_id, key),
                    _ => (),
                }
            }
            Overlay::Form(Form::Check) => match key.code {
                KeyCode::Esc => self.overlay = None,
                KeyCode::Tab | KeyCode::BackTab => {
                    self.manifest_focused = (self.manifest_focused
                        + if key.code == KeyCode::BackTab
                            || key.modifiers.contains(KeyModifiers::SHIFT)
                        {
                            3
                        } else {
                            1
                        })
                        % 4;
                    self.scroll = 0;
                }
                KeyCode::Enter if self.manifest_focused == 0 => self.manifest_focused = 1,
                KeyCode::Enter if self.manifest_focused == 1 => {
                    return Some(Intent::Submit(Form::Check));
                }
                KeyCode::Enter if self.manifest_focused == 2 => {
                    return Some(Intent::Action(Action::StandaloneProfiles));
                }
                KeyCode::Enter => {
                    self.manifest_draft.clear();
                    self.check_profiles.clear();
                    self.manifest_focused = 0;
                }
                _ if self.manifest_focused == 0 => edit_text(&mut self.manifest_draft, key),
                _ => (),
            },
            Overlay::Form(Form::Adopt) => {
                let draft = &mut self.adoption;
                match key.code {
                    KeyCode::Esc => self.overlay = None,
                    KeyCode::Tab | KeyCode::BackTab => {
                        let backwards = key.code == KeyCode::BackTab
                            || key.modifiers.contains(KeyModifiers::SHIFT);
                        draft.focused = (draft.focused + if backwards { 6 } else { 1 }) % 7;
                        self.scroll = 0;
                    }
                    KeyCode::Enter if draft.focused < 3 => draft.focused += 1,
                    KeyCode::Enter if draft.focused == 3 => {
                        return Some(Intent::Submit(Form::Adopt));
                    }
                    KeyCode::Enter if draft.focused == 4 => {
                        return Some(Intent::Action(Action::Choose));
                    }
                    KeyCode::Enter if draft.focused == 5 => {
                        return Some(Intent::Action(Action::Init));
                    }
                    KeyCode::Enter => {
                        self.adoption = AdoptionDraft::new();
                        self.scroll = 0;
                    }
                    _ => match draft.focused {
                        0 => edit_text(&mut draft.target, key),
                        1 => edit_text(&mut draft.id, key),
                        2 => edit_text(&mut draft.source, key),
                        _ => (),
                    },
                }
            }
            Overlay::Form(form) => {
                let form = *form;
                let draft = match form {
                    Form::Choose => &mut self.choose_draft,
                    Form::Init => &mut self.init_draft,
                    Form::Adopt | Form::Check | Form::KeepId | Form::RemoveId => unreachable!(),
                };
                match key.code {
                    KeyCode::Esc => self.back(),
                    KeyCode::Tab | KeyCode::BackTab => {
                        self.path_focused = (self.path_focused
                            + if key.code == KeyCode::BackTab
                                || key.modifiers.contains(KeyModifiers::SHIFT)
                            {
                                2
                            } else {
                                1
                            })
                            % 3;
                    }
                    KeyCode::Enter if self.path_focused == 0 => self.path_focused = 1,
                    KeyCode::Enter if self.path_focused == 1 => return Some(Intent::Submit(form)),
                    KeyCode::Enter => self.back(),
                    _ if self.path_focused == 0 => edit_text(draft, key),
                    _ => (),
                }
            }
            Overlay::Repositories { selected } => match key.code {
                KeyCode::Esc => self.back(),
                KeyCode::Down => *selected = selected.saturating_add(1).min(known_count + 2),
                KeyCode::Up => *selected = selected.saturating_sub(1),
                KeyCode::Enter if *selected == 0 => {
                    self.scroll = 0;
                    self.path_focused = 0;
                    self.overlay = Some(Overlay::Form(Form::Choose))
                }
                KeyCode::Enter if *selected == 1 => return Some(Intent::Active),
                KeyCode::Enter if *selected == known_count + 2 => {
                    return Some(Intent::Action(Action::Init));
                }
                KeyCode::Enter => return Some(Intent::Known(*selected - 2)),
                _ => (),
            },
            Overlay::Actions {
                query,
                selected,
                searching,
                entries,
            } => match key.code {
                KeyCode::Esc if *searching => *searching = false,
                KeyCode::Esc => self.overlay = None,
                KeyCode::Down => {
                    *searching = false;
                    *selected = selected.saturating_add(1).min(
                        super::palette::matches(entries, query)
                            .len()
                            .saturating_sub(1),
                    );
                }
                KeyCode::Up => {
                    *searching = false;
                    *selected = selected.saturating_sub(1);
                }
                KeyCode::Enter => {
                    if let Some(entry) = super::palette::matches(entries, query).get(*selected) {
                        return Some(Intent::Action(entry.action));
                    }
                }
                KeyCode::Char('/') if !*searching => *searching = true,
                KeyCode::Delete if !*searching => {
                    query.clear();
                    *selected = 0;
                }
                _ if *searching => {
                    let before = query.clone();
                    edit_text(query, key);
                    if *query != before {
                        *selected = 0;
                    }
                }
                _ => (),
            },
        }
        None
    }
}
pub(super) fn edit_text(input: &mut String, key: KeyEvent) {
    match key.code {
        KeyCode::Backspace => {
            input.pop();
        }
        KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => input.clear(),
        KeyCode::Char(c)
            if !c.is_control()
                && key
                    .modifiers
                    .intersection(KeyModifiers::CONTROL | KeyModifiers::ALT)
                    .is_empty()
                && input.len() + c.len_utf8() <= 4096 =>
        {
            input.push(c)
        }
        _ => (),
    }
}