Skip to main content

sc_lint/
render.rs

1use crate::CliError;
2use crate::CommandEnvelope;
3use crate::command::CommandContext;
4use crate::command::CommandId;
5use crate::consts;
6use serde::Serialize;
7use serde_json::Value;
8use serde_json::json;
9
10#[derive(Debug, Default, Clone, PartialEq, Eq)]
11pub struct RenderedOutput {
12    pub stdout: Option<String>,
13    pub stderr: Option<String>,
14}
15
16impl RenderedOutput {
17    pub(crate) fn stdout(value: String) -> Self {
18        Self {
19            stdout: Some(value),
20            stderr: None,
21        }
22    }
23
24    pub(crate) fn stderr(value: String) -> Self {
25        Self {
26            stdout: None,
27            stderr: Some(value),
28        }
29    }
30}
31
32pub(crate) fn render_success_json<T>(envelope: &CommandEnvelope<T>) -> String
33where
34    T: Serialize,
35{
36    match serde_json::to_string_pretty(envelope) {
37        Ok(rendered) => rendered,
38        Err(error) => fallback_render_error(
39            &envelope.command,
40            &CliError::internal("failed to serialize success envelope").with_source(error),
41        ),
42    }
43}
44
45pub(crate) fn render_error_json(command_id: &str, error: &CliError) -> String {
46    let envelope = CommandEnvelope::<Value>::failure(command_id, error.clone());
47    match serde_json::to_string_pretty(&envelope) {
48        Ok(rendered) => rendered,
49        Err(_) => fallback_render_error(command_id, error),
50    }
51}
52
53pub(crate) fn render_success_human(
54    context: &CommandContext,
55    envelope: &CommandEnvelope<Value>,
56) -> String {
57    let data = envelope.data.as_ref();
58    match context.id() {
59        CommandId::Version => {
60            let version = data_str(data, consts::FIELD_VERSION).unwrap_or("unknown");
61            format!("sc-lint {version}")
62        }
63        CommandId::LintScBoundary | CommandId::LintScPortability | CommandId::LintScRuntime => {
64            let status = data_str(data, consts::FIELD_STATUS).unwrap_or("unknown");
65            let finding_count = data_len(data, consts::FIELD_FINDINGS);
66            format!(
67                "{}: {status} ({finding_count} findings)",
68                context.id().dispatch_tool().unwrap_or(context.command_id())
69            )
70        }
71        CommandId::ConsumerTest if data.is_some_and(|value| value.get("selectors").is_some()) => {
72            render_selector_list(data)
73        }
74        CommandId::ConsumerTest
75        | CommandId::ConsumerLintCi
76        | CommandId::LintFast
77        | CommandId::LintFull
78        | CommandId::LintCi
79        | CommandId::Ci
80        | CommandId::CheckNative
81        | CommandId::CheckXwin
82        | CommandId::ClippyNative
83        | CommandId::ClippyXwin => {
84            let status = data_str(data, consts::FIELD_STATUS).unwrap_or("unknown");
85            let step_count = data_len(data, consts::FIELD_STEPS);
86            format!("{}: {status} ({step_count} steps)", context.command_id())
87        }
88        CommandId::Init => render_init_summary(data),
89        CommandId::Setup | CommandId::Upgrade => data_str(data, "summary").map_or_else(
90            || format!("{}: ok", context.command_id()),
91            ToString::to_string,
92        ),
93        CommandId::Docs => match (data_str(data, "path"), data_str(data, "content")) {
94            (Some(path), Some(content)) => format!("{path}\n\n{content}"),
95            (Some(path), None) => path.to_string(),
96            (None, Some(content)) => content.to_string(),
97            (None, None) => format!("{}: ok", context.command_id()),
98        },
99        CommandId::LintFunctionLength
100        | CommandId::LintLineCounts
101        | CommandId::LintIdentityLiterals
102        | CommandId::ViewFindings => data_str(data, "summary").map_or_else(
103            || format!("{}: ok", context.command_id()),
104            |summary| format!("{}: {summary}", context.command_id()),
105        ),
106        _ => format!("{}: ok", context.command_id()),
107    }
108}
109
110fn render_init_summary(data: Option<&Value>) -> String {
111    let Some(data) = data else {
112        return "init: ok".to_string();
113    };
114    let status = data
115        .get("status")
116        .and_then(Value::as_str)
117        .unwrap_or("current");
118    let mut lines = vec![format!("init: {status}")];
119    let created_label = if matches!(status, "would_create" | "would_update") {
120        "Would create"
121    } else {
122        "Created"
123    };
124    let refreshed_label = if status == "would_update" {
125        "Would refresh"
126    } else {
127        "Refreshed"
128    };
129    for (key, label) in [
130        ("created_files", created_label),
131        ("refreshed_files", refreshed_label),
132        ("preserved_files", "Preserved"),
133        ("version_only_stale_files", "Version-only stale"),
134    ] {
135        let files = data
136            .get(key)
137            .and_then(Value::as_array)
138            .into_iter()
139            .flatten()
140            .filter_map(Value::as_str)
141            .collect::<Vec<_>>();
142        if !files.is_empty() {
143            lines.push(format!("{label}: {}", files.join(", ")));
144        }
145    }
146    lines.join("\n")
147}
148
149/// The string at `key` of a success envelope's `data`.
150fn data_str<'a>(data: Option<&'a Value>, key: &str) -> Option<&'a str> {
151    data.and_then(|value| value.get(key))
152        .and_then(Value::as_str)
153}
154
155/// The length of the array at `key` of a success envelope's `data` (0 when absent).
156fn data_len(data: Option<&Value>, key: &str) -> usize {
157    data.and_then(|value| value.get(key))
158        .and_then(Value::as_array)
159        .map_or(0, Vec::len)
160}
161
162pub(crate) fn render_error_human(command_id: &str, error: &CliError) -> String {
163    let mut rendered = format!("{command_id}: {} ({})", error.message, error.code());
164    for (label, key) in [
165        ("Required version", "minimum_version"),
166        ("Observed version", "installed_version"),
167        ("Reported version", "reported_version"),
168        ("Binary path", "binary_path"),
169        ("Configuration path", "config_path"),
170        ("Bundle path", "bundle_path"),
171        ("Required field", "required_field"),
172        ("Exit code", consts::FIELD_EXIT_CODE),
173        ("Standard output", "stdout"),
174        ("Standard error", "stderr"),
175    ] {
176        if let Some(value) = error.details.get(key) {
177            rendered.push('\n');
178            rendered.push_str(label);
179            rendered.push_str(": ");
180            rendered.push_str(&render_detail_value(value));
181        }
182    }
183    render_step_failures(&mut rendered, error);
184    let cause_duplicates_output = error.cause.as_deref().is_some_and(|cause| {
185        let stdout = error
186            .details
187            .get("stdout")
188            .and_then(Value::as_str)
189            .unwrap_or_default();
190        let stderr = error
191            .details
192            .get("stderr")
193            .and_then(Value::as_str)
194            .unwrap_or_default();
195        cause == format!("stdout:\n{stdout}\nstderr:\n{stderr}")
196    });
197    if let Some(cause) = error.cause.as_deref().filter(|_| !cause_duplicates_output) {
198        rendered.push('\n');
199        rendered.push_str("Cause: ");
200        rendered.push_str(cause);
201    }
202    if let Some(suggested_action) = error.suggested_action.as_deref() {
203        rendered.push('\n');
204        rendered.push_str(suggested_action);
205    }
206    if let Some(documentation) = error.documentation.as_deref() {
207        rendered.push('\n');
208        rendered.push_str("Docs: ");
209        rendered.push_str(documentation);
210    }
211    rendered
212}
213
214/// `Failed steps:` and `Skipped steps (fail-fast):` sections of a
215/// `profile.steps_failed` error.
216fn render_step_failures(rendered: &mut String, error: &CliError) {
217    if let Some(failed) = error.details.get("failed_steps").and_then(Value::as_array) {
218        rendered.push_str("\nFailed steps:");
219        for step in failed {
220            let field = |key: &str| step.get(key).map(render_detail_value).unwrap_or_default();
221            let exit = step
222                .get("exit_code")
223                .and_then(Value::as_i64)
224                .map_or_else(|| "n/a".to_string(), |code| code.to_string());
225            rendered.push_str(&format!(
226                "\n  [{}] {} (exit {exit}): {}",
227                field("index"),
228                field("name"),
229                field("message")
230            ));
231        }
232    }
233    let skipped = error
234        .details
235        .get("skipped_steps")
236        .and_then(Value::as_array)
237        .filter(|skipped| !skipped.is_empty());
238    if let Some(skipped) = skipped {
239        let names = skipped
240            .iter()
241            .filter_map(|step| step.get("name").and_then(Value::as_str))
242            .collect::<Vec<_>>();
243        rendered.push_str("\nSkipped steps (fail-fast): ");
244        rendered.push_str(&names.join(", "));
245    }
246}
247
248/// One line per selector of `sc-lint test --list`:
249/// `<name>[ (default)]: <argv | group [a, b]>[ [platforms]]`.
250fn render_selector_list(data: Option<&Value>) -> String {
251    let default = data_str(data, "default");
252    data.and_then(|value| value.get("selectors"))
253        .and_then(Value::as_array)
254        .map(|selectors| {
255            selectors
256                .iter()
257                .map(|selector| {
258                    let name = selector
259                        .get("name")
260                        .and_then(Value::as_str)
261                        .unwrap_or_default();
262                    let marker = if Some(name) == default {
263                        " (default)"
264                    } else {
265                        ""
266                    };
267                    let body = match selector.get("group") {
268                        Some(group) => format!("group [{}]", string_items(Some(group)).join(", ")),
269                        None => string_items(selector.get("command")).join(" "),
270                    };
271                    let platforms = string_items(selector.get("platforms"));
272                    let platforms = if platforms.is_empty() {
273                        String::new()
274                    } else {
275                        format!(" [{}]", platforms.join(","))
276                    };
277                    format!("{name}{marker}: {body}{platforms}")
278                })
279                .collect::<Vec<_>>()
280                .join("\n")
281        })
282        .unwrap_or_default()
283}
284
285fn string_items(value: Option<&Value>) -> Vec<&str> {
286    value
287        .and_then(Value::as_array)
288        .map(|items| items.iter().filter_map(Value::as_str).collect())
289        .unwrap_or_default()
290}
291
292fn render_detail_value(value: &Value) -> String {
293    value
294        .as_str()
295        .map_or_else(|| value.to_string(), ToString::to_string)
296}
297
298fn fallback_render_error(command_id: &str, error: &CliError) -> String {
299    let fallback = json!({
300        "ok": false,
301        "command": command_id,
302        "error": error,
303        "diagnostics": [],
304    });
305    match serde_json::to_string_pretty(&fallback) {
306        Ok(rendered) => rendered,
307        Err(_) => format!(
308            "{{\"ok\":false,\"command\":\"{command_id}\",\"error\":{{\"kind\":\"internal\",\"code\":\"CLI.INTERNAL_ERROR\",\"message\":\"failed to serialize CLI output\"}},\"diagnostics\":[]}}"
309        ),
310    }
311}