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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
//! Команда `light init`: создание скелета нового проекта Light.
//!
//! Модуль генерирует минимальный проект: `Cargo.toml` с зависимостью `light`,
//! самодостаточный `src/main.rs` (окно с текстом «Hello, Light!»), `.gitignore`
//! и `light.lock`. Внешние эффекты (проверка `cargo`) идут через трейт
//! [`CommandRunner`], поэтому логика тестируется без запуска процессов.

use std::path::PathBuf;
use std::str::FromStr;

use crate::error::{Error, Result};
use crate::lockfile::{LOCKFILE_NAME, Lockfile};
use crate::process::CommandRunner;

/// Версия мета-крейта `light`, которую прописывает `light init`.
pub const LIGHT_DEPENDENCY_VERSION: &str = env!("CARGO_PKG_VERSION");

/// Содержимое `.gitignore` нового проекта.
pub const GITIGNORE: &str = "target/\n";

const COUNTER_MAIN: &str = include_str!("../../../examples/counter/src/main.rs");
const COUNTER_HTML: &str = include_str!("../../../examples/counter/templates/counter.html");
const TODO_MAIN: &str = include_str!("../../../examples/todo/src/main.rs");
const TODO_HTML: &str = include_str!("../../../examples/todo/templates/todo.html");
const CALCULATOR_MAIN: &str = include_str!("../../../examples/calculator/src/main.rs");
const CALCULATOR_HTML: &str =
    include_str!("../../../examples/calculator/templates/calculator.html");

/// Готовый пример, который `light init --template` кладёт в новый проект.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InitTemplate {
    /// Счётчик с реактивным состоянием.
    Counter,
    /// Список задач с `v-model`, `v-if` и `v-for`.
    Todo,
    /// Калькулятор с обработчиками кнопок.
    Calculator,
}

impl InitTemplate {
    /// Все поддерживаемые шаблоны.
    pub const ALL: [Self; 3] = [Self::Counter, Self::Todo, Self::Calculator];

    /// Разбирает имя шаблона из `--template`.
    pub fn parse(value: &str) -> Result<Self> {
        match value {
            "counter" => Ok(Self::Counter),
            "todo" => Ok(Self::Todo),
            "calculator" => Ok(Self::Calculator),
            other => Err(Error::Init(format!(
                "неизвестный шаблон `{other}` (поддерживаются: counter, todo, calculator)"
            ))),
        }
    }

    /// Содержимое `src/main.rs` шаблона.
    pub fn main_rs(self) -> &'static str {
        match self {
            Self::Counter => COUNTER_MAIN,
            Self::Todo => TODO_MAIN,
            Self::Calculator => CALCULATOR_MAIN,
        }
    }

    /// Дополнительные HTML-шаблоны: путь в проекте и содержимое.
    pub fn template_files(self) -> &'static [(&'static str, &'static str)] {
        match self {
            Self::Counter => &[("templates/counter.html", COUNTER_HTML)],
            Self::Todo => &[("templates/todo.html", TODO_HTML)],
            Self::Calculator => &[("templates/calculator.html", CALCULATOR_HTML)],
        }
    }
}

impl FromStr for InitTemplate {
    type Err = Error;

    fn from_str(value: &str) -> Result<Self> {
        Self::parse(value)
    }
}

/// Дополнительный компонент, подключаемый флагом `--with`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum InitComponent {
    /// `light-fw-element-form`: `<checkbox>`, `<radio>`, `<select>`/`<option>`.
    Form,
    /// `light-fw-behavior-validation`: `required`, `:validator`, `@validate`.
    Validation,
}

impl InitComponent {
    /// Все поддерживаемые компоненты в порядке вывода в `Cargo.toml`.
    pub const ALL: [Self; 2] = [Self::Form, Self::Validation];

    /// Разбирает имя компонента из `--with`.
    pub fn parse(value: &str) -> Result<Self> {
        match value {
            "form" => Ok(Self::Form),
            "validation" => Ok(Self::Validation),
            other => Err(Error::Init(format!(
                "неизвестный компонент `{other}` (поддерживаются: form, validation)"
            ))),
        }
    }

    /// Имя крейта-компонента.
    pub fn crate_name(self) -> &'static str {
        match self {
            Self::Form => "light-fw-element-form",
            Self::Validation => "light-fw-behavior-validation",
        }
    }

    /// Фича мета-крейта `light`, включающая компонент.
    pub fn light_feature(self) -> &'static str {
        match self {
            Self::Form => "elements-form",
            Self::Validation => "validation",
        }
    }
}

impl FromStr for InitComponent {
    type Err = Error;

    fn from_str(value: &str) -> Result<Self> {
        Self::parse(value)
    }
}

/// Параметры команды `light init`.
#[derive(Debug, Clone)]
pub struct InitOptions {
    /// Имя проекта (оно же имя крейта).
    pub name: String,
    /// Каталог проекта; по умолчанию — `./<name>`.
    pub path: Option<PathBuf>,
    /// Только `Cargo.toml` и `src/main.rs` (без `.gitignore` и `light.lock`).
    pub minimal: bool,
    /// Дополнительные компоненты (`--with`).
    pub components: Vec<InitComponent>,
    /// Готовый шаблон приложения (`--template`).
    pub template: Option<InitTemplate>,
}

/// Что будет создано (результат [`plan`]).
#[derive(Debug, Clone)]
pub struct InitPlan {
    /// Каталог проекта.
    pub directory: PathBuf,
    /// Файлы проекта: относительный путь и содержимое.
    pub files: Vec<(PathBuf, String)>,
    /// Создавать ли `light.lock`.
    pub write_lockfile: bool,
}

impl InitPlan {
    /// Человекочитаемый план.
    pub fn to_text(&self) -> String {
        let mut out = format!("Проект в {}\n", self.directory.display());
        for (path, _) in &self.files {
            out.push_str(&format!("  + {}\n", path.display()));
        }
        if self.write_lockfile {
            out.push_str(&format!("  + {}\n", LOCKFILE_NAME));
        }
        out
    }
}

/// Итог создания проекта.
#[derive(Debug, Clone)]
pub struct InitReport {
    /// Каталог проекта.
    pub directory: PathBuf,
    /// Созданные файлы (относительные пути).
    pub files: Vec<PathBuf>,
    /// Создан ли `light.lock`.
    pub lockfile: bool,
}

impl InitReport {
    /// Человекочитаемый отчёт с подсказкой о запуске.
    pub fn to_text(&self) -> String {
        let mut out = format!("✓ Проект создан в {}\n", self.directory.display());
        for path in &self.files {
            out.push_str(&format!("  {}\n", path.display()));
        }
        if self.lockfile {
            out.push_str(&format!("  {}\n", LOCKFILE_NAME));
        }
        out.push_str(&format!(
            "\nДалее: cd \"{}\" && cargo run\n",
            self.directory.display()
        ));
        out
    }
}

/// Проверяет, что `name` — допустимое имя крейта.
///
/// Разрешены латинские буквы, цифры, `-` и `_`; первый символ — буква или `_`.
pub fn validate_name(name: &str) -> Result<()> {
    if name.is_empty() || name.len() > 64 {
        return Err(Error::Init(
            "имя проекта должно быть длиной от 1 до 64 символов".to_string(),
        ));
    }
    let mut chars = name.chars();
    let first = chars.next().expect("непустое имя");
    if !(first.is_ascii_alphabetic() || first == '_') {
        return Err(Error::Init(format!(
            "имя `{name}` должно начинаться с латинской буквы или `_`"
        )));
    }
    if let Some(bad) = name
        .chars()
        .find(|c| !(c.is_ascii_alphanumeric() || *c == '-' || *c == '_'))
    {
        return Err(Error::Init(format!(
            "недопустимый символ `{bad}` в имени `{name}` (разрешены латинские буквы, цифры, `-`, `_`)"
        )));
    }
    Ok(())
}

/// Целевой каталог проекта из параметров.
pub fn project_dir(options: &InitOptions) -> PathBuf {
    match &options.path {
        Some(path) => path.clone(),
        None => PathBuf::from(&options.name),
    }
}

/// Компоненты без дублей в порядке [`InitComponent::ALL`].
fn normalized_components(components: &[InitComponent]) -> Vec<InitComponent> {
    InitComponent::ALL
        .into_iter()
        .filter(|component| components.contains(component))
        .collect()
}

/// Содержимое `Cargo.toml` нового проекта.
pub fn cargo_toml(name: &str, components: &[InitComponent]) -> String {
    let components = normalized_components(components);
    let mut text = format!(
        "[package]\n\
         name = \"{name}\"\n\
         version = \"0.1.0\"\n\
         edition = \"2021\"\n\
         \n\
         [dependencies]\n"
    );

    if components.is_empty() {
        text.push_str(&format!("light = \"{LIGHT_DEPENDENCY_VERSION}\"\n"));
        return text;
    }

    let features = components
        .iter()
        .map(|component| format!("\"{}\"", component.light_feature()))
        .collect::<Vec<_>>()
        .join(", ");
    text.push_str(&format!(
        "light = {{ version = \"{LIGHT_DEPENDENCY_VERSION}\", features = [{features}] }}\n"
    ));
    for component in &components {
        text.push_str(&format!(
            "{} = \"{LIGHT_DEPENDENCY_VERSION}\"\n",
            component.crate_name()
        ));
    }
    text
}

/// Закомментированный пример формы для проектов с компонентом `form`.
const FORM_EXAMPLE: &str = r#"
// Пример формы (компонент `form`):
//
// #[template("templates/form.html")]
// #[proxy]
// struct SignUp {
//     email: String,
//     agree: bool,
// }
//
// impl SignUp {
//     fn submit(&self) {
//         if self.agree() {
//             println!("email: {}", self.email());
//         }
//     }
// }
//
// templates/form.html:
// <window title="Sign up" width="360" height="240">
//     <div direction="vertical" padding="12">
//         <text v-model="email" placeholder="Email" required />
//         <checkbox v-model="agree">Согласен с условиями</checkbox>
//         <button @click="submit" :disabled="!agree">Отправить</button>
//     </div>
// </window>
"#;

/// Содержимое `src/main.rs` — минимальное приложение из одного окна.
pub fn main_rs(components: &[InitComponent]) -> String {
    let mut text = r#"use light::prelude::*;

struct App;

impl Component for App {
    fn render(&self) -> VElement {
        VElement::container(
            "",
            NodeKind::Window,
            vec![VElement::container(
                "0",
                NodeKind::Column,
                vec![VElement::leaf(
                    "0.0",
                    NodeKind::Text {
                        content: "Hello, Light!".to_string(),
                    },
                )],
            )],
        )
        .with_window(WindowConfig {
            title: "Hello, Light!".to_string(),
            width: 320,
            height: 200,
            ..Default::default()
        })
    }
}

fn main() -> light::Result<()> {
    light::run(App)
}
"#
    .to_string();

    if components.contains(&InitComponent::Form) {
        text.push_str(FORM_EXAMPLE);
    }
    text
}

/// Строит план создания проекта, проверяя, что каталог свободен.
///
/// Ошибка, если каталог существует и не пуст.
pub fn plan(options: &InitOptions) -> Result<InitPlan> {
    validate_name(&options.name)?;
    let directory = project_dir(options);

    if directory.is_dir() {
        let mut entries = std::fs::read_dir(&directory)?;
        if entries.next().is_some() {
            return Err(Error::Init(format!(
                "каталог `{}` не пуст — укажите другое имя или `--path`",
                directory.display()
            )));
        }
    } else if directory.exists() {
        return Err(Error::Init(format!(
            "`{}` существует и не является каталогом",
            directory.display()
        )));
    }

    let components = normalized_components(&options.components);
    let main = match options.template {
        Some(template) => template.main_rs().to_string(),
        None => main_rs(&components),
    };
    let mut files = vec![
        (
            PathBuf::from("Cargo.toml"),
            cargo_toml(&options.name, &components),
        ),
        (PathBuf::from("src").join("main.rs"), main),
    ];
    if let Some(template) = options.template {
        for (path, content) in template.template_files() {
            files.push((PathBuf::from(path), (*content).to_string()));
        }
    }
    if !options.minimal {
        files.push((PathBuf::from(".gitignore"), GITIGNORE.to_string()));
    }

    Ok(InitPlan {
        directory,
        files,
        write_lockfile: !options.minimal,
    })
}

/// Проверяет, что `cargo` доступен в `PATH`.
pub fn require_cargo(runner: &dyn CommandRunner) -> Result<()> {
    match runner.run("cargo", &["--version".to_string()], None) {
        Ok(_) => Ok(()),
        Err(Error::CommandNotFound(_)) => Err(Error::Init(
            "`cargo` не найден в PATH — установите Rust (https://rustup.rs)".to_string(),
        )),
        Err(error) => Err(error),
    }
}

/// Записывает файлы плана на диск, создавая каталоги по мере необходимости.
pub fn scaffold(plan: &InitPlan) -> Result<()> {
    for (relative, content) in &plan.files {
        let path = plan.directory.join(relative);
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(&path, content)?;
    }
    Ok(())
}

/// Полный цикл: проверка `cargo` → план → запись файлов → `light.lock`.
pub fn apply(runner: &dyn CommandRunner, options: &InitOptions) -> Result<InitReport> {
    require_cargo(runner)?;
    let plan = plan(options)?;
    scaffold(&plan)?;

    let lockfile = if plan.write_lockfile {
        let lock = Lockfile::from_project(&plan.directory)?;
        lock.write(&plan.directory)?;
        true
    } else {
        false
    };

    Ok(InitReport {
        directory: plan.directory,
        files: plan.files.into_iter().map(|(path, _)| path).collect(),
        lockfile,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::process::CommandOutput;
    use std::path::Path;
    use std::sync::atomic::{AtomicU64, Ordering};

    static COUNTER: AtomicU64 = AtomicU64::new(0);

    fn scratch(name: &str) -> PathBuf {
        let unique = COUNTER.fetch_add(1, Ordering::Relaxed);
        let dir = std::env::temp_dir().join(format!(
            "light-fw-cli-init-{name}-{}-{unique}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).expect("scratch dir");
        dir
    }

    struct StubRunner {
        found: bool,
    }

    impl CommandRunner for StubRunner {
        fn run(
            &self,
            program: &str,
            _args: &[String],
            _cwd: Option<&Path>,
        ) -> Result<CommandOutput> {
            if self.found {
                Ok(CommandOutput {
                    status: 0,
                    stdout: "cargo 1.99.0".to_string(),
                    stderr: String::new(),
                })
            } else {
                Err(Error::CommandNotFound(program.to_string()))
            }
        }
    }

    #[test]
    fn rejects_invalid_names() {
        assert!(validate_name("my-app").is_ok());
        assert!(validate_name("app_2").is_ok());
        assert!(validate_name("").is_err());
        assert!(validate_name("2app").is_err());
        assert!(validate_name("my app").is_err());
        assert!(validate_name("app!").is_err());
    }

    #[test]
    fn plan_default_creates_all_files() {
        let root = scratch("plan-default");
        let dir = root.join("cool-app");
        let options = InitOptions {
            name: "cool-app".to_string(),
            path: Some(dir.clone()),
            minimal: false,
            components: Vec::new(),
            template: None,
        };
        let plan = plan(&options).expect("plan");
        let names: Vec<String> = plan
            .files
            .iter()
            .map(|(path, _)| path.to_string_lossy().replace('\\', "/"))
            .collect();
        assert!(names.contains(&"Cargo.toml".to_string()));
        assert!(names.contains(&"src/main.rs".to_string()));
        assert!(names.contains(&".gitignore".to_string()));
        assert!(plan.write_lockfile);
    }

    #[test]
    fn plan_minimal_omits_gitignore_and_lockfile() {
        let root = scratch("plan-minimal");
        let options = InitOptions {
            name: "tiny".to_string(),
            path: Some(root.join("tiny")),
            minimal: true,
            components: Vec::new(),
            template: None,
        };
        let plan = plan(&options).expect("plan");
        let names: Vec<String> = plan
            .files
            .iter()
            .map(|(path, _)| path.to_string_lossy().replace('\\', "/"))
            .collect();
        assert!(!names.contains(&".gitignore".to_string()));
        assert!(!plan.write_lockfile);
    }

    #[test]
    fn plan_rejects_non_empty_directory() {
        let root = scratch("plan-nonempty");
        let target = root.join("busy");
        std::fs::create_dir_all(&target).expect("dir");
        std::fs::write(target.join("file.txt"), "x").expect("file");
        let options = InitOptions {
            name: "busy".to_string(),
            path: Some(target),
            minimal: false,
            components: Vec::new(),
            template: None,
        };
        let error = plan(&options).expect_err("должна быть ошибка");
        assert!(error.to_string().contains("не пуст"), "{error}");
    }

    #[test]
    fn cargo_toml_pins_light_version() {
        let text = cargo_toml("demo", &[]);
        assert!(text.contains("name = \"demo\""));
        assert!(text.contains(&format!("light = \"{LIGHT_DEPENDENCY_VERSION}\"")));
        assert!(!text.contains("features ="));
    }

    #[test]
    fn cargo_toml_adds_form_dependency_and_feature() {
        let text = cargo_toml("demo", &[InitComponent::Form]);
        assert!(
            text.contains(&format!(
                "light = {{ version = \"{LIGHT_DEPENDENCY_VERSION}\", features = [\"elements-form\"] }}"
            )),
            "{text}"
        );
        assert!(
            text.contains(&format!(
                "light-fw-element-form = \"{LIGHT_DEPENDENCY_VERSION}\""
            )),
            "{text}"
        );
        assert!(!text.contains("light-fw-behavior-validation"), "{text}");
    }

    #[test]
    fn cargo_toml_adds_both_dependencies_and_deduplicates() {
        let text = cargo_toml(
            "demo",
            &[
                InitComponent::Validation,
                InitComponent::Form,
                InitComponent::Form,
            ],
        );
        assert!(
            text.contains(&format!(
                "light = {{ version = \"{LIGHT_DEPENDENCY_VERSION}\", features = [\"elements-form\", \"validation\"] }}"
            )),
            "{text}"
        );
        assert_eq!(text.matches("light-fw-element-form =").count(), 1, "{text}");
        assert_eq!(
            text.matches("light-fw-behavior-validation =").count(),
            1,
            "{text}"
        );
    }

    #[test]
    fn main_rs_is_self_contained() {
        let text = main_rs(&[]);
        assert!(text.contains("Hello, Light!"));
        assert!(!text.contains("include_str!"));
        assert!(!text.contains("#[template"));
        assert!(!text.contains("Пример формы"));
    }

    #[test]
    fn main_rs_includes_form_example_only_for_form_component() {
        let text = main_rs(&[InitComponent::Form]);
        assert!(text.contains("Пример формы"), "{text}");
        let validation_only = main_rs(&[InitComponent::Validation]);
        assert!(
            !validation_only.contains("Пример формы"),
            "{validation_only}"
        );
    }

    #[test]
    fn parses_supported_templates() {
        assert_eq!(
            InitTemplate::parse("counter").expect("counter"),
            InitTemplate::Counter
        );
        assert_eq!(
            InitTemplate::parse("todo").expect("todo"),
            InitTemplate::Todo
        );
        assert_eq!(
            InitTemplate::parse("calculator").expect("calculator"),
            InitTemplate::Calculator
        );
        let error = InitTemplate::parse("unknown").expect_err("unknown template");
        assert!(error.to_string().contains("counter"), "{error}");
    }

    #[test]
    fn template_plan_includes_main_and_html() {
        let root = scratch("plan-template");
        let options = InitOptions {
            name: "todo-app".to_string(),
            path: Some(root.join("todo-app")),
            minimal: true,
            components: Vec::new(),
            template: Some(InitTemplate::Todo),
        };
        let plan = plan(&options).expect("plan");
        let by_path = |name: &str| {
            plan.files
                .iter()
                .find(|(path, _)| path.to_string_lossy().replace('\\', "/") == name)
                .map(|(_, content)| content.as_str())
        };
        assert!(by_path("src/main.rs").expect("main").contains("TodoApp"));
        assert!(
            by_path("templates/todo.html")
                .expect("todo template")
                .contains("Light Todo")
        );
        assert_eq!(plan.files.len(), 3, "Cargo.toml + main.rs + template");
    }

    #[test]
    fn require_cargo_reports_missing_tool() {
        let error = require_cargo(&StubRunner { found: false }).expect_err("нет cargo");
        assert!(error.to_string().contains("cargo"), "{error}");
        assert!(require_cargo(&StubRunner { found: true }).is_ok());
    }

    #[test]
    fn apply_creates_project_and_lockfile() {
        let root = scratch("apply");
        let dir = root.join("my-app");
        let options = InitOptions {
            name: "my-app".to_string(),
            path: Some(dir.clone()),
            minimal: false,
            components: Vec::new(),
            template: None,
        };
        let report = apply(&StubRunner { found: true }, &options).expect("apply");
        assert!(report.lockfile);
        assert!(dir.join("Cargo.toml").is_file());
        assert!(dir.join("src").join("main.rs").is_file());
        assert!(dir.join(".gitignore").is_file());
        assert!(dir.join(LOCKFILE_NAME).is_file());

        let lock = Lockfile::read(&dir).expect("read lock");
        assert_eq!(lock.core, LIGHT_DEPENDENCY_VERSION);
    }

    #[test]
    fn apply_minimal_skips_lockfile() {
        let root = scratch("apply-minimal");
        let dir = root.join("tiny");
        let options = InitOptions {
            name: "tiny".to_string(),
            path: Some(dir.clone()),
            minimal: true,
            components: Vec::new(),
            template: None,
        };
        let report = apply(&StubRunner { found: true }, &options).expect("apply");
        assert!(!report.lockfile);
        assert!(dir.join("Cargo.toml").is_file());
        assert!(!dir.join(".gitignore").exists());
        assert!(!dir.join(LOCKFILE_NAME).exists());
    }

    #[test]
    fn apply_fails_without_cargo_before_writing() {
        let root = scratch("apply-nocargo");
        let dir = root.join("nope");
        let options = InitOptions {
            name: "nope".to_string(),
            path: Some(dir.clone()),
            minimal: false,
            components: Vec::new(),
            template: None,
        };
        assert!(apply(&StubRunner { found: false }, &options).is_err());
        assert!(!dir.exists(), "каталог не должен создаваться");
    }
}