zorath-env 0.3.2

CLI tool for .env file validation against JSON schema. Validates environment variables, detects missing required vars, catches configuration drift, generates Markdown or JSON documentation. Language-agnostic, works with any stack.
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
use crate::schema::{load_schema, VarSpec, VarType};
use std::fs;

/// Generate .env.example from schema
pub fn run(schema_path: &str, output_path: Option<&str>, include_defaults: bool) -> Result<(), String> {
    let schema = load_schema(schema_path).map_err(|e| e.to_string())?;

    // Sort keys alphabetically for consistent output
    let mut keys: Vec<&String> = schema.keys().collect();
    keys.sort();

    let mut output = String::new();

    for (i, key) in keys.iter().enumerate() {
        let spec = schema.get(*key).unwrap();

        // Add blank line between variables (not before first)
        if i > 0 {
            output.push('\n');
        }

        // Generate comments for this variable
        output.push_str(&generate_var_comments(key, spec));

        // Generate the variable line
        output.push_str(&generate_var_line(key, spec, include_defaults));
        output.push('\n');
    }

    // Output to file or stdout
    if let Some(path) = output_path {
        fs::write(path, &output).map_err(|e| format!("failed to write output: {}", e))?;
        println!("Generated: {}", path);
    } else {
        print!("{}", output);
    }

    Ok(())
}

/// Generate comment lines for a variable
fn generate_var_comments(_key: &str, spec: &VarSpec) -> String {
    let mut comments = String::new();

    // Description
    if let Some(ref desc) = spec.description {
        comments.push_str(&format!("# {}\n", desc));
    }

    // Type and required status
    let type_str = match spec.var_type {
        VarType::String => "string",
        VarType::Int => "int",
        VarType::Float => "float",
        VarType::Bool => "bool",
        VarType::Url => "url",
        VarType::Enum => "enum",
    };
    let required_str = if spec.required { "required" } else { "optional" };
    comments.push_str(&format!("# Type: {} ({})\n", type_str, required_str));

    // Enum values
    if let Some(ref values) = spec.values {
        comments.push_str(&format!("# Values: {}\n", values.join(", ")));
    }

    // Default value
    if let Some(ref default) = spec.default {
        let default_str = format_default_value(default);
        comments.push_str(&format!("# Default: {}\n", default_str));
    }

    // Validation rules
    if let Some(ref validate) = spec.validate {
        let mut rules = Vec::new();

        if let Some(min) = validate.min {
            rules.push(format!("min={}", min));
        }
        if let Some(max) = validate.max {
            rules.push(format!("max={}", max));
        }
        if let Some(min_value) = validate.min_value {
            rules.push(format!("min_value={}", min_value));
        }
        if let Some(max_value) = validate.max_value {
            rules.push(format!("max_value={}", max_value));
        }
        if let Some(min_length) = validate.min_length {
            rules.push(format!("min_length={}", min_length));
        }
        if let Some(max_length) = validate.max_length {
            rules.push(format!("max_length={}", max_length));
        }
        if let Some(ref pattern) = validate.pattern {
            rules.push(format!("pattern={}", pattern));
        }

        if !rules.is_empty() {
            comments.push_str(&format!("# Validation: {}\n", rules.join(", ")));
        }
    }

    comments
}

/// Format a default value for display
fn format_default_value(value: &serde_json::Value) -> String {
    match value {
        serde_json::Value::String(s) => s.clone(),
        serde_json::Value::Number(n) => n.to_string(),
        serde_json::Value::Bool(b) => b.to_string(),
        serde_json::Value::Null => "null".to_string(),
        _ => value.to_string(),
    }
}

/// Generate the KEY=value line
fn generate_var_line(key: &str, spec: &VarSpec, include_defaults: bool) -> String {
    let value = if include_defaults {
        spec.default
            .as_ref()
            .map(format_default_value)
            .unwrap_or_default()
    } else {
        String::new()
    };

    format!("{}={}", key, value)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schema::ValidationRule;
    use std::io::Write;
    use tempfile::{tempdir, NamedTempFile};

    #[test]
    fn test_generate_var_comments_with_description() {
        let spec = VarSpec {
            var_type: VarType::String,
            required: true,
            description: Some("A test variable".to_string()),
            values: None,
            default: None,
            validate: None,
        };
        let comments = generate_var_comments("TEST", &spec);
        assert!(comments.contains("# A test variable"));
        assert!(comments.contains("# Type: string (required)"));
    }

    #[test]
    fn test_generate_var_comments_optional() {
        let spec = VarSpec {
            var_type: VarType::Int,
            required: false,
            description: None,
            values: None,
            default: None,
            validate: None,
        };
        let comments = generate_var_comments("TEST", &spec);
        assert!(comments.contains("# Type: int (optional)"));
    }

    #[test]
    fn test_generate_var_comments_enum_values() {
        let spec = VarSpec {
            var_type: VarType::Enum,
            required: true,
            description: None,
            values: Some(vec![
                "development".to_string(),
                "staging".to_string(),
                "production".to_string(),
            ]),
            default: None,
            validate: None,
        };
        let comments = generate_var_comments("NODE_ENV", &spec);
        assert!(comments.contains("# Values: development, staging, production"));
    }

    #[test]
    fn test_generate_var_comments_default_value() {
        let spec = VarSpec {
            var_type: VarType::Int,
            required: false,
            description: None,
            values: None,
            default: Some(serde_json::json!(3000)),
            validate: None,
        };
        let comments = generate_var_comments("PORT", &spec);
        assert!(comments.contains("# Default: 3000"));
    }

    #[test]
    fn test_generate_var_comments_validation_rules() {
        let spec = VarSpec {
            var_type: VarType::Int,
            required: false,
            description: None,
            values: None,
            default: None,
            validate: Some(ValidationRule {
                min: Some(1024),
                max: Some(65535),
                ..Default::default()
            }),
        };
        let comments = generate_var_comments("PORT", &spec);
        assert!(comments.contains("# Validation: min=1024, max=65535"));
    }

    #[test]
    fn test_generate_var_comments_string_validation() {
        let spec = VarSpec {
            var_type: VarType::String,
            required: true,
            description: None,
            values: None,
            default: None,
            validate: Some(ValidationRule {
                min_length: Some(32),
                pattern: Some("^sk_".to_string()),
                ..Default::default()
            }),
        };
        let comments = generate_var_comments("API_KEY", &spec);
        assert!(comments.contains("min_length=32"));
        assert!(comments.contains("pattern=^sk_"));
    }

    #[test]
    fn test_generate_var_line_without_defaults() {
        let spec = VarSpec {
            var_type: VarType::String,
            required: true,
            description: None,
            values: None,
            default: Some(serde_json::json!("test")),
            validate: None,
        };
        let line = generate_var_line("FOO", &spec, false);
        assert_eq!(line, "FOO=");
    }

    #[test]
    fn test_generate_var_line_with_defaults() {
        let spec = VarSpec {
            var_type: VarType::Int,
            required: false,
            description: None,
            values: None,
            default: Some(serde_json::json!(3000)),
            validate: None,
        };
        let line = generate_var_line("PORT", &spec, true);
        assert_eq!(line, "PORT=3000");
    }

    #[test]
    fn test_generate_var_line_string_default() {
        let spec = VarSpec {
            var_type: VarType::String,
            required: false,
            description: None,
            values: None,
            default: Some(serde_json::json!("development")),
            validate: None,
        };
        let line = generate_var_line("NODE_ENV", &spec, true);
        assert_eq!(line, "NODE_ENV=development");
    }

    #[test]
    fn test_generate_var_line_bool_default() {
        let spec = VarSpec {
            var_type: VarType::Bool,
            required: false,
            description: None,
            values: None,
            default: Some(serde_json::json!(true)),
            validate: None,
        };
        let line = generate_var_line("DEBUG", &spec, true);
        assert_eq!(line, "DEBUG=true");
    }

    #[test]
    fn test_format_default_value_string() {
        let value = serde_json::json!("hello");
        assert_eq!(format_default_value(&value), "hello");
    }

    #[test]
    fn test_format_default_value_number() {
        let value = serde_json::json!(42);
        assert_eq!(format_default_value(&value), "42");
    }

    #[test]
    fn test_format_default_value_bool() {
        let value = serde_json::json!(true);
        assert_eq!(format_default_value(&value), "true");
    }

    #[test]
    fn test_format_default_value_float() {
        let value = serde_json::json!(3.14);
        assert_eq!(format_default_value(&value), "3.14");
    }

    #[test]
    fn test_run_with_schema_file() {
        let mut file = NamedTempFile::new().unwrap();
        writeln!(
            file,
            r#"{{
                "PORT": {{"type": "int", "default": 3000, "description": "HTTP port"}},
                "DEBUG": {{"type": "bool", "default": false}}
            }}"#
        )
        .unwrap();

        let dir = tempdir().unwrap();
        let output_path = dir.path().join("test.env.example");

        let result = run(
            file.path().to_str().unwrap(),
            Some(output_path.to_str().unwrap()),
            true,
        );
        assert!(result.is_ok());

        let content = fs::read_to_string(&output_path).unwrap();
        assert!(content.contains("DEBUG=false"));
        assert!(content.contains("PORT=3000"));
        assert!(content.contains("# HTTP port"));
    }

    #[test]
    fn test_run_without_defaults() {
        let mut file = NamedTempFile::new().unwrap();
        writeln!(
            file,
            r#"{{"PORT": {{"type": "int", "default": 3000}}}}"#
        )
        .unwrap();

        let dir = tempdir().unwrap();
        let output_path = dir.path().join("test.env.example");

        let result = run(
            file.path().to_str().unwrap(),
            Some(output_path.to_str().unwrap()),
            false,
        );
        assert!(result.is_ok());

        let content = fs::read_to_string(&output_path).unwrap();
        assert!(content.contains("PORT="));
        assert!(!content.contains("PORT=3000"));
    }

    #[test]
    fn test_output_sorted_alphabetically() {
        let mut file = NamedTempFile::new().unwrap();
        writeln!(
            file,
            r#"{{
                "ZEBRA": {{"type": "string"}},
                "APPLE": {{"type": "string"}},
                "MANGO": {{"type": "string"}}
            }}"#
        )
        .unwrap();

        let dir = tempdir().unwrap();
        let output_path = dir.path().join("test.env.example");

        run(
            file.path().to_str().unwrap(),
            Some(output_path.to_str().unwrap()),
            false,
        )
        .unwrap();

        let content = fs::read_to_string(&output_path).unwrap();
        let apple_pos = content.find("APPLE=").unwrap();
        let mango_pos = content.find("MANGO=").unwrap();
        let zebra_pos = content.find("ZEBRA=").unwrap();

        assert!(apple_pos < mango_pos);
        assert!(mango_pos < zebra_pos);
    }

    #[test]
    fn test_all_types_documented() {
        let mut file = NamedTempFile::new().unwrap();
        writeln!(
            file,
            r#"{{
                "STR": {{"type": "string"}},
                "INT": {{"type": "int"}},
                "FLT": {{"type": "float"}},
                "BLN": {{"type": "bool"}},
                "URL": {{"type": "url"}},
                "ENM": {{"type": "enum", "values": ["a", "b"]}}
            }}"#
        )
        .unwrap();

        let dir = tempdir().unwrap();
        let output_path = dir.path().join("test.env.example");

        run(
            file.path().to_str().unwrap(),
            Some(output_path.to_str().unwrap()),
            false,
        )
        .unwrap();

        let content = fs::read_to_string(&output_path).unwrap();
        assert!(content.contains("# Type: string"));
        assert!(content.contains("# Type: int"));
        assert!(content.contains("# Type: float"));
        assert!(content.contains("# Type: bool"));
        assert!(content.contains("# Type: url"));
        assert!(content.contains("# Type: enum"));
    }

    #[test]
    fn test_invalid_schema_path() {
        let result = run("/nonexistent/path/schema.json", None, false);
        assert!(result.is_err());
    }
}