autumn-cli 0.5.0

CLI tool for the Autumn web framework
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
//! `autumn generate inbound_mail` — scaffold an inbound mail handler, test
//! fixture, and integration test.
//!
//! For a name like `Replies`, the generator produces:
//! - `src/inbound_mailers/replies.rs` — `RepliesMailHandler` using `#[inbound_mail]`.
//! - `src/inbound_mailers/mod.rs` — created/updated with `pub mod replies;`.
//! - `tests/replies_inbound_mail.rs` — integration test posting a captured
//!   Mailgun fixture payload and asserting the handler is invoked.
//! - `src/main.rs` — `mod inbound_mailers;` declaration and
//!   `.inbound_mail_router(…)` wired into the app builder chain.
//! - `Cargo.toml` — `"inbound-mailgun"` feature added to the `autumn-web` dependency.

use std::path::Path;

use super::emit::Plan;
use super::model::validate_resource_name;
use super::naming::{pascal, snake};
use super::schema_edit::{add_mod_declaration, ensure_autumn_web_feature, update_main_rs};
use super::{Flags, GenerateError, ensure_project_root};

/// Compute the file actions for `autumn generate inbound_mail <name>`.
///
/// # Errors
///
/// Returns [`GenerateError`] when the project layout or name is invalid.
pub fn plan_inbound_mail(project_root: &Path, name: &str) -> Result<Plan, GenerateError> {
    ensure_project_root(project_root)?;
    validate_resource_name(name)?;

    let snake_name = snake(name);
    let pascal_name = pascal(name);
    let struct_name = format!("{pascal_name}MailHandler");
    let handler_fn = snake_name.clone();
    let info_fn = format!("{snake_name}_handler_info");
    let module_path = format!("inbound_mailers::{snake_name}::{info_fn}");

    let mut plan = Plan::new(project_root);

    // ── src/inbound_mailers/<snake>.rs ─────────────────────────────────────
    plan.create(
        project_root
            .join("src")
            .join("inbound_mailers")
            .join(format!("{snake_name}.rs")),
        render_handler_file(&struct_name, &handler_fn, &snake_name),
    );

    // ── src/inbound_mailers/mod.rs ─────────────────────────────────────────
    let mod_path = project_root
        .join("src")
        .join("inbound_mailers")
        .join("mod.rs");
    plan.modify(
        mod_path.clone(),
        add_mod_declaration(&read_or_empty(&mod_path), &snake_name),
    );

    // ── tests/<snake>_inbound_mail.rs ──────────────────────────────────────
    plan.create(
        project_root
            .join("tests")
            .join(format!("{snake_name}_inbound_mail.rs")),
        render_integration_test(&struct_name, &snake_name, &handler_fn),
    );

    // ── src/main.rs — add mod inbound_mailers and .inbound_mail_router(…) ─
    let main_path = project_root.join("src").join("main.rs");
    let main_existing = std::fs::read_to_string(&main_path).map_err(|_| {
        GenerateError::Io(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            format!("missing {}", main_path.display()),
        ))
    })?;
    let with_mods = update_main_rs(&main_existing, &["inbound_mailers"], &[]);
    let updated_main = add_inbound_mail_router_to_app(&with_mods, &module_path);
    plan.modify(main_path, updated_main);

    // ── Cargo.toml — ensure autumn-web has the "inbound-mailgun" feature ───
    let cargo_path = project_root.join("Cargo.toml");
    let cargo_existing = read_or_empty(&cargo_path);
    let updated_cargo = ensure_autumn_web_feature(&cargo_existing, "inbound-mailgun");
    if updated_cargo != cargo_existing {
        plan.modify(cargo_path, updated_cargo);
    }

    Ok(plan)
}

fn read_or_empty(path: &Path) -> String {
    std::fs::read_to_string(path).unwrap_or_default()
}

fn render_handler_file(struct_name: &str, handler_fn: &str, _snake_name: &str) -> String {
    format!(
        r#"//! Generated by `autumn generate inbound_mail`.
//!
//! Edit freely — once generated this is ordinary user code.
//!
//! The `#[inbound_mail]` macro generates a `{handler_fn}_handler_info()` function
//! that returns an `InboundMailHandlerInfo` ready for registration.

use autumn_web::prelude::*;
use autumn_web::inbound_mail;
use autumn_web::inbound_mail::{{InboundEmail, InboundMailHandlerInfo}};

pub struct {struct_name};

/// Inbound mail handler.
///
/// The `to` attribute specifies the recipient pattern:
///   - Exact: `to = "support@company.com"`
///   - Plus-address: `to = "replies+{{token}}@company.com"` (token in `email.plus_token()`)
///   - Prefix: `to = "ticket+*"` (any ticket+… address)
#[inbound_mail(to = "*", processing = "background")]
async fn {handler_fn}(email: InboundEmail) -> AutumnResult<()> {{
    tracing::info!(
        from = %email.from,
        subject = %email.subject,
        attachments = email.attachments.len(),
        "{struct_name}: inbound email received"
    );
    // TODO: implement handler logic
    Ok(())
}}

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

    #[test]
    fn handler_info_has_expected_name() {{
        let info = {handler_fn}_handler_info();
        assert_eq!(info.name, "{handler_fn}");
    }}
}}
"#
    )
}

fn render_integration_test(struct_name: &str, snake_name: &str, handler_fn: &str) -> String {
    format!(
        r#"//! Integration test for `{struct_name}` inbound mail handler.
//!
//! Generated by `autumn generate inbound_mail`. Exercises the full
//! request-to-handler pipeline using a Mailgun webhook fixture.

use std::sync::atomic::{{AtomicUsize, Ordering}};

use autumn_web::inbound_mail::{{
    InboundEmail, InboundMailEndpointConfig, InboundMailHandlerInfo, InboundMailRouter,
    ProcessingMode, RecipientPattern, compute_mailgun_signature,
}};
use autumn_web::prelude::*;
use autumn_web::test::TestApp;

static HANDLER_CALLS: AtomicUsize = AtomicUsize::new(0);

fn test_handler(
    email: InboundEmail,
) -> std::pin::Pin<
    Box<dyn std::future::Future<Output = autumn_web::AutumnResult<()>> + Send + 'static>,
> {{
    HANDLER_CALLS.fetch_add(1, Ordering::SeqCst);
    let _ = email;
    Box::pin(async {{ Ok(()) }})
}}

#[get("/_ping")]
async fn ping() -> &'static str {{ "pong" }}

fn build_client(signing_key: &str) -> autumn_web::test::TestClient {{
    let router = InboundMailRouter::new()
        .endpoint(InboundMailEndpointConfig::mailgun("/inbound/mailgun", signing_key))
        .handler(InboundMailHandlerInfo {{
            name: "{handler_fn}",
            pattern: RecipientPattern::Any,
            processing: ProcessingMode::Sync,
            handler: test_handler,
        }});

    TestApp::new()
        .inbound_mail_router(router)
        .routes(routes![ping])
        .build()
}}

/// Captured Mailgun fixture — replace with a real payload from your provider
/// dashboard before shipping.
const FIXTURE_PAYLOAD: &[(&str, &str)] = &[
    ("from", "sender@example.com"),
    ("to", "inbox@company.com"),
    ("subject", "Test-email"),
    ("body-plain", "Hello-from-integration-test"),
];

#[tokio::test]
async fn {snake_name}_handler_processes_valid_mailgun_webhook() {{
    HANDLER_CALLS.store(0, Ordering::SeqCst);

    let key = "test-mailgun-signing-key";
    let ts = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs()
        .to_string();
    let token = "integration-test-token";
    let sig = compute_mailgun_signature(&ts, token, key);

    let mut body_parts: Vec<String> = vec![
        format!("timestamp={{ts}}"),
        format!("token={{token}}"),
        format!("signature={{sig}}"),
    ];
    for (k, v) in FIXTURE_PAYLOAD {{
        body_parts.push(format!("{{k}}={{v}}"));
    }}
    let body = body_parts.join("&");

    build_client(key)
        .post("/inbound/mailgun")
        .form(&body)
        .send()
        .await
        .assert_status(200);

    assert_eq!(
        HANDLER_CALLS.load(Ordering::SeqCst),
        1,
        "handler must have been invoked exactly once"
    );
}}
"#
    )
}

/// Insert an `.inbound_mail_router(...)` call with a Mailgun endpoint into
/// the app builder chain in `src/main.rs`. Idempotent.
fn add_inbound_mail_router_to_app(src: &str, handler_module_path: &str) -> String {
    let snippet = format!(
        ".inbound_mail_router(\
            ::autumn_web::inbound_mail::InboundMailRouter::new()\
                .endpoint(::autumn_web::inbound_mail::InboundMailEndpointConfig::mailgun(\
                    \"/inbound/mailgun\",\
                    std::env::var(\"MAILGUN_SIGNING_KEY\").unwrap_or_default(),\
                ))\
                .handler({handler_module_path}())\
        )"
    );

    // If a router call already exists, chain the new handler onto it instead of inserting
    // a second router. Skip if this specific handler is already registered.
    if let Some(router_pos) = src.find(".inbound_mail_router(") {
        if src.contains(handler_module_path) {
            return src.to_owned();
        }
        // Find the closing paren of the .inbound_mail_router(...) argument.
        let start = router_pos + ".inbound_mail_router(".len();
        let bytes = src.as_bytes();
        let mut depth = 1usize;
        let mut i = start;
        while i < bytes.len() {
            match bytes[i] {
                b'(' => depth += 1,
                b')' => {
                    depth -= 1;
                    if depth == 0 {
                        // Insert before the closing `)`, but skip over any
                        // trailing comma + whitespace that rustfmt may have
                        // added after the router expression. Without this,
                        // `handler(old),)` becomes `handler(old),.handler(new))`
                        // which is invalid Rust.
                        let mut insert_pos = i;
                        while insert_pos > start && bytes[insert_pos - 1].is_ascii_whitespace() {
                            insert_pos -= 1;
                        }
                        if insert_pos > start && bytes[insert_pos - 1] == b',' {
                            insert_pos -= 1;
                        }
                        let mut out = src.to_owned();
                        out.insert_str(insert_pos, &format!(".handler({handler_module_path}())"));
                        return out;
                    }
                }
                _ => {}
            }
            i += 1;
        }
        return src.to_owned();
    }

    // Insert after `.routes(` call if present, otherwise before `.run()`.
    let target = if src.contains(".routes(") {
        // Find the closing paren of the first .routes() call and insert after
        find_after_routes_call(src).map(|pos| {
            let mut out = src.to_owned();
            out.insert_str(pos, &format!("\n        {snippet}"));
            out
        })
    } else {
        None
    };

    target.unwrap_or_else(|| {
        // Fallback: insert before `.run()`.
        src.find(".run()").map_or_else(
            || format!("{src}\n// TODO: add to app builder: {snippet}"),
            |run_pos| {
                let mut out = src.to_owned();
                out.insert_str(run_pos, &format!("{snippet}\n        "));
                out
            },
        )
    })
}

fn find_after_routes_call(src: &str) -> Option<usize> {
    let mut pos = src.find(".routes(")?;
    pos += ".routes(".len();
    let bytes = src.as_bytes();
    let mut depth = 1usize;
    while pos < bytes.len() {
        match bytes[pos] {
            b'(' => depth += 1,
            b')' => {
                depth -= 1;
                if depth == 0 {
                    return Some(pos + 1);
                }
            }
            _ => {}
        }
        pos += 1;
    }
    None
}

/// CLI entry point for `autumn generate inbound_mail <name>`.
pub fn run(name: &str, flags: Flags) {
    let cwd = match std::env::current_dir() {
        Ok(d) => d,
        Err(e) => {
            eprintln!("Error: cannot determine current directory: {e}");
            std::process::exit(1);
        }
    };
    match plan_inbound_mail(&cwd, name).and_then(|p| p.execute(flags)) {
        Ok(()) => {}
        Err(e) => {
            eprintln!("Error: {e}");
            std::process::exit(1);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    fn project_with_main(main_content: &str) -> TempDir {
        let tmp = TempDir::new().unwrap();
        fs::write(
            tmp.path().join("Cargo.toml"),
            "[package]\nname=\"x\"\n\n[dependencies]\nautumn-web = \"0.6\"\n",
        )
        .unwrap();
        fs::create_dir_all(tmp.path().join("src")).unwrap();
        fs::write(tmp.path().join("src/main.rs"), main_content).unwrap();
        tmp
    }

    fn default_main() -> &'static str {
        r#"use autumn_web::prelude::*;

#[get("/")]
async fn index() -> &'static str { "ok" }

#[autumn_web::main]
async fn main() {
    autumn_web::app()
        .routes(routes![index])
        .run()
        .await;
}
"#
    }

    // ── RED: file plan assertions ─────────────────────────────────────────

    #[test]
    fn plan_creates_handler_file() {
        let tmp = project_with_main(default_main());
        let plan = plan_inbound_mail(tmp.path(), "Replies").unwrap();
        assert!(
            plan.actions
                .iter()
                .any(|a| a.path().ends_with("src/inbound_mailers/replies.rs")),
            "plan must include src/inbound_mailers/replies.rs"
        );
    }

    #[test]
    fn plan_creates_integration_test() {
        let tmp = project_with_main(default_main());
        let plan = plan_inbound_mail(tmp.path(), "Replies").unwrap();
        assert!(
            plan.actions
                .iter()
                .any(|a| a.path().ends_with("tests/replies_inbound_mail.rs")),
            "plan must include tests/replies_inbound_mail.rs"
        );
    }

    #[test]
    fn plan_updates_mod_rs() {
        let tmp = project_with_main(default_main());
        let plan = plan_inbound_mail(tmp.path(), "Replies").unwrap();
        assert!(
            plan.actions
                .iter()
                .any(|a| a.path().ends_with("inbound_mailers/mod.rs")),
            "plan must include inbound_mailers/mod.rs"
        );
    }

    #[test]
    fn plan_updates_main_rs() {
        let tmp = project_with_main(default_main());
        let plan = plan_inbound_mail(tmp.path(), "Replies").unwrap();
        assert!(
            plan.actions.iter().any(|a| a.path().ends_with("main.rs")),
            "plan must update main.rs"
        );
    }

    #[test]
    fn plan_updates_cargo_toml_feature() {
        let tmp = project_with_main(default_main());
        let plan = plan_inbound_mail(tmp.path(), "Replies").unwrap();
        assert!(
            plan.actions
                .iter()
                .any(|a| a.path().ends_with("Cargo.toml")),
            "plan must update Cargo.toml"
        );
    }

    #[test]
    fn plan_fails_for_invalid_name() {
        let tmp = project_with_main(default_main());
        let result = plan_inbound_mail(tmp.path(), "123Invalid");
        assert!(result.is_err());
    }

    #[test]
    fn plan_fails_outside_project() {
        let tmp = TempDir::new().unwrap();
        let result = plan_inbound_mail(tmp.path(), "Replies");
        assert!(matches!(result.unwrap_err(), GenerateError::NotInProject));
    }

    #[test]
    fn handler_file_contains_inbound_mail_macro() {
        let tmp = project_with_main(default_main());
        let plan = plan_inbound_mail(tmp.path(), "Support").unwrap();
        let handler_action = plan
            .actions
            .iter()
            .find(|a| a.path().ends_with("support.rs"))
            .expect("handler file must be in plan");
        let contents = match handler_action {
            super::super::emit::Action::Create { contents, .. }
            | super::super::emit::Action::Modify { contents, .. } => contents,
        };
        assert!(
            contents.contains("#[inbound_mail"),
            "handler file must contain #[inbound_mail], got:\n{contents}"
        );
    }

    #[test]
    fn integration_test_contains_compute_signature_call() {
        let tmp = project_with_main(default_main());
        let plan = plan_inbound_mail(tmp.path(), "Support").unwrap();
        let test_action = plan
            .actions
            .iter()
            .find(|a| a.path().ends_with("support_inbound_mail.rs"))
            .expect("integration test must be in plan");
        let contents = match test_action {
            super::super::emit::Action::Create { contents, .. }
            | super::super::emit::Action::Modify { contents, .. } => contents,
        };
        assert!(
            contents.contains("compute_mailgun_signature"),
            "integration test must use compute_mailgun_signature, got:\n{contents}"
        );
    }

    #[test]
    fn add_inbound_mail_router_inserts_after_routes() {
        let src = r"autumn_web::app()
        .routes(routes![index])
        .run()
        .await;";
        let updated =
            add_inbound_mail_router_to_app(src, "inbound_mailers::replies::replies_handler_info");
        assert!(
            updated.contains(".inbound_mail_router("),
            "must insert .inbound_mail_router(…), got:\n{updated}"
        );
    }

    #[test]
    fn add_inbound_mail_router_is_idempotent_when_handler_already_present() {
        // Handler already fully registered — no change expected.
        let src = r"autumn_web::app()
        .routes(routes![index])
        .inbound_mail_router(InboundMailRouter::new().handler(inbound_mailers::replies::replies_handler_info()))
        .run()
        .await;";
        let updated =
            add_inbound_mail_router_to_app(src, "inbound_mailers::replies::replies_handler_info");
        assert_eq!(
            updated, src,
            "must not modify src when handler already present"
        );
    }

    #[test]
    fn add_inbound_mail_router_chains_new_handler_onto_existing_router() {
        let src = r"autumn_web::app()
        .routes(routes![index])
        .inbound_mail_router(InboundMailRouter::new().handler(replies_handler_info()))
        .run()
        .await;";
        let updated =
            add_inbound_mail_router_to_app(src, "inbound_mailers::support::support_handler_info");
        let count = updated.matches(".inbound_mail_router(").count();
        assert_eq!(
            count, 1,
            "must not add a second router call, got:\n{updated}"
        );
        assert!(
            updated.contains("support_handler_info()"),
            "must chain new handler, got:\n{updated}"
        );
    }

    #[test]
    fn pascal_handler_name_derived_from_pascal_input() {
        let tmp = project_with_main(default_main());
        let plan = plan_inbound_mail(tmp.path(), "ReplyThread").unwrap();
        let handler_action = plan
            .actions
            .iter()
            .find(|a| a.path().ends_with("reply_thread.rs"))
            .expect("handler file must be in plan");
        let contents = match handler_action {
            super::super::emit::Action::Create { contents, .. }
            | super::super::emit::Action::Modify { contents, .. } => contents,
        };
        assert!(
            contents.contains("ReplyThreadMailHandler"),
            "handler file must contain ReplyThreadMailHandler, got:\n{contents}"
        );
    }
}