xecute-cli 0.1.21

Project and resource scaffolding for Axum applications with Xecute tools
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
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
use crate::manifest::WorkerBroker;
use std::{
    fs,
    path::{Path, PathBuf},
    process::Command,
};

type Result<T> = std::result::Result<T, String>;

// Repository-wide settings are emitted once, at the workspace root.
const WORKSPACE_FILES: &[(&str, &str)] = &[
    (
        "rust-toolchain.toml",
        include_str!("../templates/rust-toolchain.toml"),
    ),
    ("rustfmt.toml", include_str!("../templates/rustfmt.toml")),
    ("clippy.toml", include_str!("../templates/clippy.toml")),
    ("deny.toml", include_str!("../templates/deny.toml")),
    (".editorconfig", include_str!("../templates/editorconfig")),
    (".gitattributes", include_str!("../templates/gitattributes")),
    (".dockerignore", include_str!("../templates/dockerignore")),
    (
        ".github/dependabot.yml",
        include_str!("../templates/dependabot.yml"),
    ),
];

/// Project generation style, persisted for subsequent resource generators.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Architecture {
    Cqrs,
    Mvc,
}

impl Architecture {
    fn name(self) -> &'static str {
        match self {
            Self::Cqrs => "cqrs",
            Self::Mvc => "mvc",
        }
    }

    pub(crate) fn read(root: &Path) -> Result<Self> {
        match fs::read_to_string(root.join(".xecute/architecture")) {
            Ok(value) => match value.trim() {
                "cqrs" => Ok(Self::Cqrs),
                "mvc" => Ok(Self::Mvc),
                _ => Err(
                    "invalid .xecute/architecture: expected cqrs or mvc; no files changed".into(),
                ),
            },
            // Projects created before architecture selection retain their service layout.
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Self::Mvc),
            Err(error) => Err(format!("cannot read .xecute/architecture: {error}")),
        }
    }
}

pub(crate) fn names(input: &str) -> Result<(String, String)> {
    if input.is_empty()
        || !input
            .bytes()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-' || c == b'_')
        || !input.as_bytes()[0].is_ascii_lowercase()
    {
        return Err(
            "use a lowercase name starting with a letter, such as user or user-profile".into(),
        );
    }
    let snake = input.replace('-', "_");
    if snake.split('_').any(str::is_empty)
        || matches!(
            snake.as_str(),
            "self"
                | "super"
                | "crate"
                | "mod"
                | "type"
                | "fn"
                | "pub"
                | "use"
                | "impl"
                | "struct"
                | "enum"
                | "trait"
                | "async"
                | "await"
                | "loop"
                | "match"
                | "move"
                | "ref"
                | "let"
                | "const"
                | "static"
                | "where"
                | "in"
                | "for"
                | "if"
                | "else"
                | "return"
                | "break"
                | "continue"
                | "true"
                | "false"
                | "unsafe"
                | "extern"
                | "dyn"
                | "as"
                | "mut"
                | "while"
                | "union"
                | "abstract"
                | "become"
                | "box"
                | "do"
                | "final"
                | "macro"
                | "override"
                | "priv"
                | "typeof"
                | "unsized"
                | "virtual"
                | "yield"
                | "try"
                | "gen"
        )
    {
        return Err("name must be a valid non-keyword Rust module name".into());
    }
    let pascal = snake
        .split('_')
        .map(|s| format!("{}{}", s[..1].to_uppercase(), &s[1..]))
        .collect();
    Ok((snake, pascal))
}

fn write(path: &Path, content: &str) -> Result<()> {
    fs::write(path, content).map_err(|e| format!("{}: {e}", path.display()))
}

pub(crate) fn format_files(root: &Path, paths: &[String]) -> Result<()> {
    let status = Command::new("rustfmt")
        .current_dir(root)
        .args(["--edition", "2024", "--config", "skip_children=true"])
        .args(paths)
        .status()
        .map_err(|error| {
            format!("files generated but formatting failed: {error}; run cargo fmt")
        })?;
    if !status.success() {
        return Err("files generated but formatting failed; run cargo fmt".into());
    }
    Ok(())
}

fn update_manifest<F>(
    root: &Path,
    inherit_dependencies: bool,
    update: F,
    message: &str,
) -> Result<()>
where
    F: Fn(&str) -> std::result::Result<String, String>,
{
    let manifest_path = root.join("Cargo.toml");
    if !manifest_path.exists() {
        return Ok(());
    }
    let before = fs::read_to_string(&manifest_path).map_err(|e| e.to_string())?;
    let manifest = update(&before)?;
    let workspace_root = root
        .ancestors()
        .skip(1)
        .filter(|_| inherit_dependencies)
        .find(|parent| parent.join(".xecute/workspace").is_file());
    let manifest = if let Some(workspace_root) = workspace_root {
        let workspace_path = workspace_root.join("Cargo.toml");
        let before_workspace = fs::read_to_string(&workspace_path).map_err(|e| e.to_string())?;
        let (manifest, workspace) =
            crate::manifest::workspace_dependencies(&manifest, &before_workspace, false)?;
        if workspace != before_workspace {
            write(&workspace_path, &workspace)?;
        }
        manifest
    } else {
        manifest
    };
    if before != manifest {
        write(&manifest_path, &manifest)?;
        println!("{message}");
    }
    Ok(())
}

pub fn new_project(
    destination: &str,
    runtime: Option<&Path>,
    architecture: Architecture,
    name_override: Option<&str>,
) -> Result<()> {
    scaffold(destination, runtime, architecture, name_override, false)
}

fn scaffold(
    destination: &str,
    runtime: Option<&Path>,
    architecture: Architecture,
    name_override: Option<&str>,
    member: bool,
) -> Result<()> {
    let in_place = destination == ".";
    let root = if in_place {
        std::env::current_dir().map_err(|e| e.to_string())?
    } else {
        if !member {
            names(destination)?;
        }
        PathBuf::from(destination)
    };
    let derived_name = if in_place {
        root.file_name()
            .and_then(|name| name.to_str())
            .unwrap_or("")
            .to_owned()
    } else {
        destination.to_owned()
    };
    let name = name_override.unwrap_or(&derived_name);
    names(name).map_err(|error| {
        format!("{error}; use --name <project-name> to choose the package name")
    })?;
    if !in_place && root.exists() {
        return Err(format!(
            "{} already exists; use xecute new . inside that directory",
            root.display()
        ));
    }
    let dependency = if let Some(runtime) = runtime {
        let runtime = runtime
            .canonicalize()
            .map_err(|e| format!("runtime path: {e}; supply --runtime-path"))?;
        if !runtime.join("Cargo.toml").is_file() {
            return Err("runtime path must contain xecute/Cargo.toml".into());
        }
        let runtime = runtime
            .to_str()
            .ok_or("runtime path must be UTF-8")?
            .replace('\\', "\\\\")
            .replace('"', "\\\"");
        format!("xecute = {{ path = \"{runtime}\" }}")
    } else {
        "xecute = { version = \"0.1.10\" }".to_owned()
    };
    let test_dependency = crate::manifest::testing_dependency(&dependency)?;
    let templates = [
        (
            "src/tests/versions.rs",
            include_str!("../templates/tests/versions.rs"),
        ),
        (
            "src/server/versions.rs",
            include_str!("../templates/server/versions.rs"),
        ),
        ("src/modules/mod.rs", "//! Application feature modules.\n"),
        (
            "src/tests/application.rs",
            include_str!("../templates/tests/application.rs"),
        ),
        (
            "src/tests/static_files.rs",
            include_str!("../templates/tests/static_files.rs"),
        ),
        (
            "src/configs/static_files.rs",
            include_str!("../templates/configs/static_files.rs"),
        ),
        (
            "src/server/static_files.rs",
            include_str!("../templates/server/static_files.rs"),
        ),
        (
            "public/index.html",
            "<!doctype html><html lang=\"en\"><meta charset=\"utf-8\"><title>Xecute static files</title><h1>Static file serving is working</h1><p>Edit public/index.html or add files to public/.</p><a href=\"/static/hello.txt\">Example text file</a></html>\n",
        ),
        ("public/hello.txt", "Static file serving is working.\n"),
        ("src/main.rs", include_str!("../templates/main.rs")),
        (
            "src/middleware.rs",
            include_str!("../templates/middleware.rs"),
        ),
        (
            "src/tests/docs.rs",
            include_str!("../templates/tests/docs.rs"),
        ),
        (
            "src/configs/docs.rs",
            include_str!("../templates/configs/docs.rs"),
        ),
        (
            "src/server/docs.rs",
            include_str!("../templates/server/docs.rs"),
        ),
        (
            "src/configs/environment.rs",
            include_str!("../templates/configs/environment.rs"),
        ),
        (
            "src/configs/mod.rs",
            include_str!("../templates/configs/mod.rs"),
        ),
        (
            "src/configs/server.rs",
            include_str!("../templates/configs/server.rs"),
        ),
        (
            "src/server/mod.rs",
            include_str!("../templates/server/mod.rs"),
        ),
        (
            "src/server/bootstrap.rs",
            include_str!("../templates/server/bootstrap.rs"),
        ),
        (
            "src/server/error.rs",
            include_str!("../templates/server/error.rs"),
        ),
        (
            "src/server/health.rs",
            include_str!("../templates/server/health.rs"),
        ),
        (
            "src/server/rate_limit.rs",
            include_str!("../templates/server/rate_limit.rs"),
        ),
        (
            "src/server/router.rs",
            include_str!("../templates/server/router.rs"),
        ),
        (
            "src/server/shutdown.rs",
            include_str!("../templates/server/shutdown.rs"),
        ),
        (
            "src/server/logging.rs",
            include_str!("../templates/server/logging.rs"),
        ),
        (
            "src/server/middleware/mod.rs",
            include_str!("../templates/server/middleware/mod.rs"),
        ),
        (
            "src/server/middleware/guard.rs",
            include_str!("../templates/server/middleware/guard.rs"),
        ),
        (
            "src/server/middleware/request_log.rs",
            include_str!("../templates/server/middleware/request_log.rs"),
        ),
        (
            "src/server/middleware/response.rs",
            include_str!("../templates/server/middleware/response.rs"),
        ),
        (
            "src/tests/mod.rs",
            include_str!("../templates/tests/mod.rs"),
        ),
        (
            "src/tests/config.rs",
            include_str!("../templates/tests/config.rs"),
        ),
        (
            "src/tests/logging.rs",
            include_str!("../templates/tests/logging.rs"),
        ),
        (
            "src/tests/rate_limit.rs",
            include_str!("../templates/tests/rate_limit.rs"),
        ),
        (
            "src/tests/server.rs",
            include_str!("../templates/tests/server.rs"),
        ),
        (
            "src/tests/support.rs",
            include_str!("../templates/tests/support.rs"),
        ),
        (
            "src/configs/logging.rs",
            include_str!("../templates/configs/logging.rs"),
        ),
        (
            "src/configs/cors.rs",
            include_str!("../templates/configs/cors.rs"),
        ),
        (".env.example", include_str!("../templates/env.example")),
        (
            "config/AppConfig.toml",
            include_str!("../templates/config/AppConfig.toml"),
        ),
        (
            "rust-toolchain.toml",
            include_str!("../templates/rust-toolchain.toml"),
        ),
        ("rustfmt.toml", include_str!("../templates/rustfmt.toml")),
        ("clippy.toml", include_str!("../templates/clippy.toml")),
        (".editorconfig", include_str!("../templates/editorconfig")),
        (".dockerignore", include_str!("../templates/dockerignore")),
        ("Dockerfile", include_str!("../templates/Dockerfile")),
        (
            ".github/workflows/ci.yml",
            include_str!("../templates/ci.yml"),
        ),
        ("deny.toml", include_str!("../templates/deny.toml")),
        (".gitattributes", include_str!("../templates/gitattributes")),
        (
            ".github/dependabot.yml",
            include_str!("../templates/dependabot.yml"),
        ),
    ];
    if in_place {
        let mut outputs: Vec<&str> = templates.iter().map(|(path, _)| *path).collect();
        outputs.extend([
            "Cargo.toml",
            ".xecute",
            ".gitignore",
            "README.md",
            "src/app_module.rs",
            "src/modules/example",
            "src/modules/mod.rs",
        ]);
        outputs.push("Cargo.lock");
        // Validate every destination before writing anything. Symlinked parents
        // are rejected so initialization cannot write outside the chosen root.
        for output in outputs {
            let path = root.join(output);
            if path.symlink_metadata().is_ok() {
                return Err(format!(
                    "{} already exists; no files changed",
                    path.display()
                ));
            }
            let mut parent = path.parent();
            while let Some(path) = parent.filter(|path| *path != root) {
                if let Ok(metadata) = path.symlink_metadata()
                    && (!metadata.is_dir() || metadata.file_type().is_symlink())
                {
                    return Err(format!(
                        "{} must be a real directory; no files changed",
                        path.display()
                    ));
                }
                parent = path.parent();
            }
        }
    }
    fs::create_dir_all(root.join("src")).map_err(|e| e.to_string())?;
    let manifest = include_str!("../templates/Cargo.toml.in")
        .replace("__PROJECT_NAME__", name)
        .replace("__RUNTIME_DEPENDENCY__", &dependency)
        .replace("__RUNTIME_TEST_DEPENDENCY__", &test_dependency);
    let manifest = if member {
        let mut doc = manifest
            .parse::<toml_edit::DocumentMut>()
            .map_err(|e| e.to_string())?;
        doc.remove("workspace");
        doc.remove("profile");
        doc.to_string()
    } else {
        manifest
    };
    write(&root.join("Cargo.toml"), &manifest)?;
    fs::create_dir(root.join(".xecute")).map_err(|e| e.to_string())?;
    write(
        &root.join(".xecute/architecture"),
        &format!("{}\n", architecture.name()),
    )?;
    if !member {
        write(
            &root.join(".gitignore"),
            "/target/\n.env\n.env.*\n!.env.example\n/logs/\n/storage/\n",
        )?;
    }
    let mut formatted = Vec::new();
    for (path, template) in templates {
        if member
            && (path.starts_with(".github/")
                || WORKSPACE_FILES.iter().any(|(shared, _)| *shared == path))
        {
            continue;
        }
        if path.ends_with(".rs") {
            formatted.push(path.to_owned());
        }
        let path = root.join(path);
        fs::create_dir_all(path.parent().expect("template parent")).map_err(|e| e.to_string())?;
        write(&path, &template.replace("__PROJECT_NAME__", name))?;
    }
    write(
        &root.join("src/app_module.rs"),
        include_str!("../templates/app_module.rs"),
    )?;
    write(
        &root.join("README.md"),
        &include_str!("../templates/readme.md")
            .replace("__PROJECT_NAME__", name)
            .replace("__ARCHITECTURE__", architecture.name()),
    )?;
    formatted.push("src/app_module.rs".into());
    format_files(&root, &formatted)?;
    component_inner(&root, "resource", "example", !member, None)?;
    if member {
        println!("Created {name} ({})", architecture.name());
        return Ok(());
    }
    resolve_project_dependencies(&root)?;
    let cd = if in_place {
        String::new()
    } else {
        format!("  cd {destination}\n")
    };
    println!(
        "Created {name} ({})\n{cd}  xecute run dev\n  Swagger: http://127.0.0.1:3000/docs/",
        architecture.name()
    );
    Ok(())
}

/// Resolve from the registry at setup time rather than shipping an aging lockfile.
fn resolve_project_dependencies(root: &Path) -> Result<()> {
    println!("Resolving latest compatible dependencies...");
    let status = Command::new("cargo")
        .arg("generate-lockfile")
        .current_dir(root)
        .status()
        .map_err(|error| format!(
            "project files created, but dependency resolution could not start: {error}; run cargo generate-lockfile in {}",
            root.display()
        ))?;
    if !status.success() {
        return Err(format!(
            "project files created, but dependency resolution failed; check registry/network access and run cargo generate-lockfile in {}",
            root.display()
        ));
    }
    Ok(())
}

/// Create a Cargo workspace with an initial application named after the project.
pub fn new_workspace(
    destination: &str,
    runtime: Option<&Path>,
    architecture: Architecture,
    name_override: Option<&str>,
) -> Result<()> {
    let root = if destination == "." {
        std::env::current_dir().map_err(|e| e.to_string())?
    } else {
        names(destination)?;
        let root = PathBuf::from(destination);
        if root.exists() {
            return Err("destination already exists; no files changed".into());
        }
        root
    };
    let name = name_override
        .or_else(|| root.file_name().and_then(|s| s.to_str()))
        .ok_or("use --name to choose the initial app name")?;
    names(name)?;
    // Check all owned destinations before creating anything in an existing directory.
    for entry in [
        "Cargo.toml",
        "Cargo.lock",
        "apps",
        ".xecute",
        "README.md",
        ".gitignore",
        ".github",
        "rust-toolchain.toml",
        "rustfmt.toml",
        "clippy.toml",
        "deny.toml",
        ".editorconfig",
        ".gitattributes",
        ".dockerignore",
    ] {
        if root.join(entry).symlink_metadata().is_ok() {
            return Err(format!("{entry} already exists; no files changed"));
        }
    }
    let runtime = runtime
        .map(|p| p.canonicalize().map_err(|e| e.to_string()))
        .transpose()?;
    if runtime
        .as_ref()
        .is_some_and(|p| !p.join("Cargo.toml").is_file())
    {
        return Err("runtime path must contain xecute/Cargo.toml".into());
    }
    fs::create_dir_all(root.join(".xecute")).map_err(|e| e.to_string())?;
    write(&root.join(".xecute/workspace"), "1\n")?;
    write(&root.join(".xecute/architecture"), architecture.name())?;
    if let Some(runtime) = &runtime {
        write(
            &root.join(".xecute/runtime-path"),
            runtime.to_str().ok_or("runtime path must be UTF-8")?,
        )?;
    }
    write(
        &root.join("Cargo.toml"),
        "[workspace]\nmembers = [\"apps/*\"]\nresolver = \"3\"\n\n[profile.release]\nlto = \"thin\"\ncodegen-units = 1\nstrip = \"symbols\"\n",
    )?;
    write(
        &root.join(".gitignore"),
        "/target/\n.env\n.env.*\n!.env.example\n**/logs/\n**/storage/\n",
    )?;
    write(
        &root.join("README.md"),
        &format!(
            "# {name}\n\nAdd an application: `xecute g apps <app_name> [--mvc | --cqrs]`\n\nAdd a shared library: `xecute g library <library_name>`\n\nRun an application: `cd apps/{name} && xecute run dev`\n\nBuild all applications: `cargo build --workspace`\n"
        ),
    )?;
    add_app(&root, name, Some(architecture), runtime.as_deref())?;
    for (file, template) in WORKSPACE_FILES {
        let path = root.join(file);
        fs::create_dir_all(path.parent().expect("workspace file parent"))
            .map_err(|e| e.to_string())?;
        write(&path, template)?;
    }
    fs::create_dir_all(root.join(".github/workflows")).map_err(|e| e.to_string())?;
    if !root.join(".github/workflows/ci.yml").exists() {
        write(
            &root.join(".github/workflows/ci.yml"),
            "name: CI\non: [push, pull_request]\npermissions:\n  contents: read\njobs:\n  check:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n      - run: rustup show active-toolchain\n      - run: cargo fmt --all -- --check\n      - run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings\n      - run: cargo test --workspace --all-targets --all-features --locked\n",
        )?;
    }
    Ok(())
}

/// Add an application to a Xecute workspace, inheriting its architecture by default.
pub fn add_app(
    root: &Path,
    name: &str,
    architecture: Option<Architecture>,
    runtime: Option<&Path>,
) -> Result<()> {
    names(name)?;
    if !root.join(".xecute/workspace").is_file() {
        return Err(
            "run xecute g apps from a workspace created with xecute new --workspace".into(),
        );
    }
    let manifest = fs::read_to_string(root.join("Cargo.toml")).map_err(|e| e.to_string())?;
    let manifest = manifest
        .parse::<toml_edit::DocumentMut>()
        .map_err(|e| e.to_string())?;
    let members = manifest
        .get("workspace")
        .and_then(|w| w.get("members"))
        .and_then(toml_edit::Item::as_array)
        .ok_or("workspace manifest must contain members = [\"apps/*\"]")?;
    if !members
        .iter()
        .any(|member| member.as_str() == Some("apps/*"))
    {
        return Err("workspace members must include apps/*; no files changed".into());
    }
    let architecture = match architecture {
        Some(architecture) => architecture,
        None => Architecture::read(root)?,
    };
    let runtime_override = runtime.is_some();
    let inherited = match fs::read_to_string(root.join(".xecute/runtime-path")) {
        Ok(path) => Some(PathBuf::from(path.trim())),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
        Err(error) => return Err(format!("cannot read workspace runtime path: {error}")),
    };
    let runtime = runtime.or(inherited.as_deref());
    let apps = root.join("apps");
    if apps
        .symlink_metadata()
        .is_ok_and(|m| m.file_type().is_symlink() || !m.is_dir())
    {
        return Err("apps must be a real directory; no files changed".into());
    }
    let destination = apps.join(name);
    if destination.symlink_metadata().is_ok() {
        return Err("app already exists; no files changed".into());
    }
    fs::create_dir_all(&apps).map_err(|e| e.to_string())?;
    scaffold(
        destination.to_str().ok_or("app path must be UTF-8")?,
        runtime,
        architecture,
        Some(name),
        true,
    )?;
    centralize_dependencies(&destination, root, runtime_override)?;
    if runtime_override {
        let runtime = runtime
            .expect("explicit runtime")
            .canonicalize()
            .map_err(|e| e.to_string())?;
        write(
            &root.join(".xecute/runtime-path"),
            runtime.to_str().ok_or("runtime path must be UTF-8")?,
        )?;
    }
    let docker = fs::read_to_string(destination.join("Dockerfile"))
        .map_err(|e| e.to_string())?
        .replace("COPY src ./src", "COPY . .")
        .replace(
            "COPY public ./public",
            &format!("COPY apps/{name}/public ./public"),
        )
        .replace(
            "COPY config ./config",
            &format!("COPY apps/{name}/config ./config"),
        )
        .replace(
            "cargo build --release",
            &format!("cargo build -p {name} --release"),
        );
    write(&destination.join("Dockerfile"), &docker)?;
    // Resolve the new member while retaining existing dependency versions.
    let status = Command::new("cargo")
        .args(["metadata", "--format-version", "1"])
        .stdout(std::process::Stdio::null())
        .current_dir(root)
        .status()
        .map_err(|e| e.to_string())?;
    if !status.success() {
        return Err(
            "app created, but workspace lockfile generation failed; run cargo generate-lockfile"
                .into(),
        );
    }
    println!(
        "Workspace app ready: {} ({}). Run from workspace root: docker build -f apps/{name}/Dockerfile .",
        destination.display(),
        architecture.name()
    );
    Ok(())
}

fn centralize_dependencies(app: &Path, root: &Path, runtime_override: bool) -> Result<()> {
    let app_path = app.join("Cargo.toml");
    let root_path = root.join("Cargo.toml");
    let app_manifest = fs::read_to_string(&app_path).map_err(|e| e.to_string())?;
    let root_manifest = fs::read_to_string(&root_path).map_err(|e| e.to_string())?;
    let (app_manifest, root_manifest) =
        crate::manifest::workspace_dependencies(&app_manifest, &root_manifest, runtime_override)?;
    write(&root_path, &root_manifest)?;
    write(&app_path, &app_manifest)
}

pub fn component(root: &Path, kind: &str, name: &str) -> Result<()> {
    component_inner(root, kind, name, true, None)
}

/// Generate a worker, optionally backed by a distributed broker transport.
pub(crate) fn worker(root: &Path, name: &str, broker: Option<WorkerBroker>) -> Result<()> {
    component_inner(root, "worker", name, true, broker)
}

fn component_inner(
    root: &Path,
    kind: &str,
    name: &str,
    inherit_dependencies: bool,
    broker: Option<WorkerBroker>,
) -> Result<()> {
    let kind = match kind {
        "resource" | "res" => "resource",
        "module" | "mo" => "module",
        "controller" | "co" => "controller",
        "service" | "s" => "service",
        "worker" | "wo" => "worker",
        _ => {
            return Err(
                "generator must be resource, module, controller, service, or worker".into(),
            );
        }
    };
    let architecture = Architecture::read(root)?;
    let cqrs = kind == "resource" && architecture == Architecture::Cqrs;
    let (snake, pascal) = names(name)?;
    if matches!(
        snake.as_str(),
        "app_module" | "main" | "middleware" | "modules"
    ) {
        return Err("name conflicts with application files".into());
    }
    let main_path = root.join("src/main.rs");
    let app_path = root.join("src/app_module.rs");
    let mut main =
        fs::read_to_string(&main_path).map_err(|_| "run generate from a Xecute project root")?;
    let mut app = fs::read_to_string(&app_path).map_err(|_| "missing src/app_module.rs")?;
    if kind == "worker" && !app.contains("initialize_async") {
        return Err(
            "worker generation requires async container initialization; regenerate the app with this CLI or update src/app_module.rs to call initialize_async"
                .into(),
        );
    }
    let modules = root.join("src/modules");
    if let Ok(metadata) = modules.symlink_metadata()
        && (!metadata.is_dir() || metadata.file_type().is_symlink())
    {
        return Err("src/modules must be a real directory; no files changed".into());
    }
    let index = modules.join("mod.rs");
    if index
        .symlink_metadata()
        .is_ok_and(|metadata| metadata.file_type().is_symlink())
    {
        return Err("src/modules/mod.rs must not be a symlink; no files changed".into());
    }
    let mut index_content = match fs::read_to_string(&index) {
        Ok(content) => content,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            "//! Application feature modules.\n\n".into()
        }
        Err(error) => return Err(format!("cannot read src/modules/mod.rs: {error}")),
    };
    let folder = modules.join(&snake);
    if folder.exists() || root.join("src").join(&snake).exists() {
        return Err(format!(
            "{} already exists; no files changed",
            folder.display()
        ));
    }
    if kind == "resource" && root.join(format!("src/tests/{snake}.rs")).exists() {
        return Err("resource test already exists; no files changed".into());
    }
    let markers = [
        "// xecute:modules",
        "// xecute:imports",
        "// xecute:definitions",
        "// xecute:routes",
    ];
    if markers.iter().any(|m| app.matches(m).count() != 1) {
        return Err(
            "app_module.rs must have the registration markers from xecute new; no files changed"
                .into(),
        );
    }
    if main.contains(&format!("mod {snake};")) {
        return Err("module already declared; no files changed".into());
    }
    let service = if kind == "resource" {
        include_str!("../templates/resource/service.rs")
    } else {
        include_str!("../templates/resource/standalone_service.rs")
    }
    .replace("__TYPE__", &pascal)
    .replace("__FEATURE__", &snake);
    let controller = if cqrs {
        include_str!("../templates/cqrs/controller.rs")
    } else if kind == "resource" {
        include_str!("../templates/resource/controller.rs")
    } else {
        include_str!("../templates/resource/standalone_controller.rs")
    }
    .replace("__TYPE__", &pascal)
    .replace("__FEATURE__", &snake);
    let mut files: Vec<(String, String)> = Vec::new();
    let mut mods = format!("//! Public building blocks for the {snake} feature.\n\n");
    if !cqrs && matches!(kind, "resource" | "service") {
        files.push(("service.rs".into(), service));
        mods.push_str(&format!(
            "mod service;\npub use service::{pascal}Service;\n"
        ));
    }
    if matches!(kind, "resource" | "controller") {
        files.push(("controller.rs".into(), controller));
        mods.push_str(&format!(
            "mod controller;\npub use controller::{pascal}Controller;\n"
        ));
    }
    let worker_broker = if kind == "worker" { broker } else { None };
    if kind == "worker" {
        let job = if worker_broker.is_some() {
            include_str!("../templates/worker/distributed/job.rs")
        } else {
            include_str!("../templates/worker/job.rs")
        };
        files.push((
            "job.rs".into(),
            job.replace("__TYPE__", &pascal)
                .replace("__FEATURE__", &snake),
        ));
        if let Some(broker) = worker_broker {
            let broker_template = match broker {
                WorkerBroker::PostgresOutbox => {
                    include_str!("../templates/worker/distributed/postgres.rs")
                }
                WorkerBroker::RabbitMq => {
                    include_str!("../templates/worker/distributed/rabbitmq.rs")
                }
                WorkerBroker::Nats => include_str!("../templates/worker/distributed/nats.rs"),
            };
            files.push((
                "broker.rs".into(),
                broker_template
                    .replace("__TYPE__", &pascal)
                    .replace("__FEATURE__", &snake),
            ));
            mods.push_str(&format!(
                "mod job;\npub use job::{pascal}Job;\n\nmod broker;\npub use broker::{{{pascal}Queue, {pascal}QueueError}};\n\n"
            ));
        } else {
            mods.push_str(&format!("mod job;\npub use job::{pascal}Job;\n\n"));
        }
    }
    if matches!(kind, "resource" | "module" | "worker") {
        let module = if kind == "worker" {
            let template = if worker_broker.is_some() {
                include_str!("../templates/worker/distributed/module.rs")
            } else {
                include_str!("../templates/worker/module.rs")
            };
            template
                .replace("__TYPE__", &pascal)
                .replace("__FEATURE__", &snake)
        } else if cqrs {
            include_str!("../templates/cqrs/module.rs").replace("__TYPE__", &pascal)
        } else if kind == "resource" {
            include_str!("../templates/resource/module.rs").replace("__TYPE__", &pascal)
        } else {
            format!(
                "//! Dependency-injection boundary for the {snake} feature.\n//! Add injectable services and controllers to providers as the feature grows.\n\nuse xecute::module;\n\n/// Dependency-injection module.\n#[module(providers = [])]\npub struct {pascal}Module;\n"
            )
        };
        files.push(("module.rs".into(), module));
        mods.push_str(&format!("mod module;\npub use module::{pascal}Module;\n"));
        app = app
            .replace(
                markers[0],
                &format!(
                    "use crate::modules::{snake}::{pascal}Module;\n{}",
                    markers[0]
                ),
            )
            .replace(markers[1], &format!("{pascal}Module,\n    {}", markers[1]))
            .replace(
                markers[2],
                &format!("{pascal}Module::definition(),\n            {}", markers[2]),
            );
        if kind == "resource" {
            if app.contains("// xecute:api") {
                app = app.replace("// xecute:api", &format!("let operations = operations.into_iter().chain(crate::modules::{snake}::{pascal}Controller::api_operations()).collect::<Vec<_>>();\n        // xecute:api"));
            }
            let controller_container = if app.contains("fn router_with_container(") {
                "container.clone()"
            } else {
                "::std::sync::Arc::new(container.clone())"
            };
            app = app.replace(markers[3], &format!("let router = router.merge(crate::modules::{snake}::{pascal}Module::scoped_router({controller_container}));\n        {}", markers[3]));
        }
    }
    if kind == "resource" {
        for (name, template) in [
            ("dto/mod.rs", include_str!("../templates/resource/dto.rs")),
            (
                "entity/mod.rs",
                include_str!("../templates/resource/entity.rs"),
            ),
            (
                "repository/store.rs",
                include_str!("../templates/resource/repository.rs"),
            ),
        ] {
            files.push((
                name.into(),
                template
                    .replace("__TYPE__", &pascal)
                    .replace("__FEATURE__", &snake),
            ));
        }
        files.push(("repository/mod.rs".into(), format!("//! Persistence adapters for this feature.\n\nmod store;\npub use store::{{{pascal}Repository, CapacityExceeded}};\n")));
        mods.push_str("\npub mod dto;\npub mod entity;\npub mod repository;\n");
    }
    if cqrs {
        for (path, template) in [
            (
                "commands/create.rs",
                include_str!("../templates/cqrs/create.rs"),
            ),
            ("queries/list.rs", include_str!("../templates/cqrs/list.rs")),
        ] {
            files.push((path.into(), template.replace("__TYPE__", &pascal)));
        }
        files.push(("commands/mod.rs".into(), format!("//! Write operations.\nmod create;\npub use create::{{Create{pascal}Command, Create{pascal}Handler}};\n")));
        files.push(("queries/mod.rs".into(), format!("//! Read operations.\nmod list;\npub use list::{{List{pascal}Query, List{pascal}Handler}};\n")));
        mods.push_str("\npub mod commands;\npub mod queries;\n");
    }
    if kind == "resource" {
        files.push((
            "tests/http.rs".into(),
            include_str!("../templates/resource/tests.rs").replace("__FEATURE__", &snake),
        ));
        files.push((
            "tests/mod.rs".into(),
            "//! Feature HTTP integration tests.\nmod http;\n".into(),
        ));
        mods.push_str("\n#[cfg(test)]\nmod tests;\n");
    }
    files.push(("mod.rs".into(), mods));
    if index_content.contains(&format!("mod {snake};")) {
        return Err("module already declared in src/modules/mod.rs; no files changed".into());
    }
    index_content.push_str(&format!("pub mod {snake};\n"));
    let declaration = "pub mod modules;\n";
    if !main.contains("mod modules;") {
        if let Some(index) = main
            .find("pub mod app_module;")
            .or_else(|| main.find("mod app_module;"))
        {
            main.insert_str(index, declaration);
        } else {
            main.push_str(&format!("\n{declaration}"));
        }
    }
    if kind == "resource" {
        update_manifest(
            root,
            inherit_dependencies,
            crate::manifest::resource_dependencies,
            "Updated resource dependencies; cargo build will refresh Cargo.lock.",
        )?;
    }
    if kind == "worker" {
        update_manifest(
            root,
            inherit_dependencies,
            |manifest| crate::manifest::worker_dependencies(manifest, broker),
            "Updated worker dependencies; cargo build will refresh Cargo.lock.",
        )?;
    }
    fs::create_dir_all(&folder).map_err(|e| e.to_string())?;
    let mut formatted = vec![
        "src/main.rs".into(),
        "src/app_module.rs".into(),
        "src/modules/mod.rs".into(),
    ];
    for (name, content) in files {
        formatted.push(format!("src/modules/{snake}/{name}"));
        let path = folder.join(name);
        fs::create_dir_all(path.parent().unwrap()).map_err(|e| e.to_string())?;
        write(&path, &content)?;
    }
    write(&index, &index_content)?;
    write(&main_path, &main)?;
    write(&app_path, &app)?;
    format_files(root, &formatted)?;
    println!("Created {kind} {pascal} in src/modules/{snake}");
    if matches!(kind, "service" | "controller") {
        println!("Add this building block to a module's providers when ready to use it.");
    }
    if kind == "worker" {
        if let Some(broker) = worker_broker {
            match broker {
                WorkerBroker::PostgresOutbox => println!(
                    "Distributed worker uses {} storage; set DATABASE_URL before startup.",
                    broker.name()
                ),
                WorkerBroker::RabbitMq => println!(
                    "Distributed worker uses {}; set RABBITMQ_URL to override amqp://127.0.0.1:5672/%2f.",
                    broker.name()
                ),
                WorkerBroker::Nats => println!(
                    "Distributed worker uses {} (at-most-once); set NATS_URL to override nats://127.0.0.1:4222.",
                    broker.name()
                ),
            }
            println!("Inject Arc<{pascal}Queue> from a module that imports {pascal}Module.");
        } else {
            println!(
                "Inject Arc<JobQueue<{pascal}Job>> from a module that imports {pascal}Module."
            );
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn names_reject_paths_and_keywords() {
        for name in ["../user", "user/name", "mod", "user__name", "1user"] {
            assert!(names(name).is_err());
        }
        assert_eq!(
            names("user-profile").unwrap(),
            ("user_profile".into(), "UserProfile".into())
        );
    }
    #[test]
    fn resource_registers_and_duplicate_preserves_files() {
        let root = std::env::temp_dir().join(format!("xecute-cli-test-{}", std::process::id()));
        fs::create_dir_all(root.join("src")).unwrap();
        write(&root.join("src/main.rs"), "mod app_module;\n").unwrap();
        write(
            &root.join("src/app_module.rs"),
            include_str!("../templates/app_module.rs"),
        )
        .unwrap();
        component(&root, "res", "user").unwrap();
        let before = fs::read_to_string(root.join("src/app_module.rs")).unwrap();
        assert!(before.contains("UserModule::scoped_router"));
        assert!(component(&root, "res", "user").is_err());
        assert_eq!(
            before,
            fs::read_to_string(root.join("src/app_module.rs")).unwrap()
        );
        fs::remove_dir_all(root).unwrap();
    }
    #[test]
    fn standalone_module_uses_the_generated_macro_import() {
        let root =
            std::env::temp_dir().join(format!("xecute-cli-module-test-{}", std::process::id()));
        fs::create_dir_all(root.join("src")).unwrap();
        write(&root.join("src/main.rs"), "mod app_module;\n").unwrap();
        write(
            &root.join("src/app_module.rs"),
            include_str!("../templates/app_module.rs"),
        )
        .unwrap();
        component(&root, "module", "billing").unwrap();
        let module = fs::read_to_string(root.join("src/modules/billing/module.rs")).unwrap();
        assert!(module.contains("use xecute::module;"));
        fs::remove_dir_all(root).unwrap();
    }
    #[test]
    fn distributed_worker_generates_selected_broker_transport() {
        for (broker, marker, dependency) in [
            (WorkerBroker::PostgresOutbox, "xecute_email_jobs", None),
            (WorkerBroker::RabbitMq, "basic_publish", Some("lapin")),
            (WorkerBroker::Nats, "queue_subscribe", Some("async-nats")),
        ] {
            let root = std::env::temp_dir().join(format!(
                "xecute-cli-distributed-{}-{}",
                broker.name(),
                std::process::id()
            ));
            fs::create_dir_all(root.join("src")).unwrap();
            write(&root.join("src/main.rs"), "mod app_module;\n").unwrap();
            write(
                &root.join("src/app_module.rs"),
                include_str!("../templates/app_module.rs"),
            )
            .unwrap();
            write(
                &root.join("Cargo.toml"),
                "[package]\nname = \"example\"\nversion = \"0.0.0\"\nedition = \"2024\"\n\n[dependencies]\nxecute = \"0.1.10\"\n",
            )
            .unwrap();
            worker(&root, "email", Some(broker)).unwrap();
            let app = fs::read_to_string(root.join("src/app_module.rs")).unwrap();
            assert!(app.contains("EmailModule::definition()"));
            assert!(!app.contains("EmailModule::scoped_router"));
            let job = fs::read_to_string(root.join("src/modules/email/job.rs")).unwrap();
            assert!(job.contains("Serialize"));
            assert!(job.contains("Deserialize"));
            let broker_file = fs::read_to_string(root.join("src/modules/email/broker.rs")).unwrap();
            assert!(broker_file.contains(marker));
            let module = fs::read_to_string(root.join("src/modules/email/module.rs")).unwrap();
            assert!(module.contains("ProviderDefinition::singleton_async"));
            assert!(module.contains(".export::<EmailQueue>()"));
            let module_index = fs::read_to_string(root.join("src/modules/email/mod.rs")).unwrap();
            assert!(module_index.contains("pub use broker::{EmailQueue, EmailQueueError};"));
            let manifest = fs::read_to_string(root.join("Cargo.toml")).unwrap();
            assert!(manifest.contains("\"jobs\""));
            if broker == WorkerBroker::PostgresOutbox {
                assert!(manifest.contains("\"postgres\""));
            }
            if let Some(dependency) = dependency {
                assert!(manifest.contains(dependency));
            }
            assert!(worker(&root, "email", Some(broker)).is_err());
            fs::remove_dir_all(root).unwrap();
        }
    }

    #[test]
    fn worker_registers_queue_and_duplicate_preserves_files() {
        let root =
            std::env::temp_dir().join(format!("xecute-cli-worker-test-{}", std::process::id()));
        fs::create_dir_all(root.join("src")).unwrap();
        write(&root.join("src/main.rs"), "mod app_module;\n").unwrap();
        write(
            &root.join("src/app_module.rs"),
            include_str!("../templates/app_module.rs"),
        )
        .unwrap();
        write(
            &root.join("Cargo.toml"),
            "[package]\nname = \"example\"\nversion = \"0.0.0\"\nedition = \"2024\"\n\n[dependencies]\nxecute = \"0.1.10\"\n",
        )
        .unwrap();
        component(&root, "worker", "email").unwrap();
        let app = fs::read_to_string(root.join("src/app_module.rs")).unwrap();
        assert!(app.contains("use crate::modules::email::EmailModule;"));
        assert!(app.contains("EmailModule,"));
        assert!(app.contains("EmailModule::definition()"));
        assert!(!app.contains("EmailModule::scoped_router"));
        assert!(
            fs::read_to_string(root.join("src/modules/mod.rs"))
                .unwrap()
                .contains("pub mod email;")
        );
        let job = fs::read_to_string(root.join("src/modules/email/job.rs")).unwrap();
        assert!(job.contains("pub struct EmailJob"));
        assert!(job.contains("pub(crate) async fn handle"));
        let module = fs::read_to_string(root.join("src/modules/email/module.rs")).unwrap();
        assert!(module.contains("JobQueue::provider"));
        assert!(module.contains(".export::<JobQueue<EmailJob>>()"));
        let manifest = fs::read_to_string(root.join("Cargo.toml")).unwrap();
        assert!(manifest.contains("\"jobs\""));
        assert!(component(&root, "worker", "email").is_err());
        assert_eq!(
            app,
            fs::read_to_string(root.join("src/app_module.rs")).unwrap()
        );
        fs::remove_dir_all(root).unwrap();
    }
}