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
//! TOML-based generator configuration for `autumn generate scaffold`.
//!
//! Reads `[scaffold.ResourceName]` sections from a project-local TOML file
//! so scaffold metadata can be checked in and reproduced without long CLI
//! invocations.
//!
//! # File format
//!
//! ```toml
//! [scaffold.Bookmark]
//! fields      = ["url:String", "title:String", "tag:String", "alive:bool"]
//! indexes     = ["url", "tag"]
//! validations = ["url=url", "title=length:min=1,max=200"]
//! defaults    = ["alive=true"]
//! queries     = ["find_by_tag:tag", "find_by_alive:alive"]
//! ```
//!
//! # Precedence
//!
//! CLI flags win. If the caller passes any values for a repeated flag (e.g.
//! `--index`), those values completely replace the corresponding TOML list.
//! Fields (positional arguments) follow the same rule: non-empty CLI fields
//! shadow TOML fields.

use std::collections::HashMap;
use std::path::Path;

use serde::Deserialize;

use super::GenerateError;
use super::model::ModelOptions;
use super::naming::pascal;
use super::scaffold::ScaffoldOptions;

/// One resource's scaffold metadata from a TOML config file.
#[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ScaffoldConfigEntry {
    #[serde(default)]
    pub fields: Vec<String>,
    #[serde(default)]
    pub indexes: Vec<String>,
    #[serde(default)]
    pub validations: Vec<String>,
    #[serde(default)]
    pub defaults: Vec<String>,
    #[serde(default)]
    pub queries: Vec<String>,
    #[serde(default)]
    pub soft_delete: bool,
    #[serde(default)]
    pub api: bool,
}

#[derive(Debug, Clone, Default, Deserialize)]
struct GeneratorConfig {
    #[serde(default)]
    scaffold: HashMap<String, ScaffoldConfigEntry>,
}

/// Read the scaffold config entry for `resource_name` from `config_path`.
///
/// Returns `None` when the file is valid TOML but has no
/// `[scaffold.ResourceName]` section for the requested name.
///
/// # Errors
///
/// - [`GenerateError::Io`] if the file cannot be read.
/// - [`GenerateError::Config`] if the file is not valid TOML.
pub fn read_scaffold_config(
    config_path: &Path,
    resource_name: &str,
) -> Result<Option<ScaffoldConfigEntry>, GenerateError> {
    let content = std::fs::read_to_string(config_path)
        .map_err(|e| std::io::Error::new(e.kind(), format!("{}: {e}", config_path.display())))?;
    let mut config: GeneratorConfig = toml::from_str(&content).map_err(|e| {
        GenerateError::Config(format!("invalid TOML in {}: {e}", config_path.display()))
    })?;
    // Normalize to PascalCase so `bookmark` and `Bookmark` both match
    // `[scaffold.Bookmark]`, consistent with how the generator itself handles
    // resource names passed on the CLI.
    Ok(config.scaffold.remove(pascal(resource_name).as_str()))
}

/// Merge a TOML config entry with CLI-supplied values.
///
/// For each key, if the caller supplied a non-empty CLI slice that value set
/// replaces the TOML list; otherwise the TOML list is kept.
#[allow(clippy::too_many_arguments)]
pub fn merge_config_with_cli(
    config: ScaffoldConfigEntry,
    cli_fields: &[String],
    cli_indexes: &[String],
    cli_validations: &[String],
    cli_defaults: &[String],
    cli_queries: &[String],
    cli_soft_delete: bool,
    cli_api: bool,
) -> (Vec<String>, ScaffoldOptions) {
    let pick = |cli: &[String], toml: Vec<String>| -> Vec<String> {
        if cli.is_empty() { toml } else { cli.to_vec() }
    };
    let fields = pick(cli_fields, config.fields);
    let indexes = pick(cli_indexes, config.indexes);
    let validations = pick(cli_validations, config.validations);
    let defaults = pick(cli_defaults, config.defaults);
    let queries = pick(cli_queries, config.queries);
    // CLI flag wins; TOML config enables it when present.
    let soft_delete = cli_soft_delete || config.soft_delete;
    let api = cli_api || config.api;
    (
        fields,
        ScaffoldOptions {
            model: ModelOptions {
                indexes,
                validations,
                defaults,
                soft_delete,
            },
            queries,
            api,
        },
    )
}

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

    fn write_config(tmp: &TempDir, content: &str) -> std::path::PathBuf {
        let path = tmp.path().join("autumn.generate.toml");
        fs::write(&path, content).unwrap();
        path
    }

    // ── read_scaffold_config ──────────────────────────────────────────────

    #[test]
    fn parse_valid_scaffold_config() {
        let tmp = TempDir::new().unwrap();
        let path = write_config(
            &tmp,
            r#"
[scaffold.Bookmark]
fields      = ["url:String", "title:String", "tag:String", "alive:bool"]
indexes     = ["url", "tag"]
validations = ["url=url", "title=length:min=1,max=200"]
defaults    = ["alive=true"]
queries     = ["find_by_tag:tag", "find_by_alive:alive"]
"#,
        );

        let entry = read_scaffold_config(&path, "Bookmark")
            .unwrap()
            .expect("Bookmark section must be present");

        assert_eq!(
            entry.fields,
            vec!["url:String", "title:String", "tag:String", "alive:bool"]
        );
        assert_eq!(entry.indexes, vec!["url", "tag"]);
        assert_eq!(
            entry.validations,
            vec!["url=url", "title=length:min=1,max=200"]
        );
        assert_eq!(entry.defaults, vec!["alive=true"]);
        assert_eq!(
            entry.queries,
            vec!["find_by_tag:tag", "find_by_alive:alive"]
        );
    }

    #[test]
    fn parse_minimal_config_with_fields_only() {
        let tmp = TempDir::new().unwrap();
        let path = write_config(&tmp, "[scaffold.Post]\nfields = [\"title:String\"]\n");

        let entry = read_scaffold_config(&path, "Post").unwrap().unwrap();
        assert_eq!(entry.fields, vec!["title:String"]);
        assert!(entry.indexes.is_empty());
        assert!(entry.validations.is_empty());
        assert!(entry.defaults.is_empty());
        assert!(entry.queries.is_empty());
    }

    #[test]
    fn snake_case_name_matches_pascal_case_toml_section() {
        let tmp = TempDir::new().unwrap();
        let path = write_config(&tmp, "[scaffold.Bookmark]\nfields = [\"url:String\"]\n");

        // CLI input `bookmark` (snake_case) must find `[scaffold.Bookmark]`.
        let entry = read_scaffold_config(&path, "bookmark")
            .unwrap()
            .expect("snake_case name should resolve to PascalCase section");
        assert_eq!(entry.fields, vec!["url:String"]);
    }

    #[test]
    fn unknown_key_returns_config_error() {
        let tmp = TempDir::new().unwrap();
        // `index` is the wrong key; the correct key is `indexes`.
        let path = write_config(
            &tmp,
            "[scaffold.Post]\nfields = [\"title:String\"]\nindex = [\"title\"]\n",
        );

        let err = read_scaffold_config(&path, "Post").unwrap_err();
        assert!(
            matches!(err, GenerateError::Config(_)),
            "misspelled key should return Config error, got: {err:?}"
        );
        let msg = err.to_string();
        assert!(
            msg.contains("index"),
            "error should mention the unknown key; got: {msg}"
        );
    }

    #[test]
    fn missing_section_returns_none() {
        let tmp = TempDir::new().unwrap();
        let path = write_config(&tmp, "[scaffold.Post]\nfields = [\"title:String\"]\n");

        let result = read_scaffold_config(&path, "Bookmark").unwrap();
        assert!(result.is_none(), "unknown resource should return None");
    }

    #[test]
    fn invalid_toml_returns_config_error() {
        let tmp = TempDir::new().unwrap();
        let path = write_config(&tmp, "not valid toml {{{{");

        let err = read_scaffold_config(&path, "Bookmark").unwrap_err();
        assert!(
            matches!(err, GenerateError::Config(_)),
            "expected Config error, got: {err:?}"
        );
    }

    #[test]
    fn missing_file_returns_io_error() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("nonexistent.toml");

        let err = read_scaffold_config(&path, "Bookmark").unwrap_err();
        assert!(
            matches!(err, GenerateError::Io(_)),
            "expected Io error for missing file, got: {err:?}"
        );
    }

    // ── merge_config_with_cli ─────────────────────────────────────────────

    fn bookmark_entry() -> ScaffoldConfigEntry {
        ScaffoldConfigEntry {
            fields: vec!["url:String".into(), "tag:String".into()],
            indexes: vec!["url".into()],
            validations: vec!["url=url".into()],
            defaults: vec![],
            queries: vec!["find_by_url:url".into()],
            soft_delete: false,
            api: false,
        }
    }

    #[test]
    fn merge_uses_toml_when_all_cli_empty() {
        let (fields, opts) =
            merge_config_with_cli(bookmark_entry(), &[], &[], &[], &[], &[], false, false);
        assert_eq!(fields, vec!["url:String", "tag:String"]);
        assert_eq!(opts.model.indexes, vec!["url"]);
        assert_eq!(opts.model.validations, vec!["url=url"]);
        assert!(opts.model.defaults.is_empty());
        assert_eq!(opts.queries, vec!["find_by_url:url"]);
    }

    #[test]
    fn merge_cli_fields_override_toml_fields() {
        let (fields, _) = merge_config_with_cli(
            bookmark_entry(),
            &["title:String".into(), "body:Text".into()],
            &[],
            &[],
            &[],
            &[],
            false,
            false,
        );
        assert_eq!(fields, vec!["title:String", "body:Text"]);
    }

    #[test]
    fn merge_cli_indexes_override_toml_indexes() {
        let (_, opts) = merge_config_with_cli(
            bookmark_entry(),
            &[],
            &["tag".into()],
            &[],
            &[],
            &[],
            false,
            false,
        );
        assert_eq!(opts.model.indexes, vec!["tag"]);
    }

    #[test]
    fn merge_cli_validations_override_toml_validations() {
        let (_, opts) = merge_config_with_cli(
            bookmark_entry(),
            &[],
            &[],
            &["url=email".into()],
            &[],
            &[],
            false,
            false,
        );
        assert_eq!(opts.model.validations, vec!["url=email"]);
    }

    #[test]
    fn merge_cli_defaults_override_toml_defaults() {
        let mut entry = bookmark_entry();
        entry.defaults = vec!["url=example.com".into()];
        let (_, opts) = merge_config_with_cli(
            entry,
            &[],
            &[],
            &[],
            &["tag=general".into()],
            &[],
            false,
            false,
        );
        assert_eq!(opts.model.defaults, vec!["tag=general"]);
    }

    #[test]
    fn merge_cli_queries_override_toml_queries() {
        let (_, opts) = merge_config_with_cli(
            bookmark_entry(),
            &[],
            &[],
            &[],
            &[],
            &["find_by_tag:tag".into()],
            false,
            false,
        );
        assert_eq!(opts.queries, vec!["find_by_tag:tag"]);
    }

    #[test]
    fn merge_empty_cli_keeps_empty_toml() {
        let entry = ScaffoldConfigEntry::default();
        let (fields, opts) = merge_config_with_cli(entry, &[], &[], &[], &[], &[], false, false);
        assert!(fields.is_empty());
        assert!(opts.model.indexes.is_empty());
        assert!(opts.model.validations.is_empty());
        assert!(opts.model.defaults.is_empty());
        assert!(opts.queries.is_empty());
    }

    #[test]
    fn merge_cli_soft_delete_flag_wins() {
        let (_, opts) =
            merge_config_with_cli(bookmark_entry(), &[], &[], &[], &[], &[], true, false);
        assert!(
            opts.model.soft_delete,
            "cli_soft_delete=true must set soft_delete on the merged options"
        );
    }

    #[test]
    fn merge_toml_soft_delete_propagates() {
        let mut entry = bookmark_entry();
        entry.soft_delete = true;
        let (_, opts) = merge_config_with_cli(entry, &[], &[], &[], &[], &[], false, false);
        assert!(
            opts.model.soft_delete,
            "soft_delete=true in TOML config must propagate when CLI flag is false"
        );
    }

    #[test]
    fn merge_soft_delete_false_when_both_unset() {
        let (_, opts) =
            merge_config_with_cli(bookmark_entry(), &[], &[], &[], &[], &[], false, false);
        assert!(
            !opts.model.soft_delete,
            "soft_delete must be false when neither CLI nor TOML sets it"
        );
    }

    #[test]
    fn parse_scaffold_config_with_soft_delete() {
        let tmp = TempDir::new().unwrap();
        let path = write_config(
            &tmp,
            "[scaffold.Article]\nfields = [\"title:String\"]\nsoft_delete = true\n",
        );
        let entry = read_scaffold_config(&path, "Article")
            .unwrap()
            .expect("Article section must be present");
        assert!(
            entry.soft_delete,
            "soft_delete = true in TOML must be parsed into ScaffoldConfigEntry"
        );
    }

    #[test]
    fn merge_cli_api_flag_wins() {
        let (_, opts) =
            merge_config_with_cli(bookmark_entry(), &[], &[], &[], &[], &[], false, true);
        assert!(opts.api);
    }

    #[test]
    fn merge_toml_api_propagates() {
        let mut entry = bookmark_entry();
        entry.api = true;
        let (_, opts) = merge_config_with_cli(entry, &[], &[], &[], &[], &[], false, false);
        assert!(opts.api);
    }

    #[test]
    fn parse_scaffold_config_with_api() {
        let tmp = TempDir::new().unwrap();
        let path = write_config(
            &tmp,
            "[scaffold.Article]\nfields = [\"title:String\"]\napi = true\n",
        );
        let entry = read_scaffold_config(&path, "Article")
            .unwrap()
            .expect("Article section must be present");
        assert!(
            entry.api,
            "api = true in TOML must be parsed into ScaffoldConfigEntry"
        );
    }
}