light-fw-cli-core 0.7.0

Ядро CLI Light: анализ проекта, управление компонентами и light.lock
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
//! Команда `light doctor`: диагностика окружения и проекта.
//!
//! Модуль только читает данные (файлы, версии инструментов, сеть) и ничего не
//! меняет на диске. Внешние зависимости (запуск `rustc`/`cargo`/`rustup` и
//! доступность сети) инжектируются через [`EnvironmentProbe`], поэтому логика
//! тестируется без реальных процессов.

use std::path::{Path, PathBuf};

use serde::Serialize;

use crate::error::Result;
use crate::manifest::{
    has_package_section, read_cargo_toml, resolve_core_version, resolve_dependency_version,
};
use crate::process::{CommandRunner, SystemRunner, parse_program_version};
use crate::project::analyze_project;
use crate::registry::ComponentRegistry;

/// Минимальная поддерживаемая версия Rust.
pub const MIN_RUST_VERSION: (u64, u64, u64) = (1, 75, 0);

/// Источник данных об окружении.
pub trait EnvironmentProbe: Send + Sync {
    /// Версия `rustc`.
    fn rustc_version(&self) -> Option<semver::Version>;
    /// Версия `cargo`.
    fn cargo_version(&self) -> Option<semver::Version>;
    /// Версия `rustup` (опционально).
    fn rustup_version(&self) -> Option<semver::Version>;
    /// Доступна ли сеть (crates.io).
    fn network_reachable(&self) -> bool;
}

/// Реальный опрос окружения через запуск процессов.
#[derive(Debug, Clone, Copy)]
pub struct SystemProbe {
    runner: SystemRunner,
    assume_offline: bool,
}

impl Default for SystemProbe {
    fn default() -> Self {
        Self::new()
    }
}

impl SystemProbe {
    /// Создаёт пробник на базе системного раннера.
    pub fn new() -> Self {
        Self {
            runner: SystemRunner,
            assume_offline: false,
        }
    }

    /// Пробник, который не проверяет сеть (режим `--offline`).
    pub fn offline() -> Self {
        Self {
            runner: SystemRunner,
            assume_offline: true,
        }
    }

    fn probe_version(&self, program: &str) -> Option<semver::Version> {
        let output = self
            .runner
            .run(program, &["--version".to_string()], None)
            .ok()?;
        if !output.success() {
            return None;
        }
        parse_program_version(&output.stdout)
    }
}

impl EnvironmentProbe for SystemProbe {
    fn rustc_version(&self) -> Option<semver::Version> {
        self.probe_version("rustc")
    }

    fn cargo_version(&self) -> Option<semver::Version> {
        self.probe_version("cargo")
    }

    fn rustup_version(&self) -> Option<semver::Version> {
        self.probe_version("rustup")
    }

    fn network_reachable(&self) -> bool {
        if self.assume_offline {
            return false;
        }
        #[cfg(feature = "network")]
        {
            crate::fetch::ping_crates_io()
        }
        #[cfg(not(feature = "network"))]
        {
            false
        }
    }
}

/// Уровень серьёзности замечания.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
    /// Ошибка: ненулевой код возврата.
    Error,
    /// Предупреждение: не блокирует работу.
    Warning,
}

/// Замечание `light doctor`.
#[derive(Debug, Clone, Serialize)]
pub struct DoctorIssue {
    /// Уровень.
    pub severity: Severity,
    /// Описание.
    pub message: String,
}

/// Данные об окружении.
#[derive(Debug, Clone, Serialize)]
pub struct EnvironmentSection {
    /// Версия `rustc` (`null`, если не найден).
    pub rustc: Option<String>,
    /// Версия `cargo`.
    pub cargo: Option<String>,
    /// Версия `rustup` (опционально).
    pub rustup: Option<String>,
    /// Доступна ли сеть.
    pub network: bool,
    /// Версия самого CLI.
    pub cli: String,
}

/// Данные о проекте.
#[derive(Debug, Clone, Serialize)]
pub struct ProjectSection {
    /// Найден ли `Cargo.toml`.
    pub cargo_toml: bool,
    /// Есть ли секция `[package]`.
    pub package_section: bool,
    /// Найдено ли шаблонов.
    pub templates_found: usize,
    /// Есть ли `light.lock`.
    pub lockfile_present: bool,
    /// Актуален ли `light.lock` (если он есть).
    pub lockfile_actual: bool,
    /// Версия ядра проекта (если определена).
    pub core_version: Option<String>,
}

/// Статус одного установленного компонента.
#[derive(Debug, Clone, Serialize)]
pub struct ComponentStatus {
    /// Имя крейта.
    pub name: String,
    /// Установленная версия.
    pub version: Option<String>,
    /// Совместим ли с ядром.
    pub compatible: bool,
}

/// Полный отчёт `light doctor`.
#[derive(Debug, Clone, Serialize)]
pub struct DoctorReport {
    /// Окружение.
    pub environment: EnvironmentSection,
    /// Проект.
    pub project: ProjectSection,
    /// Компоненты.
    pub components: Vec<ComponentStatus>,
    /// Замечания.
    pub issues: Vec<DoctorIssue>,
}

impl DoctorReport {
    /// Есть ли ошибки (ненулевой код возврата).
    pub fn has_errors(&self) -> bool {
        self.issues.iter().any(|i| i.severity == Severity::Error)
    }

    /// Текстовый отчёт.
    pub fn to_text(&self) -> String {
        let mut out = String::new();
        out.push_str("Light doctor\n");
        out.push_str("────────────────────────────────────────\n\n");

        out.push_str("Окружение:\n");
        push_check(&mut out, self.environment.rustc.as_deref(), "rustc", true);
        push_check(&mut out, self.environment.cargo.as_deref(), "cargo", true);
        match &self.environment.rustup {
            Some(v) => out.push_str(&format!("  ✓ rustup {v}\n")),
            None => out.push_str("  ⚠ rustup не обнаружен (не обязательно)\n"),
        }
        if self.environment.network {
            out.push_str("  ✓ сеть crates.io доступна\n");
        } else {
            out.push_str("  ⚠ сеть crates.io недоступна (offline)\n");
        }
        out.push_str(&format!("  · light {}\n", self.environment.cli));

        out.push_str("\nПроект:\n");
        if self.project.cargo_toml {
            out.push_str("  ✓ Cargo.toml найден\n");
        } else {
            out.push_str("  ✗ Cargo.toml не найден\n");
        }
        out.push_str(&format!(
            "  {} templates/ — {} файлов\n",
            if self.project.templates_found > 0 {
                "✓"
            } else {
                "⚠"
            },
            self.project.templates_found
        ));
        if self.project.lockfile_present {
            if self.project.lockfile_actual {
                out.push_str("  ✓ light.lock актуален\n");
            } else {
                out.push_str("  ⚠ light.lock устарел (запустите `light lock`)\n");
            }
        } else {
            out.push_str("  ⚠ light.lock отсутствует (воспроизводимость не гарантирована)\n");
        }
        if let Some(core) = &self.project.core_version {
            out.push_str(&format!("  · light-fw-core {core}\n"));
        }

        out.push_str(&format!("\nКомпоненты ({}):\n", self.components.len()));
        if self.components.is_empty() {
            out.push_str("  (нет)\n");
        }
        for c in &self.components {
            let mark = if c.compatible { "✓" } else { "✗" };
            let version = c.version.as_deref().unwrap_or("?");
            let compat = if c.compatible {
                "совместим"
            } else {
                "несовместим"
            };
            out.push_str(&format!("  {mark} {} {version} ({compat})\n", c.name));
        }

        out.push_str("\nЗамечания:\n");
        if self.issues.is_empty() {
            out.push_str("  нет\n");
        }
        for issue in &self.issues {
            let mark = match issue.severity {
                Severity::Error => "✗",
                Severity::Warning => "⚠",
            };
            out.push_str(&format!("  {mark} {}\n", issue.message));
        }

        out.push_str("\n────────────────────────────────────────\n");
        if self.has_errors() {
            out.push_str("Итог: обнаружены проблемы.\n");
        } else {
            out.push_str("Итог: всё в порядке.\n");
        }
        out
    }

    /// Отчёт в формате JSON (совпадает со структурой [`DoctorReport`]).
    pub fn to_json(&self) -> serde_json::Value {
        serde_json::to_value(self).unwrap_or(serde_json::Value::Null)
    }
}

fn push_check(out: &mut String, version: Option<&str>, program: &str, required: bool) {
    match version {
        Some(v) => out.push_str(&format!("  ✓ {program} {v}\n")),
        None if required => out.push_str(&format!("  ✗ {program} не найден\n")),
        None => out.push_str(&format!("  ⚠ {program} не найден (не обязательно)\n")),
    }
}

/// Запускает диагностику проекта `project_root`.
pub fn doctor(project_root: &Path, probe: &dyn EnvironmentProbe) -> Result<DoctorReport> {
    let mut issues = Vec::new();

    let environment = check_environment(probe, &mut issues);
    let (project, components) = check_project(project_root, &mut issues)?;

    Ok(DoctorReport {
        environment,
        project,
        components,
        issues,
    })
}

fn check_environment(
    probe: &dyn EnvironmentProbe,
    issues: &mut Vec<DoctorIssue>,
) -> EnvironmentSection {
    let rustc = probe.rustc_version();
    let cargo = probe.cargo_version();
    let rustup = probe.rustup_version();
    let network = probe.network_reachable();

    match &rustc {
        Some(v) => {
            let min =
                semver::Version::new(MIN_RUST_VERSION.0, MIN_RUST_VERSION.1, MIN_RUST_VERSION.2);
            if *v < min {
                issues.push(DoctorIssue {
                    severity: Severity::Error,
                    message: format!(
                        "rustc {v} старше требуемой {}.{}.{}",
                        MIN_RUST_VERSION.0, MIN_RUST_VERSION.1, MIN_RUST_VERSION.2
                    ),
                });
            }
        }
        None => issues.push(DoctorIssue {
            severity: Severity::Error,
            message: "rustc не найден в PATH".to_string(),
        }),
    }
    if cargo.is_none() {
        issues.push(DoctorIssue {
            severity: Severity::Error,
            message: "cargo не найден в PATH".to_string(),
        });
    }
    if rustup.is_none() {
        issues.push(DoctorIssue {
            severity: Severity::Warning,
            message: "rustup не обнаружен (не обязательно)".to_string(),
        });
    }
    if !network {
        issues.push(DoctorIssue {
            severity: Severity::Warning,
            message: "сеть crates.io недоступна — доступен только vendor/workspace".to_string(),
        });
    }

    EnvironmentSection {
        rustc: rustc.map(|v| v.to_string()),
        cargo: cargo.map(|v| v.to_string()),
        rustup: rustup.map(|v| v.to_string()),
        network,
        cli: env!("CARGO_PKG_VERSION").to_string(),
    }
}

fn check_project(
    project_root: &Path,
    issues: &mut Vec<DoctorIssue>,
) -> Result<(ProjectSection, Vec<ComponentStatus>)> {
    let cargo_path = project_root.join("Cargo.toml");
    let cargo_toml = cargo_path.is_file();
    let mut package_section = false;
    if !cargo_toml {
        issues.push(DoctorIssue {
            severity: Severity::Error,
            message: "Cargo.toml не найден в указанном каталоге".to_string(),
        });
    } else {
        let text = read_cargo_toml(&cargo_path)?;
        package_section = has_package_section(&text)?;
        if !package_section {
            issues.push(DoctorIssue {
                severity: Severity::Warning,
                message: "в Cargo.toml нет секции [package]".to_string(),
            });
        }
    }

    let (installed, templates_found) = if cargo_toml {
        let report = analyze_project(project_root)?;
        (report.installed, report.scan.files.len())
    } else {
        (
            Vec::new(),
            crate::scan::scan_templates(project_root)?.files.len(),
        )
    };
    if templates_found == 0 {
        issues.push(DoctorIssue {
            severity: Severity::Warning,
            message: "не найдено ни одного *.html-шаблона (templates/)".to_string(),
        });
    }

    let core_version = if cargo_toml {
        resolve_core_version(project_root)?
    } else {
        None
    };
    if core_version.is_none() && cargo_toml {
        issues.push(DoctorIssue {
            severity: Severity::Warning,
            message: "не удалось определить версию light-fw-core".to_string(),
        });
    }

    let registry = ComponentRegistry::builtin();
    let mut components = Vec::new();
    for dep in &installed {
        let info = registry.by_name(&dep.name);
        let dep_version = resolve_dependency_version(project_root, &dep.name)?
            .or_else(|| info.map(|i| i.latest_version.clone()));
        let compatible = match (info, &core_version) {
            (Some(info), Some(core)) => info.core_requirement.matches(core),
            _ => true,
        };
        if !compatible {
            let reason = info
                .map(|i| i.core_requirement.to_string())
                .unwrap_or_default();
            issues.push(DoctorIssue {
                severity: Severity::Error,
                message: format!(
                    "{} несовместим с light-fw-core {} (требуется {})",
                    dep.name,
                    core_version
                        .as_ref()
                        .map(|v| v.to_string())
                        .unwrap_or_default(),
                    reason
                ),
            });
        }
        components.push(ComponentStatus {
            name: dep.name.clone(),
            version: dep_version.map(|v| v.to_string()),
            compatible,
        });
    }

    let lock_path = project_root.join(crate::lockfile::LOCKFILE_NAME);
    let lockfile_present = lock_path.is_file();
    let lockfile_actual = if lockfile_present && cargo_toml {
        crate::lockfile::is_actual(project_root)?
    } else {
        false
    };

    let project = ProjectSection {
        cargo_toml,
        package_section,
        templates_found,
        lockfile_present,
        lockfile_actual,
        core_version: core_version.map(|v| v.to_string()),
    };
    Ok((project, components))
}

/// Каталог проекта по умолчанию.
pub fn default_project_dir() -> PathBuf {
    std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;

    struct MockProbe {
        rustc: Option<semver::Version>,
        cargo: Option<semver::Version>,
        rustup: Option<semver::Version>,
        network: bool,
    }

    impl EnvironmentProbe for MockProbe {
        fn rustc_version(&self) -> Option<semver::Version> {
            self.rustc.clone()
        }
        fn cargo_version(&self) -> Option<semver::Version> {
            self.cargo.clone()
        }
        fn rustup_version(&self) -> Option<semver::Version> {
            self.rustup.clone()
        }
        fn network_reachable(&self) -> bool {
            self.network
        }
    }

    fn ok_probe() -> MockProbe {
        MockProbe {
            rustc: Some(semver::Version::new(1, 80, 0)),
            cargo: Some(semver::Version::new(1, 80, 0)),
            rustup: Some(semver::Version::new(1, 27, 0)),
            network: true,
        }
    }

    fn temp_dir(name: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("light-fw-cli-doctor-{name}"));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).expect("create temp dir");
        dir
    }

    fn write_project(dir: &Path, cargo: &str, templates: &[(&str, &str)]) {
        fs::write(dir.join("Cargo.toml"), cargo).expect("write Cargo.toml");
        if !templates.is_empty() {
            let tdir = dir.join("templates");
            fs::create_dir_all(&tdir).expect("create templates");
            for (name, content) in templates {
                fs::write(tdir.join(name), content).expect("write template");
            }
        }
    }

    #[test]
    fn detects_core_version_in_workspace() {
        let root = temp_dir("workspace-core");
        fs::write(
            root.join("Cargo.toml"),
            "[workspace]\nmembers = [\"app\", \"light\"]\nresolver = \"2\"\n\n\
             [workspace.package]\nversion = \"0.2.3\"\n\n\
             [workspace.dependencies]\nlight = { path = \"light\" }\n",
        )
        .expect("root manifest");
        let app = root.join("app");
        fs::create_dir_all(&app).expect("app");
        fs::write(
            app.join("Cargo.toml"),
            "[package]\nname = \"app\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n\
             [dependencies]\nlight = { workspace = true }\n",
        )
        .expect("app manifest");
        let light = root.join("light");
        fs::create_dir_all(light.join("src")).expect("light src");
        fs::write(light.join("src/lib.rs"), "").expect("light lib");
        fs::write(
            light.join("Cargo.toml"),
            "[package]\nname = \"light\"\nversion.workspace = true\nedition = \"2021\"\n",
        )
        .expect("light manifest");

        let report = doctor(&app, &ok_probe()).expect("doctor");
        assert_eq!(report.project.core_version.as_deref(), Some("0.2.3"));
        assert!(
            !report.issues.iter().any(|i| i

                .message
                .contains("не удалось определить версию light-fw-core")),
            "ядро определено: {:?}",
            report.issues
        );
    }

    #[test]
    fn healthy_project_has_no_errors() {
        let dir = temp_dir("healthy");
        write_project(
            &dir,
            "[package]\nname = \"p\"\nversion = \"0.1.0\"\n[workspace]\n\n[dependencies]\nlight = \"0.1\"\n",
            &[("app.html", "<div></div>")],
        );
        let report = doctor(&dir, &ok_probe()).expect("doctor");
        assert!(!report.has_errors(), "issues: {:?}", report.issues);
        assert_eq!(report.project.templates_found, 1);
        assert!(!report.project.lockfile_present);
        assert!(report.components.is_empty());
    }

    #[test]
    fn old_rustc_is_an_error() {
        let dir = temp_dir("old-rustc");
        write_project(
            &dir,
            "[package]\nname = \"p\"\nversion = \"0.1.0\"\n[workspace]\n\n[dependencies]\nlight = \"0.1\"\n",
            &[("app.html", "<div></div>")],
        );
        let mut probe = ok_probe();
        probe.rustc = Some(semver::Version::new(1, 60, 0));
        let report = doctor(&dir, &probe).expect("doctor");
        assert!(report.has_errors());
    }

    #[test]
    fn missing_templates_is_warning_not_error() {
        let dir = temp_dir("no-templates");
        write_project(
            &dir,
            "[package]\nname = \"p\"\nversion = \"0.1.0\"\n[workspace]\n\n[dependencies]\nlight = \"0.1\"\n",
            &[],
        );
        let report = doctor(&dir, &ok_probe()).expect("doctor");
        assert!(!report.has_errors());
        assert_eq!(report.project.templates_found, 0);
        assert!(
            report
                .issues
                .iter()
                .any(|i| i.severity == Severity::Warning && i.message.contains("шаблон"))
        );
    }

    #[test]
    fn incompatible_component_is_error() {
        let dir = temp_dir("incompatible");
        write_project(
            &dir,
            "[package]\nname = \"p\"\nversion = \"0.1.0\"\n[workspace]\n\n[dependencies]\nlight = \"0.1\"\nlight-fw-element-form = \"0.1\"\n",
            &[("app.html", "<checkbox></checkbox>")],
        );
        // Registry требует core ^0.6; проект на light 0.1 — несовместимо.
        let report = doctor(&dir, &ok_probe()).expect("doctor");
        assert!(
            report
                .components
                .iter()
                .any(|c| c.name == "light-fw-element-form")
        );
        assert!(report.has_errors(), "issues: {:?}", report.issues);
    }

    #[test]
    fn missing_cargo_toml_is_error() {
        let dir = temp_dir("no-manifest");
        let report = doctor(&dir, &ok_probe()).expect("doctor");
        assert!(report.has_errors());
    }

    #[test]
    fn json_serializes_and_round_trips() {
        let dir = temp_dir("json");
        write_project(
            &dir,
            "[package]\nname = \"p\"\nversion = \"0.1.0\"\n[workspace]\n\n[dependencies]\nlight = \"0.1\"\n",
            &[("app.html", "<div></div>")],
        );
        let report = doctor(&dir, &ok_probe()).expect("doctor");
        let value = report.to_json();
        assert_eq!(value["project"]["templates_found"], 1);
        assert_eq!(value["environment"]["cli"], env!("CARGO_PKG_VERSION"));
        assert!(value["issues"].is_array());
    }
}