esp-generate 1.3.0-rc.0

Template generation tool to create no_std applications targeting Espressif's chips
Documentation
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
use anyhow::{Result, bail};
use clap::{Parser, Subcommand};
use esp_generate::template::{GeneratorOption, GeneratorOptionItem, Template};
use esp_generate::{
    append_list_as_sentence,
    config::{ActiveConfiguration, Relationships},
};
use esp_generate::{
    cargo,
    config::{find_option, flatten_options},
};
use esp_metadata::Chip;
use indexmap::IndexMap;
use inquire::{Select, Text};
use ratatui::crossterm::event;
use std::collections::HashSet;
use std::{
    collections::HashMap,
    env, fs,
    path::{Path, PathBuf},
    process::Command,
    sync::LazyLock,
    time::Duration,
};
use strum::IntoEnumIterator;
use taplo::formatter::Options;

use crate::template_files::TEMPLATE_FILES;

mod check;
mod module_selector;
mod template_files;
mod toolchain;
mod tui;

static TEMPLATE: LazyLock<Template> = LazyLock::new(|| {
    serde_yaml::from_str(
        template_files::TEMPLATE_FILES
            .iter()
            .find_map(|(k, v)| if *k == "template.yaml" { Some(v) } else { None })
            .unwrap(),
    )
    .unwrap()
});

#[derive(Parser, Debug)]
#[command(author, version, about = about(), long_about = None, subcommand_negates_reqs = true)]
struct Args {
    /// Name of the project to generate
    name: Option<String>,

    /// Chip to target
    #[arg(short, long)]
    chip: Option<Chip>,

    /// Run in headless mode (i.e. do not use the TUI)
    #[arg(long)]
    headless: bool,

    /// Generation options
    #[arg(short, long, help = {
        let mut all_options = Vec::new();
        for option in TEMPLATE.options.iter() {
            for opt in option.options() {
                // Remove duplicates, which usually are chip-specific variations of an option.
                // An example of this is probe-rs.
                if !all_options.contains(&opt) && opt != "PLACEHOLDER" {
                    all_options.push(opt);
                }
            }
        }
        format!("Generation options: {} - For more information regarding the different options check the esp-generate README.md (https://github.com/esp-rs/esp-generate/blob/main/README.md).",all_options.join(", "))
    })]
    option: Vec<String>,

    /// Directory in which to generate the project
    #[arg(short = 'O', long)]
    output_path: Option<PathBuf>,

    /// Do not check for updates
    #[arg(short, long, global = true, action)]
    #[cfg(feature = "update-informer")]
    skip_update_check: bool,

    /// Rust toolchain to use (rustup toolchain name; must support the selected chip target)
    ///
    /// Note that in headless mode this is not checked.
    #[arg(long)]
    toolchain: Option<String>,

    #[clap(subcommand)]
    subcommands: Option<SubCommands>,
}

#[derive(Subcommand, Debug)]
enum SubCommands {
    /// List available template options
    ListOptions,

    /// Print information about a template option
    Explain { option: String },
}

impl SubCommands {
    fn handle(&self) -> Result<()> {
        fn chip_info_text(options: &[&GeneratorOption], opt: &GeneratorOption) -> String {
            let mut chips = Vec::new();
            for option in options.iter().filter(|o| o.name == opt.name) {
                chips.extend_from_slice(&option.chips);
            }

            let chip_count = Chip::iter().count();

            if chips.is_empty() || chips.len() == chip_count {
                String::new()
            } else if chips.len() < chip_count / 2 {
                format!(
                    "Only available on {}.",
                    chips
                        .iter()
                        .map(ToString::to_string)
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            } else {
                format!(
                    "Not available on {}.",
                    Chip::iter()
                        .filter(|c| !chips.contains(c))
                        .map(|c| c.to_string())
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            }
        }

        match self {
            SubCommands::ListOptions => {
                println!(
                    "The following template options are available. The group names are not part of the option name. Only one option in a group can be selected."
                );
                let mut groups = IndexMap::new();
                let mut seen = HashSet::new();
                let all_options = TEMPLATE.all_options();
                for (index, option) in all_options
                    .iter()
                    .enumerate()
                    .filter(|(_, o)| !["toolchain", "module"].contains(&o.selection_group.as_str()))
                {
                    let group = groups.entry(&option.selection_group).or_insert(Vec::new());

                    if seen.insert(&option.name) {
                        group.push(index);
                    }
                }
                for (group, options) in groups {
                    println!("Group: {}", group);
                    for option in options {
                        let option = &all_options[option];
                        let mut help_text = option.display_name.clone();

                        if !option.requires.is_empty() {
                            help_text.push_str(" Requires: ");
                            let readable = option.requires.iter().map(|option| {
                                if let Some(stripped) = option.strip_prefix('!') {
                                    format!("{} unselected", stripped)
                                } else {
                                    option.to_string()
                                }
                            });
                            help_text.push_str(&readable.collect::<Vec<String>>().join(", "));
                            help_text.push('.');
                        }
                        let chip_info = chip_info_text(&all_options, option);
                        if !chip_info.is_empty() {
                            help_text.push(' ');
                            help_text.push_str(&chip_info);
                        }
                        println!("    {}: {help_text}", option.name);
                    }
                }
                Ok(())
            }
            SubCommands::Explain { option } => {
                let all_options = TEMPLATE.all_options();
                if let Some(option) = all_options.iter().find(|o| &o.name == option) {
                    println!(
                        "Option: {}\n\n{}{}",
                        option.name,
                        option.display_name,
                        if option.help.is_empty() {
                            String::new()
                        } else {
                            format!("\n{}\n", option.help)
                        }
                    );
                    if !option.requires.is_empty() {
                        println!();
                        let positive_req = option.requires.iter().filter(|r| !r.starts_with("!"));
                        let negative_req = option.requires.iter().filter(|r| r.starts_with("!"));
                        if positive_req.clone().next().is_some() {
                            println!("Requires the following options to be set:");
                            for require in positive_req {
                                println!("    {}", require);
                            }
                        }
                        if negative_req.clone().next().is_some() {
                            println!("Requires the following options to NOT be set:");
                            for require in negative_req {
                                if let Some(stripped) = require.strip_prefix('!') {
                                    println!("    {}", stripped);
                                }
                            }
                        }
                    }
                    let chip_info = chip_info_text(&all_options, option);
                    if !chip_info.is_empty() {
                        println!("{}", chip_info);
                    }
                } else {
                    println!("Unknown option: {}", option);
                }
                Ok(())
            }
        }
    }
}

/// Check crates.io for a new version of the application
#[cfg(feature = "update-informer")]
fn check_for_update(name: &str, version: &str) {
    use update_informer::{Check, registry};
    // By setting the interval to 0 seconds we invalidate the cache with each
    // invocation and ensure we're getting up-to-date results
    let informer =
        update_informer::new(registry::Crates, name, version).interval(Duration::from_secs(0));

    if let Some(version) = informer.check_version().ok().flatten() {
        log::warn!("🚀 A new version of {name} is available: {version}");
    }
}

fn about() -> String {
    let mut about = String::from(
        "Template generation tool to create no_std applications targeting Espressif's chips.\n\nThe template will use these versions:\n",
    );

    let toml = cargo::CargoToml::load(
        TEMPLATE_FILES
            .iter()
            .find(|(k, _)| *k == "Cargo.toml")
            .expect("Cargo.toml not found in template")
            .1,
    )
    .expect("Failed to read Cargo.toml");

    toml.visit_dependencies(|_, name, table| {
        if name == "dependencies" {
            for entry in table.iter() {
                let name = entry.0;
                if name.starts_with("esp-") {
                    about.push_str(&format!("{:23 } {}\n", name, toml.dependency_version(name)));
                }
            }
        }
    });

    about
}

fn setup_args_interactive(args: &mut Args) -> Result<()> {
    if args.headless {
        let mut missing = String::from(
            "You are in headless mode, but esp-generate needs more information to generate your project.",
        );
        if args.chip.is_none() {
            missing.push_str(
                "\nThe target chip is missing. Add --chip <your-chip-name> to the command.",
            );
        }
        if args.name.is_none() {
            missing.push_str("\nThe project name is missing. Add the name of your project to the end of the command.");
        }

        bail!("{missing}");
    }

    if args.chip.is_none() {
        let chip_variants = Chip::iter().collect::<Vec<_>>();

        let chip = Select::new("Select your target chip:", chip_variants).prompt()?;

        args.chip = Some(chip);
    }

    if args.name.is_none() {
        let project_name = Text::new("Enter project name:")
            .with_default("my-esp-project")
            .prompt()?;

        args.name = Some(project_name);
    }

    Ok(())
}

fn main() -> Result<()> {
    tui::setup_logger().expect("logger should only be initialized once");

    let mut args = Args::parse();

    if let Some(subcommand) = args.subcommands {
        return subcommand.handle();
    }

    // Only check for updates once the command-line arguments have been processed,
    // to avoid printing any update notifications when the help message is
    // displayed.
    #[cfg(feature = "update-informer")]
    if !args.skip_update_check {
        check_for_update(env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
    }

    // Run the interactive TUI only if chip or name is missing
    if args.chip.is_none() || args.name.is_none() {
        setup_args_interactive(&mut args)?;
    }

    let chip = args.chip.unwrap();

    let name = args.name.clone().unwrap();

    let path = &args
        .output_path
        .clone()
        .unwrap_or_else(|| env::current_dir().unwrap());

    if !path.is_dir() {
        bail!("Output path must be a directory");
    }

    if path.join(&name).exists() {
        bail!("Directory already exists");
    }

    let versions = cargo::CargoToml::load(
        TEMPLATE_FILES
            .iter()
            .find(|(k, _)| *k == "Cargo.toml")
            .expect("Cargo.toml not found in template")
            .1,
    )
    .expect("Failed to read Cargo.toml");

    let esp_hal_version = versions.dependency_version("esp-hal");
    let esp_hal_version_full = if let Some(stripped) = esp_hal_version.strip_prefix("~") {
        let mut processed = stripped.to_string();
        while processed.chars().filter(|c| *c == '.').count() < 2 {
            processed.push_str(".0");
        }
        processed
    } else {
        esp_hal_version.clone()
    };

    let msrv: check::Version = versions.msrv().parse().unwrap();

    // Start toolchain scan as early as we know chip and msrv (TUI only).
    let mut toolchain_scan = if args.headless {
        None
    } else {
        Some(toolchain::start_toolchain_scan(
            chip,
            args.toolchain.clone(),
            msrv.clone(),
        ))
    };

    let mut template = TEMPLATE.clone();
    remove_incompatible_chip_options(chip, &mut template.options);
    module_selector::populate_module_category(chip, &mut template.options);
    process_options(&template, &args)?;

    // Initial selection for TUI/headless, including toolchain if provided.
    let mut initial_selected = args.option.clone();
    if let Some(ref tc) = args.toolchain {
        initial_selected.push(tc.clone());
    }

    let mut selected = if !args.headless {
        let repository = tui::Repository::new(chip, template.options.clone(), &initial_selected);

        let mut app = tui::App::new(repository);

        let mut terminal = tui::init_terminal()?;

        let mut final_selected: Option<Vec<String>> = None;
        let mut running = true;
        let mut toolchains_populated = false;

        while running {
            // Toolchain scan in the background.
            // In order to prevent the application from being slow,
            // toolchain scanning and filtering is done in a separate thread
            // and we poll the result before each frame is drawn
            if let Some(scan) = toolchain_scan.as_mut() {
                match scan.try_get_toolchain_list() {
                    None => {
                        // still loading
                        app.set_toolchains_loading(true);
                    }
                    Some(Ok(list)) => {
                        if !toolchains_populated {
                            toolchain::populate_toolchain_category_from_list(
                                &mut template.options,
                                &mut Vec::new(),
                                list,
                            )?;

                            toolchain::populate_toolchain_category_from_list(
                                &mut app.repository.config.options,
                                &mut app.repository.config.flat_options,
                                list,
                            )?;

                            toolchains_populated = true;
                        }
                        app.set_toolchains_loading(false);
                    }

                    Some(Err(err)) => {
                        log::warn!("Toolchain scan failed: {err}");
                        app.set_toolchains_loading(false);
                        toolchains_populated = true;
                    }
                }
            }

            // draw a frame
            app.draw(&mut terminal)?;

            // handle input (non-blocking poll)
            if event::poll(Duration::from_millis(100))? {
                match app.handle_event(event::read()?)? {
                    tui::AppResult::Continue => {}
                    tui::AppResult::Quit => {
                        final_selected = None;
                        running = false;
                    }
                    tui::AppResult::Save => {
                        final_selected = Some(app.selected_options());
                        running = false;
                    }
                }
            }
        }

        tui::restore_terminal()?;
        // done with the TUI

        let Some(selected) = final_selected else {
            return Ok(());
        };

        selected
    } else {
        initial_selected
    };

    let flat_options = flatten_options(&template.options);
    let mut toolchain_replaced = false;
    let selected_options = format!(
        "--chip {}{}",
        chip,
        selected.iter().fold(String::new(), |mut acc, s| {
            if Some(s) == args.toolchain.as_ref() && !toolchain_replaced {
                acc.push_str(" --toolchain ");
                // Just in case someone decides to call their toolchain `defmt`, make sure we only replace it once
                toolchain_replaced = true;
            } else {
                acc.push_str(" -o ");
            };
            acc.push_str(s);
            acc
        })
    );
    if !args.headless {
        println!("Selected options: {selected_options}");
    }

    let selected_toolchain = if args.headless {
        args.toolchain.clone()
    } else {
        selected.iter().find_map(|name| {
            let (_, opt) = find_option(name, &flat_options, chip)?;
            if opt.selection_group == "toolchain" {
                Some(name.clone())
            } else {
                None
            }
        })
    };

    let selected_module = selected.iter().find_map(|name| {
        let (_, opt) = find_option(name, &flat_options, chip)?;
        if opt.selection_group == "module" {
            Some(name.clone())
        } else {
            None
        }
    });

    // Also add the active selection groups
    for idx in 0..selected.len() {
        let (_, option) = find_option(&selected[idx], &flat_options, chip).unwrap();
        selected.push(option.selection_group.clone());
    }

    selected.push(chip.to_string());

    selected.push(if chip.is_riscv() {
        "riscv".to_string()
    } else {
        "xtensa".to_string()
    });

    // mark that a toolchain was explicitly selected for template replacements
    if selected_toolchain.is_some() {
        selected.push("toolchain-selected".to_string());
    }

    let wokwi_devkit = match chip {
        Chip::Esp32 => "board-esp32-devkit-c-v4",
        Chip::Esp32c2 => "",
        Chip::Esp32c3 => "board-esp32-c3-devkitm-1",
        Chip::Esp32c5 => "board-esp32-c5-devkitc-1",
        Chip::Esp32c6 => "board-esp32-c6-devkitc-1",
        Chip::Esp32c61 => "board-esp32-c61-devkitc-1",
        Chip::Esp32h2 => "board-esp32-h2-devkitm-1",
        Chip::Esp32s2 => "board-esp32-s2-devkitm-1",
        Chip::Esp32s3 => "board-esp32-s3-devkitc-1",
    };

    // based on esp32 linker scripts
    // TODO: add this to esp-metadata
    let max_dram2 = match chip {
        Chip::Esp32 => 98768,
        Chip::Esp32c2 => 66416, // 0x3fcdeb70 -0x3fcce800
        Chip::Esp32c3 => 66320, // 0x3fcde710 - 3fcce400
        Chip::Esp32c5 => 65536, // 0x4085e5a0 - 0x4084e5a0
        Chip::Esp32c6 => 65536, // 0x4087e610 - 0x4086e610
        Chip::Esp32c61 => 65536, // 0x4084ea70 - 0x4083ea70
        Chip::Esp32h2 => 69392, // 0x4084fee0 - 0x4083efd0
        Chip::Esp32s2 => 139264,
        Chip::Esp32s3 => 73744, // 0x3FCED710 - 0x3FCDB700
    };

    let mut variables = vec![
        ("project-name".to_string(), name.clone()),
        ("mcu".to_string(), chip.to_string()),
        ("wokwi-board".to_string(), wokwi_devkit.to_string()),
        (
            "generate-version".to_string(),
            env!("CARGO_PKG_VERSION").to_string(),
        ),
        ("generate-parameters".to_string(), selected_options),
        ("esp-hal-version-full".to_string(), esp_hal_version_full),
        ("max-dram2-uninit".to_string(), format!("{max_dram2}")),
    ];

    variables.push(("rust_target".to_string(), chip.target().to_string()));

    if let Some(tc) = selected_toolchain.as_ref() {
        variables.push(("rust_toolchain".to_string(), tc.clone()));
    }

    if let Some(ref module_name) = selected_module {
        if let Some(module) = esp_generate::modules::find_module(module_name) {
            // Only set module-selected if there are GPIOs to reserve,
            // otherwise the generated code would have unused `peripherals` variable
            if !module.reserved_gpios.is_empty() {
                selected.push("module-selected".to_string());
                if module.octal_psram {
                    selected.push("octal-psram".to_string());
                }
                let reserved_gpio_code = module
                    .reserved_gpios
                    .iter()
                    .map(|g| format!("    let _ = peripherals.GPIO{g};"))
                    .collect::<Vec<_>>()
                    .join("\n");
                variables.push(("reserved_gpio_code".to_string(), reserved_gpio_code));
            }
        }
    }

    let project_dir = path.join(&name);
    fs::create_dir(&project_dir)?;

    for &(file_path, contents) in template_files::TEMPLATE_FILES.iter() {
        let mut file_path = file_path.to_string();
        if let Some(processed) = process_file(contents, &selected, &variables, &mut file_path) {
            let file_path = project_dir.join(file_path);

            fs::create_dir_all(file_path.parent().unwrap())?;
            fs::write(file_path, processed)?;
        }
    }

    // Run cargo fmt:
    Command::new("cargo")
        .args([
            "fmt",
            "--",
            "--config",
            "group_imports=StdExternalCrate",
            "--config",
            "imports_granularity=Module",
        ])
        .current_dir(&project_dir)
        .output()?;

    // Format Cargo.toml:
    let input = fs::read_to_string(project_dir.join("Cargo.toml"))?;
    let format_options = Options {
        align_entries: true,
        reorder_keys: true,
        reorder_arrays: true,
        ..Default::default()
    };
    let formated = taplo::formatter::format(&input, format_options);
    fs::write(project_dir.join("Cargo.toml"), formated)?;

    if should_initialize_git_repo(&project_dir) {
        // Run git init:
        Command::new("git")
            .arg("init")
            .current_dir(&project_dir)
            .output()?;
    } else {
        log::warn!("Current directory is already in a git repository, skipping git initialization");
    }

    check::check(
        &project_dir,
        chip,
        selected.contains(&"probe-rs".to_string()),
        msrv,
        selected.contains(&"stack-smashing-protection".to_string())
            && selected.contains(&"riscv".to_string()),
        args.headless,
        selected_toolchain.as_deref(),
    );

    Ok(())
}

fn remove_incompatible_chip_options(chip: Chip, options: &mut Vec<GeneratorOptionItem>) {
    options.retain_mut(|opt| match opt {
        GeneratorOptionItem::Category(category) => {
            remove_incompatible_chip_options(chip, &mut category.options);
            !category.options.is_empty()
        }
        GeneratorOptionItem::Option(option) => {
            option.chips.is_empty() || option.chips.contains(&chip)
        }
    });
}

#[derive(Clone, Copy)]
enum BlockKind {
    // All lines are included
    Root,

    // (current branch to be included, any previous branches included)
    IfElse(bool, bool),
}

impl BlockKind {
    fn include_line(self) -> bool {
        match self {
            BlockKind::Root => true,
            BlockKind::IfElse(current, any) => current && !any,
        }
    }

    fn new_if(current: bool) -> BlockKind {
        BlockKind::IfElse(current, false)
    }

    fn into_else_if(self, condition: bool) -> BlockKind {
        let BlockKind::IfElse(previous, any) = self else {
            panic!("ELIF without IF");
        };
        BlockKind::IfElse(condition, any || previous)
    }

    fn into_else(self) -> BlockKind {
        let BlockKind::IfElse(previous, any) = self else {
            panic!("ELSE without IF");
        };
        BlockKind::IfElse(!any, any || previous)
    }
}

fn process_file(
    contents: &str,                 // Raw content of the file
    options: &[String],             // Selected options
    variables: &[(String, String)], // Variables and their values in tuples
    file_path: &mut String,         // File path to be modified
) -> Option<String> {
    let mut res = String::new();

    let mut replace: Option<Vec<(String, String)>> = None;
    let mut include = vec![BlockKind::Root];
    let mut file_directives = true;

    // Create a new Rhai engine and scope
    let mut engine = somni_expr::Context::new();

    // Define a custom function to check if conditions of the options.
    engine.add_function("option", move |cond: &str| -> bool {
        options.iter().any(|c| c == cond)
    });

    let mut include_file = true;

    for (line_no, line) in contents.lines().enumerate() {
        let line_no = line_no + 1;
        let trimmed: &str = line.trim();

        // We check for the first line to see if we should include the file
        if file_directives {
            // Determine if the line starts with a known include directive
            if let Some(cond) = trimmed
                .strip_prefix("//INCLUDEFILE ")
                .or_else(|| trimmed.strip_prefix("#INCLUDEFILE "))
                .or_else(|| trimmed.strip_prefix("--INCLUDEFILE "))
            {
                include_file = engine.evaluate::<bool>(cond).unwrap();
                continue;
            } else if let Some(include_as) = trimmed
                .strip_prefix("//INCLUDE_AS ")
                .or_else(|| trimmed.strip_prefix("#INCLUDE_AS "))
                .or_else(|| trimmed.strip_prefix("--INCLUDE_AS "))
            {
                *file_path = include_as.trim().to_string();
                continue;
            }
        }
        if !include_file {
            return None;
        }

        file_directives = false;

        // that's a bad workaround
        if trimmed == "#[rustfmt::skip]" {
            log::info!("Skipping rustfmt");
            continue;
        }

        // Check if we should replace the next line with the key/value of a variable
        if let Some(what) = trimmed
            .strip_prefix("#REPLACE ")
            .or_else(|| trimmed.strip_prefix("//REPLACE "))
            .or_else(|| trimmed.strip_prefix("--REPLACE "))
        {
            let replacements = what
                .split(" && ")
                .filter_map(|pair| {
                    let mut parts = pair.split_whitespace();
                    if let (Some(pattern), Some(var_name)) = (parts.next(), parts.next()) {
                        if let Some((_, value)) = variables.iter().find(|(key, _)| key == var_name)
                        {
                            Some((pattern.to_string(), value.clone()))
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                })
                .collect::<Vec<_>>();

            if !replacements.is_empty() {
                replace = Some(replacements);
            }
        // Check if we should include the next line(s)
        } else if trimmed.starts_with("#IF ")
            || trimmed.starts_with("//IF ")
            || trimmed.starts_with("--IF ")
        {
            let cond = trimmed
                .strip_prefix("#IF ")
                .or_else(|| trimmed.strip_prefix("//IF "))
                .or_else(|| trimmed.strip_prefix("--IF "))
                .unwrap();
            let last = *include.last().unwrap();

            // Only evaluate condition if this IF is in a branch that should be included
            let current = if last.include_line() {
                engine.evaluate::<bool>(cond).unwrap()
            } else {
                false
            };

            include.push(BlockKind::new_if(current));
        } else if trimmed.starts_with("#ELIF ")
            || trimmed.starts_with("//ELIF ")
            || trimmed.starts_with("--ELIF ")
        {
            let cond = trimmed
                .strip_prefix("#ELIF ")
                .or_else(|| trimmed.strip_prefix("//ELIF "))
                .or_else(|| trimmed.strip_prefix("--ELIF "))
                .unwrap();
            let last = include.pop().unwrap();

            // Only evaluate condition if no other branches evaluated to true
            let current = if matches!(last, BlockKind::IfElse(false, false)) {
                engine.evaluate::<bool>(cond).unwrap()
            } else {
                false
            };

            include.push(last.into_else_if(current));
        } else if trimmed.starts_with("#ELSE")
            || trimmed.starts_with("//ELSE")
            || trimmed.starts_with("--ELSE")
        {
            let last = include.pop().unwrap();
            include.push(last.into_else());
        } else if trimmed.starts_with("#ENDIF")
            || trimmed.starts_with("//ENDIF")
            || trimmed.starts_with("--ENDIF")
        {
            let prev = include.pop();
            assert!(
                matches!(prev, Some(BlockKind::IfElse(_, _))),
                "ENDIF without IF in {file_path}:{line_no}"
            );
        // Trim #+ and //+
        } else if include.iter().all(|v| v.include_line()) {
            let mut line = line.to_string();

            if trimmed.starts_with("#+") {
                line = line.replace("#+", "");
            }

            if trimmed.starts_with("//+") {
                line = line.replace("//+", "");
            }

            if trimmed.starts_with("--+") {
                line = line.replace("--+", "");
            }

            if let Some(replacements) = &replace {
                for (pattern, value) in replacements {
                    line = line.replace(pattern, value);
                }
            }

            res.push_str(&line);
            res.push('\n');

            replace = None;
        }
    }

    Some(res)
}

fn process_options(template: &Template, args: &Args) -> Result<()> {
    let mut success = true;
    let all_options = template.all_options();

    let arg_chip = args.chip.unwrap();

    let flat_options = flatten_options(&template.options);
    let selected_config = ActiveConfiguration {
        chip: arg_chip,
        selected: args
            .option
            .iter()
            .flat_map(|opt_name| flat_options.iter().position(|o| &o.name == opt_name))
            .collect(),
        flat_options,
        options: template.options.clone(),
    };

    let mut same_selection_group: HashMap<&str, Vec<&str>> = HashMap::new();

    for option in &selected_config.selected {
        let option = selected_config.flat_options[*option].name.as_str();
        // Find the matching option in the template
        let mut option_found = false;
        let mut option_found_for_chip = false;
        for &option_item in all_options.iter().filter(|item| item.name == option) {
            option_found = true; // The input refers to an existing option.

            // Check if the chip is supported. If the chip list is empty, all chips are supported.
            // We don't immediately fail in case the option is not present for the chip, because
            // it may exist as a separate entry (e.g. with different properties).
            if !option_item.chips.contains(&arg_chip) && !option_item.chips.is_empty() {
                continue;
            }

            option_found_for_chip = true;

            // Is the option allowed to be selected?
            if selected_config.is_option_active(option_item) {
                // Even if the option is active, another from the same selection group may be present.
                // The TUI would deselect the previous option, but when specified from the command line,
                // we shouldn't assume which one the user actually wants. Therefore, we collect the selected
                // options that belong to a selection group and return an error (later) if multiple ones
                // are selected in the same group.
                if !option_item.selection_group.is_empty() {
                    let options = same_selection_group
                        .entry(&option_item.selection_group)
                        .or_default();

                    if !options.contains(&option) {
                        options.push(option);
                    }
                }
                continue;
            }

            // Something is wrong, print the constraints that are not met.
            success = false;
            let o = GeneratorOptionItem::Option(option_item.clone());
            let Relationships {
                requires,
                disabled_by,
                ..
            } = selected_config.collect_relationships(&o);

            if !requires
                .iter()
                .all(|requirement| args.option.iter().any(|r| r == requirement))
            {
                log::error!(
                    "Option '{}' requires {}",
                    option_item.name,
                    option_item.requires.join(", ")
                );
            }

            for disabled in disabled_by {
                log::error!("Option '{}' is disabled by {}", option_item.name, disabled);
            }
        }

        if !option_found {
            log::error!("Unknown option '{option}'");
            success = false;
        } else if !option_found_for_chip {
            log::error!("Option '{option}' is not supported for chip {arg_chip}");
            success = false;
        }
    }

    for (_group, entries) in same_selection_group {
        if entries.len() > 1 {
            log::error!(
                "{}",
                append_list_as_sentence(
                    "The following options can not be enabled together:",
                    "",
                    &entries
                )
            );
            success = false;
        }
    }

    if !success {
        bail!("Invalid options provided");
    } else {
        Ok(())
    }
}

fn should_initialize_git_repo(mut path: &Path) -> bool {
    loop {
        let dotgit_path = path.join(".git");
        if dotgit_path.exists() && dotgit_path.is_dir() {
            return false;
        }

        if let Some(parent) = path.parent() {
            path = parent;
        } else {
            break;
        }
    }

    true
}

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

    #[test]
    fn test_nested_if_else1() {
        let res = process_file(
            r#"
        #IF option("opt1")
        opt1
        #IF option("opt2")
        opt2
        #ELSE
        !opt2
        #ENDIF
        #ELSE
        !opt1
        #ENDIF
        "#,
            &["opt1".to_string(), "opt2".to_string()],
            &[],
            &mut String::from("main.rs"),
        )
        .unwrap();

        assert_eq!(
            r#"
        opt1
        opt2
        "#
            .trim(),
            res.trim()
        );
    }

    #[test]
    fn test_nested_if_else2() {
        let res = process_file(
            r#"
        #IF option("opt1")
        opt1
        #IF option("opt2")
        opt2
        #ELSE
        !opt2
        #ENDIF
        #ELSE
        !opt1
        #ENDIF
        "#,
            &[],
            &[],
            &mut String::from("main.rs"),
        )
        .unwrap();

        assert_eq!(
            r#"
        !opt1
        "#
            .trim(),
            res.trim()
        );
    }

    #[test]
    fn test_nested_if_else3() {
        let res = process_file(
            r#"
        #IF option("opt1")
        opt1
        #IF option("opt2")
        opt2
        #ELSE
        !opt2
        #ENDIF
        #ELSE
        !opt1
        #ENDIF
        "#,
            &["opt1".to_string()],
            &[],
            &mut String::from("main.rs"),
        )
        .unwrap();

        assert_eq!(
            r#"
        opt1
        !opt2
        "#
            .trim(),
            res.trim()
        );
    }

    #[test]
    fn test_nested_if_else4() {
        let res = process_file(
            r#"
        #IF option("opt1")
        #IF option("opt2")
        opt2
        #ELSE
        !opt2
        #ENDIF
        opt1
        #ENDIF
        "#,
            &["opt1".to_string()],
            &[],
            &mut String::from("main.rs"),
        )
        .unwrap();

        assert_eq!(
            r#"
        !opt2
        opt1
        "#
            .trim(),
            res.trim()
        );
    }

    #[test]
    fn test_nested_if_else5() {
        let res = process_file(
            r#"
        #IF option("opt1")
        #IF option("opt2")
        opt2
        #ELSE
        !opt2
        #ENDIF
        opt1
        #ENDIF
        "#,
            &["opt2".to_string()],
            &[],
            &mut String::from("main.rs"),
        )
        .unwrap();

        assert_eq!(
            r#"
        "#
            .trim(),
            res.trim()
        );
    }

    #[test]
    fn test_basic_elseif() {
        let template = r#"
        #IF option("opt1")
        opt1
        #ELIF option("opt2")
        opt2
        #ELIF option("opt3")
        opt3
        #ELSE
        opt4
        #ENDIF
        "#;

        const PAIRS: &[(&[&str], &str)] = &[
            (&["opt1"], "opt1"),
            (&["opt1", "opt2"], "opt1"),
            (&["opt1", "opt3"], "opt1"),
            (&["opt1", "opt2", "opt3"], "opt1"),
            (&["opt2"], "opt2"),
            (&["opt2", "opt3"], "opt2"),
            (&["opt3"], "opt3"),
            (&["opt4"], "opt4"),
            (&[], "opt4"),
        ];

        for (options, expected) in PAIRS.iter().cloned() {
            let res = process_file(
                template,
                &options.iter().map(|o| o.to_string()).collect::<Vec<_>>(),
                &[],
                &mut String::from("main.rs"),
            )
            .unwrap();
            assert_eq!(expected, res.trim(), "options: {:?}", options);
        }
    }
}