rok-ui-cli 0.8.0

cargo rok-ui: create rok-ui apps, generate BLoC features, vendor components and write route trees.
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
733
734
735
736
737
738
//! `cargo rok-ui generate` (`g`): write a feature, or part of one, from flags and JSON.
//!
//! The pipeline: flags and `-j` JSON make a [`spec::Spec`] (flags win), [`resolve`] fills in
//! defaults and checks it into a [`resolve::Plan`], [`render`] writes each file's code, and
//! [`output`] works out barrels, `app.rs` lines and conflicts before writing anything.

pub mod names;
pub mod output;
pub mod render;
pub mod resolve;
pub mod spec;

use std::{fs, io::Read as _, path::PathBuf, process::ExitCode};

use output::{Options, Part};
use spec::{
    ConcurrencyKind, EndpointSpec, EventSpec, FieldSpec, Kind, ProviderKind, ProviderSpec,
    RepositorySpec, ServerErrorsSpec, Spec, StateSpec, StateStyle, TypeSpec, ViewSpec,
};

use crate::Arguments;

/// `generate`'s help.
pub const USAGE: &str = "cargo rok-ui generate (g): write a feature, or part of one

USAGE:
    cargo rok-ui g feature <name> [flags]      models, provider, repository, bloc, view, route, tests
    cargo rok-ui g bloc <Name> [flags]         a bloc with its tests (data layer when missing)
    cargo rok-ui g cubit <Name> [flags]        a cubit with its tests (data layer when missing)
    cargo rok-ui g repository <Name> [flags]   a repository (provider and models when missing)
    cargo rok-ui g provider <Name> [flags]     a provider (models when missing)
    cargo rok-ui g view <feature> [flags]      a page and its route
    cargo rok-ui g api <feature> [flags]       an HTTP provider, its DTOs and its repository
    cargo rok-ui g schema                      print the JSON Schema of `-j`

FLAGS (flags win over JSON, JSON over defaults):
    -j, --json <JSON|@file|->          the whole spec as JSON (see `g schema`)
    --feature <name>                   the feature, for bloc/cubit/repository/provider
    --event <Name[:field:Type,...]>    an event (repeatable; replaces the JSON's events)
    --kind <bloc|cubit>
    --concurrency <sequential|droppable|restartable|concurrent>
    --state-style <struct|enum>
    --status <a,b,c>                   statuses (default: initial,loading,success,failure)
    --repository <Name>
    --provider <Name[:memory|db|http|file]>
    --api-base <path>                  the HTTP provider's path prefix
    --endpoint <method:VERB:path:Response>   an HTTP endpoint (repeatable); typed path
                                       parameters: /notes/{id:NoteId}
    --dto <Name[:field:Type,...]>      a wire type for the endpoints (repeatable)
    --skip-expire                      the --endpoint ones do not expire the session on 401
    --server-errors                    the form maps API errors onto its fields
    --view / --no-view                 write the page (default: with `feature` only)
    --no-tests                         skip tests/features/<feature>/
    --path <dir>                       the project (default: the current directory)
    --dry-run                          print what would change, write nothing
    --force                            overwrite generated files that changed
    --no-wire                          leave barrel files and src/app.rs alone

EXIT CODES: 0 done, 1 invalid input, 2 conflicts (nothing written).";

/// Run `generate`.
pub fn run(arguments: &Arguments) -> ExitCode {
    match try_run(arguments) {
        Ok(code) => code,
        Err(message) => {
            eprintln!("error: {message}");
            ExitCode::FAILURE
        }
    }
}

fn try_run(arguments: &Arguments) -> Result<ExitCode, String> {
    let Some(subcommand) = arguments.positional.first() else {
        println!("{USAGE}");
        return Ok(ExitCode::SUCCESS);
    };
    let part = match subcommand.as_str() {
        "schema" => {
            let schema =
                serde_json::to_string_pretty(&spec::schema()).map_err(|error| error.to_string())?;
            println!("{schema}");
            return Ok(ExitCode::SUCCESS);
        }
        "help" => {
            println!("{USAGE}");
            return Ok(ExitCode::SUCCESS);
        }
        "feature" => Part::Feature,
        "bloc" | "cubit" => Part::Bloc,
        "repository" => Part::Repository,
        "provider" => Part::Provider,
        "view" => Part::View,
        "api" => Part::Api,
        other => return Err(format!("unknown generator `{other}`\n\n{USAGE}")),
    };
    let mut spec = match arguments.flag("json") {
        Some(json) => parse_json(json)?,
        None => Spec::default(),
    };
    apply_flags(
        &mut spec,
        subcommand,
        arguments.positional.get(1).map(String::as_str),
        arguments,
    )?;
    let plan = match resolve::resolve(&spec) {
        Ok(plan) => plan,
        Err(errors) => {
            let mut message = String::from("the spec is invalid:");
            for error in errors {
                message.push_str("\n  ");
                message.push_str(&error);
            }
            return Err(message);
        }
    };
    let root = PathBuf::from(arguments.flag("path").unwrap_or("."));
    let crate_name = crate_name(&root)?;
    let options = Options {
        force: arguments.has("force"),
        view: if arguments.has("no-view") {
            Some(false)
        } else if arguments.has("view") {
            Some(true)
        } else {
            None
        },
        no_wire: arguments.has("no-wire"),
    };
    let changes = output::plan(&root, &plan, part, &crate_name, options)?;
    let dry_run = arguments.has("dry-run");
    print!("{}", output::report(&changes, dry_run));
    let conflicts = changes.conflicts();
    if !conflicts.is_empty() {
        eprintln!(
            "error: {} file(s) exist and differ; nothing was written. Pass --force to overwrite them.",
            conflicts.len()
        );
        return Ok(ExitCode::from(2));
    }
    if !dry_run {
        output::write(&root, &changes)?;
    }
    Ok(ExitCode::SUCCESS)
}

/// Generate the feature `json` describes into the new app at `root`, quietly.
///
/// # Errors
///
/// When the JSON is invalid or a file cannot be written (both generator bugs here).
pub fn feature_into(root: &std::path::Path, json: &str) -> Result<(), String> {
    let spec = from_json(json)?;
    let plan = resolve::resolve(&spec).map_err(|errors| errors.join("\n"))?;
    let crate_name = crate_name(root)?;
    let changes = output::plan(root, &plan, Part::Feature, &crate_name, Options::default())?;
    output::write(root, &changes)
}

/// The library crate's name, from `Cargo.toml`.
fn crate_name(root: &std::path::Path) -> Result<String, String> {
    let manifest = fs::read_to_string(root.join("Cargo.toml")).map_err(|_| {
        format!(
            "{} has no Cargo.toml; run this in your app (or pass --path)",
            root.display()
        )
    })?;
    let mut in_package = false;
    for line in manifest.lines() {
        let line = line.trim();
        if line.starts_with('[') {
            in_package = line == "[package]" || line == "[lib]";
            continue;
        }
        if in_package {
            if let Some(value) = line
                .strip_prefix("name")
                .map(str::trim)
                .and_then(|rest| rest.strip_prefix('='))
            {
                return Ok(value.trim().trim_matches('"').replace('-', "_"));
            }
        }
    }
    Err("Cargo.toml has no package name".into())
}

/// `-j`: JSON inline, `@file`, or `-` for standard input.
fn parse_json(source: &str) -> Result<Spec, String> {
    let text = if source == "-" {
        let mut text = String::new();
        std::io::stdin()
            .read_to_string(&mut text)
            .map_err(|error| error.to_string())?;
        text
    } else if let Some(path) = source.strip_prefix('@') {
        fs::read_to_string(path).map_err(|error| format!("{path}: {error}"))?
    } else {
        source.to_string()
    };
    from_json(&text)
}

/// Parse a spec, with errors that name the JSON path.
///
/// # Errors
///
/// When the JSON is malformed, has unknown keys or wrong types.
pub fn from_json(text: &str) -> Result<Spec, String> {
    let deserializer = &mut serde_json::Deserializer::from_str(text);
    serde_path_to_error::deserialize(deserializer).map_err(|error| {
        let path = error.path().to_string();
        let inner = error.into_inner();
        if path == "." {
            format!("invalid JSON: {inner}")
        } else {
            format!("invalid JSON at `{path}`: {inner}")
        }
    })
}

fn parse_choice<T: serde::de::DeserializeOwned>(flag: &str, value: &str) -> Result<T, String> {
    serde_json::from_value(serde_json::Value::String(value.to_string()))
        .map_err(|_| format!("--{flag}: `{value}` is not one of the choices (see --help)"))
}

/// Split at top-level commas: `a:Vec<u8>,b:HashMap<K, V>` into two.
fn split_top(text: &str, separator: char) -> Vec<String> {
    let mut parts = Vec::new();
    let mut depth = 0_i32;
    let mut current = String::new();
    for character in text.chars() {
        match character {
            '<' | '(' | '[' | '{' => depth += 1,
            '>' | ')' | ']' | '}' => depth -= 1,
            _ => {}
        }
        if character == separator && depth == 0 {
            parts.push(std::mem::take(&mut current));
        } else {
            current.push(character);
        }
    }
    if !current.trim().is_empty() {
        parts.push(current);
    }
    parts
        .into_iter()
        .map(|part| part.trim().to_string())
        .collect()
}

/// `--event NoteAdded:title:String,body:String`.
fn parse_event(value: &str) -> Result<EventSpec, String> {
    let (name, rest) = value.split_once(':').unwrap_or((value, ""));
    let mut fields = Vec::new();
    for field in split_top(rest, ',') {
        let Some((field_name, ty)) = field.split_once(':') else {
            return Err(format!("--event {value}: `{field}` should be `name:Type`"));
        };
        fields.push(FieldSpec {
            name: field_name.trim().to_string(),
            ty: ty.trim().to_string(),
            ..FieldSpec::default()
        });
    }
    Ok(EventSpec {
        name: name.trim().to_string(),
        fields,
        ..EventSpec::default()
    })
}

/// `--endpoint list_notes:GET:/notes:Vec<NoteDto>`.
fn parse_endpoint(value: &str, skip_expire: bool) -> Result<EndpointSpec, String> {
    // Split at colons outside `{..}` and `<..>`; the response type keeps any `::`.
    let parts = split_top(value, ':');
    let [method, verb, path, response @ ..] = &parts[..] else {
        return Err(format!(
            "--endpoint {value}: use `method:VERB:/path:ResponseType`"
        ));
    };
    if response.is_empty() {
        return Err(format!(
            "--endpoint {value}: use `method:VERB:/path:ResponseType`"
        ));
    }
    // `{id}` is a `String` parameter; `{id:NoteId}` names its type.
    let mut path_params = Vec::new();
    let mut clean_path = Vec::new();
    for segment in path.split('/') {
        match segment
            .strip_prefix('{')
            .and_then(|rest| rest.strip_suffix('}'))
        {
            Some(param) => {
                let (name, ty) = param.split_once(':').unwrap_or((param, "String"));
                path_params.push(FieldSpec {
                    name: name.trim().to_string(),
                    ty: ty.trim().to_string(),
                    ..FieldSpec::default()
                });
                clean_path.push(format!("{{{}}}", name.trim()));
            }
            None => clean_path.push(segment.to_string()),
        }
    }
    Ok(EndpointSpec {
        method: method.clone(),
        verb: verb.to_uppercase(),
        path: clean_path.join("/"),
        path_params,
        response: response.join("::"),
        skip_expire,
        ..EndpointSpec::default()
    })
}

/// `--dto NoteDto:id:NoteId,title:String`.
fn parse_dto(value: &str) -> Result<TypeSpec, String> {
    let event = parse_event(value).map_err(|error| error.replace("--event", "--dto"))?;
    Ok(TypeSpec {
        name: event.name,
        fields: event.fields,
        variants: Vec::new(),
    })
}

/// Apply the subcommand's name and the flags over `spec`.
fn apply_flags(
    spec: &mut Spec,
    subcommand: &str,
    name: Option<&str>,
    arguments: &Arguments,
) -> Result<(), String> {
    let feature_flag = arguments.flag("feature").map(str::to_string);
    let derived_feature =
        |name: &str, suffixes: &[&str]| names::snake(&names::base(name, suffixes));
    match (subcommand, name) {
        ("feature" | "view" | "api", Some(name)) => spec.feature = Some(name.to_string()),
        ("bloc" | "cubit", Some(name)) => {
            spec.kind = Some(if subcommand == "cubit" {
                Kind::Cubit
            } else {
                Kind::Bloc
            });
            spec.name = Some(name.to_string());
            if spec.feature.is_none() {
                spec.feature = Some(derived_feature(name, &["bloc", "cubit"]));
            }
        }
        ("repository", Some(name)) => {
            let repository = spec.repository.get_or_insert_with(RepositorySpec::default);
            repository.name = format!(
                "{}Repository",
                names::pascal(&names::base(name, &["repository"]))
            );
            if spec.feature.is_none() {
                spec.feature = Some(derived_feature(name, &["repository"]));
            }
        }
        ("provider", Some(name)) => {
            let provider = spec.provider.get_or_insert_with(ProviderSpec::default);
            provider.name = names::pascal(name);
            if spec.feature.is_none() {
                spec.feature = Some(derived_feature(name, &["provider"]));
            }
        }
        ("bloc" | "cubit", None) if spec.name.is_some() => {
            spec.kind = Some(if subcommand == "cubit" {
                Kind::Cubit
            } else {
                Kind::Bloc
            });
        }
        (_, None) if spec.feature.is_some() || feature_flag.is_some() => {}
        (_, None) => return Err(format!("usage: cargo rok-ui g {subcommand} <name> [flags]")),
        _ => {}
    }
    if let Some(feature) = feature_flag {
        spec.feature = Some(feature);
    }
    if subcommand == "api" {
        let provider = spec.provider.get_or_insert_with(|| ProviderSpec {
            name: String::new(),
            ..ProviderSpec::default()
        });
        if provider.name.is_empty() {
            let feature = names::pascal(spec.feature.as_deref().unwrap_or_default());
            provider.name = format!("{feature}Api");
        }
        provider.kind = Some(ProviderKind::Http);
    }
    if let Some(kind) = arguments.flag("kind") {
        spec.kind = Some(parse_choice::<Kind>("kind", kind)?);
    }
    if let Some(concurrency) = arguments.flag("concurrency") {
        spec.concurrency = Some(parse_choice::<ConcurrencyKind>("concurrency", concurrency)?);
    }
    let events = arguments.flags("event");
    if !events.is_empty() {
        spec.events = events
            .into_iter()
            .map(parse_event)
            .collect::<Result<_, _>>()?;
    }
    if let Some(style) = arguments.flag("state-style") {
        spec.state.get_or_insert_with(StateSpec::default).style =
            Some(parse_choice::<StateStyle>("state-style", style)?);
    }
    if let Some(status) = arguments.flag("status") {
        spec.state.get_or_insert_with(StateSpec::default).status = split_top(status, ',');
    }
    if let Some(repository) = arguments.flag("repository") {
        spec.repository
            .get_or_insert_with(RepositorySpec::default)
            .name = names::pascal(repository);
    }
    if let Some(provider) = arguments.flag("provider") {
        let (name, kind) = provider.split_once(':').unwrap_or((provider, ""));
        let spec_provider = spec.provider.get_or_insert_with(ProviderSpec::default);
        spec_provider.name = names::pascal(name);
        if !kind.is_empty() {
            spec_provider.kind = Some(parse_choice::<ProviderKind>("provider", kind)?);
        }
    }
    if let Some(base) = arguments.flag("api-base") {
        spec.provider
            .get_or_insert_with(ProviderSpec::default)
            .api_base = Some(base.to_string());
    }
    let endpoints = arguments.flags("endpoint");
    if !endpoints.is_empty() {
        let skip_expire = arguments.has("skip-expire");
        let parsed = endpoints
            .into_iter()
            .map(|endpoint| parse_endpoint(endpoint, skip_expire))
            .collect::<Result<Vec<_>, _>>()?;
        let provider = spec.provider.get_or_insert_with(ProviderSpec::default);
        if provider.kind.is_none() {
            provider.kind = Some(ProviderKind::Http);
        }
        provider.endpoints = parsed;
    }
    let dtos = arguments.flags("dto");
    if !dtos.is_empty() {
        spec.dtos = dtos.into_iter().map(parse_dto).collect::<Result<_, _>>()?;
    }
    if arguments.has("server-errors") {
        let form = spec
            .view
            .get_or_insert_with(ViewSpec::default)
            .form
            .as_mut()
            .ok_or("--server-errors needs a form (`view.form` in the JSON)")?;
        form.server_errors
            .get_or_insert_with(ServerErrorsSpec::default);
    }
    if arguments.has("no-tests") {
        spec.tests = Some(false);
    }
    if let Some(provider) = &spec.provider {
        if provider.name.is_empty() {
            return Err("provider.name: missing".into());
        }
    }
    if let Some(repository) = &spec.repository {
        if repository.name.is_empty() {
            return Err("repository.name: missing".into());
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::path::{Path, PathBuf};

    use super::*;
    use crate::templates::{Template, BLOC_FEATURE, BLOC_HTTP_FEATURES};

    /// A new app from the bloc template's skeleton, without its generated feature.
    fn skeleton(name: &str) -> PathBuf {
        skeleton_of(Template::Bloc, name)
    }

    /// A new app from `template`'s skeleton, without its generated features.
    fn skeleton_of(template: Template, name: &str) -> PathBuf {
        let root =
            std::env::temp_dir().join(format!("rok-ui-generate-{name}-{}", std::process::id()));
        fs::remove_dir_all(&root).ok();
        for file in template.files() {
            let path = root.join(file.path);
            fs::create_dir_all(path.parent().unwrap()).unwrap();
            let text = file
                .text
                .replace("{{name}}", "demo-app")
                .replace("{{crate_name}}", "demo_app")
                .replace("{{rok_ui}}", "rok-ui = \"*\"")
                .replace("{{rok_ui_build}}", "rok-ui-build = \"*\"");
            fs::write(path, text).unwrap();
        }
        root
    }

    fn generate(root: &Path, json: &str, part: Part, options: Options) -> output::Changes {
        let plan = resolve::resolve(&from_json(json).unwrap()).unwrap();
        output::plan(root, &plan, part, "demo_app", options).unwrap()
    }

    fn rustfmt_installed() -> bool {
        std::process::Command::new("rustfmt")
            .arg("--version")
            .output()
            .is_ok_and(|output| output.status.success())
    }

    /// Generate `features` into a new `template` app and compare every file written with
    /// `tests/snapshots/<name>/`. Run with `UPDATE_SNAPSHOTS=1` to accept changes.
    fn check_snapshots(template: Template, name: &str, features: &[&str]) {
        if !rustfmt_installed() {
            eprintln!("skipped: the snapshots are formatted with rustfmt, which is not installed");
            return;
        }
        let root = skeleton_of(template, name);
        let mut written = std::collections::BTreeSet::new();
        for feature in features {
            let changes = generate(&root, feature, Part::Feature, Options::default());
            for (path, (action, _)) in &changes.files {
                assert_ne!(*action, output::Action::Conflict, "{path}");
                written.insert(path.clone());
            }
            output::write(&root, &changes).unwrap();
        }
        let snapshots = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/snapshots")
            .join(name);
        let update = std::env::var_os("UPDATE_SNAPSHOTS").is_some();
        let mut mismatches = Vec::new();
        for path in &written {
            let text = fs::read_to_string(root.join(path)).unwrap();
            let snapshot = snapshots.join(path);
            if update {
                fs::create_dir_all(snapshot.parent().unwrap()).unwrap();
                fs::write(&snapshot, &text).unwrap();
            } else if fs::read_to_string(&snapshot).ok().as_deref() != Some(text.as_str()) {
                mismatches.push(path.clone());
            }
        }
        fs::remove_dir_all(&root).ok();
        assert!(
            mismatches.is_empty(),
            "these files differ from tests/snapshots/{name} (UPDATE_SNAPSHOTS=1 accepts them): {mismatches:?}"
        );
    }

    #[test]
    fn notes_fixture_matches_its_snapshots() {
        check_snapshots(Template::Bloc, "notes", &[BLOC_FEATURE]);
    }

    #[test]
    fn http_fixtures_match_their_snapshots() {
        check_snapshots(Template::BlocHttp, "http", BLOC_HTTP_FEATURES);
    }

    #[test]
    fn http_specs_are_checked() {
        let invalid = resolve::resolve(
            &from_json(
                r#"{"feature": "auth",
                    "repository": {"name": "AuthRepository", "methods": [
                        {"name": "sign_in", "returns": "User", "session": "sign_in"},
                        {"name": "gone"}]},
                    "provider": {"name": "AuthApi", "kind": "http", "endpoints": [
                        {"method": "sign_in", "verb": "POST", "path": "sessions", "response": "SignedInDto"},
                        {"method": "me", "verb": "GET", "path": "/users/{id}", "response": "UserDto"}]},
                    "dtos": [{"name": "SignedInDto", "fields": [{"name": "jwt", "type": "String"}]}],
                    "view": {"form": {"event": "AuthRequested", "server_errors": {"conflict_field": "email"}}}}"#,
            )
            .unwrap(),
        )
        .unwrap_err()
        .join("\n");
        for expected in [
            "repository.methods[0].session: `sign_in` needs the endpoint's response DTO to have a `token` field",
            "repository.methods[1].name: there is no provider endpoint `gone`",
            "provider.endpoints[0].path",
            "provider.endpoints[1]",
            "view.form.server_errors.conflict_field: the form has no field `email`",
        ] {
            assert!(invalid.contains(expected), "missing {expected:?} in:\n{invalid}");
        }
    }

    #[test]
    fn generating_twice_changes_nothing() {
        let root = skeleton("twice");
        let first = generate(&root, BLOC_FEATURE, Part::Feature, Options::default());
        output::write(&root, &first).unwrap();
        let second = generate(&root, BLOC_FEATURE, Part::Feature, Options::default());
        let changed: Vec<&String> = second
            .files
            .iter()
            .filter(|(_, (action, _))| *action != output::Action::Unchanged)
            .map(|(path, _)| path)
            .collect();
        assert!(changed.is_empty(), "changed on the second run: {changed:?}");
        let app = fs::read_to_string(root.join("src/app.rs")).unwrap();
        assert_eq!(app.matches("NotesRepositoryImpl::new").count(), 1);
        let features = fs::read_to_string(root.join("src/features.rs")).unwrap();
        assert_eq!(features.matches("pub mod notes;").count(), 1);
        fs::remove_dir_all(&root).ok();
    }

    #[test]
    fn edited_files_conflict_unless_forced() {
        let root = skeleton("conflict");
        let first = generate(&root, BLOC_FEATURE, Part::Feature, Options::default());
        output::write(&root, &first).unwrap();
        let edited = root.join("src/features/notes/bloc/notes_bloc.rs");
        let mut text = fs::read_to_string(&edited).unwrap();
        text.push_str("// mine\n");
        fs::write(&edited, text).unwrap();
        let again = generate(&root, BLOC_FEATURE, Part::Feature, Options::default());
        assert_eq!(again.conflicts(), ["src/features/notes/bloc/notes_bloc.rs"]);
        let forced = generate(
            &root,
            BLOC_FEATURE,
            Part::Feature,
            Options {
                force: true,
                ..Options::default()
            },
        );
        assert_eq!(forced.conflicts(), Vec::<&str>::new());
        fs::remove_dir_all(&root).ok();
    }

    #[test]
    fn barrels_stay_sorted() {
        let text = "//! Features.\n\npub mod notes;\npub mod todos;\n";
        assert_eq!(
            output::declare(text, "settings", true),
            "//! Features.\n\npub mod notes;\npub mod settings;\npub mod todos;\n"
        );
        assert_eq!(output::declare(text, "notes", true), text);
        assert_eq!(
            output::declare("//! Tests.\n", "notes", false),
            "//! Tests.\n\nmod notes;\n"
        );
    }

    #[test]
    fn json_errors_name_the_path() {
        let unknown = from_json(r#"{"feature": "notes", "events": [{"name": "A", "feilds": []}]}"#)
            .unwrap_err();
        assert!(
            unknown.contains("events[0]") && unknown.contains("feilds"),
            "{unknown}"
        );
        let wrong_type = from_json(r#"{"feature": "notes", "tests": "yes"}"#).unwrap_err();
        assert!(wrong_type.contains("tests"), "{wrong_type}");
        let invalid = resolve::resolve(
            &from_json(
                r#"{"feature": "type", "events": [{"name": "noteAdded", "fields": [{"name": "x", "type": "Vec<"}]}]}"#,
            )
            .unwrap(),
        )
        .unwrap_err();
        let joined = invalid.join("\n");
        assert!(
            joined.contains("feature: feature name `type` is a Rust keyword"),
            "{joined}"
        );
        assert!(joined.contains("events[0].name"), "{joined}");
        assert!(joined.contains("events[0].fields[0].type"), "{joined}");
    }

    #[test]
    fn flags_win_over_json() {
        let arguments = Arguments::parse(
            [
                "bloc",
                "Notes",
                "--kind",
                "cubit",
                "--event",
                "NoteAdded:title:String,tags:Vec<String>",
            ]
            .into_iter()
            .map(String::from),
        );
        let mut spec =
            from_json(r#"{"feature": "notes", "kind": "bloc", "events": [{"name": "Old"}]}"#)
                .unwrap();
        apply_flags(&mut spec, "bloc", Some("Notes"), &arguments).unwrap();
        assert_eq!(spec.kind, Some(Kind::Cubit));
        assert_eq!(spec.events.len(), 1);
        assert_eq!(spec.events[0].name, "NoteAdded");
        assert_eq!(spec.events[0].fields[1].ty, "Vec<String>");
    }

    #[test]
    fn endpoints_parse_from_flags() {
        let endpoint = parse_endpoint("get_note:get:/notes/{id:NoteId}:NoteDto", true).unwrap();
        assert_eq!(endpoint.verb, "GET");
        assert_eq!(endpoint.path, "/notes/{id}");
        assert_eq!(endpoint.path_params[0].name, "id");
        assert_eq!(endpoint.path_params[0].ty, "NoteId");
        assert!(endpoint.skip_expire);
        let endpoint = parse_endpoint("list:GET:/notes:Vec<NoteDto>", false).unwrap();
        assert_eq!(endpoint.response, "Vec<NoteDto>");
        assert!(parse_endpoint("get_note:GET", false).is_err());
    }

    #[test]
    fn the_schema_describes_every_key() {
        let schema = spec::schema();
        let properties = schema["properties"].as_object().unwrap();
        for key in [
            "feature",
            "kind",
            "events",
            "state",
            "repository",
            "provider",
            "dtos",
            "view",
        ] {
            assert!(properties.contains_key(key), "{key}");
        }
        assert_eq!(
            schema["additionalProperties"],
            serde_json::Value::Bool(false)
        );
    }
}