Skip to main content

zoi_cli/cmd/
ux.rs

1//! User experience (UX) utilities for the Zoi CLI.
2//!
3//! This module contains types and functions for formatting output,
4//! providing hints to the user, and emitting machine-readable plans.
5
6use std::collections::BTreeMap;
7
8use anyhow::anyhow;
9use colored::Colorize;
10use serde::Serialize;
11use serde_json::Value;
12pub use zoi_common::ux::*;
13
14/// Prints a preflight summary to the console.
15pub fn print_preflight(summary: &PreflightSummary) {
16    let title = summary.title.bold();
17    println!("\n{} {title}", "::".bold().blue());
18    for row in &summary.rows {
19        let key = format!("{}:", row.key).cyan();
20        println!("  {:<24}{}", key, row.value);
21    }
22}
23
24/// Prints a transaction summary to the console.
25pub fn print_transaction_summary(summary: &TransactionSummary) {
26    let command = &summary.command;
27    let success = summary.success.to_string().green();
28    let failed = summary.failed.to_string().red();
29    let skipped = summary.skipped.to_string().yellow();
30    println!(
31        "\n{} {command} summary: success={success}, failed={failed}, \
32         skipped={skipped}",
33        "::".bold().blue()
34    );
35}
36
37/// Emits a plan in JSON format to stdout.
38///
39/// # Errors
40///
41/// Returns an error if the plan cannot be serialized to JSON.
42pub fn emit_plan_json<T: Serialize>(plan: &T) -> anyhow::Result<()> {
43    let json = serde_json::to_string_pretty(plan)?;
44    println!("{json}");
45    Ok(())
46}
47
48/// Emits a version 1 plan in JSON format to stdout.
49///
50/// # Errors
51///
52/// Returns an error if the plan cannot be serialized to JSON.
53pub fn emit_plan_json_v1(command: &str, payload: Value) -> anyhow::Result<()> {
54    let mut fields = BTreeMap::new();
55    match payload {
56        Value::Object(map) => {
57            for (key, value) in map {
58                fields.insert(key, value);
59            }
60        }
61        other => {
62            fields.insert("data".to_string(), other);
63        }
64    }
65    let plan = PlanJsonV1::new(command, fields);
66    emit_plan_json(&plan)
67}
68
69/// Prints an explanation report to the console.
70pub fn print_explain(report: &ExplainReport) {
71    let title = &report.title;
72    println!("\n{} {title}", "::".bold().blue());
73    for item in &report.items {
74        let subject = item.subject.cyan();
75        let reason = &item.reason;
76        println!("  - {subject} {reason}");
77        for detail in &item.details {
78            let detail = detail.dimmed();
79            println!("    {detail}");
80        }
81    }
82}
83
84/// Classifies the origin of a package based on its source string and the action
85/// being performed.
86#[must_use]
87pub fn classify_source_origin(
88    source: &str,
89    action_name: &str
90) -> InstallOrigin {
91    if source.starts_with("http://") || source.starts_with("https://") {
92        return InstallOrigin::RemoteUrl;
93    }
94    let path = std::path::Path::new(source);
95    if path.extension().is_some_and(|ext| {
96        ext.eq_ignore_ascii_case("zpa")
97            || ext.eq_ignore_ascii_case("zsa")
98            || source.ends_with(".pkg.tar.zst")
99    }) {
100        return InstallOrigin::LocalArchive;
101    }
102    if (source.ends_with(".pkg.lua") || source.ends_with(".manifest.yaml"))
103        && path.exists()
104    {
105        return InstallOrigin::LocalPackage;
106    }
107    if action_name == "download" {
108        InstallOrigin::RegistryPrebuilt
109    } else if action_name == "build" {
110        InstallOrigin::RegistrySource
111    } else {
112        InstallOrigin::Unknown
113    }
114}
115
116/// Wraps an error with a user-friendly hint if one is available for the given
117/// error message and command.
118#[must_use]
119pub fn with_failure_hint(command: &str, err: anyhow::Error) -> anyhow::Error {
120    let msg = err.to_string();
121    let hint = failure_hint(&msg, command);
122    hint.map_or(err, |hint_text| anyhow!("{msg}\nHint: {hint_text}"))
123}
124
125/// Returns a user-friendly hint for a given error message and command.
126fn failure_hint(message: &str, command: &str) -> Option<&'static str> {
127    let m = message.to_lowercase();
128    if m.contains("not synced") || m.contains("registry") && m.contains("sync")
129    {
130        return Some("Run `zoi sync` and retry.");
131    }
132    if m.contains("not enough disk space") {
133        return Some("Free space (e.g. `zoi clean`) and retry.");
134    }
135    if m.contains("policy") || m.contains("compliance") {
136        return Some("Review policy settings in config and rerun.");
137    }
138    if m.contains("vulnerab") || m.contains("advisory") {
139        return Some("Run `zoi audit` to inspect advisories before retrying.");
140    }
141    if m.contains("lockfile") {
142        return Some(
143            "Regenerate project lock state with a normal project install, \
144             then retry."
145        );
146    }
147    if m.contains("hash verification failed") || m.contains("checksum") {
148        return Some(
149            "Resync metadata and retry; verify upstream archive integrity."
150        );
151    }
152    if command == "uninstall" && m.contains("ambiguous package name") {
153        return Some("Specify an explicit source like `#handle@repo/name`.");
154    }
155    if command == "update" && m.contains("not installed") {
156        return Some("Use `zoi install` for new packages.");
157    }
158    None
159}
160
161#[cfg(test)]
162mod tests {
163    use super::*;
164
165    #[test]
166    fn classify_origin_remote_url() {
167        let origin =
168            classify_source_origin("https://example.com/pkg.lua", "download");
169        assert_eq!(origin, InstallOrigin::RemoteUrl);
170    }
171
172    #[test]
173    fn classify_origin_registry_prebuilt() {
174        let origin = classify_source_origin("@core/hello", "download");
175        assert_eq!(origin, InstallOrigin::RegistryPrebuilt);
176    }
177
178    #[test]
179    fn appends_failure_hint_for_disk_errors() {
180        let err = anyhow!("Not enough disk space");
181        let with_hint = with_failure_hint("install", err).to_string();
182        assert!(with_hint.contains("Hint:"));
183    }
184
185    #[test]
186    fn plan_json_v1_has_schema_and_command() {
187        let mut fields = BTreeMap::new();
188        fields.insert("dry_run".to_string(), Value::Bool(true));
189        let plan = PlanJsonV1::new("install", fields);
190        assert_eq!(plan.schema, "zoi.plan.v1");
191        assert_eq!(plan.command, "install");
192    }
193
194    #[test]
195    fn preflight_summary_builder_collects_rows() {
196        let summary = PreflightSummary::new("Install preflight")
197            .row("Scope", "User")
198            .row("Retry attempts", "3");
199        assert_eq!(summary.rows.len(), 2);
200        if let Some(row) = summary.rows.first() {
201            assert_eq!(row.key, "Scope");
202        }
203        if let Some(row) = summary.rows.get(1) {
204            assert_eq!(row.value, "3");
205        }
206    }
207}