Skip to main content

commit_wizard/core/usecases/
doctor.rs

1use std::time::Instant;
2
3use crate::{
4    core::{Context, CoreResult},
5    engine::{
6        capabilities::config::init::{self, ConfigContext, ConfigOption, ConfigSpec},
7        config::resolver::{load_project_config, load_rules_config, load_standard_config},
8        constants::{
9            emoji::{ERROR, INFO, SUCCESS, WARN},
10            paths::resolve_new_project_config_path,
11            resolve_global_config_path, resolve_global_rules_path, resolve_project_config_path,
12        },
13    },
14};
15
16enum CheckStatus {
17    Ok,
18    Warn,
19    Info,
20    Error,
21}
22
23struct CheckResult {
24    label: String,
25    status: CheckStatus,
26    detail: String,
27}
28
29impl CheckResult {
30    fn ok(label: impl Into<String>, detail: impl Into<String>) -> Self {
31        Self {
32            label: label.into(),
33            status: CheckStatus::Ok,
34            detail: detail.into(),
35        }
36    }
37
38    fn warn(label: impl Into<String>, detail: impl Into<String>) -> Self {
39        Self {
40            label: label.into(),
41            status: CheckStatus::Warn,
42            detail: detail.into(),
43        }
44    }
45
46    fn info(label: impl Into<String>, detail: impl Into<String>) -> Self {
47        Self {
48            label: label.into(),
49            status: CheckStatus::Info,
50            detail: detail.into(),
51        }
52    }
53
54    fn error(label: impl Into<String>, detail: impl Into<String>) -> Self {
55        Self {
56            label: label.into(),
57            status: CheckStatus::Error,
58            detail: detail.into(),
59        }
60    }
61
62    fn icon(&self) -> &str {
63        match self.status {
64            CheckStatus::Ok => SUCCESS,
65            CheckStatus::Warn => WARN,
66            CheckStatus::Info => INFO,
67            CheckStatus::Error => ERROR,
68        }
69    }
70
71    fn is_error(&self) -> bool {
72        matches!(self.status, CheckStatus::Error)
73    }
74}
75
76pub fn run(ctx: &Context) -> CoreResult<()> {
77    let ui = ctx.ui();
78    let start = Instant::now();
79    let git = ctx.git();
80
81    let mut checks: Vec<CheckResult> = Vec::new();
82
83    // --- Git ---
84    let git_installed = git.is_installed();
85    checks.push(if git_installed {
86        CheckResult::ok("Git", "git is available in PATH")
87    } else {
88        CheckResult::error("Git", "git is not available in PATH")
89    });
90
91    let in_git_repo = ctx.in_git_repo();
92    checks.push(if in_git_repo {
93        CheckResult::ok(
94            "Git repository",
95            format!("repo root: {}", ctx.repo_root().display()),
96        )
97    } else {
98        CheckResult::warn("Git repository", "not inside a git repository")
99    });
100
101    // --- Project config / rules ---
102    let repo_config_path = resolve_project_config_path(
103        ctx.cwd(),
104        if in_git_repo {
105            Some(ctx.repo_root())
106        } else {
107            None
108        },
109        in_git_repo,
110        ctx.runtime().explicit_config_path().map(|p| p.as_path()),
111    );
112
113    checks.push(match &repo_config_path {
114        Some(path) => {
115            if load_project_config(path, Some(&ui)).is_none() {
116                CheckResult::error(
117                    "Project config",
118                    format!("malformed config at {}", path.display()),
119                )
120            } else {
121                CheckResult::ok("Project config", path.display().to_string())
122            }
123        }
124        None => CheckResult::info("Project config", "not found — default policy will be used"),
125    });
126
127    let repo_rules_path = repo_config_path
128        .as_ref()
129        .map(|p| p.parent().unwrap_or(p).join(".cwizard.rules.toml"));
130    if let Some(ref path) = repo_rules_path
131        && path.exists()
132    {
133        checks.push(if load_rules_config(path).is_none() {
134            CheckResult::error(
135                "Project rules",
136                format!("malformed rules at {}", path.display()),
137            )
138        } else {
139            CheckResult::ok("Project rules", path.display().to_string())
140        });
141    }
142
143    // --- Global config / rules ---
144    let global_config_path = resolve_global_config_path().ok();
145    checks.push(match &global_config_path {
146        Some(path) if path.exists() => {
147            if load_standard_config(path).is_none() {
148                CheckResult::error(
149                    "Global config",
150                    format!("malformed config at {}", path.display()),
151                )
152            } else {
153                CheckResult::ok("Global config", path.display().to_string())
154            }
155        }
156        _ => CheckResult::info("Global config", "not found — default policy will be used"),
157    });
158
159    let global_rules_path = resolve_global_rules_path().ok();
160    checks.push(match &global_rules_path {
161        Some(path) if path.exists() => {
162            if load_rules_config(path).is_none() {
163                CheckResult::error(
164                    "Global rules",
165                    format!("malformed rules at {}", path.display()),
166                )
167            } else {
168                CheckResult::ok("Global rules", path.display().to_string())
169            }
170        }
171        _ => CheckResult::info("Global rules", "not found — default policy will be used"),
172    });
173
174    // --- Registries ---
175    let sources = &ctx.sources();
176    let registry_count = sources.registries.len();
177    checks.push(if registry_count > 0 {
178        let ids: Vec<&str> = sources.registries.iter().map(|r| r.id.as_str()).collect();
179        CheckResult::ok(
180            "Registries",
181            format!("{} loaded: {}", registry_count, ids.join(", ")),
182        )
183    } else {
184        CheckResult::info("Registries", "none configured")
185    });
186    for failure in &sources.registry_failures {
187        checks.push(CheckResult::warn("Registry", failure.clone()));
188    }
189
190    // --- Print results ---
191    for check in &checks {
192        ui.logger()
193            .kv(&format!("{}  {}", check.icon(), check.label), &check.detail);
194    }
195
196    let error_count = checks.iter().filter(|c| c.is_error()).count();
197    let warn_count = checks
198        .iter()
199        .filter(|c| matches!(c.status, CheckStatus::Warn))
200        .count();
201    let duration_ms = start.elapsed().as_millis() as u64;
202
203    ui.logger().detail("");
204    if error_count == 0 && warn_count == 0 {
205        ui.logger().ok(&format!("{SUCCESS}  All checks passed"));
206    } else if error_count > 0 {
207        ui.logger()
208            .warn(&format!("{WARN}  {error_count} error(s) found"));
209    } else {
210        ui.logger()
211            .warn(&format!("{WARN}  {warn_count} warning(s) found"));
212    }
213
214    let content = ui
215        .new_output_content()
216        .title("Doctor")
217        .subtitle("Environment diagnostics and configuration status")
218        .heading(2, "Paths")
219        .key_value("cwd", ctx.cwd().display().to_string())
220        .key_value("repo_root", ctx.repo_root().display().to_string())
221        .key_value(
222            "global_config",
223            ctx.runtime().global_config_path().display().to_string(),
224        )
225        .key_value(
226            "global_state",
227            ctx.runtime().global_state_path().display().to_string(),
228        )
229        .key_value(
230            "global_cache",
231            ctx.runtime().global_cache_path().display().to_string(),
232        )
233        .heading(2, "Environment")
234        .key_value("in_git_repo", in_git_repo.to_string())
235        .key_value("git_installed", git_installed.to_string())
236        .key_value(
237            "has_project_config",
238            sources
239                .repo_config
240                .as_ref()
241                .map(|c| c.base.is_some())
242                .unwrap_or(false)
243                .to_string(),
244        )
245        .key_value(
246            "has_project_rules",
247            sources
248                .repo_config
249                .as_ref()
250                .map(|c| c.rules.is_some())
251                .unwrap_or(false)
252                .to_string(),
253        )
254        .key_value(
255            "has_global_config",
256            sources
257                .global_config
258                .as_ref()
259                .map(|c| c.base.is_some())
260                .unwrap_or(false)
261                .to_string(),
262        )
263        .key_value(
264            "has_global_rules",
265            sources
266                .global_config
267                .as_ref()
268                .map(|c| c.rules.is_some())
269                .unwrap_or(false)
270                .to_string(),
271        )
272        .key_value(
273            "has_env_config",
274            sources
275                .env_config
276                .as_ref()
277                .map(|c| c.base.is_some())
278                .unwrap_or(false)
279                .to_string(),
280        )
281        .key_value(
282            "has_cli_config",
283            sources
284                .cli_config
285                .as_ref()
286                .map(|c| c.base.is_some())
287                .unwrap_or(false)
288                .to_string(),
289        )
290        .heading(2, "Registry Pool")
291        .key_value("total_registries", registry_count.to_string());
292
293    // Add details for each registry
294    let mut content = content;
295    for (idx, registry) in sources.registries.iter().enumerate() {
296        let status = if registry.is_active {
297            "[ACTIVE]"
298        } else {
299            "[available]"
300        };
301        let registry_info = format!(
302            "{}: {} (tag: {}) {}",
303            idx + 1,
304            registry.url,
305            registry.tag,
306            status
307        );
308        content = content.key_value(format!("registry_{}", idx + 1), registry_info);
309    }
310
311    // Load and display state information
312    let state_file_path = ctx.runtime().state_file_path();
313    use crate::engine::models::state::AppState;
314    let state = AppState::load(&state_file_path).unwrap_or_default();
315
316    let content = if let Some(registry_state) = &state.registry {
317        content
318            .heading(2, "Registry State")
319            .key_value("state_file", state_file_path.display().to_string())
320            .key_value(
321                "registry_name",
322                registry_state.name.as_deref().unwrap_or("(unnamed)"),
323            )
324            .key_value("registry_url", registry_state.url.clone())
325            .key_value("registry_ref", registry_state.r#ref.clone())
326            .key_value(
327                "registry_section",
328                registry_state.section.as_deref().unwrap_or("(root)"),
329            )
330            .key_value("resolved_commit", registry_state.resolved_commit.clone())
331            .key_value("cache_path", registry_state.cache_path.clone())
332    } else {
333        content
334            .heading(2, "Registry State")
335            .key_value("state_file", state_file_path.display().to_string())
336            .plain("No registry state saved")
337    };
338
339    let content = content
340        .heading(2, "AI")
341        .heading(2, "Summary")
342        .key_value("errors", error_count.to_string())
343        .key_value("warnings", warn_count.to_string())
344        .plain(format!(
345            "{} check(s) passed, {} warning(s) found, {} error(s) found",
346            checks.len() - error_count - warn_count,
347            warn_count,
348            error_count
349        ));
350
351    let meta = ui
352        .new_output_meta()
353        .with_command("doctor".to_string())
354        .with_duration_ms(duration_ms)
355        .with_timestamp(chrono::Utc::now().to_string())
356        .with_dry_run(false);
357
358    ui.print_with_meta(&content, Some(&meta), true)
359}
360
361pub fn fix(ctx: &Context) -> CoreResult<()> {
362    let ui = ctx.ui();
363    let start = Instant::now();
364
365    ui.logger().info("Checking for fixable issues...");
366
367    let sources = ctx.sources();
368    let mut repaired = 0usize;
369    let mut already_ok = 0usize;
370    let mut unfixable = 0usize;
371
372    if !ctx.in_git_repo() {
373        ui.logger().warn(&format!(
374            "{WARN}  Not inside a git repository — no automatic fix available"
375        ));
376        unfixable += 1;
377    } else {
378        ui.logger()
379            .ok(&format!("{SUCCESS}  Git repository detected"));
380        already_ok += 1;
381
382        if sources.repo_config.is_some() {
383            ui.logger()
384                .ok(&format!("{SUCCESS}  Project config present"));
385            already_ok += 1;
386        } else {
387            let output_path = resolve_new_project_config_path(
388                ctx.cwd(),
389                Some(ctx.repo_root().as_path()),
390                true,
391                ctx.explicit_config_path().map(|p| p.as_path()),
392                true,
393            );
394            init::init_config(&ConfigContext {
395                option: ConfigOption::Project,
396                output_path: output_path.clone(),
397                spec: ConfigSpec::Standard,
398                force: false,
399                auto_yes: ctx.auto_yes(),
400                dry_run: ctx.dry_run(),
401                hidden: true,
402                with_rules: false,
403                registry_options: Default::default(),
404            })?;
405            let verb = if ctx.dry_run() {
406                "Would create"
407            } else {
408                "Created"
409            };
410            ui.logger().ok(&format!(
411                "{SUCCESS}  {verb} project config at {}",
412                output_path.display()
413            ));
414            repaired += 1;
415        }
416    }
417
418    let duration_ms = start.elapsed().as_millis() as u64;
419
420    ui.logger().detail("");
421    if repaired > 0 || already_ok > 0 {
422        ui.logger()
423            .info("Run 'cw doctor' to verify the environment.");
424    }
425
426    let content = ui
427        .new_output_content()
428        .title("Doctor Fix")
429        .subtitle("Automatic repair attempt")
430        .key_value("repaired", repaired.to_string())
431        .key_value("already_ok", already_ok.to_string())
432        .key_value("unfixable", unfixable.to_string())
433        .heading(1, "Repairs attempted")
434        .paragraph(format!(
435            "Repaired {repaired} item(s); {already_ok} already fine; {unfixable} could not be fixed automatically."
436        ));
437
438    let meta = ui
439        .new_output_meta()
440        .with_command("doctor fix".to_string())
441        .with_duration_ms(duration_ms)
442        .with_timestamp(chrono::Utc::now().to_string())
443        .with_dry_run(ctx.dry_run());
444
445    ui.print_with_meta(&content, Some(&meta), true)
446}