cargo-forge 0.2.0

An interactive Rust project generator with templates and common features
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
use crate::external_generators;
use crate::features::ci::CIPlugin;
use crate::features::database::DatabasePlugin;
use crate::features::docker::{DockerBuildStage, DockerPlugin};
use crate::features::{PluginManager, ProjectContext as FeatureContext};
use anyhow::{anyhow, Result};
use std::fs;
use std::path::{Path, PathBuf};

#[derive(Debug, Clone)]
pub struct ProjectConfig {
    pub name: String,
    pub project_type: String,
    pub author: String,
    pub description: Option<String>,
    pub license: Option<String>,
    pub features: Vec<String>,
    pub target: Option<String>,
    pub esp32_chip: Option<String>,
}

pub struct Generator;

/// Escape a value for use inside a basic TOML string (handles the
/// description/author/license free-text fields users type). Control
/// characters become \u escapes so the manifest always stays parseable.
fn toml_escape(value: &str) -> String {
    let mut out = String::with_capacity(value.len());
    for c in value.chars() {
        match c {
            '\\' => out.push_str("\\\\"),
            '"' => out.push_str("\\\""),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if (c as u32) < 0x20 || c as u32 == 0x7f => {
                out.push_str(&format!("\\u{:04X}", c as u32))
            }
            c => out.push(c),
        }
    }
    out
}

impl Generator {
    pub fn new() -> Self {
        Self
    }

    pub fn generate(&self, config: &ProjectConfig, output_dir: &Path) -> Result<()> {
        // For ESP32 projects do not create the directory structure. esp-generate will handle it
        if let Some(target) = &config.target {
            if target == "esp32" {
                if let Some(parent) = output_dir.parent() {
                    if !parent.exists() {
                        fs::create_dir_all(parent)?;
                    }
                }
                // Call esp-generate directory without creating project structure
                return self.generate_embedded(config, output_dir);
            }
        }

        // Create directory if it doesn't exist, but check for conflicts first
        if output_dir.exists() {
            if !output_dir.is_dir() {
                return Err(anyhow!(
                    "Output path exists but is not a directory: {}",
                    output_dir.display()
                ));
            }
            // Directory exists and is a directory - check if it's empty for safety
            if output_dir.read_dir()?.next().is_some() {
                return Err(anyhow!("Directory '{}' is not empty", output_dir.display()));
            }
        } else {
            // Create the directory
            fs::create_dir_all(output_dir)?;
        }

        // Atomic exclusivity: O_EXCL-create a claim file so that exactly one
        // generator wins a directory even under concurrent invocations. The
        // guard removes the claim on every exit path (success, error return,
        // panic unwind); only a hard process kill leaves it behind, and a
        // later run then fails with "not empty" alongside the partial files.
        struct ClaimGuard(PathBuf);
        impl Drop for ClaimGuard {
            fn drop(&mut self) {
                let _ = fs::remove_file(&self.0);
            }
        }
        let claim_path = output_dir.join(".cargo-forge-claim");
        let _claim = match fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&claim_path)
        {
            Ok(_) => ClaimGuard(claim_path.clone()),
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
                return Err(anyhow!(
                    "Directory '{}' is already being generated by another cargo-forge process",
                    output_dir.display()
                ));
            }
            Err(e) => {
                return Err(anyhow!(
                    "Failed to claim generation directory '{}': {}",
                    output_dir.display(),
                    e
                ));
            }
        };

        // The emptiness check above ran BEFORE the claim was taken. Between
        // that check and this point another generator may have completed a
        // full project and released its own claim, so exclusivity requires a
        // second look: once we hold the claim, the directory must hold
        // nothing but the claim file.
        ensure_empty_except_claim(output_dir, &claim_path)?;

        // Reject feature/project-type combinations that cannot compile
        // before writing anything: the database family (sqlx) needs a
        // native binary or library target.
        for feature in &config.features {
            if !feature_supported(feature, &config.project_type) {
                return Err(anyhow!(
                    "Feature '{}' is not supported for '{}' projects",
                    feature,
                    config.project_type
                ));
            }
        }

        // Only create src directory for non-workspace projects
        if config.project_type != "workspace" {
            fs::create_dir_all(output_dir.join("src"))?;
        }

        // Generate files based on project type
        match config.project_type.as_str() {
            "api-server" => self.generate_api_server(config, output_dir)?,
            "cli-tool" => self.generate_cli_tool(config, output_dir)?,
            "library" => self.generate_library(config, output_dir)?,
            "wasm-app" => self.generate_wasm_app(config, output_dir)?,
            "game-engine" => self.generate_game_engine(config, output_dir)?,
            "embedded" => self.generate_embedded(config, output_dir)?,
            "workspace" => self.generate_workspace(config, output_dir)?,
            _ => return Err(anyhow!("Unknown project type: {}", config.project_type)),
        }

        // Create feature context and apply plugins before generating common files
        let mut feature_context = FeatureContext::new(&config.name);
        if !config.features.is_empty() {
            let mut plugin_manager = PluginManager::new();

            // Register plugins based on selected features
            let mut database_registered = false;
            for feature in &config.features {
                match feature.as_str() {
                    "docker" => {
                        let port = match config.project_type.as_str() {
                            "api-server" => Some(3000),
                            "wasm-app" => Some(8080),
                            _ => None,
                        };
                        let mut docker_plugin =
                            DockerPlugin::new().with_build_stage(DockerBuildStage::MultiStage);
                        if let Some(p) = port {
                            docker_plugin = docker_plugin.expose_port(p);
                        }
                        plugin_manager.register(Box::new(docker_plugin));
                    }
                    "ci" | "github-actions" => {
                        use crate::features::ci::CIPlatform;
                        plugin_manager.register(Box::new(CIPlugin::new(CIPlatform::GitHubActions)));
                    }
                    "database" | "postgres" => {
                        use crate::features::database::DatabaseType;
                        if database_registered {
                            eprintln!(
                                "⚠️  Only one database flavor is supported — keeping the first, skipping '{}'.",
                                feature
                            );
                        } else {
                            plugin_manager
                                .register(Box::new(DatabasePlugin::new(DatabaseType::PostgreSQL)));
                            database_registered = true;
                        }
                    }
                    "sqlite" => {
                        use crate::features::database::DatabaseType;
                        if database_registered {
                            eprintln!(
                                "⚠️  Only one database flavor is supported — keeping the first, skipping '{}'.",
                                feature
                            );
                        } else {
                            plugin_manager
                                .register(Box::new(DatabasePlugin::new(DatabaseType::SQLite)));
                            database_registered = true;
                        }
                    }
                    "mysql" => {
                        use crate::features::database::DatabaseType;
                        if database_registered {
                            eprintln!(
                                "⚠️  Only one database flavor is supported — keeping the first, skipping '{}'.",
                                feature
                            );
                        } else {
                            plugin_manager
                                .register(Box::new(DatabasePlugin::new(DatabaseType::MySQL)));
                            database_registered = true;
                        }
                    }
                    _ => {
                        eprintln!(
                            "⚠️  Feature '{}' is not implemented yet — skipping it.",
                            feature
                        );
                    }
                }
            }

            // Apply all plugins
            plugin_manager
                .configure_all(&mut feature_context)
                .map_err(|e| anyhow!("Plugin configuration failed: {}", e))?;
        }

        // Generate common files with feature integration
        self.generate_cargo_toml(config, output_dir, &feature_context)?;
        self.generate_gitignore_with_features(config, output_dir, &feature_context)?;
        self.generate_readme_with_features(config, output_dir, &feature_context)?;

        // Generate feature-specific files
        if !config.features.is_empty() {
            self.generate_feature_files(&feature_context, output_dir)?;
        }

        // Generation complete: the claim guard removes the file on drop.
        drop(_claim);

        Ok(())
    }

    fn generate_feature_files(
        &self,
        feature_context: &FeatureContext,
        output_dir: &Path,
    ) -> Result<()> {
        // Create directories specified by plugins
        for dir in &feature_context.directories {
            fs::create_dir_all(output_dir.join(dir))?;
        }

        // Write template files from plugins
        for (path, content) in &feature_context.template_files {
            let file_path = output_dir.join(path);
            if let Some(parent) = file_path.parent() {
                fs::create_dir_all(parent)?;
            }
            fs::write(&file_path, content)?;

            // Make scripts executable on Unix
            #[cfg(unix)]
            if path.starts_with("scripts/") && path.ends_with(".sh") {
                use std::os::unix::fs::PermissionsExt;
                let mut perms = fs::metadata(&file_path)?.permissions();
                perms.set_mode(0o755);
                fs::set_permissions(&file_path, perms)?;
            }
        }

        Ok(())
    }

    fn generate_gitignore_with_features(
        &self,
        config: &ProjectConfig,
        output_dir: &Path,
        feature_context: &FeatureContext,
    ) -> Result<()> {
        let mut content = String::from("/target\n**/*.rs.bk\n.DS_Store\n");

        // Add Cargo.lock for libraries
        if config.project_type == "library" {
            content.push_str("Cargo.lock\n");
        }

        // Add project-type specific ignores
        match config.project_type.as_str() {
            "wasm-app" => {
                content.push_str("node_modules\n");
                content.push_str("dist/\n");
                content.push_str("pkg/\n");
            }
            "game-engine" => {
                content.push_str("wasm/\n");
                content.push_str("*.wasm\n");
                content.push_str(".DS_Store\n");
            }
            "embedded" => {
                content.push_str("*.bin\n");
                content.push_str("*.hex\n");
                content.push_str("*.elf\n");
                content.push_str(".vscode/\n");
            }
            "workspace" => {
                content.push_str("Cargo.lock\n");
            }
            _ => {}
        }

        // Add feature-specific gitignore entries
        for entry in &feature_context.gitignore_entries {
            content.push_str(entry);
            content.push('\n');
        }

        fs::write(output_dir.join(".gitignore"), content)?;
        Ok(())
    }

    fn generate_readme_with_features(
        &self,
        config: &ProjectConfig,
        output_dir: &Path,
        feature_context: &FeatureContext,
    ) -> Result<()> {
        let mut content = format!("# {}\n\n", config.name);

        if let Some(desc) = &config.description {
            content.push_str(desc);
            content.push_str("\n\n");
        }

        // Add project-type specific content
        match config.project_type.as_str() {
            "api-server" => {
                content.push_str("## API Server\n\n");
                content.push_str("This is a REST API server built with Axum.\n\n");
                content.push_str("### Endpoints\n\n");
                content.push_str("- `GET /` - Health check endpoint\n");
                content.push_str("- More endpoints coming soon...\n\n");
                content.push_str("### Running\n\n");
                content.push_str("```bash\ncargo run\n```\n\n");
                content.push_str("The server will start on `http://localhost:3000`\n");
            }
            "cli-tool" => {
                content.push_str("## CLI Tool\n\n");
                content.push_str("### Usage\n\n");
                content.push_str("```bash\ncargo run -- --help\n```\n\n");
                content.push_str("### Commands\n\n");
                content.push_str("Available commands and arguments will be shown in help.\n");
            }
            "library" => {
                content.push_str("## Library\n\n");
                content.push_str("### Usage\n\n");
                content.push_str("Add this to your `Cargo.toml`:\n\n");
                content.push_str("```toml\n[dependencies]\n");
                content.push_str(&format!("{} = \"0.1.0\"\n", config.name));
                content.push_str("```\n\n");
                content.push_str("### Example\n\n");
                content.push_str("```rust\n// Example usage\n```\n\n");
                content.push_str("### API Documentation\n\n");
                content.push_str("Run `cargo doc --open` to view the documentation.\n");
            }
            "wasm-app" => {
                content.push_str("## WebAssembly App\n\n");
                content.push_str("This project compiles Rust to WebAssembly for the browser.\n\n");
                content.push_str("### Building\n\n");
                content.push_str("```bash\nwasm-pack build --target web\n```\n\n");
                content.push_str("### Running locally\n\n");
                content.push_str("Serve the project directory and open `index.html`:\n\n");
                content.push_str("```bash\npython3 -m http.server 8080\n```\n\n");
                content.push_str("### Testing\n\n");
                content.push_str("```bash\nwasm-pack test --headless --firefox\n```\n");
            }
            "game-engine" => {
                content.push_str("## Game Engine Project\n\n");
                content.push_str("A game built on the Bevy engine.\n\n");
                content.push_str("### Prerequisites (Linux)\n\n");
                content.push_str(
                    "Bevy's windowing stack needs system libraries. On Debian/Ubuntu:\n\n",
                );
                content.push_str(
                    "```bash\nsudo apt install libwayland-dev libxkbcommon-dev pkg-config\n```\n\n",
                );
                content.push_str("### Running\n\n");
                content.push_str("```bash\ncargo run\n```\n\n");
                content.push_str("### Assets\n\n");
                content.push_str(
                    "Place sprites, sounds, and other assets in the `assets/` directory.\n\n",
                );
                content.push_str("### Release builds\n\n");
                content.push_str("```bash\ncargo build --release\n```\n\n");
                content.push_str("Release builds enable optimizations for smooth frame rates.\n");
            }
            "embedded" => {
                content.push_str("## Embedded Project\n\n");
                content.push_str("Bare-metal firmware for microcontrollers (no_std).\n\n");
                content.push_str("### Building\n\n");
                content.push_str("```bash\ncargo build --release\n```\n\n");
                content.push_str("### Flashing\n\n");
                content.push_str("```bash\ncargo run --release  # via probe-rs runner\n```\n\n");
                content.push_str("### Target\n\n");
                content.push_str(
                    "See `.cargo/config.toml` for the configured target triple and runner.\n",
                );
            }
            "workspace" => {
                content.push_str("## Cargo Workspace\n\n");
                content.push_str("A multi-crate workspace layout.\n\n");
                content.push_str("### Structure\n\n");
                content.push_str("- `crates/` — member crates\n");
                content.push_str("- `Cargo.toml` — workspace manifest\n\n");
                content.push_str("### Building everything\n\n");
                content.push_str("```bash\ncargo build --workspace\n```\n\n");
                content.push_str("### Testing everything\n\n");
                content.push_str("```bash\ncargo test --workspace\n```\n");
            }
            _ => {}
        }

        // Add feature-specific readme sections
        for section in &feature_context.readme_sections {
            content.push_str(section);
            content.push_str("\n");
        }

        fs::write(output_dir.join("README.md"), content)?;
        Ok(())
    }

    fn generate_api_server(&self, _config: &ProjectConfig, output_dir: &Path) -> Result<()> {
        // Minimal working Axum server: GET / returns a JSON health check.
        let main_rs = r#"use tokio::net::TcpListener;

mod handlers;
mod models;
mod routes;

#[tokio::main]
async fn main() {
    let app = routes::routes();

    let port: u16 = std::env::var("PORT")
        .ok()
        .and_then(|p| p.parse().ok())
        .unwrap_or(3000);

    let listener = TcpListener::bind(("0.0.0.0", port))
        .await
        .expect("failed to bind listener");

    println!("API server listening on http://localhost:{port}");

    axum::serve(listener, app).await.expect("server error");
}
"#;
        fs::write(output_dir.join("src/main.rs"), main_rs)?;

        let routes_rs = r#"use axum::{routing::get, Router};

use crate::handlers;

pub fn routes() -> Router {
    Router::new().route("/", get(handlers::health))
}
"#;
        fs::write(output_dir.join("src/routes.rs"), routes_rs)?;

        let handlers_rs = r#"use axum::Json;

use crate::models::Health;

/// GET / — health check
pub async fn health() -> Json<Health> {
    Json(Health::ok())
}
"#;
        fs::write(output_dir.join("src/handlers.rs"), handlers_rs)?;

        let models_rs = r#"use serde::Serialize;

#[derive(Serialize)]
pub struct Health {
    pub status: String,
}

impl Health {
    pub fn ok() -> Self {
        Self {
            status: "ok".to_string(),
        }
    }
}
"#;
        fs::write(output_dir.join("src/models.rs"), models_rs)?;

        fs::create_dir_all(output_dir.join("config"))?;
        fs::write(
            output_dir.join("config/default.toml"),
            "# Server configuration (loaded by your config code as needed)\n[server]\nport = 3000\n",
        )?;
        fs::write(
            output_dir.join(".env.example"),
            "# The server binds to the PORT environment variable when set\n# (default 3000). Nothing else reads this file; the starter has no\n# dotenv dependency, so exporting PORT is what takes effect.\n# PORT=3000\n",
        )?;

        Ok(())
    }

    fn generate_cli_tool(&self, config: &ProjectConfig, output_dir: &Path) -> Result<()> {
        // Minimal working Clap CLI with a `hello` subcommand.
        let main_rs = r#"mod cli;
mod commands;

use clap::Parser;

use crate::cli::{Cli, Commands};

fn main() {
    let cli = Cli::parse();

    match cli.command {
        Some(Commands::Hello { name }) => commands::hello(name.as_deref()),
        None => {
            println!(
                "{} — run with --help to see available commands.",
                env!("CARGO_PKG_NAME")
            );
        }
    }
}
"#;
        fs::write(output_dir.join("src/main.rs"), main_rs)?;

        let cli_rs = r#"use clap::{Parser, Subcommand};

#[derive(Parser)]
#[command(name = env!("CARGO_PKG_NAME"), version, about = env!("CARGO_PKG_DESCRIPTION"))]
pub struct Cli {
    #[command(subcommand)]
    pub command: Option<Commands>,
}

#[derive(Subcommand)]
pub enum Commands {
    /// Print a greeting
    Hello {
        /// Name to greet (defaults to "world")
        #[arg(short, long)]
        name: Option<String>,
    },
}
"#;
        fs::write(output_dir.join("src/cli.rs"), cli_rs)?;

        let commands_rs = r#"pub fn hello(name: Option<&str>) {
    println!("Hello, {}!", name.unwrap_or("world"));
}
"#;
        fs::write(output_dir.join("src/commands.rs"), commands_rs)?;

        // Smoke test so `cargo test` has something real to run.
        fs::create_dir_all(output_dir.join("tests"))?;
        fs::write(
            output_dir.join("tests/cli.rs"),
            &format!(
                r#"#[test]
fn hello_command_greets_by_name() {{
    let output = std::process::Command::new(env!("CARGO_BIN_EXE_{}"))
        .args(["hello", "--name", "forge"])
        .output()
        .expect("failed to run binary");
    assert!(output.status.success());
    assert!(String::from_utf8_lossy(&output.stdout).contains("Hello, forge!"));
}}
"#,
                config.name
            ),
        )?;

        Ok(())
    }

    fn generate_library(&self, config: &ProjectConfig, output_dir: &Path) -> Result<()> {
        // Small real API with a unit test, plus a runnable example.
        let lib_name = config.name.replace('-', "_");
        // Multi-line descriptions become multiple `//!` lines so the crate
        // stays compilable regardless of what the user typed.
        let doc_header: String = config
            .description
            .as_deref()
            .unwrap_or("A Rust library")
            .replace('\r', "\n") // lone CR would break rustc doc comments
            .lines()
            .map(|line| format!("//! {}\n", line))
            .collect();
        let lib_content = format!(
            "{doc_header}\
/// Return a greeting for `name`.
pub fn greet(name: &str) -> String {{
    format!(\"Hello, {{}}!\", name)
}}

#[cfg(test)]
mod tests {{
    use super::greet;

    #[test]
    fn greets_by_name() {{
        assert_eq!(greet(\"forge\"), \"Hello, forge!\");
    }}
}}
"
        );
        fs::write(output_dir.join("src/lib.rs"), lib_content)?;

        fs::create_dir_all(output_dir.join("examples"))?;
        fs::write(
            output_dir.join("examples/basic.rs"),
            &format!(
                "fn main() {{\n    println!(\"{{}}\", {}::greet(\"world\"));\n}}\n",
                lib_name
            ),
        )?;

        Ok(())
    }

    fn generate_wasm_app(&self, config: &ProjectConfig, output_dir: &Path) -> Result<()> {
        // Working wasm-bindgen export; build flow matches the generated README
        // (wasm-pack --target web + static server), so no node/webpack files.
        let lib_rs = r#"use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn greet(name: &str) -> String {
    format!("Hello, {}!", name)
}
"#;
        fs::write(output_dir.join("src/lib.rs"), lib_rs)?;

        let index_html = format!(
            r#"<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>{name}</title>
  </head>
  <body>
    <script type="module">
      import init, {{ greet }} from "./pkg/{pkg}.js";

      init().then(() => {{
        document.body.textContent = greet("world");
      }});
    </script>
  </body>
</html>
"#,
            name = config.name,
            pkg = config.name.replace('-', "_")
        );
        fs::write(output_dir.join("index.html"), index_html)?;

        Ok(())
    }

    fn generate_game_engine(&self, _config: &ProjectConfig, output_dir: &Path) -> Result<()> {
        // Minimal Bevy app that opens a window.
        let main_rs = r#"use bevy::prelude::*;

fn main() {
    App::new().add_plugins(DefaultPlugins).run();
}
"#;
        fs::write(output_dir.join("src/main.rs"), main_rs)?;

        // Create assets directory structure
        fs::create_dir_all(output_dir.join("assets/models"))?;
        fs::create_dir_all(output_dir.join("assets/textures"))?;
        fs::create_dir_all(output_dir.join("assets/sounds"))?;
        fs::create_dir_all(output_dir.join("assets/shaders"))?;

        // Create basic asset README
        fs::write(
            output_dir.join("assets/README.md"),
            "# Assets\n\nPlace your game assets here.",
        )?;

        Ok(())
    }

    fn generate_embedded(&self, config: &ProjectConfig, output_dir: &Path) -> Result<()> {
        // Check if it is an esp32 project
        if let Some(target) = &config.target {
            if target == "esp32" {
                let chip = config.esp32_chip.as_deref().unwrap_or("esp32");
                println!("🔧 Generating project for chip : {}", chip);
                return external_generators::generate_esp32_project(&config.name, chip, output_dir);
            }
        }

        // Default to Cortex-M embedded project (existing logic)
        println!("🔧 Generating Cortex-M embedded project");
        self.generate_cortex_m_embedded(config, output_dir)
    }

    fn generate_cortex_m_embedded(&self, _config: &ProjectConfig, output_dir: &Path) -> Result<()> {
        // Create embedded specific files with proper no_std setup
        let main_content = r#"#![no_std]
#![no_main]

use panic_halt as _; // panic handler

use cortex_m_rt::entry;

#[entry]
fn main() -> ! {
    // Initialize the allocator BEFORE you use the heap
    
    // Main application logic
    loop {
        // Your code here
    }
}
"#;
        fs::write(output_dir.join("src/main.rs"), main_content)?;

        // Create cargo config
        fs::create_dir_all(output_dir.join(".cargo"))?;
        let cargo_config_content = r#"[target.thumbv7em-none-eabihf]
runner = "probe-rs-cli run --chip STM32F401RETx"

[build]
target = "thumbv7em-none-eabihf"

[env]
DEFMT_LOG = "debug"
"#;
        fs::write(output_dir.join(".cargo/config.toml"), cargo_config_content)?;

        // Create memory layout file
        let memory_x_content = r#"/* Linker script for the STM32F401RET6 */
MEMORY
{
  /* NOTE 1 K = 1 KiBi = 1024 bytes */
  FLASH : ORIGIN = 0x08000000, LENGTH = 512K
  RAM : ORIGIN = 0x20000000, LENGTH = 96K
}

/* This is where the call stack will be allocated. */
/* The stack is of the full descending type. */
/* You may want to use this variable to locate the call stack and static
   variables in different memory regions. Below is shown the default value */
/* _stack_start = ORIGIN(RAM) + LENGTH(RAM); */

/* You can use this symbol to customize the location of the .text section */
/* If omitted the .text section will be placed right after the .vector_table
   section */
/* This can be useful if you want to move the firmware to some address other
   than the default one (= 0x00000000 in thumb mode, 0x00000008 in non-thumb mode) */
/* ENTRY_POINT = 0x08000000; */
"#;
        fs::write(output_dir.join("memory.x"), memory_x_content)?;

        // Create probe-rs config
        let embed_toml_content = r#"[default.probe]
protocol = "Swd"

[default.flashing]
enabled = true

[default.reset]
enabled = true

[default.general]
chip = "STM32F401RETx"

[default.rtt]
enabled = true
up_mode = "NoBlockSkip"
"#;
        fs::write(output_dir.join("Embed.toml"), embed_toml_content)?;

        Ok(())
    }

    fn generate_workspace(&self, config: &ProjectConfig, output_dir: &Path) -> Result<()> {
        // Free-text author can contain quotes — escape for the member manifests.
        let author = toml_escape(&config.author);
        let license_line = config
            .license
            .as_ref()
            .map(|l| format!(r#"license = "{}""#, toml_escape(l)))
            .unwrap_or_default();
        // Create workspace structure
        fs::create_dir_all(output_dir.join("crates/core/src"))?;
        fs::create_dir_all(output_dir.join("crates/api/src"))?;
        fs::create_dir_all(output_dir.join("crates/cli/src"))?;

        // Create core crate
        fs::write(
            output_dir.join("crates/core/src/lib.rs"),
            "//! Core library\n\npub fn hello() {\n    println!(\"Hello from core!\");\n}\n",
        )?;
        fs::write(output_dir.join("crates/core/src/error.rs"), "//! Error types for the core library\n\nuse std::fmt;\n\n#[derive(Debug)]\npub enum CoreError {\n    Generic(String),\n}\n\nimpl fmt::Display for CoreError {\n    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n        match self {\n            CoreError::Generic(msg) => write!(f, \"Core error: {}\", msg),\n        }\n    }\n}\n\nimpl std::error::Error for CoreError {}\n")?;
        fs::write(output_dir.join("crates/core/src/lib.rs"), "//! Core library\n\npub mod error;\n\npub use error::CoreError;\n\npub fn hello() {\n    println!(\"Hello from core!\");\n}\n")?;
        fs::write(output_dir.join("crates/core/src/models.rs"), "//! Data models\n\n#[derive(Debug, Clone)]\npub struct User {\n    pub id: u64,\n    pub name: String,\n    pub email: String,\n}\n\nimpl User {\n    pub fn new(id: u64, name: String, email: String) -> Self {\n        Self { id, name, email }\n    }\n}\n")?;
        fs::write(output_dir.join("crates/core/src/utils.rs"), "//! Utility functions\n\npub fn format_name(first: &str, last: &str) -> String {\n    format!(\"{} {}\", first, last)\n}\n\npub fn validate_email(email: &str) -> bool {\n    email.contains('@') && email.contains('.')\n}\n")?;

        let core_cargo_toml = format!(
            r#"[package]
name = "{}-core"
version = "0.1.0"
edition = "2021"
authors = ["{}"]
{license_line}
[dependencies]
serde = {{ version = "1.0", features = ["derive"] }}
anyhow = "1.0"
"#,
            config.name,
            author,
            license_line = if license_line.is_empty() {
                String::new()
            } else {
                format!("{}\n", license_line)
            }
        );
        fs::write(output_dir.join("crates/core/Cargo.toml"), core_cargo_toml)?;

        // Create API crate
        fs::write(output_dir.join("crates/api/src/lib.rs"), "//! API library\n\nuse anyhow::Result;\n\npub fn start_server() -> Result<()> {\n    println!(\"Starting API server...\");\n    Ok(())\n}\n")?;
        fs::write(output_dir.join("crates/api/src/state.rs"), "//! Application state management\n\nuse std::sync::Arc;\nuse tokio::sync::RwLock;\n\n#[derive(Clone)]\npub struct AppState {\n    pub counter: Arc<RwLock<u64>>,\n}\n\nimpl AppState {\n    pub fn new() -> Self {\n        Self {\n            counter: Arc::new(RwLock::new(0)),\n        }\n    }\n}\n\nimpl Default for AppState {\n    fn default() -> Self {\n        Self::new()\n    }\n}\n")?;

        let api_cargo_toml = format!(
            r#"[package]
name = "{}-api"
version = "0.1.0"
edition = "2021"
authors = ["{}"]
{license_line}
[dependencies]
{}-core = {{ path = "../core" }}
tokio = {{ version = "1", features = ["full"] }}
anyhow = "1.0"
serde = {{ version = "1.0", features = ["derive"] }}

[lib]
name = "{}_api"
"#,
            config.name,
            author,
            config.name,
            config.name.replace('-', "_"),
            license_line = if license_line.is_empty() {
                String::new()
            } else {
                format!("{}\n", license_line)
            }
        );
        fs::write(output_dir.join("crates/api/Cargo.toml"), api_cargo_toml)?;

        // Create CLI crate
        fs::write(output_dir.join("crates/cli/src/main.rs"), &format!("use {}_core::hello;\nuse anyhow::Result;\n\nfn main() -> Result<()> {{\n    println!(\"Welcome to {}!\");\n    hello();\n    Ok(())\n}}\n", config.name.replace('-', "_"), config.name))?;

        let cli_cargo_toml = format!(
            r#"[package]
name = "{}-cli"
version = "0.1.0"
edition = "2021"
authors = ["{}"]
{license_line}
[[bin]]
name = "{}"
path = "src/main.rs"

[dependencies]
{}-core = {{ path = "../core" }}
clap = {{ version = "4", features = ["derive"] }}
anyhow = "1.0"
"#,
            config.name,
            author,
            config.name,
            config.name,
            license_line = if license_line.is_empty() {
                String::new()
            } else {
                format!("{}\n", license_line)
            }
        );
        fs::write(output_dir.join("crates/cli/Cargo.toml"), cli_cargo_toml)?;

        Ok(())
    }

    fn generate_cargo_toml(
        &self,
        config: &ProjectConfig,
        output_dir: &Path,
        feature_context: &FeatureContext,
    ) -> Result<()> {
        // Skip generating Cargo.toml for esp32 projects
        if let Some(target) = &config.target {
            if target == "esp32" {
                return Ok(());
            }
        }
        let mut content = String::new();

        // Generate workspace Cargo.toml for workspace projects
        if config.project_type == "workspace" {
            // Workspace root is a virtual manifest: no [package] section,
            // since the root has no src/ targets of its own.
            content.push_str("[workspace]\n");
            content.push_str("resolver = \"2\"\n");
            content.push_str("members = [\n");
            content.push_str("  \"crates/core\",\n");
            content.push_str("  \"crates/api\",\n");
            content.push_str("  \"crates/cli\",\n");
            content.push_str("]\n\n");

            content.push_str("[workspace.package]\n");
            content.push_str(&format!(r#"version = "0.1.0""#));
            content.push('\n');
            content.push_str(&format!(r#"authors = ["{}"]"#, toml_escape(&config.author)));
            content.push('\n');
            content.push_str(r#"edition = "2021""#);
            content.push('\n');
            if let Some(desc) = &config.description {
                content.push_str(&format!(r#"description = "{}""#, toml_escape(desc)));
                content.push('\n');
            }
            if let Some(license) = &config.license {
                content.push_str(&format!(r#"license = "{}""#, toml_escape(license)));
                content.push('\n');
            }
            content.push_str("\n");

            content.push_str("[workspace.dependencies]\n");
            content.push_str("tokio = { version = \"1\", features = [\"full\"] }\n");
            content.push_str("serde = { version = \"1\", features = [\"derive\"] }\n");
            content.push_str("anyhow = \"1\"\n");
            content.push_str("clap = { version = \"4\", features = [\"derive\"] }\n");

            fs::write(output_dir.join("Cargo.toml"), content)?;
            return Ok(());
        }

        // Generate regular package Cargo.toml for other project types
        content.push_str("[package]\n");
        content.push_str(&format!(r#"name = "{}""#, config.name));
        content.push('\n');
        content.push_str(r#"version = "0.1.0""#);
        content.push('\n');
        content.push_str(&format!(r#"authors = ["{}"]"#, toml_escape(&config.author)));
        content.push('\n');
        content.push_str(r#"edition = "2021""#);
        content.push('\n');

        if let Some(desc) = &config.description {
            content.push_str(&format!(r#"description = "{}""#, toml_escape(desc)));
            content.push('\n');
        }

        if let Some(license) = &config.license {
            content.push_str(&format!(r#"license = "{}""#, toml_escape(license)));
            content.push('\n');
        }

        content.push_str("\n[dependencies]\n");

        // Add project-type specific dependencies
        match config.project_type.as_str() {
            "api-server" => {
                content.push_str("axum = \"0.7\"\n");
                content.push_str("tokio = { version = \"1\", features = [\"full\"] }\n");
                content.push_str("serde = { version = \"1\", features = [\"derive\"] }\n");
                content.push_str("serde_json = \"1\"\n");
                content.push_str("tower = \"0.4\"\n");
            }
            "cli-tool" => {
                content.push_str("clap = { version = \"4\", features = [\"derive\"] }\n");
                content.push_str("anyhow = \"1\"\n");
                content.push_str("env_logger = \"0.10\"\n");

                content.push_str("\n[[bin]]\n");
                content.push_str(&format!(r#"name = "{}""#, config.name));
                content.push('\n');
                content.push_str("path = \"src/main.rs\"\n");
            }
            "library" => {
                content.push_str("\n[lib]\n");
                content.push_str(&format!(r#"name = "{}""#, config.name.replace('-', "_")));
                content.push('\n');
            }
            "wasm-app" => {
                content.push_str("wasm-bindgen = \"0.2\"\n");
                content.push_str("web-sys = \"0.3\"\n");
                content.push_str("js-sys = \"0.3\"\n");

                content.push_str("\n[lib]\n");
                content.push_str(r#"crate-type = ["cdylib"]"#);
                content.push('\n');
            }
            "game-engine" => {
                content.push_str("bevy = \"0.20\"\n");

                content.push_str("\n[target.'cfg(target_arch = \"wasm32\")'.dependencies]\n");
                content.push_str("wasm-bindgen = \"0.2\"\n");
                content.push_str("web-sys = \"0.3\"\n");
                content.push_str("console_error_panic_hook = \"0.1\"\n");

                content.push_str("\n[profile.dev]\n");
                content.push_str("opt-level = 1\n");
                content.push_str("\n[profile.dev.package.\"*\"]\n");
                content.push_str("opt-level = 3\n");
            }
            "embedded" => {
                content.push_str("cortex-m = \"0.7\"\n");
                content.push_str("cortex-m-rt = \"0.7\"\n");
                content.push_str("panic-halt = \"0.2\"\n");

                content.push_str("\n[profile.dev]\n");
                content.push_str("opt-level = 1\n");
                content.push_str("\n[profile.release]\n");
                content.push_str("lto = \"fat\"\n");
                content.push_str("opt-level = 3\n");
            }
            "workspace" => {
                // Workspace projects have different structure - skip dependencies here
            }
            _ => {}
        }

        // Feature plugins contribute dependencies (e.g. sqlx for the
        // database feature) so generated projects compile with the feature
        // files they ship. Those deps must land INSIDE [dependencies],
        // which is not the manifest's last table for every type
        // (game-engine/embedded append [target]/[profile] tables after
        // their deps; cli-tool/library/wasm-app append [[bin]]/[lib]), so
        // they are inserted right after the [dependencies] header rather
        // than appended at the end. Skip names already provided by the
        // project-type defaults (e.g. tokio for api-server) to keep the
        // manifest free of duplicate keys. Workspace roots are virtual
        // manifests and do not take a [dependencies] section.
        if config.project_type != "workspace" {
            let dep_lines: Vec<String> = feature_context
                .dependencies
                .iter()
                .filter(|(name, _)| !dep_already_present(&content, "dependencies", name))
                .map(|(name, spec)| format!("{} = {}\n", name, spec))
                .collect();
            let dev_dep_lines: Vec<String> = feature_context
                .dev_dependencies
                .iter()
                .filter(|(name, _)| !dep_already_present(&content, "dev-dependencies", name))
                .map(|(name, spec)| format!("{} = {}\n", name, spec))
                .collect();
            if !dep_lines.is_empty() {
                insert_in_table(&mut content, "[dependencies]", &dep_lines);
            }
            if !dev_dep_lines.is_empty() {
                insert_in_table(&mut content, "[dev-dependencies]", &dev_dep_lines);
            }
        }

        fs::write(output_dir.join("Cargo.toml"), content)?;
        Ok(())
    }
}

/// True when a `name = …` key already exists in `table` of the manifest, so
/// a plugin-provided dependency the project type already declares is skipped
/// instead of duplicated. Parsed as TOML so a match in a different table
/// (e.g. a `[target.'…'.dependencies]` entry) never hides a main-table dep.
fn dep_already_present(content: &str, table: &str, name: &str) -> bool {
    toml::from_str::<toml::Value>(content)
        .ok()
        .and_then(|v| v.get(table).map(|t| t.get(name).is_some()))
        .unwrap_or(false)
}

/// Features the generator can honestly apply per project type. The database
/// family (sqlx + tokio) only links for native binaries and libraries:
/// embedded is no_std, wasm-app targets wasm32, game-engine carries a
/// wasm32 target table, and workspace roots are virtual manifests whose
/// feature dependencies are skipped on purpose. `postgres` registers the
/// same plugin as `database` (see the registration match) and is guarded
/// identically.
pub fn feature_supported(feature: &str, project_type: &str) -> bool {
    match feature {
        "database" | "postgres" | "sqlite" | "mysql" => {
            matches!(project_type, "api-server" | "cli-tool" | "library")
        }
        _ => true,
    }
}

/// Re-verify the directory holds nothing except our claim file. The initial
/// emptiness check runs before the claim is taken; between that check and
/// this one another generator may have finished a complete project and
/// released its claim, so exclusivity requires a second look.
fn ensure_empty_except_claim(output_dir: &Path, claim_path: &Path) -> Result<()> {
    for entry in fs::read_dir(output_dir)? {
        let entry = entry?;
        if entry.path() == claim_path {
            continue;
        }
        anyhow::bail!("Directory '{}' is not empty", output_dir.display());
    }
    Ok(())
}

#[cfg(test)]
mod claim_tests {
    use super::*;

    #[test]
    fn stray_file_beside_the_claim_is_rejected() {
        let temp = tempfile::TempDir::new().unwrap();
        let dir = temp.path().join("proj");
        fs::create_dir_all(&dir).unwrap();
        let claim = dir.join(".cargo-forge-claim");
        fs::write(&claim, "").unwrap();
        fs::write(dir.join("src"), "").unwrap(); // leftover from a prior run
        assert!(ensure_empty_except_claim(&dir, &claim).is_err());
    }

    #[test]
    fn claim_only_directory_passes() {
        let temp = tempfile::TempDir::new().unwrap();
        let dir = temp.path().join("proj");
        fs::create_dir_all(&dir).unwrap();
        let claim = dir.join(".cargo-forge-claim");
        fs::write(&claim, "").unwrap();
        assert!(ensure_empty_except_claim(&dir, &claim).is_ok());
    }
}

/// Insert `lines` directly under `header` in a generated manifest. The
/// header is matched on the exact trimmed line, so nested tables like
/// `[target.'…'.dependencies]` can never shadow `[dependencies]`. A missing
/// header (e.g. no [dev-dependencies] table yet) appends a new table at the
/// end of the manifest.
fn insert_in_table(content: &mut String, header: &str, lines: &[String]) {
    if let Some(idx) = content.lines().position(|l| l.trim() == header) {
        let mut out = String::with_capacity(content.len() + 64);
        for (i, line) in content.lines().enumerate() {
            out.push_str(line);
            out.push('\n');
            if i == idx {
                for l in lines {
                    out.push_str(l.trim_end_matches('\n'));
                    out.push('\n');
                }
            }
        }
        *content = out;
    } else {
        content.push('\n');
        content.push_str(header);
        content.push('\n');
        for line in lines {
            content.push_str(line);
        }
    }
}

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