Skip to main content

euv_cli/dx/doctor/
fn.rs

1use super::*;
2
3/// Collects a full toolchain and 38-target readiness report by probing the active host environment.
4///
5/// # Returns
6///
7/// - `FullDoctorReport` - Complete toolchain and target readiness report.
8#[must_use]
9pub fn collect_full_doctor_report() -> FullDoctorReport {
10    let probe: HostCapabilityProbe = HostCapabilityProbe::detect();
11    collect_full_doctor_report_from_probe(&probe)
12}
13
14/// Builds a `FullDoctorReport` deterministically from a pre-collected `HostCapabilityProbe`.
15///
16/// # Arguments
17///
18/// - `&HostCapabilityProbe` - Host tool, SDK, and triple snapshot.
19///
20/// # Returns
21///
22/// - `FullDoctorReport` - Structured toolchain and 38-target readiness report.
23#[must_use]
24pub fn collect_full_doctor_report_from_probe(probe: &HostCapabilityProbe) -> FullDoctorReport {
25    let tool_specs: [(&str, &str, bool, &str, &str); 25] = [
26        (
27            BIN_RUSTC,
28            TOOL_CAT_RUST,
29            false,
30            REQ_ALL_TARGETS,
31            HINT_RUSTUP_INSTALL,
32        ),
33        (
34            BIN_CARGO,
35            TOOL_CAT_RUST,
36            false,
37            REQ_ALL_TARGETS,
38            HINT_RUSTUP_INSTALL,
39        ),
40        (
41            BIN_RUSTUP,
42            TOOL_CAT_RUST,
43            false,
44            REQ_ALL_TARGETS,
45            HINT_RUSTUP_INSTALL,
46        ),
47        (
48            BIN_WASM_BINDGEN,
49            TOOL_CAT_WEB,
50            false,
51            REQ_WEB_MINIAPP,
52            HINT_INSTALL_WASM_BINDGEN,
53        ),
54        (
55            BIN_WASM_OPT,
56            TOOL_CAT_WEB,
57            false,
58            REQ_WEB_SIZE_OPT,
59            HINT_WASM_OPT,
60        ),
61        (
62            BIN_WASM_PACK,
63            TOOL_CAT_WEB,
64            false,
65            REQ_WEB_LEGACY,
66            HINT_WASM_PACK,
67        ),
68        (
69            BIN_CARGO_NDK,
70            TOOL_CAT_ANDROID,
71            false,
72            REQ_ANDROID_WEAROS,
73            HINT_CARGO_NDK,
74        ),
75        (
76            ENV_ANDROID_HOME,
77            TOOL_CAT_ANDROID,
78            true,
79            REQ_ANDROID_WEAROS,
80            HINT_ANDROID_HOME,
81        ),
82        (
83            ENV_ANDROID_NDK,
84            TOOL_CAT_ANDROID,
85            true,
86            REQ_ANDROID_WEAROS,
87            HINT_INSTALL_ANDROID_NDK,
88        ),
89        (
90            BIN_ADB,
91            TOOL_CAT_ANDROID,
92            false,
93            REQ_ANDROID_INSTALL,
94            HINT_ADB,
95        ),
96        (
97            BIN_JAVA,
98            TOOL_CAT_ANDROID,
99            false,
100            REQ_ANDROID_WEAROS,
101            HINT_JDK,
102        ),
103        (
104            BIN_JAVAC,
105            TOOL_CAT_ANDROID,
106            false,
107            REQ_ANDROID_WEAROS,
108            HINT_JDK,
109        ),
110        (
111            BIN_AAPT2,
112            TOOL_CAT_ANDROID,
113            false,
114            REQ_ANDROID_WEAROS,
115            HINT_INSTALL_ANDROID_BUILD_TOOLS,
116        ),
117        (
118            BIN_D8,
119            TOOL_CAT_ANDROID,
120            false,
121            REQ_ANDROID_WEAROS,
122            HINT_INSTALL_ANDROID_BUILD_TOOLS,
123        ),
124        (
125            BIN_ZIPALIGN,
126            TOOL_CAT_ANDROID,
127            false,
128            REQ_ANDROID_WEAROS,
129            HINT_INSTALL_ANDROID_BUILD_TOOLS,
130        ),
131        (
132            BIN_APKSIGNER,
133            TOOL_CAT_ANDROID,
134            false,
135            REQ_ANDROID_WEAROS,
136            HINT_INSTALL_ANDROID_BUILD_TOOLS,
137        ),
138        (
139            BIN_XCRUN,
140            TOOL_CAT_APPLE,
141            false,
142            REQ_APPLE_TARGETS,
143            HINT_INSTALL_XCODE,
144        ),
145        (
146            BIN_XCODEBUILD,
147            TOOL_CAT_APPLE,
148            false,
149            REQ_APPLE_TARGETS,
150            HINT_XCODE_FULL,
151        ),
152        (
153            TOOL_KEY_SIMCTL,
154            TOOL_CAT_APPLE,
155            false,
156            REQ_APPLE_SIM,
157            HINT_XCODE_FULL,
158        ),
159        (
160            BIN_CODESIGN,
161            TOOL_CAT_APPLE,
162            false,
163            REQ_APPLE_TARGETS,
164            HINT_INSTALL_XCODE,
165        ),
166        (
167            ENV_OHOS_SDK,
168            TOOL_CAT_HARMONY,
169            true,
170            REQ_HARMONY_TARGETS,
171            HINT_INSTALL_OHOS_SDK,
172        ),
173        (
174            BIN_HVIGORW,
175            TOOL_CAT_HARMONY,
176            false,
177            REQ_HARMONY_TARGETS,
178            HINT_HARMONY_TOOLS,
179        ),
180        (
181            BIN_HDC,
182            TOOL_CAT_HARMONY,
183            false,
184            REQ_HARMONY_TARGETS,
185            HINT_HARMONY_TOOLS,
186        ),
187        (
188            BIN_CRATE_CLI,
189            TOOL_CAT_DX,
190            false,
191            REQ_FMT_STANDARDS,
192            HINT_CRATE_CLI,
193        ),
194        (BIN_NODE, TOOL_CAT_DX, false, REQ_ECOSYSTEM_TOOLS, HINT_NODE),
195    ];
196    let mut tools: Vec<ToolProbeEntry> = Vec::with_capacity(tool_specs.len());
197    for (name, category, is_sdk, required_for, install_hint) in tool_specs.iter() {
198        let found: Option<&String> = if *is_sdk {
199            probe.get_env_sdks().get(*name)
200        } else {
201            probe.get_available_tools().get(*name)
202        };
203        let (available, detail): (bool, String) = match found {
204            Some(val) => (true, val.clone()),
205            None => (false, STATUS_MISSING.to_string()),
206        };
207        tools.push(ToolProbeEntry::new(
208            (*name).to_string(),
209            (*category).to_string(),
210            available,
211            detail,
212            (*required_for).to_string(),
213            (*install_hint).to_string(),
214        ));
215    }
216    let targets: Vec<TargetCapability> = probe.probe_all();
217    let ready_target_count: usize = targets
218        .iter()
219        .filter(|cap: &&TargetCapability| cap.get_ready())
220        .count();
221    let total_target_count: usize = targets.len();
222    FullDoctorReport::new(
223        probe.get_host_os().clone(),
224        probe.get_host_arch().clone(),
225        tools,
226        targets,
227        ready_target_count,
228        total_target_count,
229    )
230}
231
232/// Runs `rustup target add <triple>` for every host-supported missing Rust target reported by `probe`.
233///
234/// # Arguments
235///
236/// - `&HostCapabilityProbe` - Current host capability snapshot.
237///
238/// # Returns
239///
240/// - `Vec<DoctorFixResult>` - Ordered outcome for each attempted target installation.
241pub fn run_doctor_fix(probe: &HostCapabilityProbe) -> Vec<DoctorFixResult> {
242    let missing_triples: Vec<String> = probe.missing_installable_triples();
243    let mut results: Vec<DoctorFixResult> = Vec::with_capacity(missing_triples.len());
244    for triple in missing_triples.into_iter() {
245        let cmd_args: Vec<String> = vec![
246            ARG_TARGET_SUB.to_string(),
247            ARG_ADD.to_string(),
248            triple.clone(),
249        ];
250        let cmd_str: String = format!("{BIN_RUSTUP} {} {} {triple}", ARG_TARGET_SUB, ARG_ADD);
251        match Command::new(BIN_RUSTUP).args(&cmd_args).output() {
252            Ok(out) if out.status.success() => {
253                results.push(DoctorFixResult::new(
254                    triple,
255                    cmd_str,
256                    true,
257                    STATUS_OK.to_string(),
258                ));
259            }
260            Ok(out) => {
261                let stderr_msg: String = String::from_utf8_lossy(&out.stderr).trim().to_string();
262                results.push(DoctorFixResult::new(triple, cmd_str, false, stderr_msg));
263            }
264            Err(err) => {
265                results.push(DoctorFixResult::new(
266                    triple,
267                    cmd_str,
268                    false,
269                    err.to_string(),
270                ));
271            }
272        }
273    }
274    results
275}
276
277/// Formats a `FullDoctorReport` into aligned terminal tables showing tool readiness, targets, and fix actions.
278///
279/// # Arguments
280///
281/// - `&FullDoctorReport` - Collected full doctor report.
282/// - `bool` - When `true`, renders only the target readiness table (omitting the tool inventory).
283///
284/// # Returns
285///
286/// - `String` - Human-readable terminal report.
287#[must_use]
288pub fn format_full_doctor_report(report: &FullDoctorReport, targets_only: bool) -> String {
289    let mut out: String = format!(
290        "euv doctor — host: {}-{} ({}/{} targets ready)\n\n",
291        report.get_host_os(),
292        report.get_host_arch(),
293        report.get_ready_target_count(),
294        report.get_total_target_count()
295    );
296    if !targets_only {
297        let mut tool_table: TerminalTable = TerminalTable::with_headers(vec![
298            HEADER_STATUS.to_string(),
299            DOCTOR_HDR_TOOL.to_string(),
300            DOCTOR_HDR_CATEGORY.to_string(),
301            DOCTOR_HDR_DETAIL.to_string(),
302        ]);
303        for entry in report.get_tools().iter() {
304            let badge: &str = if entry.get_available() {
305                StatusBadge::Pass.as_str()
306            } else {
307                StatusBadge::Skip.as_str()
308            };
309            let detail: String = if entry.get_available() {
310                entry.get_detail().clone()
311            } else {
312                format!("{} ({})", STATUS_MISSING, entry.get_install_hint())
313            };
314            tool_table.push_row(vec![
315                badge.to_string(),
316                entry.get_name().clone(),
317                entry.get_category().clone(),
318                detail,
319            ]);
320        }
321        out.push_str(&tool_table.render());
322        out.push('\n');
323    }
324    out.push_str(&format_targets_table(report.get_targets(), false));
325    if !report.get_fix_actions().is_empty() {
326        out.push_str(DOCTOR_FIX_SECTION_HDR);
327        for action in report.get_fix_actions().iter() {
328            let badge: &str = if action.get_succeeded() {
329                StatusBadge::Pass.as_str()
330            } else {
331                StatusBadge::Fail.as_str()
332            };
333            out.push_str(&format!(
334                "  [{}] {} — {}\n",
335                badge,
336                action.get_command(),
337                action.get_message()
338            ));
339        }
340    }
341    out
342}
343
344/// Formats a slice of `TargetCapability` entries into an aligned readiness matrix table.
345///
346/// # Arguments
347///
348/// - `&[TargetCapability]` - Per-target readiness records.
349/// - `bool` - When `true`, hides targets that are not ready on the current host.
350///
351/// # Returns
352///
353/// - `String` - Aligned plain-text target table.
354#[must_use]
355pub fn format_targets_table(capabilities: &[TargetCapability], ready_only: bool) -> String {
356    let mut table: TerminalTable = TerminalTable::with_headers(vec![
357        HEADER_STATUS.to_string(),
358        DOCTOR_HDR_TARGET.to_string(),
359        DOCTOR_HDR_CATEGORY.to_string(),
360        DOCTOR_HDR_TRIPLE.to_string(),
361        DOCTOR_HDR_MISSING.to_string(),
362    ]);
363    let mut ready_count: usize = 0;
364    let mut shown_count: usize = 0;
365    for cap in capabilities.iter() {
366        if cap.get_ready() {
367            ready_count += 1;
368        }
369        if ready_only && !cap.get_ready() {
370            continue;
371        }
372        shown_count += 1;
373        let status_label: &str = if cap.get_ready() {
374            StatusBadge::Pass.as_str()
375        } else if !cap.get_host_supported() {
376            DOCTOR_STATUS_UNSUPPORTED
377        } else {
378            StatusBadge::Skip.as_str()
379        };
380        let note: String = if cap.get_ready() {
381            DOCTOR_STATUS_READY.to_string()
382        } else if let Some(first_hint) = cap.get_install_hints().first() {
383            format!("{} | {first_hint}", cap.get_missing_tools().join(", "))
384        } else {
385            cap.get_missing_tools().join(", ")
386        };
387        table.push_row(vec![
388            status_label.to_string(),
389            cap.get_target().clone(),
390            cap.get_category().clone(),
391            cap.get_triple().clone(),
392            note,
393        ]);
394    }
395    let mut out: String = table.render();
396    out.push_str(&format!(
397        "Targets: {ready_count}/{} ready (showing {shown_count})\n",
398        capabilities.len()
399    ));
400    out
401}