autumn-cli 0.10.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
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
//! autumn generate plugin — plan the generation of a conformant plugin crate.

use std::fs;
use std::path::Path;

use super::emit::Plan;
use super::{Flags, GenerateError};

#[derive(Debug)]
pub struct PluginPlan {
    pub plan: Plan,
    pub name_kebab: String,
    pub name_snake: String,
    pub struct_name: String,
    pub target_dir_relative: String,
}

#[allow(clippy::too_many_lines)]
pub fn plan_plugin(
    project_root: &Path,
    name: &str,
    path: Option<&Path>,
    flags: Flags,
) -> Result<PluginPlan, GenerateError> {
    // Call ensure_project_root first
    super::ensure_project_root(project_root)?;

    // Strip prefixes/suffixes
    let mut clean_name = name;
    if let Some(stripped) = clean_name.strip_prefix("autumn-") {
        clean_name = stripped;
    } else if let Some(stripped) = clean_name.strip_prefix("autumn_") {
        clean_name = stripped;
    }

    if let Some(stripped) = clean_name.strip_suffix("-plugin") {
        clean_name = stripped;
    } else if let Some(stripped) = clean_name.strip_suffix("_plugin") {
        clean_name = stripped;
    } else if let Some(stripped) = clean_name.strip_suffix("Plugin") {
        clean_name = stripped;
    } else if let Some(stripped) = clean_name.strip_suffix("plugin") {
        clean_name = stripped;
    }

    // Validate clean_name
    if clean_name.is_empty() {
        return Err(GenerateError::InvalidName(
            name.to_string(),
            "Name cannot be empty".to_string(),
        ));
    }

    let mut chars = clean_name.chars();
    let first = chars.next().unwrap();
    if !first.is_ascii_alphabetic() && first != '_' {
        return Err(GenerateError::InvalidName(
            name.to_string(),
            "Name must start with a letter or underscore".to_string(),
        ));
    }

    if !chars.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
        return Err(GenerateError::InvalidName(
            name.to_string(),
            "Name must contain only alphanumeric characters, dashes, or underscores".to_string(),
        ));
    }

    let name_kebab = super::naming::snake(clean_name).replace('_', "-");
    let name_snake = name_kebab.replace('-', "_");
    let struct_name = format!("{}Plugin", super::naming::pascal(&name_snake));

    // Validate path components
    if let Some(p) = path {
        for component in p.components() {
            match component {
                std::path::Component::ParentDir => {
                    return Err(GenerateError::Config(
                        "Path cannot contain parent directory traversal ('..')".to_string(),
                    ));
                }
                std::path::Component::RootDir => {
                    return Err(GenerateError::Config(
                        "Path cannot be an absolute path".to_string(),
                    ));
                }
                std::path::Component::Prefix(_) => {
                    return Err(GenerateError::Config(
                        "Path cannot contain prefix components (e.g. drive letters)".to_string(),
                    ));
                }
                _ => {}
            }
        }
    }

    let target_dir = path.map_or_else(
        || project_root.join(format!("autumn-{name_kebab}-plugin")),
        |p| project_root.join(p),
    );

    // Prevent target_dir == project_root
    let clean_target: std::path::PathBuf = target_dir
        .components()
        .filter(|c| !matches!(c, std::path::Component::CurDir))
        .collect();
    let clean_root: std::path::PathBuf = project_root
        .components()
        .filter(|c| !matches!(c, std::path::Component::CurDir))
        .collect();
    if clean_target == clean_root {
        return Err(GenerateError::Config(
            "Target directory cannot be the project root itself".to_string(),
        ));
    }

    if !flags.dry_run && target_dir.exists() && !flags.force {
        let is_empty_dir = target_dir.is_dir() && fs::read_dir(&target_dir)?.next().is_none();
        if !is_empty_dir {
            return Err(GenerateError::Config(format!(
                "target directory '{}' already exists and is not empty. Use --force to override.",
                target_dir.display().to_string().replace('\\', "/")
            )));
        }
    }

    let plan_root = target_dir.parent().unwrap_or(project_root);
    let mut plan = Plan::new(plan_root);

    let cargo_version = env!("CARGO_PKG_VERSION");
    let major_minor = cargo_version
        .split('.')
        .take(2)
        .collect::<Vec<_>>()
        .join(".");

    // The range the scaffolded plugin declares in `Plugin::contract` (issue
    // #1601). Below 1.0 that is the minor series and from 1.0 on the major —
    // the compatibility key `STABILITY.md` defines — which is *wider* than the
    // `major_minor` dependency line above once past 1.0, and deliberately so:
    // the dependency says what cargo resolves, the contract says what the
    // plugin claims to work with.
    let autumn_web_range = autumn_web::plugin_contract::lockstep_range(cargo_version);

    let cargo_toml_content = format!(
        r#"[package]
name = "autumn-{name_kebab}-plugin"
version = "0.1.0"
edition = "2024"

[dependencies]
autumn-web = {{ version = "{major_minor}" }}
serde = {{ version = "1", features = ["derive"] }}
"#
    );

    let lib_rs_content = format!(
        r#"//! autumn-{name_kebab}-plugin

use std::borrow::Cow;

use autumn_web::app::AppBuilder;
use autumn_web::plugin::Plugin;

pub struct {struct_name};

impl {struct_name} {{
    #[must_use]
    pub fn new() -> Self {{
        Self
    }}
}}

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

impl Plugin for {struct_name} {{
    fn name(&self) -> Cow<'static, str> {{
        Cow::Borrowed("autumn-{name_kebab}-plugin")
    }}

    /// The `autumn-web` range this plugin supports (issue #1601).
    ///
    /// An app built on a framework outside this range fails at registration
    /// with a diagnostic naming both versions, instead of misbehaving quietly.
    /// Widen the range as you verify newer releases; `autumn plugin-check`
    /// reports what you declare.
    fn contract(&self) -> Option<autumn_web::plugin_contract::PluginContract> {{
        Some(
            autumn_web::plugin_contract::PluginContract::new(env!("CARGO_PKG_NAME"))
                .plugin_version(env!("CARGO_PKG_VERSION"))
                .autumn_web("{autumn_web_range}"),
        )
    }}

    fn build(self, app: AppBuilder) -> AppBuilder {{
        // Wire a commented example route contribution:
        // let app = app.routes(autumn_web::routes![index]);
        app
    }}
}}

// Commented index route function:
// #[autumn_web::get("/autumn-{name_kebab}-plugin")]
// async fn index() -> &'static str {{
//     "Hello from plugin!"
// }}
"#
    );

    let relative_path = target_dir.strip_prefix(project_root).map_or_else(
        |_| target_dir.display().to_string().replace('\\', "/"),
        |p| format!("./{}", p.display().to_string().replace('\\', "/")),
    );

    let readme_content = format!(
        r#"# autumn-{name_kebab}-plugin

An Autumn plugin for {name}.

## Installation

Add this to your `Cargo.toml`:

```toml
[dependencies]
autumn-{name_kebab}-plugin = {{ path = "{relative_path}" }}
```

## Setup

Register the plugin with your Autumn application in `src/main.rs`:

```rust
use autumn_{name_snake}_plugin::{struct_name};

#[autumn_web::main]
async fn main() {{
    autumn_web::app()
        .plugin({struct_name}::new())
        .run()
        .await;
}}
```
"#
    );

    let conformance_rs_content = format!(
        r#"#[cfg(test)]
mod conformance_tests {{
    use autumn_web::plugin_conformance::{{ConformanceConfig, run_conformance}};
    use autumn_web::route_listing::{{RouteInfo, RouteSource}};

    #[test]
    fn plugin_passes_conformance() {{
        // Simulate the routes your plugin contributes
        let routes = vec![
            RouteInfo {{
                method: "GET".to_owned(),
                path: "/autumn-{name_kebab}-plugin".to_owned(),
                handler: "autumn_{name_snake}_plugin::index".to_owned(),
                source: RouteSource::Plugin("autumn-{name_kebab}-plugin".to_owned()),
                ..Default::default()
            }},
        ];

        let config = ConformanceConfig::new("autumn-{name_kebab}-plugin")
            .prefix("/autumn-{name_kebab}-plugin")
            .sensitive_route("/autumn-{name_kebab}-plugin", "Role: admin required")
            // Pass the plugin's own contract so the `experimental-surface`
            // check runs instead of being skipped (issue #1601).
            .contract({struct_name}::new().contract().expect("a declared contract"));

        let report = run_conformance(&config, &routes);
        assert!(
            report.passed(),
            "conformance failed:\n{{}}",
            report.to_text_report()
        );
    }}
}}
"#
    );

    plan.create(target_dir.join("Cargo.toml"), cargo_toml_content);
    plan.create(target_dir.join("src/lib.rs"), lib_rs_content);
    plan.create(target_dir.join("README.md"), readme_content);
    plan.create(
        target_dir.join("tests/conformance.rs"),
        conformance_rs_content,
    );

    let target_dir_relative = target_dir.strip_prefix(project_root).map_or_else(
        |_| target_dir.display().to_string().replace('\\', "/"),
        |p| p.display().to_string().replace('\\', "/"),
    );

    Ok(PluginPlan {
        plan,
        name_kebab,
        name_snake,
        struct_name,
        target_dir_relative,
    })
}

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

    /// The scaffold must satisfy the CLI's own author gate: `plugin-check`'s
    /// `plugin-contract` check fails a plugin that declares no contract, so a
    /// freshly generated plugin cannot ship without one (issue #1601).
    fn assert_scaffold_declares_a_contract(lib_content: &str) {
        assert!(lib_content.contains("fn contract(&self)"));
        assert!(lib_content.contains("PluginContract::new(env!(\"CARGO_PKG_NAME\"))"));
        assert!(
            lib_content.contains(&format!(
                ".autumn_web(\"{}\")",
                autumn_web::plugin_contract::lockstep_range(env!("CARGO_PKG_VERSION"))
            )),
            "the declared range must track this CLI's own series"
        );
    }

    /// The generated conformance test has to pass the plugin's own contract, or
    /// the `experimental-surface` check silently skips (issue #1601).
    fn assert_scaffold_conformance_test_is_wired(conformance_content: &str) {
        assert!(conformance_content.contains("run_conformance"));
        assert!(conformance_content.contains("ConformanceConfig::new"));
        assert!(
            conformance_content.contains(".contract("),
            "the generated conformance test must pass the plugin's contract"
        );
    }

    #[test]
    fn plan_creates_plugin_files() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let project_root = temp_dir.path();
        fs::write(project_root.join("Cargo.toml"), "").unwrap();
        let target_dir = project_root.join("autumn-foo-plugin");

        let plugin_plan = plan_plugin(project_root, "Foo", None, Flags::default()).unwrap();
        let plan = plugin_plan.plan;

        // Verify Cargo.toml, src/lib.rs, README.md, and tests/conformance.rs are planned for creation
        let paths: std::collections::HashSet<PathBuf> = plan
            .actions
            .iter()
            .map(|a| a.path().to_path_buf())
            .collect();

        assert!(
            paths.contains(&target_dir.join("Cargo.toml")),
            "Should plan Cargo.toml"
        );
        assert!(
            paths.contains(&target_dir.join("src/lib.rs")),
            "Should plan src/lib.rs"
        );
        assert!(
            paths.contains(&target_dir.join("README.md")),
            "Should plan README.md"
        );
        assert!(
            paths.contains(&target_dir.join("tests/conformance.rs")),
            "Should plan tests/conformance.rs"
        );

        // Verify crate name and struct name
        let cargo_action = plan
            .actions
            .iter()
            .find(|a| a.path() == target_dir.join("Cargo.toml"))
            .unwrap();
        let super::super::emit::Action::Create {
            contents: cargo_content,
            ..
        } = cargo_action
        else {
            panic!("Expected Create action");
        };
        assert!(
            cargo_content.contains("name = \"autumn-foo-plugin\""),
            "Expected Cargo.toml to contain the lowercase kebab-case crate name"
        );

        let lib_action = plan
            .actions
            .iter()
            .find(|a| a.path() == target_dir.join("src/lib.rs"))
            .unwrap();
        let super::super::emit::Action::Create {
            contents: lib_content,
            ..
        } = lib_action
        else {
            panic!("Expected Create action");
        };
        assert!(
            lib_content.contains("pub struct FooPlugin;"),
            "Expected src/lib.rs to define FooPlugin"
        );
    }

    #[test]
    fn plan_includes_correct_contents_and_conformance_run() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let project_root = temp_dir.path();
        fs::write(project_root.join("Cargo.toml"), "").unwrap();
        let target_dir = project_root.join("autumn-foo-plugin");

        let plugin_plan = plan_plugin(project_root, "foo", None, Flags::default()).unwrap();
        let plan = plugin_plan.plan;

        // Check Cargo.toml content
        let cargo_action = plan
            .actions
            .iter()
            .find(|a| a.path() == target_dir.join("Cargo.toml"))
            .unwrap();
        let super::super::emit::Action::Create {
            contents: cargo_content,
            ..
        } = cargo_action
        else {
            panic!("Expected Create action")
        };
        assert!(cargo_content.contains("[package]"));
        assert!(cargo_content.contains("name = \"autumn-foo-plugin\""));
        assert!(cargo_content.contains("edition = \"2024\""));
        let expected_version = env!("CARGO_PKG_VERSION")
            .split('.')
            .take(2)
            .collect::<Vec<_>>()
            .join(".");
        assert!(cargo_content.contains(&format!(
            "autumn-web = {{ version = \"{expected_version}\" }}"
        )));
        assert!(cargo_content.contains("serde = { version = \"1\", features = [\"derive\"] }"));

        // Check src/lib.rs content
        let lib_action = plan
            .actions
            .iter()
            .find(|a| a.path() == target_dir.join("src/lib.rs"))
            .unwrap();
        let super::super::emit::Action::Create {
            contents: lib_content,
            ..
        } = lib_action
        else {
            panic!("Expected Create action")
        };
        assert!(lib_content.contains("impl Plugin for FooPlugin"));
        assert!(lib_content.contains("fn name(&self) -> Cow<'static, str>"));
        assert!(lib_content.contains("Cow::Borrowed(\"autumn-foo-plugin\")"));
        assert!(lib_content.contains("// let app = app.routes("));
        assert_scaffold_declares_a_contract(lib_content);
        assert!(lib_content.contains("index"));

        // Check README.md content
        let readme_action = plan
            .actions
            .iter()
            .find(|a| a.path() == target_dir.join("README.md"))
            .unwrap();
        let super::super::emit::Action::Create {
            contents: readme_content,
            ..
        } = readme_action
        else {
            panic!("Expected Create action")
        };
        assert!(readme_content.contains("autumn-foo-plugin = { path = \"./autumn-foo-plugin\" }"));
        assert!(readme_content.contains(".plugin(FooPlugin::new())"));

        // Check tests/conformance.rs content
        let conformance_action = plan
            .actions
            .iter()
            .find(|a| a.path() == target_dir.join("tests/conformance.rs"))
            .unwrap();
        let super::super::emit::Action::Create {
            contents: conformance_content,
            ..
        } = conformance_action
        else {
            panic!("Expected Create action")
        };
        assert_scaffold_conformance_test_is_wired(conformance_content);

        // Test non-empty directory collision check
        let collision_dir = project_root.join("autumn-bar-plugin");
        fs::create_dir_all(&collision_dir).unwrap();
        fs::write(collision_dir.join("some-file.txt"), "hello").unwrap();

        let err = plan_plugin(project_root, "bar", None, Flags::default()).unwrap_err();
        match err {
            GenerateError::Config(msg) => {
                let expected = format!(
                    "target directory '{}' already exists and is not empty. Use --force to override.",
                    collision_dir.display().to_string().replace('\\', "/")
                );
                assert_eq!(msg, expected);
            }
            _ => panic!("Expected GenerateError::Config, got {err:?}"),
        }

        // If force is true, it should bypass the check and succeed
        let plan_forced = plan_plugin(
            project_root,
            "bar",
            None,
            Flags {
                force: true,
                ..Default::default()
            },
        );
        assert!(plan_forced.is_ok());
    }

    #[test]
    fn name_normalization_and_validation() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let project_root = temp_dir.path();
        fs::write(project_root.join("Cargo.toml"), "").unwrap();

        for name in &["autumn-foo-plugin", "FooPlugin", "autumn_foo_plugin"] {
            let res = plan_plugin(project_root, name, None, Flags::default()).unwrap();
            assert_eq!(res.name_kebab, "foo");
            assert_eq!(res.name_snake, "foo");
            assert_eq!(res.struct_name, "FooPlugin");
        }

        for invalid in &["", "1foo", "-foo", "../foo", "foo/bar", "foo..bar"] {
            let res = plan_plugin(project_root, invalid, None, Flags::default());
            assert!(
                matches!(res, Err(GenerateError::InvalidName(..))),
                "expected InvalidName for '{invalid}', got {res:?}"
            );
        }
    }

    #[test]
    fn path_traversal_validation() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let project_root = temp_dir.path();
        fs::write(project_root.join("Cargo.toml"), "").unwrap();

        let invalid_paths = &[
            Path::new("foo/../bar"),
            Path::new("/abs/path"),
            Path::new(""),
            Path::new("."),
        ];

        for p in invalid_paths {
            let res = plan_plugin(project_root, "foo", Some(p), Flags::default());
            assert!(
                matches!(res, Err(GenerateError::Config(..))),
                "expected Config error for path '{p:?}', got {res:?}"
            );
        }
    }

    #[test]
    fn dry_run_bypasses_collision_check() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let project_root = temp_dir.path();
        fs::write(project_root.join("Cargo.toml"), "").unwrap();

        let collision_dir = project_root.join("autumn-foo-plugin");
        fs::create_dir_all(&collision_dir).unwrap();
        fs::write(collision_dir.join("some-file.txt"), "hello").unwrap();

        let res = plan_plugin(
            project_root,
            "foo",
            None,
            Flags {
                dry_run: false,
                force: false,
            },
        );
        assert!(res.is_err());

        let res_dry = plan_plugin(
            project_root,
            "foo",
            None,
            Flags {
                dry_run: true,
                force: false,
            },
        );
        assert!(res_dry.is_ok());
    }
}