dort 0.2.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
//! Install records and record close. Closing does not replay an install.
use super::input::Hits;
use super::{actions::Task, components as ui, input::Target, shell::edit_text};
use dort_core::tools::{inspection::NpmBinding, install};
use ratatui::{
    Frame,
    crossterm::event::{KeyCode, KeyEvent, KeyModifiers},
    layout::Rect,
    text::Line,
};
use std::path::PathBuf;
use ui::reader::{ReviewScroll, ReviewStage};
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
    #[default]
    Attempts,
    CloseInputs,
    LoadingClose,
    CloseReview,
}
#[derive(Default)]
pub struct State {
    pub mode: Mode,
    pub close_preview: Option<install::ClosePreview>,
    pub close_request: Option<install::CloseRequest>,
    pub attempts: Vec<install::Attempt>,
    pub error: Option<String>,
    pub selected: usize,
    viewport: super::navigation::ListViewport,
    pub fields: [String; 4],
    pub close_npm: bool,
    pub close_brew: bool,
    drafts: [[String; 4]; 2],
    pub focus: usize,
    pub details: bool,
    pub scroll: u16,
    reader: ReviewScroll,
    pub scope: Option<install::Scope>,
}
pub enum Outcome {
    Back,
    Task(Box<Task>),
}
impl State {
    pub fn clear_approvals(&mut self) {
        self.close_preview = None;
        if matches!(self.mode, Mode::LoadingClose | Mode::CloseReview) {
            self.mode = Mode::Attempts;
        }
    }
    pub fn text_entry(&self) -> bool {
        self.mode == Mode::CloseInputs
    }
    pub fn open_attempts(&mut self) -> Task {
        self.clear_approvals();
        self.mode = Mode::Attempts;
        self.details = false;
        self.error = None;
        Task::ToolAttempts
    }
    pub fn attempts_ready(&mut self, result: Result<Vec<install::Attempt>, String>) {
        self.attempts.clear();
        match result {
            Ok(attempts) => {
                self.attempts = attempts;
                self.error = None;
            }
            Err(e) => self.error = Some(e),
        }
        self.mode = Mode::Attempts;
        self.selected = self.selected.min(self.attempts.len().saturating_sub(1));
        self.scroll = 0;
    }
    pub fn preparation_failed(&mut self, error: &str) {
        self.clear_approvals();
        self.error = Some(error.into());
    }
    pub fn retry_preview(&mut self) -> Option<Task> {
        let request = self.close_request.clone()?;
        self.mode = Mode::LoadingClose;
        Some(Task::ToolClosePrepare(request))
    }
    fn prepare_close(&mut self) -> Option<Task> {
        let attempt = self.attempts.get(self.selected)?;
        if !attempt.unresolved {
            return None;
        }
        self.scope = attempt.scope.clone();
        let request = install::CloseRequest {
            id: attempt.id.clone(),
            executable: None,
            search_dirs: vec![],
            npm_binding: None,
            brew_prefix: None,
        };
        self.close_request = Some(request.clone());
        self.error = None;
        if attempt.scope.is_some() {
            self.mode = Mode::LoadingClose;
            Some(Task::ToolClosePrepare(request))
        } else {
            if !self.close_npm && !self.close_brew {
                self.close_brew = true;
            }
            self.mode = Mode::CloseInputs;
            self.focus = 0;
            None
        }
    }
    pub(super) fn close_field_count(&self) -> usize {
        if self.close_npm {
            4
        } else if self.close_brew {
            3
        } else {
            2
        }
    }
    pub(super) fn closure_provider(&self) -> usize {
        if self.close_npm { 0 } else { 1 }
    }
    pub(super) fn choose_closure_provider(&mut self, selected: usize) {
        if selected >= 2 || self.mode != Mode::CloseInputs {
            return;
        }
        self.drafts[self.closure_provider()] = self.fields.clone();
        self.close_npm = selected == 0;
        self.close_brew = selected == 1;
        self.fields = self.drafts[selected].clone();
        self.focus = 0;
    }
    pub fn close_reviewed(&mut self, preview: install::ClosePreview) {
        self.reader = ReviewScroll::default();
        self.close_preview = Some(preview);
        self.mode = Mode::CloseReview;
        self.scroll = 0;
    }
    pub fn closed(&mut self, result: Result<install::Attempt, String>) {
        self.clear_approvals();
        self.mode = Mode::Attempts;
        self.details = true;
        match result {
            Ok(attempt) => {
                if let Some(old) = self.attempts.iter_mut().find(|a| a.id == attempt.id) {
                    *old = attempt;
                }
                self.error = None;
            }
            Err(e) => self.error = Some(e),
        }
    }
    fn submit_fields(&mut self) -> Option<Task> {
        let count = self.close_field_count();
        if let Some(i) = self.fields[..count].iter().position(String::is_empty) {
            self.focus = i;
            self.error = Some("Complete the package manager settings first.".into());
            return None;
        }
        let request = self.close_request.as_mut()?;
        request.executable = Some(PathBuf::from(&self.fields[0]));
        request.search_dirs = self.fields[1]
            .split(':')
            .filter(|s| !s.is_empty())
            .map(PathBuf::from)
            .collect();
        request.brew_prefix = self.close_brew.then(|| PathBuf::from(&self.fields[2]));
        request.npm_binding = self.close_npm.then(|| NpmBinding {
            runtime_tool: "historical-runtime".into(),
            node: PathBuf::from(&self.fields[0]),
            npm_cli: PathBuf::from(&self.fields[2]),
            prefix: PathBuf::from(&self.fields[3]),
        });
        self.mode = Mode::LoadingClose;
        Some(Task::ToolClosePrepare(request.clone()))
    }
    fn approval(&self, dry_run: bool, hits: &Hits) -> ui::approval::Approval {
        ui::approval::Approval::review(
            hits,
            ReviewStage::CloseRecord,
            dry_run,
            self.close_preview.is_none(),
        )
    }

    pub fn key(&mut self, key: KeyEvent, dry_run: bool, hits: &Hits) -> Option<Outcome> {
        if self.mode == Mode::CloseInputs {
            let n = self.close_field_count();
            let task = match key.code {
                KeyCode::Esc => {
                    self.mode = Mode::Attempts;
                    None
                }
                KeyCode::Tab => {
                    self.focus = (self.focus + 1) % n;
                    None
                }
                KeyCode::BackTab => {
                    self.focus = (self.focus + n - 1) % n;
                    None
                }
                KeyCode::Enter => self.submit_fields(),
                _ => {
                    edit_text(&mut self.fields[self.focus.min(n - 1)], key);
                    None
                }
            };
            return task.map(|t| Outcome::Task(Box::new(t)));
        }
        if self.mode == Mode::CloseReview {
            match key.code {
                KeyCode::Esc => {
                    hits.invalidate_review();
                    self.clear_approvals();
                }
                _ if self.approval(dry_run, hits).accepts(key) => {
                    return self
                        .close_preview
                        .take()
                        .map(|p| Outcome::Task(Box::new(Task::ToolClose(Box::new(p.approve())))));
                }
                _ => self.reader.key(hits, ReviewStage::CloseRecord, key.code),
            }
            return None;
        }
        if self.details {
            match key.code {
                KeyCode::Esc => {
                    self.details = false;
                    self.scroll = 0;
                }
                KeyCode::Char('x') => {
                    return self.prepare_close().map(|t| Outcome::Task(Box::new(t)));
                }
                _ => self.scroll(key.code),
            }
            return None;
        }
        match key.code {
            KeyCode::Esc => return Some(Outcome::Back),
            KeyCode::Enter if !self.attempts.is_empty() => {
                self.details = true;
                self.scroll = 0;
            }
            KeyCode::Char('r') => return Some(Outcome::Task(Box::new(self.open_attempts()))),
            KeyCode::Char('x') => return self.prepare_close().map(|t| Outcome::Task(Box::new(t))),
            KeyCode::Down | KeyCode::PageDown => {
                let count = if key.code == KeyCode::Down {
                    1
                } else {
                    self.viewport.page()
                };
                self.selected = (self.selected + count).min(self.attempts.len().saturating_sub(1));
            }
            KeyCode::Up | KeyCode::PageUp => {
                let count = if key.code == KeyCode::Up {
                    1
                } else {
                    self.viewport.page()
                };
                self.selected = self.selected.saturating_sub(count);
            }
            KeyCode::Home => self.selected = 0,
            KeyCode::End => self.selected = self.attempts.len().saturating_sub(1),
            _ => (),
        }
        None
    }
    fn scroll(&mut self, code: KeyCode) {
        ui::reader::ScrollKeys::new(2, 2)
            .with_end()
            .apply(&mut self.scroll, code);
    }
    fn draw_attempt(
        &self,
        frame: &mut Frame,
        area: Rect,
        hits: &super::input::Hits,
        focused: bool,
    ) {
        let mut lines = vec![];
        if let Some(attempt) = self.attempts.get(self.selected) {
            let s = attempt.summary();
            lines.extend([
                ui::metadata("Record", &attempt.id),
                ui::metadata("Status", s.status.label()),
                Line::raw(s.explanation),
                Line::raw(s.package_note()),
                Line::raw(s.binary_note),
            ]);
            if let Some(scope) = &attempt.scope {
                lines.push(ui::metadata("Tool", &scope.tool));
                lines.push(ui::metadata(
                    "Package",
                    &format!("{} {}", scope.package, scope.version),
                ));
                lines.push(ui::metadata(
                    "Program",
                    &scope.executable.display().to_string(),
                ));
                lines.push(ui::metadata(
                    "Repository",
                    &scope.repository.display().to_string(),
                ));
            }
            lines.push(ui::metadata(
                "Record closed",
                if attempt.explicitly_closed {
                    "Yes; this does not prove installation succeeded"
                } else {
                    "No"
                },
            ));
        }
        if let Some(e) = &self.error {
            lines.push(ui::metadata("Problem", e));
        }
        ui::reader::Reader::new(hits)
            .with_wheel(super::input::Wheel::Tools)
            .report(
                frame,
                area,
                "Installation details",
                lines.into(),
                self.scroll,
                focused,
            );
    }
    pub fn draw(&self, frame: &mut Frame, area: Rect, dry_run: bool, hits: &super::input::Hits) {
        let action = |label, key, code| {
            hits.present(ui::ActionButton {
                label,
                key,
                target: Target::Key(KeyEvent::new(code, KeyModifiers::NONE)),
            })
        };
        if self.mode == Mode::CloseInputs {
            let labels = if self.close_npm {
                [
                    "Node program",
                    "Command search directories",
                    "npm CLI script",
                    "Global prefix",
                ]
            } else {
                [
                    "Package manager program",
                    "Command search directories",
                    "Homebrew prefix",
                    "",
                ]
            };
            let fields = labels
                .iter()
                .zip(&self.fields)
                .take(self.close_field_count())
                .map(|(a, b)| (*a, b.as_str()))
                .collect::<Vec<_>>();
            ui::field_page(frame,area,&fields,self.focus,hits,|i|Target::ToolInstallControl(i,false),ui::FormActions {choices:&[],buttons:&[ui::ActionButton {label:"Review close",key:"Enter",target:Target::ToolInstallControl(4,true)},ui::ActionButton {label:"Change package manager",key:"F4",target:Target::ToolInstallProvider},ui::ActionButton {label:"Back",key:"Esc",target:Target::Back}],feedback:Some(ui::Feedback {text:self.error.as_deref().unwrap_or("The original record is damaged. Choose the package manager and its paths for a fresh check. Nothing is retried."),tone:ui::design::Tone::Attention})});
            return;
        }
        if let Some(preview) = &self.close_preview {
            let r = preview.review();
            let mut lines = vec![
                Line::raw("Close installation record"),
                ui::metadata("Record", r.attempt_id),
                ui::metadata("Program", &r.query.executable.display().to_string()),
                ui::metadata("Arguments", &r.query.arguments.join(" ")),
                ui::metadata("HOME", &r.query.home.display().to_string()),
                ui::metadata(
                    "Search path",
                    &r.query
                        .trusted_search_path
                        .iter()
                        .map(|p| p.display().to_string())
                        .collect::<Vec<_>>()
                        .join(":"),
                ),
                Line::raw(r.explanation),
                Line::raw(r.query.warning),
            ];
            if let Some(binding) = &r.query.npm_binding {
                lines.push(ui::metadata("Node", &binding.node.display().to_string()));
                lines.push(ui::metadata(
                    "npm CLI",
                    &binding.npm_cli.display().to_string(),
                ));
                lines.push(ui::metadata(
                    "Prefix",
                    &binding.prefix.display().to_string(),
                ));
            }
            if let Some(prefix) = r.brew_prefix {
                lines.push(ui::metadata(
                    "Homebrew prefix",
                    &prefix.display().to_string(),
                ));
            }
            for args in &r.fresh_probes {
                lines.push(ui::metadata("Fresh probe arguments", &args.join(" ")));
            }
            ui::reader::Reader::new(hits)
                .with_wheel(super::input::Wheel::Tools)
                .review(
                    frame,
                    area,
                    Some("Close installation record"),
                    lines.into(),
                    ReviewStage::CloseRecord,
                    &self.reader,
                );
            self.approval(dry_run, hits)
                .present_key(hits, "Confirm close");
            action("Cancel", "Esc", KeyCode::Esc);
            return;
        }
        let selected = self.attempts.get(self.selected);
        use super::workspace::{Region, Scope, Workspace};
        let active = Region::from_details(self.details && selected.is_some());
        let workspace = Workspace::new(Scope::InstallAttempts, area, active, selected.is_some());
        workspace.bind(hits);
        if let Some(pane) = workspace.details {
            self.draw_attempt(frame, pane, hits, active == Region::Details);
        }
        if active == Region::Details {
            if selected.is_some_and(|a| a.unresolved) {
                action("Close record", "x", KeyCode::Char('x'));
            }
            action("Back", "Esc", KeyCode::Esc);
            if !workspace.is_split() {
                return;
            }
        }
        let list = if selected.is_some() {
            workspace
                .queue_content(frame, "Installation history")
                .expect("visible queue")
        } else {
            area
        };
        let capacity = ui::design::pair_capacity(list);
        let first = self.viewport.start(
            self.attempts.len(),
            capacity,
            selected.map(|_| self.selected),
        );
        let rows = self
            .attempts
            .iter()
            .enumerate()
            .skip(first)
            .take(capacity)
            .map(|(index, attempt)| {
                (
                    index,
                    attempt
                        .scope
                        .as_ref()
                        .map_or("Unknown tool", |s| s.tool.as_str()),
                    attempt.summary().status.label(),
                )
            })
            .map(|(identity, tool, status)| ui::design::PairRow {
                identity,
                values: [tool, status],
            })
            .collect::<Vec<_>>();
        if rows.is_empty() {
            ui::design::notice(
                frame,
                area,
                if self.error.is_some() {
                    "History unavailable"
                } else {
                    "No installation history"
                },
                self.error
                    .as_deref()
                    .unwrap_or("Install records appear here after an approved install."),
                if self.error.is_some() {
                    ui::design::Tone::Attention
                } else {
                    ui::design::Tone::Neutral
                },
            );
        } else {
            ui::design::pairs(
                frame,
                list,
                ui::design::PairTable {
                    headers: ["TOOL", "OUTCOME"],
                    rows: &rows,
                    selected: self.selected,
                },
                hits,
                Target::ToolAttemptRow,
            );
            if active == Region::Queue {
                action("Install record", "Enter", KeyCode::Enter);
            }
            if selected.is_some_and(|a| a.unresolved) {
                action("Close record", "x", KeyCode::Char('x'));
            }
        }
        action("Refresh history", "R", KeyCode::Char('R'));
        action("Back", "Esc", KeyCode::Esc);
    }
}