1use std::collections::BTreeMap;
7
8use anyhow::anyhow;
9use colored::Colorize;
10use serde::Serialize;
11use serde_json::Value;
12pub use zoi_common::ux::*;
13
14pub 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
24pub 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
37pub 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
48pub 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
69pub 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#[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
116pub fn format_display_name(
119 registry: &str,
120 repo: &str,
121 name: &str,
122 sub: Option<&str>,
123 config: &zoi_core::types::Config
124) -> String {
125 let base_name = if let Some(s) = sub {
126 format!("{name}:{s}")
127 } else {
128 name.to_string()
129 };
130
131 if registry == "local" && repo.starts_with("git/") {
132 let repo_name = &repo[4..];
133 return format!("#git@{repo_name}/{base_name}");
134 }
135
136 let default_handle = config
137 .default_registry
138 .as_ref()
139 .map_or("", |r| r.handle.as_str());
140 let active_repos = &config.repos;
141
142 if registry == default_handle || registry == "local" || registry.is_empty()
143 {
144 if active_repos.contains(&repo.to_string()) || repo.is_empty() {
145 base_name
146 } else {
147 format!("@{repo}/{base_name}")
148 }
149 } else {
150 format!("#{registry}@{repo}/{base_name}")
151 }
152}
153
154#[must_use]
157pub fn with_failure_hint(command: &str, err: anyhow::Error) -> anyhow::Error {
158 let msg = err.to_string();
159 let hint = failure_hint(&msg, command);
160 hint.map_or(err, |hint_text| anyhow!("{msg}\nHint: {hint_text}"))
161}
162
163fn failure_hint(message: &str, command: &str) -> Option<&'static str> {
165 let m = message.to_lowercase();
166 if m.contains("not synced") || m.contains("registry") && m.contains("sync")
167 {
168 return Some("Run `zoi sync` and retry.");
169 }
170 if m.contains("not enough disk space") {
171 return Some("Free space (e.g. `zoi clean`) and retry.");
172 }
173 if m.contains("policy") || m.contains("compliance") {
174 return Some("Review policy settings in config and rerun.");
175 }
176 if m.contains("vulnerab") || m.contains("advisory") {
177 return Some("Run `zoi audit` to inspect advisories before retrying.");
178 }
179 if m.contains("lockfile") {
180 return Some(
181 "Regenerate project lock state with a normal project install, \
182 then retry."
183 );
184 }
185 if m.contains("hash verification failed") || m.contains("checksum") {
186 return Some(
187 "Resync metadata and retry; verify upstream archive integrity."
188 );
189 }
190 if command == "uninstall" && m.contains("ambiguous package name") {
191 return Some("Specify an explicit source like `#handle@repo/name`.");
192 }
193 if command == "update" && m.contains("not installed") {
194 return Some("Use `zoi install` for new packages.");
195 }
196 None
197}
198
199#[cfg(test)]
200mod tests {
201 use super::*;
202
203 #[test]
204 fn classify_origin_remote_url() {
205 let origin =
206 classify_source_origin("https://example.com/pkg.lua", "download");
207 assert_eq!(origin, InstallOrigin::RemoteUrl);
208 }
209
210 #[test]
211 fn classify_origin_registry_prebuilt() {
212 let origin = classify_source_origin("@core/hello", "download");
213 assert_eq!(origin, InstallOrigin::RegistryPrebuilt);
214 }
215
216 #[test]
217 fn appends_failure_hint_for_disk_errors() {
218 let err = anyhow!("Not enough disk space");
219 let with_hint = with_failure_hint("install", err).to_string();
220 assert!(with_hint.contains("Hint:"));
221 }
222
223 #[test]
224 fn plan_json_v1_has_schema_and_command() {
225 let mut fields = BTreeMap::new();
226 fields.insert("dry_run".to_string(), Value::Bool(true));
227 let plan = PlanJsonV1::new("install", fields);
228 assert_eq!(plan.schema, "zoi.plan.v1");
229 assert_eq!(plan.command, "install");
230 }
231
232 #[test]
233 fn preflight_summary_builder_collects_rows() {
234 let summary = PreflightSummary::new("Install preflight")
235 .row("Scope", "User")
236 .row("Retry attempts", "3");
237 assert_eq!(summary.rows.len(), 2);
238 if let Some(row) = summary.rows.first() {
239 assert_eq!(row.key, "Scope");
240 }
241 if let Some(row) = summary.rows.get(1) {
242 assert_eq!(row.value, "3");
243 }
244 }
245}