Skip to main content

espforge_lib/examples/
mod.rs

1pub mod builder;
2pub mod config;
3pub mod fs;
4pub mod template;
5pub mod ui;
6
7use crate::cli::interactive::{self, Prompter};
8use crate::cli::model::ExampleConfig;
9use anyhow::Result;
10use builder::ConfigBuilder;
11use fs::OutputDirectory;
12use template::{ExampleExporter, ExampleTemplate};
13use ui::ResultPrinter;
14
15pub struct ExamplesArgs {
16    pub name: String,
17    pub project_name: Option<String>,
18    pub chip: Option<String>,
19}
20
21pub fn execute(args: ExamplesArgs) -> Result<()> {
22    let prompter = interactive::DialoguerPrompter::new();
23    execute_with_prompter(args, &prompter)
24}
25
26pub fn execute_noninteractive(args: ExamplesArgs) -> Result<()> {
27    let template_name = args.name.clone();
28    let project_name = args.project_name.unwrap_or_else(|| args.name.clone());
29
30    // Resolve chip: use --chip arg > read from example.yaml > default to esp32c3
31    let chip = if let Some(chip) = args.chip {
32        chip
33    } else {
34        ExampleTemplate::find(&template_name)
35            .ok()
36            .and_then(|t| t.read_chip_from_yaml())
37            .unwrap_or_else(|| "esp32c3".to_string())
38    };
39
40    let config = ExampleConfig {
41        template_name,
42        project_name,
43        chip,
44    };
45
46    // Validate example exists BEFORE creating any directories
47    ExampleTemplate::find(&config.template_name)
48        .map_err(|_| anyhow::anyhow!("Example '{}' not found", config.template_name))?;
49
50    // 2. Prepare Output Directory (Check existence, fail if exists)
51    let output = OutputDirectory::prepare_noninteractive(&config)?;
52
53    // 3. Export the Template and Update Config
54    let exporter = ExampleExporter::new();
55    let result = exporter.export(&config, &output)?;
56
57    // 4. Display Success
58    ResultPrinter::display_success(&result);
59
60    Ok(())
61}
62
63fn execute_with_prompter(args: ExamplesArgs, prompter: &dyn Prompter) -> Result<()> {
64    // 1. Resolve Configuration (Args + User Input)
65    let config = ConfigBuilder::from_args(args, prompter)?.build()?;
66
67    // 2. Prepare Output Directory (Check existence, confirm overwrite)
68    let output = OutputDirectory::prepare(&config, prompter)?;
69
70    // 3. Export the Template and Update Config
71    let exporter = ExampleExporter::new();
72    let result = exporter.export(&config, &output)?;
73
74    // 4. Display Success
75    ResultPrinter::display_success(&result);
76
77    Ok(())
78}