rustio-admin-macros 0.1.0

Proc-macros for rustio-admin (re-exported from the rustio-admin crate).
Documentation
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
//! Procedural macros for `rustio-admin`.
//!
//! `#[derive(RustioAdmin)]`. Given a user-written struct, the derive
//! emits `impl AdminModel for TheStruct` with `ADMIN_NAME`,
//! `DISPLAY_NAME`, `SINGULAR_NAME`, `FIELDS`, and the row/form/update
//! helpers.
//!
//! The macro deliberately stays dumb: all runtime behaviour lives in
//! `rustio_admin`. Keeping the macro small makes it easier to debug —
//! if something feels wrong, read the generated code with
//! `cargo expand`.

use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use syn::{parse_macro_input, Data, DeriveInput, Fields, Lit, Meta};

#[proc_macro_derive(RustioAdmin, attributes(rustio))]
pub fn derive_rustio_admin(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    expand(input)
        .unwrap_or_else(|e| e.to_compile_error())
        .into()
}

fn expand(input: DeriveInput) -> syn::Result<TokenStream2> {
    let struct_name = &input.ident;
    let fields = struct_fields(&input)?;

    let admin_name = plural_snake(&struct_name.to_string());
    let display_name = humanise(&plural_snake(&struct_name.to_string()));
    let singular = struct_name.to_string();

    let mut field_metas = Vec::new();
    let mut display_value_arms = Vec::new();
    let mut from_form_parses = Vec::new();
    let mut from_form_fields = Vec::new();
    let mut update_tuples = Vec::new();

    for f in fields {
        let fname = f.ident.as_ref().unwrap();
        let fname_str = fname.to_string();
        let kind = classify_type(&f.ty)?;
        // Fields named `created_at` / `updated_at` are
        // managed by the framework: hidden from forms, defaulted to
        // `Utc::now()` in `from_form`. The macro wires that behaviour
        // through `FieldKind::DateTimeAuto`; this promotion is the
        // missing trigger that makes the variant reachable for the
        // conventionally named timestamp columns.
        let kind = if matches!(kind, FieldKind::DateTime) && is_auto_timestamp_name(&fname_str) {
            FieldKind::DateTimeAuto
        } else {
            kind
        };
        let editable = fname_str != "id" && kind != FieldKind::DateTimeAuto;

        let type_variant = kind.field_type_ident();
        let relation = parse_relation_attr(&f.attrs, &fname_str)?;
        let relation_tokens = match &relation {
            Some((target, display)) => {
                let display_tok = match display {
                    Some(d) => quote! { ::std::option::Option::Some(#d) },
                    None => quote! { ::std::option::Option::None },
                };
                quote! {
                    ::std::option::Option::Some(::rustio_admin::admin::AdminRelation {
                        target_model: #target,
                        display_field: #display_tok,
                        // Single belongs_to relations default to
                        // single `<select>`. Many-to-many is opt-in via
                        // a future `#[rustio(many_to_many)]` attribute;
                        // the macro emits `false` for now so consumers
                        // that want multi-select must hand-set the
                        // field on the generated AdminRelation.
                        multi: false,
                    })
                }
            }
            None => quote! { ::std::option::Option::None },
        };

        field_metas.push(quote! {
            ::rustio_admin::admin::AdminField {
                name: #fname_str,
                label: #fname_str,
                field_type: ::rustio_admin::admin::FieldType::#type_variant,
                editable: #editable,
                relation: #relation_tokens,
                // Derived models don't carry enum choices yet. A future
                // macro pass will accept `#[rustio(choices = [...])]`
                // and populate this; today consumers that want a
                // `<select>` backed by a static value list set this on
                // the generated AdminField directly.
                choices: ::std::option::Option::None,
            }
        });

        // `display_values`: stringify the field for the list page.
        let display_arm = match kind {
            FieldKind::String => quote! {
                out.push((#fname_str.to_string(), self.#fname.clone()));
            },
            FieldKind::OptionalString => quote! {
                // `Option<String>` does not implement `Display`, so we
                // can't share the String arm. None → empty string,
                // Some(v) → v.
                out.push((#fname_str.to_string(), match &self.#fname {
                    Some(v) => v.clone(),
                    None => String::new(),
                }));
            },
            FieldKind::I32 | FieldKind::I64 => quote! {
                out.push((#fname_str.to_string(), self.#fname.to_string()));
            },
            FieldKind::OptionalI64 => quote! {
                out.push((#fname_str.to_string(), match &self.#fname {
                    Some(v) => v.to_string(),
                    None => String::new(),
                }));
            },
            FieldKind::Bool => quote! {
                out.push((#fname_str.to_string(), if self.#fname { "true".to_string() } else { "false".to_string() }));
            },
            FieldKind::DateTime | FieldKind::DateTimeAuto => quote! {
                // ISO-8601 form with `T` separator. This is the exact
                // wire format `<input type="datetime-local">` expects
                // (`%Y-%m-%dT%H:%M`); the form-render path puts this
                // string straight into the input's `value=` attribute.
                // The list path detects the same shape (16 chars, `T`
                // at index 10) and splits it into the two-line cell
                // layout. NOTE: `datetime-local` cannot encode timezone;
                // we surface UTC values directly.
                out.push((#fname_str.to_string(), self.#fname.format("%Y-%m-%dT%H:%M").to_string()));
            },
        };
        display_value_arms.push(display_arm);

        // `from_form`: read the HTML form body into a struct field.
        if fname_str == "id" {
            from_form_fields.push(quote! { #fname: 0 });
            continue;
        }

        // Precompute human-readable validation messages at expansion
        // time so the runtime error path doesn't repeat the same
        // `format!` work per request and so every model emits
        // identically-styled copy.
        let humanised_label = humanise_field(&fname_str);
        let required_msg = format!("{humanised_label} is required.");
        let number_msg = format!("{humanised_label} must be a number.");
        let date_invalid_msg = format!("{humanised_label} is not a valid date.");

        match kind {
            FieldKind::String => {
                // Trim incoming whitespace so a `"   "` submission is
                // treated as empty (and triggers the required-field
                // error) instead of silently saving a whitespace-only
                // string.
                from_form_parses.push(quote! {
                    let #fname = match form.get(#fname_str).map(str::trim) {
                        Some(v) if !v.is_empty() => v.to_string(),
                        _ => { errors.push(#required_msg.to_string()); String::new() }
                    };
                });
                from_form_fields.push(quote! { #fname });
            }
            FieldKind::OptionalString => {
                // Trim, then collapse trimmed-empty to None so the
                // column stores NULL instead of `""`.
                from_form_parses.push(quote! {
                    let #fname: Option<String> = form
                        .get(#fname_str)
                        .map(|s| s.trim().to_string())
                        .filter(|s| !s.is_empty());
                });
                from_form_fields.push(quote! { #fname });
            }
            FieldKind::I32 => {
                from_form_parses.push(quote! {
                    let #fname: i32 = match form.get(#fname_str).and_then(|v| v.parse().ok()) {
                        Some(v) => v,
                        None => { errors.push(#number_msg.to_string()); 0 }
                    };
                });
                from_form_fields.push(quote! { #fname });
            }
            FieldKind::I64 => {
                from_form_parses.push(quote! {
                    let #fname: i64 = match form.get(#fname_str).and_then(|v| v.parse().ok()) {
                        Some(v) => v,
                        None => { errors.push(#number_msg.to_string()); 0 }
                    };
                });
                from_form_fields.push(quote! { #fname });
            }
            FieldKind::OptionalI64 => {
                // Distinguish "user left it blank" (None, legitimate)
                // from "user typed garbage" (validation error, NOT
                // silently dropped).
                from_form_parses.push(quote! {
                    let #fname: Option<i64> = match form.get(#fname_str).map(str::trim) {
                        None | Some("") => None,
                        Some(raw) => match raw.parse::<i64>() {
                            Ok(n) => Some(n),
                            Err(_) => {
                                errors.push(#number_msg.to_string());
                                None
                            }
                        },
                    };
                });
                from_form_fields.push(quote! { #fname });
            }
            FieldKind::Bool => {
                from_form_parses.push(quote! {
                    let #fname: bool = form.bool_flag(#fname_str);
                });
                from_form_fields.push(quote! { #fname });
            }
            FieldKind::DateTime => {
                from_form_parses.push(quote! {
                    let #fname = match form.get(#fname_str) {
                        Some(raw) if !raw.is_empty() => {
                            match ::chrono::NaiveDateTime::parse_from_str(raw, "%Y-%m-%dT%H:%M") {
                                Ok(dt) => ::chrono::DateTime::<::chrono::Utc>::from_naive_utc_and_offset(dt, ::chrono::Utc),
                                Err(_) => { errors.push(#date_invalid_msg.to_string()); ::chrono::Utc::now() }
                            }
                        }
                        _ => { errors.push(#required_msg.to_string()); ::chrono::Utc::now() }
                    };
                });
                from_form_fields.push(quote! { #fname });
            }
            FieldKind::DateTimeAuto => {
                // created_at-style fields default to now().
                from_form_parses.push(quote! {
                    let #fname = ::chrono::Utc::now();
                });
                from_form_fields.push(quote! { #fname });
            }
        }

        update_tuples.push(quote! {
            (#fname_str, self.#fname.clone().into())
        });
    }

    let object_label_expr = find_label_field(fields)
        .map(|n| {
            let id = format_ident!("{n}");
            quote! { self.#id.clone().to_string() }
        })
        .unwrap_or_else(|| quote! { format!("#{}", self.id) });

    Ok(quote! {
        impl ::rustio_admin::admin::AdminModel for #struct_name {
            const ADMIN_NAME: &'static str = #admin_name;
            const DISPLAY_NAME: &'static str = #display_name;
            const SINGULAR_NAME: &'static str = #singular;
            const FIELDS: &'static [::rustio_admin::admin::AdminField] = &[
                #(#field_metas),*
            ];

            fn display_values(&self) -> ::std::vec::Vec<(::std::string::String, ::std::string::String)> {
                let mut out = ::std::vec::Vec::new();
                #(#display_value_arms)*
                out
            }

            fn from_form(form: &::rustio_admin::http::FormData) -> ::std::result::Result<Self, ::std::vec::Vec<::std::string::String>>
            where
                Self: Sized,
            {
                let mut errors: ::std::vec::Vec<::std::string::String> = ::std::vec::Vec::new();
                #(#from_form_parses)*
                if !errors.is_empty() {
                    return Err(errors);
                }
                Ok(Self { #(#from_form_fields),* })
            }

            fn object_label(&self) -> ::std::string::String {
                #object_label_expr
            }

            fn id(&self) -> i64 {
                self.id
            }

            fn values_to_update(&self) -> ::std::vec::Vec<(&'static str, ::rustio_admin::orm::Value)> {
                ::std::vec![#(#update_tuples),*]
            }
        }
    })
}

fn struct_fields(
    input: &DeriveInput,
) -> syn::Result<&syn::punctuated::Punctuated<syn::Field, syn::Token![,]>> {
    let data = match &input.data {
        Data::Struct(s) => s,
        _ => {
            return Err(syn::Error::new_spanned(
                &input.ident,
                "RustioAdmin can only derive on structs",
            ))
        }
    };
    match &data.fields {
        Fields::Named(named) => Ok(&named.named),
        _ => Err(syn::Error::new_spanned(
            &input.ident,
            "RustioAdmin requires a struct with named fields",
        )),
    }
}

#[derive(Debug, PartialEq, Clone, Copy)]
enum FieldKind {
    I32,
    I64,
    Bool,
    String,
    DateTime,
    DateTimeAuto,
    OptionalString,
    OptionalI64,
}

impl FieldKind {
    fn field_type_ident(&self) -> proc_macro2::Ident {
        match self {
            FieldKind::I32 => format_ident!("I32"),
            FieldKind::I64 => format_ident!("I64"),
            FieldKind::Bool => format_ident!("Bool"),
            FieldKind::String => format_ident!("String"),
            FieldKind::DateTime | FieldKind::DateTimeAuto => format_ident!("DateTime"),
            FieldKind::OptionalString => format_ident!("OptionalString"),
            FieldKind::OptionalI64 => format_ident!("OptionalI64"),
        }
    }
}

/// Names treated as framework-managed timestamps. These fields are
/// auto-promoted to `FieldKind::DateTimeAuto` regardless of declared
/// type so the admin UI doesn't render them and `from_form` fills
/// them with `Utc::now()`. Conservative list; expand only when a real
/// model needs another conventionally-named timestamp.
fn is_auto_timestamp_name(name: &str) -> bool {
    matches!(name, "created_at" | "updated_at")
}

/// Turn a snake_case column name into a Title-Case label for human-
/// readable validation errors emitted by `from_form`. Mirrors the
/// runtime humanise helper so error labels and rendered form labels
/// use identical capitalisation.
fn humanise_field(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut next_upper = true;
    for ch in s.chars() {
        if ch == '_' {
            out.push(' ');
            next_upper = true;
        } else if next_upper {
            out.push(ch.to_ascii_uppercase());
            next_upper = false;
        } else {
            out.push(ch);
        }
    }
    out
}

fn classify_type(ty: &syn::Type) -> syn::Result<FieldKind> {
    let as_string = quote! { #ty }.to_string().replace(' ', "");
    let kind = match as_string.as_str() {
        "i32" => FieldKind::I32,
        "i64" => FieldKind::I64,
        "bool" => FieldKind::Bool,
        "String" => FieldKind::String,
        "DateTime<Utc>" | "chrono::DateTime<chrono::Utc>" => FieldKind::DateTime,
        "Option<String>" => FieldKind::OptionalString,
        "Option<i64>" => FieldKind::OptionalI64,
        other => {
            return Err(syn::Error::new_spanned(
                ty,
                format!("unsupported field type for RustioAdmin: {other}"),
            ))
        }
    };
    Ok(kind)
}

fn parse_relation_attr(
    attrs: &[syn::Attribute],
    field_name: &str,
) -> syn::Result<Option<(String, Option<String>)>> {
    for attr in attrs {
        if !attr.path().is_ident("rustio") {
            continue;
        }
        let mut target: Option<String> = None;
        let mut display: Option<String> = None;
        attr.parse_nested_meta(|m| {
            if m.path.is_ident("belongs_to") {
                let value = m.value()?;
                let lit: Lit = value.parse()?;
                if let Lit::Str(s) = lit {
                    target = Some(s.value());
                }
                Ok(())
            } else if m.path.is_ident("display") {
                let value = m.value()?;
                let lit: Lit = value.parse()?;
                if let Lit::Str(s) = lit {
                    display = Some(s.value());
                }
                Ok(())
            } else {
                Err(m.error(format!("unknown rustio attribute for field `{field_name}`")))
            }
        })?;
        if let Some(t) = target {
            return Ok(Some((t, display)));
        }
        if display.is_some() {
            return Err(syn::Error::new_spanned(
                attr,
                "`display` requires `belongs_to` alongside it",
            ));
        }
    }
    // Suppress the unused warning for `Meta`.
    let _ = std::marker::PhantomData::<Meta>;
    Ok(None)
}

fn plural_snake(camel: &str) -> String {
    let snake = camel_to_snake(camel);
    if snake.ends_with('s') {
        snake
    } else {
        format!("{snake}s")
    }
}

fn camel_to_snake(s: &str) -> String {
    let mut out = String::new();
    for (i, c) in s.chars().enumerate() {
        if c.is_ascii_uppercase() && i > 0 {
            out.push('_');
        }
        out.push(c.to_ascii_lowercase());
    }
    out
}

fn humanise(snake: &str) -> String {
    // "blog_posts" → "Blog posts"
    let mut chars = snake.chars();
    let mut out = String::new();
    if let Some(first) = chars.next() {
        out.push(first.to_ascii_uppercase());
    }
    for c in chars {
        if c == '_' {
            out.push(' ');
        } else {
            out.push(c);
        }
    }
    out
}

fn find_label_field(
    fields: &syn::punctuated::Punctuated<syn::Field, syn::Token![,]>,
) -> Option<String> {
    // Heuristic: prefer `name`, then `title`, then `full_name`, then
    // fall through to `#id`. Keeps `object_label()` useful without
    // forcing users to implement anything.
    let names = ["name", "title", "full_name", "label", "email"];
    for candidate in names {
        if fields
            .iter()
            .any(|f| f.ident.as_ref().map(|i| i == candidate).unwrap_or(false))
        {
            return Some(candidate.to_string());
        }
    }
    None
}