confers-macros 0.4.0

Production-ready Rust configuration library with zero boilerplate
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
//! Attribute parsing for the Config derive macro.
//!
//! Uses darling for derive-aware attribute parsing with precise error spans.

use darling::{FromDeriveInput, FromField};
use syn::{GenericArgument, Ident, PathArguments, Type};

/// Maximum allowed length for environment variable prefix.
const MAX_PREFIX_LENGTH: usize = 64;

/// Maximum allowed length for names (app_name, etc.).
const MAX_NAME_LENGTH: usize = 256;

/// Parsed attributes from the struct level.
#[derive(Debug, FromDeriveInput)]
#[darling(attributes(config), supports(struct_named))]
#[allow(dead_code)]
pub struct StructAttrs {
    /// The struct identifier
    pub ident: Ident,

    /// Whether to enable validation
    #[darling(default)]
    pub validate: bool,

    /// Environment variable prefix
    pub env_prefix: Option<String>,

    /// Application name for config search
    pub app_name: Option<String>,

    /// Whether to error on unknown CLI arguments
    #[darling(default)]
    pub strict: bool,

    /// Whether to enable file watching
    #[darling(default)]
    pub watch: bool,

    /// Configuration version for migrations
    pub version: Option<u32>,

    /// Whether to enable profile overlay
    #[darling(default)]
    pub profile: bool,

    /// Profile environment variable name
    pub profile_env: Option<String>,
}

impl StructAttrs {
    /// Get the effective environment prefix.
    pub fn effective_env_prefix(&self) -> &str {
        self.env_prefix.as_deref().unwrap_or("")
    }

    /// Get the effective profile environment variable name.
    #[allow(dead_code)]
    pub fn effective_profile_env(&self) -> &str {
        self.profile_env.as_deref().unwrap_or("APP_ENV")
    }

    /// Validate struct attributes.
    ///
    /// This method performs comprehensive validation of all struct-level attributes:
    /// - Version must be positive (if specified)
    /// - env_prefix must not be empty, must not exceed max length, and must only contain
    ///   alphanumeric characters and underscores
    /// - app_name must not be empty and must not exceed max length
    ///
    /// # Arguments
    ///
    /// * `input` - The derive input for error span reporting
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` if all validations pass, or accumulates errors.
    pub fn validate(&self, input: &syn::DeriveInput) -> darling::Result<()> {
        let mut errors = darling::Error::accumulator();

        // Validate version
        if let Some(version) = self.version {
            if version == 0 {
                errors.push(
                    darling::Error::custom("version must be a positive integer (1 or greater)")
                        .with_span(&input.ident),
                );
            }
        }

        // Validate env_prefix
        if let Some(ref prefix) = self.env_prefix {
            // Length check
            if prefix.len() > MAX_PREFIX_LENGTH {
                errors.push(
                    darling::Error::custom(format!(
                        "env_prefix exceeds maximum length of {} characters (current: {})",
                        MAX_PREFIX_LENGTH,
                        prefix.len()
                    ))
                    .with_span(&input.ident),
                );
            }

            // Empty check
            if prefix.is_empty() {
                errors.push(
                    darling::Error::custom(
                        "env_prefix cannot be empty. Remove the attribute to use no prefix",
                    )
                    .with_span(&input.ident),
                );
            }

            // Character whitelist check
            if !prefix
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '_')
            {
                errors.push(
                    darling::Error::custom(
                        "env_prefix must only contain alphanumeric characters and underscores",
                    )
                    .with_span(&input.ident),
                );
            }

            // Control character check
            if prefix.chars().any(|c| c.is_control()) {
                errors.push(
                    darling::Error::custom("env_prefix cannot contain control characters")
                        .with_span(&input.ident),
                );
            }
        }

        // Validate app_name
        if let Some(ref app_name) = self.app_name {
            if app_name.len() > MAX_NAME_LENGTH {
                errors.push(
                    darling::Error::custom(format!(
                        "app_name exceeds maximum length of {} characters",
                        MAX_NAME_LENGTH
                    ))
                    .with_span(&input.ident),
                );
            }

            if app_name.is_empty() {
                errors.push(
                    darling::Error::custom("app_name cannot be empty").with_span(&input.ident),
                );
            }
        }

        errors.finish()
    }
}

/// Parsed attributes from a field.
#[derive(Debug, FromField)]
#[darling(attributes(config))]
#[allow(dead_code)]
pub struct FieldAttrs {
    /// Field identifier
    pub ident: Option<Ident>,

    /// Field type
    pub ty: Type,

    /// Default value expression
    pub default: Option<syn::Expr>,

    /// Field description for documentation
    pub description: Option<String>,

    /// Override configuration key name
    pub name: Option<String>,

    /// Override environment variable name
    pub name_env: Option<String>,

    /// CLI long argument name
    pub name_clap_long: Option<String>,

    /// CLI short argument character
    pub name_clap_short: Option<char>,

    /// Whether this field is sensitive (hidden in logs)
    #[darling(default)]
    pub sensitive: bool,

    /// Encryption algorithm for this field
    pub encrypt: Option<String>,

    /// Whether to flatten this field into parent namespace
    #[darling(default)]
    pub flatten: bool,

    /// Whether to skip this field during loading
    #[darling(default)]
    pub skip: bool,

    /// Whether to enable interpolation for this field
    #[darling(default)]
    pub interpolate: bool,

    /// Merge strategy for this field
    pub merge_strategy: Option<String>,

    /// Whether to generate a DynamicField handle
    #[darling(default)]
    pub dynamic: bool,

    /// Module group for this field (config groups)
    pub module_group: Option<String>,
}

impl FieldAttrs {
    /// Get the effective configuration key name
    pub fn effective_name(&self) -> String {
        self.name.clone().unwrap_or_else(|| {
            self.ident
                .as_ref()
                .map(|i| i.to_string())
                .unwrap_or_default()
        })
    }

    /// Get the effective environment variable name
    pub fn effective_env_name(&self, prefix: &str) -> String {
        if let Some(ref name_env) = self.name_env {
            name_env.clone()
        } else {
            let key = self.effective_name();
            format!("{}{}", prefix, key.to_uppercase().replace('.', "_"))
        }
    }

    /// Check if this field is a SecretString type
    pub fn is_secret_string(&self) -> bool {
        is_secret_type(&self.ty)
    }

    /// Check if this field should be treated as sensitive
    pub fn is_sensitive_effective(&self) -> bool {
        self.sensitive || self.encrypt.is_some() || self.is_secret_string()
    }

    /// Validate field attributes and return errors with helpful suggestions
    pub fn validate(&self, _field: &syn::Field) -> darling::Result<()> {
        let mut errors = darling::Error::accumulator();

        // Validate encrypt algorithm
        if let Some(ref algo) = self.encrypt {
            match algo.as_str() {
                "xchacha20" | "aes256-gcm" => {}
                _ => {
                    if let Some(ident) = self.ident.as_ref() {
                        errors.push(
                            darling::Error::custom(format!(
                                "unsupported encryption algorithm '{}'\n\
                                 supported algorithms: \"xchacha20\", \"aes256-gcm\"",
                                algo
                            ))
                            .with_span(ident),
                        );
                    }
                }
            }
        }

        // Validate merge_strategy
        if let Some(ref strategy) = self.merge_strategy {
            let valid_strategies = [
                "replace",
                "join",
                "append",
                "prepend",
                "join_append",
                "deep_merge",
            ];
            if !valid_strategies.contains(&strategy.as_str()) {
                if let Some(ident) = self.ident.as_ref() {
                    errors.push(
                        darling::Error::custom(format!(
                            "invalid merge strategy '{}'\n\
                             valid strategies: {}",
                            strategy,
                            valid_strategies.join(", ")
                        ))
                        .with_span(ident),
                    );
                }
            }
        }

        // Validate sensitive field type
        if self.sensitive && !self.is_secret_string() {
            if let Some(ident) = self.ident.as_ref() {
                errors.push(
                    darling::Error::custom(format!(
                        "sensitive field '{}' should use SecretString or SecretBytes type for security",
                        ident
                    ))
                    .with_span(ident),
                );
            }
        }

        errors.finish()
    }
}

/// Check if a type is SecretString or SecretBytes (optimized version)
pub fn is_secret_type(ty: &Type) -> bool {
    if let Type::Path(type_path) = ty {
        if let Some(segment) = type_path.path.segments.last() {
            return segment.ident == "SecretString" || segment.ident == "SecretBytes";
        }
    }
    false
}

/// Type category for optimized type handling
#[allow(dead_code)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TypeCategory {
    String,
    Integer,
    Float,
    Boolean,
    Option,
    Vec,
    Map,
    Secret,
    Custom,
}

impl TypeCategory {
    /// Determine the category of a type (optimized version)
    #[allow(dead_code)]
    pub fn from_type(ty: &Type) -> Self {
        if let Type::Path(type_path) = ty {
            if let Some(segment) = type_path.path.segments.last() {
                match segment.ident.to_string().as_str() {
                    "String" | "str" => return Self::String,
                    "i8" | "i16" | "i32" | "i64" | "i128" | "isize" => return Self::Integer,
                    "u8" | "u16" | "u32" | "u64" | "u128" | "usize" => return Self::Integer,
                    "f32" | "f64" => return Self::Float,
                    "bool" => return Self::Boolean,
                    "Option" => return Self::Option,
                    "Vec" => return Self::Vec,
                    "HashMap" | "BTreeMap" | "Map" => return Self::Map,
                    "SecretString" | "SecretBytes" => return Self::Secret,
                    _ => {}
                }
            }
        }
        Self::Custom
    }
}

/// Check if a type is Option<T>
pub fn is_option_type(ty: &Type) -> bool {
    if let syn::Type::Path(type_path) = ty {
        if let Some(segment) = type_path.path.segments.last() {
            return segment.ident == "Option";
        }
    }
    false
}

/// Check if a type is Vec<T>
pub fn is_vec_type(ty: &Type) -> bool {
    if let syn::Type::Path(type_path) = ty {
        if let Some(segment) = type_path.path.segments.last() {
            return segment.ident == "Vec";
        }
    }
    false
}

/// Extract the inner type from Option<T> or Vec<T>
#[allow(dead_code)]
pub fn extract_inner_type(ty: &Type) -> Option<&Type> {
    if let syn::Type::Path(type_path) = ty {
        if let Some(segment) = type_path.path.segments.last() {
            if let PathArguments::AngleBracketed(args) = &segment.arguments {
                if let Some(GenericArgument::Type(inner)) = args.args.first() {
                    return Some(inner);
                }
            }
        }
    }
    None
}

/// Merge strategy enum for code generation
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[allow(dead_code)]
pub enum MergeStrategyKind {
    #[default]
    Replace,
    Join,
    Append,
    Prepend,
    JoinAppend,
    DeepMerge,
}

impl MergeStrategyKind {
    #[allow(dead_code)]
    pub fn from_str(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "join" => Self::Join,
            "append" => Self::Append,
            "prepend" => Self::Prepend,
            "join_append" | "joinappend" => Self::JoinAppend,
            "deep_merge" | "deepmerge" => Self::DeepMerge,
            _ => Self::Replace,
        }
    }
}

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

    #[test]
    fn test_is_option_type() {
        let ty: Type = parse_quote!(Option<String>);
        assert!(is_option_type(&ty));

        let ty: Type = parse_quote!(String);
        assert!(!is_option_type(&ty));
    }

    #[test]
    fn test_is_vec_type() {
        let ty: Type = parse_quote!(Vec<String>);
        assert!(is_vec_type(&ty));

        let ty: Type = parse_quote!(String);
        assert!(!is_vec_type(&ty));
    }

    #[test]
    fn test_extract_inner_type() {
        let ty: Type = parse_quote!(Option<String>);
        let inner = extract_inner_type(&ty);
        assert!(inner.is_some());

        let ty: Type = parse_quote!(Vec<i32>);
        let inner = extract_inner_type(&ty);
        assert!(inner.is_some());
    }

    #[test]
    fn test_merge_strategy_from_str() {
        assert_eq!(
            MergeStrategyKind::from_str("replace"),
            MergeStrategyKind::Replace
        );
        assert_eq!(MergeStrategyKind::from_str("join"), MergeStrategyKind::Join);
        assert_eq!(
            MergeStrategyKind::from_str("append"),
            MergeStrategyKind::Append
        );
        assert_eq!(
            MergeStrategyKind::from_str("deep_merge"),
            MergeStrategyKind::DeepMerge
        );
    }
}