espforge 0.6.0

a scaffolding++ tool for creating esp32 no_std esphal without the hassle
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
//! `espforge build` / `espforge gen`: ESPF source -> firmware project
//! (-> `cargo build`).
//!
//! Pipeline: resolve the source (FILE, `--example`, or the `.espf` in the
//! current directory) -> `pipeline::validate` (the same as `check`) ->
//! generate -> write -> optional compile.
//!
//! `gen` is this command with `Stage::Generate`; `build` is `Stage::All`.
//!
//! Exit codes: 0 success, 1 user errors (diagnostics already printed),
//! 2 internal / IO failure.

use anyhow::{Result, anyhow};
use clap::Args;
use espforge_core::project::{self, ProjectError};
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode};

use espforge_core::pipeline;
use espforge_core::source::{Source, resolve_source as resolve_src};

use super::answers::AnswerArgs;
use super::report;

/// How far the pipeline runs. Not a flag: the `gen` / `build` commands pick it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Stage {
    /// Write the project, stop before cargo (`gen`).
    Generate,
    /// Generate, then `cargo build` (`build`).
    #[default]
    All,
}

#[derive(Args, Debug, Clone, Default)]
pub struct BuildArgs {
    /// Path to the ESPF project file (default: the single .espf in the current directory).
    /// App logic: src/app.rs or app/rust/app.rs next to it
    pub file: Option<PathBuf>,
    /// Use an embedded example instead of a file, e.g. 01.Basics/helloworld
    #[arg(long, value_name = "CATEGORY/NAME", conflicts_with = "file")]
    pub example: Option<String>,
    /// Output directory for the generated project
    #[arg(short, long, default_value = "build")]
    pub out: PathBuf,
    /// Set by the command (`gen` / `build`), not by a flag.
    #[arg(skip)]
    pub stage: Stage,
    /// Set by `build --release`.
    #[arg(skip)]
    pub release: bool,
    /// Use a local espforge-runtime crate instead of the published one
    /// (or set ESPFORGE_RUNTIME_PATH)
    #[arg(long)]
    pub runtime_path: Option<PathBuf>,
    /// Also write the effective spec (file + flag overrides) to this path
    #[arg(long, value_name = "PATH")]
    pub write_spec: Option<PathBuf>,
    #[command(flatten)]
    pub answers: AnswerArgs,
}

/// Why a build stopped.
#[derive(Debug)]
pub enum Failure {
    /// The user's input is at fault; the message / diagnostics are already printed.
    User,
    /// Something broke inside espforge or the OS.
    Internal(anyhow::Error),
}

impl From<anyhow::Error> for Failure {
    fn from(e: anyhow::Error) -> Self {
        Failure::Internal(e)
    }
}

impl From<std::io::Error> for Failure {
    fn from(e: std::io::Error) -> Self {
        Failure::Internal(e.into())
    }
}

/// Print `❌ msg` and return the user-error marker.
fn user(msg: impl std::fmt::Display) -> Failure {
    eprintln!("❌ {msg}");
    Failure::User
}

pub fn run(args: BuildArgs) -> ExitCode {
    match execute(&args) {
        Ok(()) => ExitCode::SUCCESS,
        Err(Failure::User) => ExitCode::from(1),
        Err(Failure::Internal(e)) => {
            eprintln!("❌ {e:#}");
            ExitCode::from(2)
        }
    }
}

// -------------------------------------------------------------------- source
//
// File collection (Wokwi overlays, app logic, runtime source) lives in
// `espforge_core::source` (step 3c); only process-spawning `cargo_build` stays here.

fn resolve_source(args: &BuildArgs) -> Result<Source, Failure> {
    resolve_src(args.file.as_deref(), args.example.as_deref()).map_err(user)
}

fn cargo_build(out: &Path, release: bool) -> Result<(), Failure> {
    if !out.join("Cargo.toml").is_file() {
        return Err(user(format!(
            "nothing to compile: {} has no Cargo.toml",
            out.display()
        )));
    }
    let mut cmd = Command::new("cargo");
    cmd.arg("build");
    if release {
        cmd.arg("--release");
    }
    let status = cmd
        .current_dir(out)
        .status()
        .map_err(|e| Failure::Internal(anyhow!("failed to run cargo: {e}")))?;
    if status.success() {
        println!("build: compiled {}", out.display());
        Ok(())
    } else {
        Err(user("cargo build failed"))
    }
}

/// A core failure with a terminal and an exit code: located spec problems
/// render as snippets, user problems as the one-line `❌`, ours as exit 2.
fn failed(error: ProjectError, source: &Source) -> Failure {
    match error {
        ProjectError::Spec(diagnostics) => {
            report::diagnostics(&source.name, &source.text, &diagnostics);
            Failure::User
        }
        ProjectError::User(message) => user(message),
        ProjectError::Internal(e) => Failure::Internal(e),
    }
}

// ------------------------------------------------------------------ pipeline

pub fn execute(args: &BuildArgs) -> Result<(), Failure> {
    let source = resolve_source(args)?;

    // Exactly what `check` runs.
    let checked = match pipeline::validate(&source.text, &args.answers.overrides()) {
        Ok(c) => c,
        Err(invalid) => {
            report::invalid(&invalid, &source.name, &source.text);
            return Err(Failure::User);
        }
    };
    for note in &checked.notes {
        eprintln!("{note}");
    }

    // Be explicit rather than silently generating firmware that lacks devices.
    // Wiring errors render as snippets, like the `validate` path above.
    let board = match pipeline::board(&checked) {
        Ok(board) => board,
        Err(invalid) => {
            report::invalid(&invalid, &source.name, &source.text);
            return Err(Failure::User);
        }
    };

    if let Some(path) = &args.write_spec {
        project::write_spec(&checked, path).map_err(|e| failed(e, &source))?;
        println!("build: wrote spec to {}", path.display());
    }

    let written = project::generate(
        &source,
        &checked,
        &board,
        args.runtime_path.clone(),
        &args.out,
    )
    .map_err(|e| failed(e, &source))?;

    println!(
        "build: wrote '{}' to {}",
        written.crate_name,
        args.out.display()
    );
    if args.stage == Stage::Generate {
        println!("  next: cd {} && cargo build", args.out.display());
        return Ok(());
    }
    cargo_build(&args.out, args.release)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::commands::answers::{ConsoleArg, RuntimeArg};

    fn example_args(example: &str, out: &Path) -> BuildArgs {
        BuildArgs {
            example: Some(example.into()),
            out: out.to_path_buf(),
            stage: Stage::Generate,
            ..Default::default()
        }
    }

    fn is_user<T: std::fmt::Debug>(r: Result<T, Failure>) -> bool {
        matches!(r, Err(Failure::User))
    }

    #[test]
    fn builds_the_helloworld_example() {
        let dir = tempfile::tempdir().unwrap();
        let out = dir.path().join("out");
        execute(&example_args("01.Basics/helloworld", &out)).unwrap();
        for f in [
            "Cargo.toml",
            "build.rs",
            "src/lib.rs",
            "src/bin/main.rs",
            "src/app.rs",
            "README.txt",
            ".espforge/manifest.json",
        ] {
            assert!(out.join(f).is_file(), "missing {f}");
        }
        assert!(
            std::fs::read_to_string(out.join("src/app.rs"))
                .unwrap()
                .contains("Hello World!")
        );
        assert!(
            std::fs::read_to_string(out.join("Cargo.toml"))
                .unwrap()
                .contains("name = \"hello_world\"")
        );
    }

    #[test]
    fn builds_the_blink_example_with_a_led_component() {
        let dir = tempfile::tempdir().unwrap();
        let out = dir.path().join("out");
        execute(&example_args("01.Basics/blink", &out)).unwrap();
        let generated = std::fs::read_to_string(out.join("src/generated.rs")).unwrap();
        assert!(
            generated.contains("pub red_led: espforge_runtime::Led,"),
            "{generated}"
        );
        assert!(generated.contains("GPIO18"), "{generated}");
        let diagram = std::fs::read_to_string(out.join("diagram.json")).unwrap();
        assert!(diagram.contains("esp:18"), "{diagram}");
        assert!(
            std::fs::read_to_string(out.join("src/bin/main.rs"))
                .unwrap()
                .contains("Components::new(&mut registry)")
        );
    }

    #[test]
    fn rebuilding_is_fine_but_edited_owned_files_are_refused() {
        let dir = tempfile::tempdir().unwrap();
        let out = dir.path().join("out");
        let args = example_args("01.Basics/helloworld", &out);
        execute(&args).unwrap();
        execute(&args).unwrap();
        std::fs::write(out.join("src/lib.rs"), "// mine").unwrap();
        assert!(is_user(execute(&args)));
    }

    #[test]
    fn flags_override_the_file_in_the_output() {
        let dir = tempfile::tempdir().unwrap();
        let out = dir.path().join("out");
        let mut args = example_args("01.Basics/helloworld", &out);
        args.answers.chip = Some("esp32s3".into());
        args.answers.runtime = Some(RuntimeArg::Embassy);
        args.answers.console = Some(ConsoleArg::JtagSerial);
        execute(&args).unwrap();
        let cargo = std::fs::read_to_string(out.join("Cargo.toml")).unwrap();
        assert!(
            cargo.contains("\"esp32s3\"")
                && cargo.contains("\"jtag-serial\"")
                && cargo.contains("embassy")
        );
    }

    #[test]
    fn option_errors_from_flags_are_user_errors() {
        let dir = tempfile::tempdir().unwrap();
        let mut args = example_args("01.Basics/helloworld", &dir.path().join("out"));
        args.answers.options = vec!["wifi=true".into()]; // derived: not user-settable
        assert!(is_user(execute(&args)));
        args.answers.options = vec!["nope=1".into()];
        assert!(is_user(execute(&args)));
    }

    #[test]
    fn unsupported_sections_are_reported_not_silently_dropped() {
        let dir = tempfile::tempdir().unwrap();
        let src = "# espforge\n  <project name=\"t\" />\n  <chip type=\"esp32c3\" />\n  <runtime type=\"blocking\" />\n# peripherals\n  <pwm id=\"pwm0\" />\n# components\n# devices\n# services\n";
        let f = dir.path().join("pwm.espf");
        std::fs::write(&f, src).unwrap();
        let args = BuildArgs {
            file: Some(f),
            out: dir.path().join("out"),
            stage: Stage::Generate,
            ..Default::default()
        };
        assert!(is_user(execute(&args)));
    }

    #[test]
    fn builds_the_button_example_with_button_and_led_components() {
        let dir = tempfile::tempdir().unwrap();
        let out = dir.path().join("out");
        execute(&example_args("02.Digital/button", &out)).unwrap();
        let generated = std::fs::read_to_string(out.join("src/generated.rs")).unwrap();
        assert!(
            generated.contains("pub red_led: espforge_runtime::Led,"),
            "{generated}"
        );
        assert!(
            generated.contains("pub button: espforge_runtime::Button,"),
            "{generated}"
        );
        assert!(generated.contains("GPIO9"), "{generated}");
        let diagram = std::fs::read_to_string(out.join("diagram.json")).unwrap();
        assert!(diagram.contains("esp:9"), "{diagram}");
    }

    #[test]
    fn source_must_be_exactly_one_of_file_or_example() {
        // No source at all: looks for a single .espf in the current directory
        // (the crate dir under `cargo test`, which has none).
        let none = BuildArgs {
            stage: Stage::Generate,
            ..Default::default()
        };
        assert!(is_user(execute(&none)));
        let both = BuildArgs {
            file: Some("x.espf".into()),
            example: Some("01.Basics/helloworld".into()),
            stage: Stage::Generate,
            ..Default::default()
        };
        assert!(is_user(execute(&both)));
        let missing = BuildArgs {
            example: Some("no/such".into()),
            stage: Stage::Generate,
            ..Default::default()
        };
        assert!(is_user(execute(&missing)));
    }

    #[test]
    fn syntax_errors_in_a_file_are_user_errors() {
        let dir = tempfile::tempdir().unwrap();
        let f = dir.path().join("bad.espf");
        std::fs::write(&f, "# espforge\n  <gpio id=\"a\" pin=\"4 />\n").unwrap();
        let args = BuildArgs {
            file: Some(f),
            out: dir.path().join("out"),
            stage: Stage::Generate,
            ..Default::default()
        };
        assert!(is_user(execute(&args)));
    }

    #[test]
    fn builds_a_file_and_finds_app_logic_in_either_layout() {
        let dir = tempfile::tempdir().unwrap();
        let spec_dir = dir.path().join("proj");
        std::fs::create_dir_all(&spec_dir).unwrap();
        let hello = espforge_examples::find("01.Basics/helloworld").unwrap();
        std::fs::write(spec_dir.join("hello.espf"), &hello.content).unwrap();
        let out = dir.path().join("out");
        let args = BuildArgs {
            file: Some(spec_dir.join("hello.espf")),
            out: out.clone(),
            stage: Stage::Generate,
            ..Default::default()
        };

        // no app logic at all
        assert!(is_user(execute(&args)));

        // example layout
        std::fs::create_dir_all(spec_dir.join("app/rust")).unwrap();
        std::fs::write(spec_dir.join("app/rust/app.rs"), "// example layout").unwrap();
        execute(&args).unwrap();
        assert_eq!(
            std::fs::read_to_string(out.join("src/app.rs")).unwrap(),
            "// example layout"
        );

        // src/app.rs wins when both exist
        std::fs::create_dir_all(spec_dir.join("src")).unwrap();
        std::fs::write(spec_dir.join("src/app.rs"), "// preferred").unwrap();
        execute(&args).unwrap();
        assert_eq!(
            std::fs::read_to_string(out.join("src/app.rs")).unwrap(),
            "// preferred"
        );
    }

    #[test]
    fn write_spec_produces_a_loadable_effective_spec() {
        let dir = tempfile::tempdir().unwrap();
        let spec_path = dir.path().join("effective.espf");
        let mut args = example_args("01.Basics/helloworld", &dir.path().join("out"));
        args.write_spec = Some(spec_path.clone());
        args.answers.chip = Some("esp32c6".into());
        execute(&args).unwrap();
        let text = std::fs::read_to_string(&spec_path).unwrap();
        assert!(text.contains("<chip type=\"esp32c6\" />"), "{text}");
        assert!(espforge_core::frontend::load(&text).is_ok(), "{text}");
    }

    #[test]
    fn runtime_path_is_validated_and_used() {
        let dir = tempfile::tempdir().unwrap();
        let rt = dir.path().join("rt");
        std::fs::create_dir_all(&rt).unwrap();
        let out = dir.path().join("out");
        let mut args = example_args("01.Basics/helloworld", &out);
        args.runtime_path = Some(rt.clone());
        execute(&args).unwrap();
        let cargo = std::fs::read_to_string(out.join("Cargo.toml")).unwrap();
        assert!(
            cargo.contains(&rt.to_string_lossy().replace('\\', "/")),
            "{cargo}"
        );

        args.runtime_path = Some(dir.path().join("not-a-dir"));
        assert!(is_user(execute(&args)));
    }

    #[test]
    fn cargo_build_needs_a_generated_project() {
        let dir = tempfile::tempdir().unwrap();
        assert!(is_user(cargo_build(dir.path(), false)));
    }

    #[test]
    fn an_unsupported_overlay_placeholder_is_a_user_error() {
        let dir = tempfile::tempdir().unwrap();
        let f = dir.path().join("t.espf");
        std::fs::write(
            &f,
            "# espforge\n  <project name=\"t\" />\n  <chip type=\"esp32c3\" />\n  <runtime type=\"blocking\" />\n# peripherals\n# components\n# devices\n# services\n",
        )
        .unwrap();
        std::fs::write(dir.path().join("diagram.json"), "{ \"x\": \"{{ nope }}\" }").unwrap();
        let args = BuildArgs {
            file: Some(f),
            out: dir.path().join("out"),
            stage: Stage::Generate,
            ..Default::default()
        };
        assert!(is_user(execute(&args)));
    }
}