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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
use std::str::FromStr;
use convert_case::Case as ConvertCase;
use quote::quote;
use syn::{meta::ParseNestedMeta, parse::Parse};
#[derive(Debug, strum::EnumString)]
pub enum Case {
/// Converts all characters to lowercase and removes binding characters.
///
/// Used if [ContainerAttributes::rename_all] is set to `lowercase` or
/// `lower`
///
/// ### Example
///
/// Renames `EXAMPLE_ENV` to `exampleenv`
///
/// ```
/// #[derive(Fill)]
/// #[fill(rename_all = "lowercase")]
/// struct Example {
/// #[fill(env = "EXAMPLE_ENV")]
/// field: String,
/// }
///
/// let _ = Example::try_invoke()?;
/// ```
#[strum(serialize = "lowercase", serialize = "lower")]
Lower,
/// Converts all characters to uppercase and removes binding characters.
///
/// Used if [ContainerAttributes::rename_all] is set to `UPPERCASE` or
/// `UPPER`
///
/// ### Example
///
/// Renames `example_env` to `EXAMPLEENV`
///
/// ```
/// #[derive(Fill)]
/// #[fill(rename_all = "UPPERCASE")]
/// struct Example {
/// #[fill(env = "example_env")]
/// field: String,
/// }
///
/// let _ = Example::try_invoke()?;
/// ```
#[strum(serialize = "UPPERCASE", serialize = "UPPER")]
Upper,
/// Capitalizes the first letter of each word and removes binding
/// characters.
///
/// Used if [ContainerAttributes::rename_all] is set to `PascalCase`
///
/// ### Example
///
/// Renames `some_field_name` to `SomeFieldName`
///
/// ```
/// #[derive(Fill)]
/// #[fill(rename_all = "PascalCase")]
/// struct Example {
/// #[fill(env = "some_field_name")]
/// field: String,
/// }
///
/// let _ = Example::try_invoke()?;
/// ```
#[strum(serialize = "PascalCase")]
Pascal,
/// Lowercases the first letter but capitalizes the first letter of
/// subsequent words while removing binding characters.
///
/// Used if [ContainerAttributes::rename_all] is set to `camelCase`
///
/// ### Example
///
/// Renames `some_field_name` to `someFieldName`
///
/// ```
/// #[derive(Fill)]
/// #[fill(rename_all = "camelCase")]
/// struct Example {
/// #[fill(env = "some_field_name")]
/// field: String,
/// }
///
/// let _ = Example::try_invoke()?;
/// ```
#[strum(serialize = "camelCase")]
Camel,
/// Converts names to lowercase and uses underscores `_` to separate words.
///
/// Used if [ContainerAttributes::rename_all] is set to `snake_case`
///
/// ### Example
///
/// Renames `someFieldName` to `some_field_name`
///
/// ```
/// #[derive(Fill)]
/// #[fill(rename_all = "snake_case")]
/// struct Example {
/// #[fill(env = "someFieldName")]
/// field: String,
/// }
///
/// let _ = Example::try_invoke()?;
/// ```
#[strum(serialize = "snake_case")]
Snake,
/// Converts names to uppercase and uses underscores `_` to separate words.
///
/// Used if [ContainerAttributes::rename_all] is set to
/// `SCREAMING_SNAKE_CASE`
///
/// ### Example
///
/// Renames `some_field_name` to `SOME_FIELD_NAME`
///
/// ```
/// #[derive(Fill)]
/// #[fill(rename_all = "SCREAMING_SNAKE_CASE")]
/// struct Example {
/// #[fill(env = "some_field_name")]
/// field: String,
/// }
///
/// let _ = Example::try_invoke()?;
/// ```
#[strum(serialize = "SCREAMING_SNAKE_CASE")]
ScreamingSnake,
/// Converts names to lowercase and uses hyphens `-` to separate words.
///
/// Used if [ContainerAttributes::rename_all] is set to `kebab-case`
///
/// ### Example
///
/// Renames `some_field_name` to `some-field-name`
///
/// ```
/// #[derive(Fill)]
/// #[fill(rename_all = "kebab-case")]
/// struct Example {
/// #[fill(env = "some_field_name")]
/// field: String,
/// }
///
/// let _ = Example::try_invoke()?;
/// ```
#[strum(serialize = "kebab-case")]
Kebab,
/// Converts names to uppercase and uses hyphens `-` to separate words.
///
/// Used if [ContainerAttributes::rename_all] is set to
/// `SCREAMING-KEBAB-CASE`
///
/// ### Example
///
/// Renames `some_field_name` to `SOME-FIELD-NAME`
///
/// ```
/// #[derive(Fill)]
/// #[fill(rename_all = "SCREAMING-KEBAB-CASE")]
/// struct Example {
/// #[fill(env = "some_field_name")]
/// field: String,
/// }
///
/// let _ = Example::try_invoke()?;
/// ```
#[strum(serialize = "SCREAMING-KEBAB-CASE")]
ScreamingKebab,
}
impl syn::parse::Parse for Case {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let c: syn::LitStr = input.parse()?;
let case =
Case::from_str(&c.value()).map_err(|_| input.error("unknown naming convention"))?;
Ok(case)
}
}
impl From<&Case> for ConvertCase {
fn from(value: &Case) -> Self {
match value {
Case::Lower => ConvertCase::Flat,
Case::Upper => ConvertCase::UpperFlat,
Case::Pascal => ConvertCase::Pascal,
Case::Camel => ConvertCase::Camel,
Case::Snake => ConvertCase::Snake,
Case::ScreamingSnake => ConvertCase::UpperSnake,
Case::Kebab => ConvertCase::Kebab,
Case::ScreamingKebab => ConvertCase::UpperKebab,
}
}
}
#[derive(Debug, Default)]
pub struct ContainerAttributes {
/// Prefix to prepend to all environment variable names.
///
/// ### Example
///
/// The example below will load the environment variable `TEST_field`
///
/// ```
/// #[derive(Fill)]
/// #[fill(prefix = "TEST", delimiter = "_")]
/// struct Example {
/// #[fill(env)]
/// field: String,
/// ...
/// }
///
/// let _ = Example::try_invoke()?;
/// ```
///
/// </br>
///
/// **Default:** `None`
pub prefix: Option<String>,
/// Suffix to append to all environment variable names.
///
/// ### Example
///
/// The example below will load the environment variable `field_TEST`
///
/// ```
/// #[derive(Fill)]
/// #[fill(suffix = "TEST", delimiter = "_")]
/// struct Example {
/// #[fill(env)]
/// field: String,
/// ...
/// }
///
/// let _ = Example::try_invoke()?;
/// ```
///
/// </br>
///
/// **Default:** `None`
pub suffix: Option<String>,
/// Delimiter used to separate the prefix, environment variable name, and
/// suffix.
///
/// If [`ContainerAttributes::rename_all`] is set, it will override this
/// delimiter. Although it can still be good to include the delimiter to
/// separate the prefix/suffix from the original name!
///
/// See [ContainerAttributes::prefix] or [ContainerAttributes::suffix] for
/// examples on how to use this attribute
///
/// **Default:** `"_"`
pub delimiter: Option<String>,
/// Converts environment variable names to the specified case format.
///
/// See [Case] for a full list of supported cases
///
/// ### Example
///
/// The example below will load the environment variable
/// `PREFIX_FIELD_SUFFIX`
///
/// ```
/// #[derive(Fill)]
/// #[fill(prefix = "prefix", suffix = "prefix", delimiter = "_", rename_all = "UPPERCASE")]
/// struct Example {
/// #[fill(env)]
/// field: String,
/// ...
/// }
///
/// let _ = Example::try_invoke()?;
/// ```
///
/// </br>
///
/// **Default:** `None`
pub rename_all: Option<Case>,
}
impl ContainerAttributes {
pub fn get_prefix(&self) -> &str {
self.prefix.as_deref().unwrap_or_default()
}
pub fn get_suffix(&self) -> &str {
self.suffix.as_deref().unwrap_or_default()
}
pub fn get_delimiter(&self) -> &str {
self.delimiter.as_deref().unwrap_or_default()
}
pub fn parse_attrs(attrs: &Vec<syn::Attribute>) -> syn::Result<Self> {
let mut ca = ContainerAttributes::default();
for attr in attrs {
if !attr.path().is_ident("fill") {
continue;
}
attr.parse_nested_meta(|meta| {
if meta.path.is_ident("prefix") {
if ca.prefix.is_some() {
return Err(meta.error("container attribute `prefix` already set"));
}
let str: syn::LitStr = meta.value()?.parse()?;
ca.prefix = Some(str.value());
return Ok(());
}
if meta.path.is_ident("suffix") {
if ca.suffix.is_some() {
return Err(meta.error("container attribute `suffix` already set"));
}
let str: syn::LitStr = meta.value()?.parse()?;
ca.suffix = Some(str.value());
return Ok(());
}
if meta.path.is_ident("delimiter") {
if ca.delimiter.is_some() {
return Err(meta.error("container attribute `delimiter` already set"));
}
let str: syn::LitStr = meta.value()?.parse()?;
ca.delimiter = Some(str.value());
return Ok(());
}
if meta.path.is_ident("rename_all") {
if ca.rename_all.is_some() {
return Err(meta.error("container attribute `rename_all` already set"));
}
let case: Case = meta.value()?.parse()?;
ca.rename_all = Some(case);
return Ok(());
}
let ident = match meta.path.get_ident() {
Some(ident) => ident.to_string(),
None => "unknown".to_string(),
};
Err(meta.error(format!("unknown container attribute `{ident}`")))
})?;
}
Ok(ca)
}
}
#[derive(Debug)]
pub enum DefaultValue {
Type(syn::Type),
Lit(syn::ExprLit),
Path(syn::ExprPath),
Call {
path: syn::ExprPath,
args: Vec<syn::Expr>,
},
}
impl Parse for DefaultValue {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let expr: syn::Expr = input.parse()?;
match expr {
syn::Expr::Lit(lit) => Ok(DefaultValue::Lit(lit)),
syn::Expr::Path(path) => Ok(DefaultValue::Path(path)),
syn::Expr::Call(call) => {
if let syn::Expr::Path(path) = *call.func {
Ok(DefaultValue::Call {
path,
args: call.args.into_iter().collect(),
})
} else {
Err(syn::Error::new_spanned(call, "Expected a function path"))
}
}
_ => Err(syn::Error::new_spanned(
expr,
"Unexpected default value format",
)),
}
}
}
#[derive(Debug, Default)]
pub struct ValidateFn {
/// A function to call after loading the value from the environment variable
/// to validate it
pub before: Option<syn::Path>,
/// A function to call after parsing the value to validate the parsed value
pub after: Option<syn::Path>,
}
impl ValidateFn {
fn from_nested_meta(meta: &ParseNestedMeta) -> syn::Result<Self> {
let mut vfn = Self {
before: None,
after: None,
};
meta.parse_nested_meta(|meta| {
if meta.path.is_ident("before") {
let validate_fn = meta.value()?.parse()?;
vfn.before = Some(validate_fn);
return Ok(());
}
if meta.path.is_ident("after") {
let validate_fn = meta.value()?.parse()?;
vfn.after = Some(validate_fn);
return Ok(());
}
let ident = match meta.path.get_ident() {
Some(ident) => ident.to_string(),
None => "unknown".to_string(),
};
Err(meta.error(format!("unknown validate_fn attribute `{ident}`")))
})?;
Ok(vfn)
}
fn from_direct_assignment(meta: &ParseNestedMeta) -> syn::Result<Self> {
let validate_fn = meta.value()?.parse()?;
Ok(Self {
before: None,
after: Some(validate_fn),
})
}
}
#[derive(Debug, Default)]
pub struct FieldAttributes {
/// Environment variables to load the field value from.
///
/// The macro attempts to load each listed environment variable in order.
/// The first found value is parsed and set as the field value. If parsing
/// fails, the operation stops, and no further variables are checked.
///
/// ### Usage
///
/// **1.** `env`
///
/// The example below will load the value from environment variable `field`
/// ```
/// #[derive(Fill)]
/// struct Example {
/// #[fill(env)]
/// field: i32,
/// ...
/// }
///
/// let _ = Example::try_invoke()?;
/// ```
///
/// </br>
///
/// **2.** `env = "<key>"`
///
/// The example below will load the value from environment variable `ENV`
/// ```
/// #[derive(Fill)]
/// struct Example {
/// #[fill(env = "ENV")]
/// field: i32,
/// ...
/// }
///
/// let _ = Example::try_invoke()?;
/// ```
///
/// `env` and `env = "<key>"` can be used together, as well as can be added
/// on as many times as needed. Note that they will be loaded in the order
/// they are defined
///
/// </br>
///
/// **Default:** `None`.
pub envs: Option<Vec<String>>,
/// Use the default value if the environment variable is not found
///
/// This function can be used without specifying `envs` to provide a static
/// fallback.
///
/// ### Usage
///
/// **1.** `default`
///
/// The example below will `field` with `i32::default()` which is `0`
/// ```
/// #[derive(Fill)]
/// struct Example {
/// #[fill(default)]
/// field: i32,
/// ...
/// }
///
/// let _ = Example::try_invoke()?;
/// ```
///
/// </br>
///
/// **2.** `default = <value>`
///
/// The example below will `field` with `10`
/// ```
/// #[derive(Fill)]
/// struct Example {
/// #[fill(default = 10)]
/// field: i32,
/// ...
/// }
///
/// let _ = Example::try_invoke()?;
/// ```
///
/// </br>
///
/// **3.** `default = <func>()`
///
/// The example below will `field` with `10` (if result remains unchanged)
/// ```
/// fn field_default() -> i32 {
/// let result = 10;
/// ... // extra steps if need
/// result
/// }
///
/// #[derive(Fill)]
/// struct Example {
/// #[fill(default = field_default())]
/// field: i32
/// ...
/// }
///
/// let _ = Example::try_invoke()?;
/// ```
///
/// Additionally arguments can be parsed to field_default() if needed
///
/// </br>
///
/// **Default:** `None`
pub default: Option<DefaultValue>,
/// A function to parse the loaded value with before applying to the field.
/// Requires `arg_type` to be set if used.
///
/// Allows for custom types which normally isn't supported by envoke-rs
///
/// ### Example
///
/// The example below takes the value from environment variable `field` and
/// runs it through the `to_duration` function before assigning it to the
/// field value
///
/// ```
/// fn to_duration(secs: u64) -> std::time::Duration {
/// std::time::Duration::from_secs(secs)
/// }
///
/// #[derive(Fill)]
/// struct Example {
/// #[fill(env, parse_fn = to_duration, arg_type = u64)]
/// field: std::time::Duration,
/// ...
/// }
///
/// let _ = Example::try_invoke()?;
/// ```
///
/// </br>
///
/// **Default:** `None`
pub parse_fn: Option<syn::Path>,
/// Arg type in the parse_fn function. Required by `parse_fn` if used.
///
/// See [FieldAttributes::parse_fn] for an example on how to use it
///
/// **Default:** `None`
pub arg_type: Option<syn::Type>,
/// A function to call after the value is loaded and parsed for extra
/// validations, e.g., ensuring i64 is above 0
///
/// ### Example
///
/// The example below takes and i64 and checks that it is above 0
///
/// ```
/// fn above_zero(secs: u64) -> std::result::Result<()> {
/// match secs > 0 {
/// true => Ok(),
/// false => Err("duration cannot be less than 0")
/// }
/// }
///
/// #[derive(Fill)]
/// struct Example {
/// #[fill(env, parse_fn = to_duration, arg_type = u64, validate_fn = above_zero)]
/// field: std::time::Duration,
/// ...
/// }
/// ```
///
/// **Default:** `None`
pub validate_fn: ValidateFn,
/// Delimiter used when parsing list-type fields (e.g., `Vec<String>`).
///
/// ### Example
///
/// The example below will parse, e.g., `value1;value2;value3` to
/// Vec<String>. Note that the delimiter `=` is reserved as its the
/// delimiter for key and values in a map string
///
/// ```
/// #[derive(Fill)]
/// struct Example {
/// #[fill(env, delimiter = ";")]
/// field: Vec<String>,
/// ...
/// }
/// ```
///
/// </br>
///
/// **Default:** `","`
pub delimiter: Option<String>,
/// Disable adding prefix to this environment variables. This will also
/// remove the delimiter that wouldn't normally be between the environment
/// variable and prefix
///
/// **Default:** `false`
pub no_prefix: bool,
/// Disable adding prefix to this environment variables. This will also
/// remove the delimiter that wouldn't normally be between the environment
/// variable and suffix
///
/// **Default:** `false`
pub no_suffix: bool,
/// Indicates the the field is a nested struct in which the parser needs to
/// call try_envoke on
///
/// ### Example
///
/// ```rust
/// #[derive(Fill)]
/// struct Inner {
/// #[fill(env)]
/// field: String,
/// ...
/// }
///
/// #[derive(Fill)]
/// struct Outer {
/// #[fill(nested)]
/// inner: Inner,
/// ...
/// }
/// ```
///
/// The structs can nested multiple times
///
/// </br>
///
/// **Default**: false
pub nested: bool,
}
impl FieldAttributes {
fn add_env(&mut self, env: String) {
self.envs.get_or_insert_with(Vec::new).push(env);
}
pub fn parse_attrs(field: &syn::Field, attrs: &Vec<syn::Attribute>) -> syn::Result<Self> {
let mut fa = FieldAttributes::default();
for attr in attrs {
if !attr.path().is_ident("fill") {
continue;
}
attr.parse_nested_meta(|meta| {
if meta.path.is_ident("env") {
// Allows the user to specify both
// 1. `#[fill(env)]` - Uses the field name as environment variable
// 2. `#[fill(env = "env")]` - Uses `env` as the environment variable
match meta.input.peek(syn::Token![=]) {
true => {
let str: syn::LitStr = meta.value()?.parse()?;
let env = str.value();
if env.is_empty() {
return Err(meta.error("field attribute `env` cannot be empty"));
}
fa.add_env(env);
}
false => {
let ident = &field.ident;
let name = quote! { #ident }.to_string();
fa.add_env(name.to_owned())
}
}
return Ok(());
}
// Allows the user to specify both
// 1. `#[fill(default)]` - Uses the field types default value
// 2. `#[fill(default = default_t)]` - Uses `default_t` as the field value
// 3. `#[fill(default = default_fn)]` - Uses `default_fn` return value as the
// field value
if meta.path.is_ident("default") {
fa.default = match meta.input.peek(syn::Token![=]) {
true => Some(meta.value()?.parse()?),
false => {
let ty = &field.ty;
Some(DefaultValue::Type(ty.clone()))
}
};
return Ok(());
}
if meta.path.is_ident("parse_fn") {
let parse_fn = meta.value()?.parse()?;
fa.parse_fn = Some(parse_fn);
return Ok(());
}
if meta.path.is_ident("arg_type") {
let arg_type = meta.value()?.parse()?;
fa.arg_type = Some(arg_type);
return Ok(());
}
if meta.path.is_ident("validate_fn") {
// Check if we can parse validate_fn as a nested meta aka.
// #[fill(validate_fn(before = ..., after = ...))]
if let Ok(vfn) = ValidateFn::from_nested_meta(&meta) {
fa.validate_fn = vfn;
return Ok(());
}
// If first parse fail, try to parse as if its a direct assignment aka.
// #[fill(validate_fn = ...)]
match ValidateFn::from_direct_assignment(&meta) {
Ok(vfn) => {
fa.validate_fn = vfn;
return Ok(());
}
Err(_) => {
return Err(
meta.error("expected either direct assignment or parentheses")
)
}
}
}
if meta.path.is_ident("delimiter") {
let str: syn::LitStr = meta.value()?.parse()?;
let delimiter = str.value();
if delimiter == "=" {
return Err(
meta.error("delimiter `=` is reserved by the macro and cannot be used")
);
}
if delimiter.is_empty() {
return Err(meta.error("field attribute `delimiter` cannot be empty"));
}
fa.delimiter = Some(delimiter);
return Ok(());
}
if meta.path.is_ident("no_prefix") {
fa.no_prefix = true;
return Ok(());
}
if meta.path.is_ident("no_suffix") {
fa.no_suffix = true;
return Ok(());
}
if meta.path.is_ident("nested") {
fa.nested = true;
return Ok(());
}
let ident = match meta.path.get_ident() {
Some(ident) => ident.to_string(),
None => "unknown".to_string(),
};
Err(meta.error(format!("unknown field attribute `{ident}`")))
})?;
}
Ok(fa)
}
}