knixl 1.2.1

Compile opinionated KDL into maintainable, committed NixOS module source.
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
//! The interactive knixl TUI (bubbletea-rs + lipgloss). `knixl tui` opens the hub; `knixl
//! install <pkg>` opens the Install screen directly.
//!
//! bubbletea's `Model::init()` takes no arguments, so everything the screens need (the host
//! list, the entry point, and an injected verify function) is stashed in a `OnceLock` before
//! the program runs. Each screen exposes a `update(msg, size) -> Step` reducer and a
//! `view(size) -> String`; the bubbletea `Model` impl is a thin layer that forwards messages
//! and turns a `Step` into a command. The pure decision logic inside each screen is unit
//! tested; only the runtime glue (spawning the program, real key reads, async `Cmd`s) is not.

mod author;
mod browse;
mod home;
mod install;
mod theme;
mod widgets;

use std::path::PathBuf;
use std::sync::{Arc, OnceLock};

use bubbletea_rs::event::{QuitMsg, WindowSizeMsg};
use bubbletea_rs::{command, Cmd, Model, Msg, Program};
use lipgloss::{place, CENTER};

use author::AuthorModel;
use browse::BrowseModel;
use home::HomeModel;
use install::InstallModel;

pub use install::{Parse, Resolve};

use knixl_pipeline::install::HostInfo;

static CONFIG: OnceLock<TuiConfig> = OnceLock::new();

/// The result of the async nix verify, handed to the Install screen.
#[derive(Debug, Clone)]
pub struct Verified {
    pub preview: String,
    pub resolves: Resolve,
    pub parses: Parse,
}

/// Runs the (blocking) nix verify for a package on a host. Injected so tests and the real CLI
/// supply their own; it is `Send + Sync` so the Install screen can run it off the event loop.
pub type VerifyFn = Arc<dyn Fn(&str, &HostInfo) -> Verified + Send + Sync>;

/// The result of the async package build (`--build`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BuildOutcome {
    Ok,
    Failed,
    Skipped,
}

/// Builds `pkgs.<pkg>` (host-independent). Injected only when `--build` is requested;
/// `Send + Sync` so the Install screen runs it off the event loop.
pub type BuildFn = Arc<dyn Fn(&str) -> BuildOutcome + Send + Sync>;

/// The result of resolving `pkg@version` to a nixpkgs commit.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PinOutcome {
    Resolved(String),
    NotFound,
    Unavailable,
    Failed,
}

/// Resolves `name@version` to a nixpkgs commit (host-independent). Injected only when a
/// version was requested; `Send + Sync` so the Install screen runs it off the event loop.
pub type PinFn = Arc<dyn Fn(&str, &str) -> PinOutcome + Send + Sync>;

/// The result of deciding a pin strategy for `name` at a resolved commit (#28: this replaces
/// the CLI's post-Apply, second build-test with a decision made once, inside the TUI, before
/// commit time).
#[derive(Debug, Clone)]
pub enum StrategyOutcome {
    /// A strategy was chosen; `label` is the same short phrase the `pinned ... via ...` status
    /// line prints (e.g. "build ok", "override build failed").
    Chosen {
        strategy: knixl_lock::model::PinStrategy,
        label: String,
    },
    /// Neither candidate strategy build-tested successfully; carries a message for display.
    Failed(String),
}

/// Decides a pin strategy for `name@version` resolved to `rev`, against `host_name`'s own
/// baseline (#28 review fix: the decision is host-dependent, since each host can declare its
/// own nixpkgs baseline, so it must be recomputed for whichever host is currently selected
/// rather than fixed at injection time). Injected only when a version was requested;
/// `Send + Sync` so the Install screen runs it off the event loop.
pub type StrategyFn = Arc<dyn Fn(&str, &str, &str) -> StrategyOutcome + Send + Sync>;

/// A registered module as the Browse screen sees it: its claimed node, a kind tag, the
/// rendered schema doc, and a skeleton to splice into a host. Precomputed by the CLI so the
/// TUI never touches the (non-`Send`) registry.
#[derive(Debug, Clone)]
pub struct BrowseModule {
    pub node: String,
    pub kind: String,
    pub doc: String,
    pub skeleton: String,
    /// The manifest path (`modules/<dir>/knixl-module.kdl`) for a declarative module, so Browse
    /// can open it in the Author screen's Edit mode. `None` for a built-in module, which has no
    /// manifest to edit.
    pub manifest: Option<PathBuf>,
}

/// How the TUI was launched.
pub enum Entry {
    /// `knixl tui`: start at Home.
    Hub,
    /// `knixl install <pkg>` or `knixl install <pkg>@<version>`: open the Install screen with
    /// the package prefilled, and the version (if any) to be resolved and pinned on Apply.
    Install {
        pkg: String,
        strict: bool,
        host: Option<String>,
        version: Option<String>,
        /// Threaded from `install()`'s `--no-abi-check` flag, so the strategy build-gate is
        /// honoured on the interactive path too (it was previously hardcoded to `false` at
        /// commit time, silently ignoring the flag).
        no_abi_check: bool,
    },
}

/// What the session decided, returned by `run` for the CLI to act on.
pub enum Outcome {
    /// Nothing to do (plain quit, or backed out of Home).
    Quit,
    /// The install screen was cancelled.
    Cancelled,
    /// Apply this package to this host. `version`/`pin` are set only when a version was
    /// requested and resolved: the CLI writes the pin (rev) before committing.
    Install {
        host: HostInfo,
        pkg: String,
        strict: bool,
        version: Option<String>,
        pin: Option<String>,
        no_abi_check: bool,
        /// The strategy chosen by the Install screen's strategy-selection step (#28), for a
        /// versioned install; `None` for an unversioned one. The CLI writes the pin with this
        /// strategy directly, rather than build-testing a second time at commit.
        strategy: Option<knixl_lock::model::PinStrategy>,
        /// The reason the strategy was chosen (e.g. "build ok", "matches baseline"), the same
        /// phrase `StrategyOutcome::Chosen` carried: threaded through so the committed status
        /// line reads `pinned ... via ... (reason)`, matching the plain path's wording. `None`
        /// for an unversioned install.
        strategy_reason: Option<String>,
    },
    /// Scaffold this module's node into this host's KDL.
    Insert {
        host: HostInfo,
        node: String,
        skeleton: String,
    },
    /// Write a new declarative module manifest (`modules/<name>/knixl-module.kdl`).
    Scaffold { name: String, manifest: String },
    /// Overwrite an existing module manifest with edited text (Author screen's Edit mode).
    SaveModule {
        path: std::path::PathBuf,
        text: String,
    },
}

/// Everything the screens read, injected before the program runs.
pub struct TuiConfig {
    // Read by the Browse/Author screens (later checkpoints).
    #[allow(dead_code)]
    pub root: PathBuf,
    pub hosts: Vec<HostInfo>,
    pub entry: Entry,
    pub verify: VerifyFn,
    pub modules: Vec<BrowseModule>,
    pub build: Option<BuildFn>,
    pub pin: Option<PinFn>,
    /// Injected only when a version was requested (#28): decides the pin strategy inside the
    /// Install screen's Apply-gated verify sequence, replacing the CLI's post-Apply build-test.
    pub strategy: Option<StrategyFn>,
}

fn config() -> &'static TuiConfig {
    CONFIG.get().expect("TUI config set before run")
}

/// A screen's navigation intent, returned by its reducer.
pub enum Nav {
    Stay,
    Quit,
    /// Back out of the current screen (to Home, or end the session if launched directly).
    Back,
    /// Open another screen by key.
    Goto(&'static str),
    /// Commit the install and end the session.
    Apply {
        host: HostInfo,
        pkg: String,
        strict: bool,
        version: Option<String>,
        pin: Option<String>,
        no_abi_check: bool,
        /// The strategy chosen by the Install screen's strategy-selection step (#28), for a
        /// versioned install; `None` for an unversioned one. Threaded straight through to
        /// `Outcome::Install`, for the CLI to pass to `commit_tui_install`.
        strategy: Option<knixl_lock::model::PinStrategy>,
        /// The reason the strategy was chosen, threaded straight through to
        /// `Outcome::Install` alongside `strategy` (#28 review fix).
        strategy_reason: Option<String>,
    },
    /// Scaffold a module node into a host and end the session.
    Insert {
        host: HostInfo,
        node: String,
        skeleton: String,
    },
    /// Write a new module manifest and end the session.
    Scaffold {
        name: String,
        manifest: String,
    },
    /// Overwrite an existing module manifest and end the session (Author screen's Edit mode).
    SaveModule {
        path: std::path::PathBuf,
        text: String,
    },
    /// Open a declarative module's manifest in the Author screen's Edit mode.
    EditModule {
        manifest: std::path::PathBuf,
    },
}

/// A reducer's result: a navigation intent plus an optional command to run.
pub struct Step {
    pub nav: Nav,
    pub cmd: Option<Cmd>,
}

impl Step {
    fn stay() -> Step {
        Step {
            nav: Nav::Stay,
            cmd: None,
        }
    }
    fn nav(nav: Nav) -> Step {
        Step { nav, cmd: None }
    }
}

enum Screen {
    Home(Box<HomeModel>),
    // Boxed: these own widget state and are large, so keep the enum small.
    Install(Box<InstallModel>),
    Browse(Box<BrowseModel>),
    Author(Box<AuthorModel>),
}

pub struct App {
    size: (u16, u16),
    screen: Screen,
    outcome: Outcome,
}

impl Model for App {
    fn init() -> (Self, Option<Cmd>) {
        let size = (80, 24);
        let (screen, cmd) = match config().entry {
            Entry::Install { .. } => {
                let (m, cmd) = InstallModel::enter(size);
                (Screen::Install(Box::new(m)), cmd)
            }
            Entry::Hub => (Screen::Home(Box::new(HomeModel::new())), None),
        };
        // Ask for the real terminal size up front so the first frame fills the screen (rather
        // than the 80x24 default), batched with any screen's own init command.
        let init_cmd = match cmd {
            Some(c) => command::batch(vec![command::window_size(), c]),
            None => command::window_size(),
        };
        (
            App {
                size,
                screen,
                outcome: Outcome::Quit,
            },
            Some(init_cmd),
        )
    }

    fn update(&mut self, msg: Msg) -> Option<Cmd> {
        if msg.downcast_ref::<QuitMsg>().is_some() {
            return None;
        }
        if let Some(ws) = msg.downcast_ref::<WindowSizeMsg>() {
            self.size = (ws.width, ws.height);
        }
        let step = match &mut self.screen {
            Screen::Home(h) => h.update(msg, self.size),
            Screen::Install(i) => i.update(msg, self.size),
            Screen::Browse(b) => b.update(msg, self.size),
            Screen::Author(a) => a.update(msg, self.size),
        };
        self.apply(step)
    }

    fn view(&self) -> String {
        let content = match &self.screen {
            Screen::Home(h) => h.view(self.size),
            Screen::Install(i) => i.view(self.size),
            Screen::Browse(b) => b.view(self.size),
            Screen::Author(a) => a.view(self.size),
        };
        // Centre the screen in the full terminal so the alternate screen is used end to end.
        let (w, h) = self.size;
        place(w as i32, h as i32, CENTER, CENTER, &content, &[])
    }
}

impl App {
    fn apply(&mut self, step: Step) -> Option<Cmd> {
        match step.nav {
            Nav::Stay => step.cmd,
            Nav::Quit => Some(command::quit()),
            Nav::Apply {
                host,
                pkg,
                strict,
                version,
                pin,
                no_abi_check,
                strategy,
                strategy_reason,
            } => {
                self.outcome = Outcome::Install {
                    host,
                    pkg,
                    strict,
                    version,
                    pin,
                    no_abi_check,
                    strategy,
                    strategy_reason,
                };
                Some(command::quit())
            }
            Nav::Insert {
                host,
                node,
                skeleton,
            } => {
                self.outcome = Outcome::Insert {
                    host,
                    node,
                    skeleton,
                };
                Some(command::quit())
            }
            Nav::Scaffold { name, manifest } => {
                self.outcome = Outcome::Scaffold { name, manifest };
                Some(command::quit())
            }
            Nav::SaveModule { path, text } => {
                self.outcome = Outcome::SaveModule { path, text };
                Some(command::quit())
            }
            Nav::EditModule { manifest } => {
                // A read or parse failure stays on Browse (a no-op) rather than opening a
                // broken editor; there is nowhere sensible to show the error from here.
                if let Ok(text) = std::fs::read_to_string(&manifest) {
                    if let Ok(m) = AuthorModel::edit(self.size, manifest, &text) {
                        self.screen = Screen::Author(Box::new(m));
                    }
                }
                None
            }
            Nav::Back => match config().entry {
                // Launched straight into a screen: backing out ends the session.
                Entry::Install { .. } => {
                    self.outcome = Outcome::Cancelled;
                    Some(command::quit())
                }
                Entry::Hub => {
                    self.screen = Screen::Home(Box::new(HomeModel::new()));
                    None
                }
            },
            Nav::Goto("install") => {
                let (m, cmd) = InstallModel::enter(self.size);
                self.screen = Screen::Install(Box::new(m));
                cmd
            }
            Nav::Goto("browse") => {
                self.screen = Screen::Browse(Box::new(BrowseModel::enter(self.size)));
                None
            }
            Nav::Goto("author") => {
                self.screen = Screen::Author(Box::new(AuthorModel::enter(self.size)));
                None
            }
            Nav::Goto(_) => None,
        }
    }
}

/// Run the TUI, returning what the session decided. Sets the config, builds a tokio runtime,
/// drives the bubbletea program, and reads the outcome off the final model.
#[allow(clippy::too_many_arguments)]
pub fn run(
    entry: Entry,
    root: PathBuf,
    hosts: Vec<HostInfo>,
    verify: VerifyFn,
    modules: Vec<BrowseModule>,
    build: Option<BuildFn>,
    pin: Option<PinFn>,
    strategy: Option<StrategyFn>,
) -> Result<Outcome, String> {
    let _ = CONFIG.set(TuiConfig {
        root,
        hosts,
        entry,
        verify,
        modules,
        build,
        pin,
        strategy,
    });
    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(|e| e.to_string())?;
    rt.block_on(async {
        let program = Program::<App>::builder()
            .alt_screen(true)
            .build()
            .map_err(|e| e.to_string())?;
        let app = program.run().await.map_err(|e| e.to_string())?;
        Ok(app.outcome)
    })
}