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    ] {
134        let files = data
135            .get(key)
136            .and_then(Value::as_array)
137            .into_iter()
138            .flatten()
139            .filter_map(Value::as_str)
140            .collect::<Vec<_>>();
141        if !files.is_empty() {
142            lines.push(format!("{label}: {}", files.join(", ")));
143        }
144    }
145    lines.join("\n")
146}
147
148/// The string at `key` of a success envelope's `data`.
149fn data_str<'a>(data: Option<&'a Value>, key: &str) -> Option<&'a str> {
150    data.and_then(|value| value.get(key))
151        .and_then(Value::as_str)
152}
153
154/// The length of the array at `key` of a success envelope's `data` (0 when absent).
155fn data_len(data: Option<&Value>, key: &str) -> usize {
156    data.and_then(|value| value.get(key))
157        .and_then(Value::as_array)
158        .map_or(0, Vec::len)
159}
160
161pub(crate) fn render_error_human(command_id: &str, error: &CliError) -> String {
162    let mut rendered = format!("{command_id}: {} ({})", error.message, error.code());
163    for (label, key) in [
164        ("Required version", "minimum_version"),
165        ("Observed version", "installed_version"),
166        ("Reported version", "reported_version"),
167        ("Binary path", "binary_path"),
168        ("Configuration path", "config_path"),
169        ("Bundle path", "bundle_path"),
170        ("Required field", "required_field"),
171        ("Exit code", consts::FIELD_EXIT_CODE),
172        ("Standard output", "stdout"),
173        ("Standard error", "stderr"),
174    ] {
175        if let Some(value) = error.details.get(key) {
176            rendered.push('\n');
177            rendered.push_str(label);
178            rendered.push_str(": ");
179            rendered.push_str(&render_detail_value(value));
180        }
181    }
182    render_step_failures(&mut rendered, error);
183    let cause_duplicates_output = error.cause.as_deref().is_some_and(|cause| {
184        let stdout = error
185            .details
186            .get("stdout")
187            .and_then(Value::as_str)
188            .unwrap_or_default();
189        let stderr = error
190            .details
191            .get("stderr")
192            .and_then(Value::as_str)
193            .unwrap_or_default();
194        cause == format!("stdout:\n{stdout}\nstderr:\n{stderr}")
195    });
196    if let Some(cause) = error.cause.as_deref().filter(|_| !cause_duplicates_output) {
197        rendered.push('\n');
198        rendered.push_str("Cause: ");
199        rendered.push_str(cause);
200    }
201    if let Some(suggested_action) = error.suggested_action.as_deref() {
202        rendered.push('\n');
203        rendered.push_str(suggested_action);
204    }
205    if let Some(documentation) = error.documentation.as_deref() {
206        rendered.push('\n');
207        rendered.push_str("Docs: ");
208        rendered.push_str(documentation);
209    }
210    rendered
211}
212
213/// `Failed steps:` and `Skipped steps (fail-fast):` sections of a
214/// `profile.steps_failed` error.
215fn render_step_failures(rendered: &mut String, error: &CliError) {
216    if let Some(failed) = error.details.get("failed_steps").and_then(Value::as_array) {
217        rendered.push_str("\nFailed steps:");
218        for step in failed {
219            let field = |key: &str| step.get(key).map(render_detail_value).unwrap_or_default();
220            let exit = step
221                .get("exit_code")
222                .and_then(Value::as_i64)
223                .map_or_else(|| "n/a".to_string(), |code| code.to_string());
224            rendered.push_str(&format!(
225                "\n  [{}] {} (exit {exit}): {}",
226                field("index"),
227                field("name"),
228                field("message")
229            ));
230        }
231    }
232    let skipped = error
233        .details
234        .get("skipped_steps")
235        .and_then(Value::as_array)
236        .filter(|skipped| !skipped.is_empty());
237    if let Some(skipped) = skipped {
238        let names = skipped
239            .iter()
240            .filter_map(|step| step.get("name").and_then(Value::as_str))
241            .collect::<Vec<_>>();
242        rendered.push_str("\nSkipped steps (fail-fast): ");
243        rendered.push_str(&names.join(", "));
244    }
245}
246
247/// One line per selector of `sc-lint test --list`:
248/// `<name>[ (default)]: <argv | group [a, b]>[ [platforms]]`.
249fn render_selector_list(data: Option<&Value>) -> String {
250    let default = data_str(data, "default");
251    data.and_then(|value| value.get("selectors"))
252        .and_then(Value::as_array)
253        .map(|selectors| {
254            selectors
255                .iter()
256                .map(|selector| {
257                    let name = selector
258                        .get("name")
259                        .and_then(Value::as_str)
260                        .unwrap_or_default();
261                    let marker = if Some(name) == default {
262                        " (default)"
263                    } else {
264                        ""
265                    };
266                    let body = match selector.get("group") {
267                        Some(group) => format!("group [{}]", string_items(Some(group)).join(", ")),
268                        None => string_items(selector.get("command")).join(" "),
269                    };
270                    let platforms = string_items(selector.get("platforms"));
271                    let platforms = if platforms.is_empty() {
272                        String::new()
273                    } else {
274                        format!(" [{}]", platforms.join(","))
275                    };
276                    format!("{name}{marker}: {body}{platforms}")
277                })
278                .collect::<Vec<_>>()
279                .join("\n")
280        })
281        .unwrap_or_default()
282}
283
284fn string_items(value: Option<&Value>) -> Vec<&str> {
285    value
286        .and_then(Value::as_array)
287        .map(|items| items.iter().filter_map(Value::as_str).collect())
288        .unwrap_or_default()
289}
290
291fn render_detail_value(value: &Value) -> String {
292    value
293        .as_str()
294        .map_or_else(|| value.to_string(), ToString::to_string)
295}
296
297fn fallback_render_error(command_id: &str, error: &CliError) -> String {
298    let fallback = json!({
299        "ok": false,
300        "command": command_id,
301        "error": error,
302        "diagnostics": [],
303    });
304    match serde_json::to_string_pretty(&fallback) {
305        Ok(rendered) => rendered,
306        Err(_) => format!(
307            "{{\"ok\":false,\"command\":\"{command_id}\",\"error\":{{\"kind\":\"internal\",\"code\":\"CLI.INTERNAL_ERROR\",\"message\":\"failed to serialize CLI output\"}},\"diagnostics\":[]}}"
308        ),
309    }
310}