helixforge 1.0.5

Build, configure and optimise a Linux machine from a terminal menu: installs, dotfiles, updates, backups and health checks, every change planned and confirmed first.
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
//! `--json`: what the commands print, as one JSON document for other
//! programs. The shapes here are the stable interface, documented in
//! docs/JSON.md; they are written out field by field rather than derived from
//! the engine's types, so changing those does not change them. A new field
//! may appear in a later version; a field is never removed or changed in
//! meaning without raising `SCHEMA`.

use helixforge_catalog::Catalog;
use helixforge_core::{Action, Entry, Item, NixAction, Risk};
use helixforge_engine::{
    Plan, backups, doctor, history,
    inventory::{Status, which},
    preflight, updates,
};
use helixforge_platform::LinuxInfo;
use serde_json::{Value, json};

/// The version of these shapes.
pub const SCHEMA: u32 = 1;

/// Print one command's result, wrapped with the schema version.
pub fn print(command: &str, data: Value) {
    let document = json!({
        "schema": SCHEMA,
        "helixforge": crate::VERSION,
        "command": command,
        "data": data,
    });
    println!(
        "{}",
        serde_json::to_string_pretty(&document).unwrap_or_default()
    );
}

pub fn system(platform: &LinuxInfo) -> Value {
    let tools: serde_json::Map<String, Value> = ["sudo", "nix", "home-manager", "flatpak"]
        .into_iter()
        .map(|tool| (tool.to_string(), Value::Bool(which(tool).is_some())))
        .collect();
    json!({
        "distribution": {
            "id": platform.id,
            "name": platform.pretty_name,
            "id_like": platform.id_like,
        },
        "package_manager": platform.manager.map(|manager| manager.executable()),
        "kernel": std::fs::read_to_string("/proc/sys/kernel/osrelease")
            .map(|text| text.trim().to_string())
            .ok(),
        "architecture": std::env::consts::ARCH,
        "tools": tools,
    })
}

fn kind(entry: &Entry) -> &'static str {
    match entry.action {
        Action::Package { .. } => "package",
        Action::Script { .. } => "script",
        Action::Command { .. } => "command",
        Action::Nix { .. } => "nix",
        Action::Native { .. } => "native",
        Action::Profile { .. } => "profile",
    }
}

/// What every listing says about an entry.
pub fn entry(entry: &Entry) -> Value {
    json!({
        "id": entry.id,
        "name": entry.name,
        "description": entry.description,
        "flags": entry.flags,
        "kind": kind(entry),
    })
}

fn items(items: &[Item]) -> Vec<Value> {
    items
        .iter()
        .map(|item| match item {
            Item::Group(group) => json!({
                "type": "group",
                "name": group.name,
                "items": self::items(&group.items),
            }),
            Item::Entry(found) => {
                let mut value = entry(found);
                value["type"] = json!("entry");
                value
            }
        })
        .collect()
}

pub fn list(catalog: &Catalog) -> Value {
    json!({
        "tabs": catalog
            .tabs
            .iter()
            .map(|tab| json!({ "id": tab.id, "name": tab.name, "items": items(&tab.items) }))
            .collect::<Vec<_>>(),
    })
}

pub fn search(query: &str, found: &[(u32, &Entry)]) -> Value {
    json!({
        "query": query,
        "results": found
            .iter()
            .map(|(score, found)| {
                let mut value = entry(found);
                value["score"] = json!(score);
                value
            })
            .collect::<Vec<_>>(),
    })
}

/// One entry in full; `status` is how it stands, for package entries.
pub fn info(found: &Entry, status: Option<&Status>) -> Value {
    let mut value = entry(found);
    value["action"] = match &found.action {
        Action::Package {
            binary,
            packages,
            aur,
            flatpak,
            conflicts,
            removable,
        } => {
            let packages: serde_json::Map<String, Value> = packages
                .all()
                .into_iter()
                .filter_map(|(family, name)| Some((family.to_string(), json!(name?))))
                .collect();
            json!({
                "binary": binary,
                "packages": packages,
                "aur": aur,
                "flatpak": flatpak,
                "conflicts": conflicts,
                "removable": removable,
            })
        }
        Action::Script { file, interactive } => json!({
            "file": file,
            "interactive": interactive,
        }),
        Action::Command { line } => json!({ "line": line }),
        Action::Nix { action } => match action {
            NixAction::ProfileInstall { installable } => {
                json!({ "nix": "profile-install", "installable": installable })
            }
            NixAction::HomeManagerSwitch { flake } => {
                json!({ "nix": "home-manager-switch", "flake": flake })
            }
        },
        Action::Native { action } => json!({ "native": action.id() }),
        Action::Profile { entries } => json!({ "entries": entries }),
    };
    value["status"] = status.map(self::status).unwrap_or(Value::Null);
    value
}

/// How a package entry stands.
pub fn status(status: &Status) -> Value {
    let mut value = match status {
        Status::Installed {
            source,
            version,
            shadowed,
        } => json!({
            "state": "installed",
            "source": source,
            "version": version,
            "shadowed_by": shadowed,
        }),
        Status::Update {
            source,
            version,
            latest,
            shadowed,
        } => json!({
            "state": "update",
            "source": source,
            "version": version,
            "latest": latest,
            "shadowed_by": shadowed,
        }),
        Status::Managed { by, version } => json!({
            "state": "managed",
            "by": by,
            "version": version,
        }),
        Status::Elsewhere { path } => json!({ "state": "elsewhere", "path": path }),
        Status::Absent { replaces } => json!({ "state": "absent", "replaces": replaces }),
    };
    value["label"] = json!(status.label());
    value["detail"] = json!(status.detail());
    value
}

pub fn statuses(found: &[(&Entry, Option<Status>)]) -> Value {
    json!({
        "entries": found
            .iter()
            .map(|(found, state)| json!({
                "id": found.id,
                "name": found.name,
                "status": state.as_ref().map(status),
            }))
            .collect::<Vec<_>>(),
    })
}

fn risk(risk: Risk) -> &'static str {
    match risk {
        Risk::Low => "low",
        Risk::Medium => "medium",
        Risk::High => "high",
    }
}

/// A plan and what the checks before a run found.
pub fn plan(planned: &Plan, findings: &[preflight::Finding]) -> Value {
    json!({
        "steps": planned
            .steps
            .iter()
            .enumerate()
            .map(|(index, step)| json!({
                "index": index,
                "id": step.id(),
                "name": step.name(),
                "command": step.display(),
                "fallbacks": step.fallbacks(),
                "depends_on": planned.depends.get(index).cloned().unwrap_or_default(),
            }))
            .collect::<Vec<_>>(),
        "notes": planned.notes,
        "blocked": planned.blocked,
        "requirements": planned.requirements,
        "privileged": planned.privileged,
        "risk": risk(planned.risk),
        "keep_going": planned.keep_going,
        "findings": findings
            .iter()
            .map(|finding| json!({
                "severity": match finding.severity {
                    preflight::Severity::Blocker => "blocker",
                    preflight::Severity::Warning => "warning",
                },
                "message": finding.message,
            }))
            .collect::<Vec<_>>(),
        "runnable": !planned.is_empty() && !preflight::blocked(findings),
    })
}

pub fn history(records: &[history::Record]) -> Value {
    json!({
        "runs": records
            .iter()
            .map(|record| json!({
                "unix_timestamp": record.unix_timestamp,
                "entries": record.entries,
                "names": record.names,
                "success": record.success,
                "result": record.result,
                "log": record.log,
            }))
            .collect::<Vec<_>>(),
    })
}

pub fn updates(channels: &[updates::Channel], online: bool) -> Value {
    json!({
        "online": online,
        "channels": channels
            .iter()
            .map(|channel| json!({
                "id": channel.id,
                "name": channel.name,
                "count": channel.count(),
                "pending": channel.pending.as_ref().map(|pending| pending
                    .iter()
                    .map(|item| json!({ "name": item.name, "from": item.from, "to": item.to }))
                    .collect::<Vec<_>>()),
                "note": channel.note,
                "commands": channel.commands,
                "caveat": channel.caveat,
            }))
            .collect::<Vec<_>>(),
    })
}

pub fn doctor(found: &[doctor::Diagnosis]) -> Value {
    json!({
        "checks": found
            .iter()
            .map(|diagnosis| json!({
                "id": diagnosis.id,
                "title": diagnosis.title,
                "health": match diagnosis.health {
                    doctor::Health::Good => "good",
                    doctor::Health::Notice => "notice",
                    doctor::Health::Problem => "problem",
                },
                "summary": diagnosis.summary,
                "evidence": diagnosis.evidence,
                "advice": diagnosis.advice,
                "repair": diagnosis.repair.as_ref().map(|repair| json!({
                    "label": repair.label,
                    "commands": repair.commands,
                })),
                "entry": diagnosis.entry,
            }))
            .collect::<Vec<_>>(),
    })
}

pub fn backups(snapshots: Option<backups::Snapshots>, found: &[backups::Backup]) -> Value {
    json!({
        "snapshots": snapshots.map(|tool| json!({
            "tool": tool.label(),
            "restore": tool.how_to_restore(),
        })),
        "backups": found
            .iter()
            .map(|backup| json!({
                "original": backup.original,
                "backup": backup.backup,
                "taken": backup.taken,
                "system": backup.system,
                "directory": backup.directory,
            }))
            .collect::<Vec<_>>(),
    })
}

pub fn profiles(found: &[(String, helixforge_engine::profiles::Profile)]) -> Value {
    json!({
        "profiles": found
            .iter()
            .map(|(slug, profile)| json!({
                "id": format!("{}{slug}", helixforge_engine::profiles::PREFIX),
                "name": profile.name,
                "description": profile.description,
                "entries": profile.entries,
            }))
            .collect::<Vec<_>>(),
    })
}

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

    #[test]
    fn statuses_name_their_state() {
        let value = status(&Status::Update {
            source: "pacman".into(),
            version: Some("1-1".into()),
            latest: Some("2-1".into()),
            shadowed: None,
        });
        assert_eq!(value["state"], "update");
        assert_eq!(value["latest"], "2-1");
        assert_eq!(value["label"], "Update");
        assert_eq!(value["shadowed_by"], Value::Null);
        let value = status(&Status::Absent {
            replaces: vec!["wine".into()],
        });
        assert_eq!(value["state"], "absent");
        assert_eq!(value["replaces"], json!(["wine"]));
    }

    #[test]
    fn update_channels_keep_unknown_counts_apart_from_none() {
        let channel = |pending| updates::Channel {
            id: "pacman".into(),
            name: "Arch packages".into(),
            pending,
            note: String::new(),
            commands: vec![vec!["sudo".into(), "pacman".into(), "-Syu".into()]],
            requires: Vec::new(),
            caveat: None,
        };
        let value = updates(&[channel(None), channel(Some(Vec::new()))], false);
        assert_eq!(value["channels"][0]["count"], Value::Null);
        assert_eq!(value["channels"][0]["pending"], Value::Null);
        assert_eq!(value["channels"][1]["count"], 0);
        assert_eq!(
            value["channels"][1]["commands"],
            json!([["sudo", "pacman", "-Syu"]])
        );
    }

    #[test]
    fn control_characters_stay_escaped() {
        let text = serde_json::to_string(&json!({ "name": "evil\u{1b}[2J" })).unwrap();
        assert!(!text.contains('\u{1b}'));
        assert!(text.contains("\\u001b"));
    }
}