zorath-env 0.3.9

Fast CLI for .env validation against JSON/YAML schemas. 14 types, secret detection, watch mode, remote schemas, 7 export formats, CI templates, health diagnostics, code scanning, auto-fix. Language-agnostic single binary.
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
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
use std::collections::HashMap;
use std::fs;

use crate::envfile;
use crate::errors::CliError;
use crate::schema::{self, LoadOptions};

/// Supported export formats
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ExportFormat {
    Shell,         // export FOO="bar"
    Docker,        // ENV FOO=bar
    K8s,           // ConfigMap YAML
    Json,          // JSON object
    Systemd,       // Environment=FOO=bar
    Dotenv,        // FOO=bar (standard .env)
    GithubSecrets, // gh secret set commands
}

impl std::str::FromStr for ExportFormat {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "shell" | "bash" | "sh" => Ok(ExportFormat::Shell),
            "docker" | "dockerfile" => Ok(ExportFormat::Docker),
            "k8s" | "kubernetes" | "configmap" => Ok(ExportFormat::K8s),
            "json" => Ok(ExportFormat::Json),
            "systemd" | "service" => Ok(ExportFormat::Systemd),
            "dotenv" | "env" => Ok(ExportFormat::Dotenv),
            "github-secrets" | "gh-secrets" | "github" => Ok(ExportFormat::GithubSecrets),
            _ => Err(format!(
                "Unknown format '{}'. Valid formats:\n  \
                shell (aliases: bash, sh)\n  \
                docker (alias: dockerfile)\n  \
                k8s (aliases: kubernetes, configmap)\n  \
                json\n  \
                systemd (alias: service)\n  \
                dotenv (alias: env)\n  \
                github-secrets (aliases: gh-secrets, github)",
                s
            )),
        }
    }
}

impl std::fmt::Display for ExportFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.name())
    }
}

impl ExportFormat {
    pub fn name(&self) -> &'static str {
        match self {
            ExportFormat::Shell => "shell",
            ExportFormat::Docker => "docker",
            ExportFormat::K8s => "k8s",
            ExportFormat::Json => "json",
            ExportFormat::Systemd => "systemd",
            ExportFormat::Dotenv => "dotenv",
            ExportFormat::GithubSecrets => "github-secrets",
        }
    }
}

/// Export environment variables to a string (library function)
///
/// This is the pure library function that takes an environment HashMap
/// and returns the exported content as a String. No file I/O.
///
/// # Arguments
/// * `env_map` - HashMap of environment variable key-value pairs
/// * `format` - Export format (use ExportFormat::from_str to parse)
///
/// # Returns
/// The exported content as a String, or an error message
///
/// # Example
/// ```ignore
/// let mut env = HashMap::new();
/// env.insert("PORT".to_string(), "3000".to_string());
/// let output = export_to_string(&env, ExportFormat::Shell)?;
/// ```
pub fn export_to_string(env_map: &HashMap<String, String>, format: ExportFormat) -> Result<String, String> {
    // Sort keys for consistent output
    let mut keys: Vec<&String> = env_map.keys().collect();
    keys.sort();

    match format {
        ExportFormat::Shell => export_shell(&keys, env_map),
        ExportFormat::Docker => export_docker(&keys, env_map),
        ExportFormat::K8s => export_k8s(&keys, env_map),
        ExportFormat::Json => export_json(&keys, env_map),
        ExportFormat::Systemd => export_systemd(&keys, env_map),
        ExportFormat::Dotenv => export_dotenv(&keys, env_map),
        ExportFormat::GithubSecrets => export_github_secrets(&keys, env_map),
    }
}

#[doc(hidden)]
pub fn run(
    env_path: &str,
    schema_path: Option<&str>,
    format: &str,
    output: Option<&str>,
    no_cache: bool,
    verify_hash: Option<&str>,
    ca_cert: Option<&str>,
) -> Result<(), CliError> {
    // Parse format
    let export_format: ExportFormat = format.parse().map_err(CliError::Input)?;

    // Load and parse env file
    let env_map = envfile::parse_env_file(env_path)
        .map_err(|e| CliError::Input(format!("Failed to parse {}: {}", env_path, e)))?;

    // Interpolate variables
    let env_map = envfile::interpolate_env(env_map)
        .map_err(|e| CliError::Input(format!("Interpolation error: {}", e)))?;

    // Optionally validate against schema
    if let Some(schema_path) = schema_path {
        let options = LoadOptions {
            no_cache,
            verify_hash: verify_hash.map(|s| s.to_string()),
            ca_cert: ca_cert.map(|s| s.to_string()),
            rate_limit_seconds: None,
        };
        let schema = schema::load_schema_with_options(schema_path, &options)
            .map_err(|e| CliError::Schema(e.to_string()))?;

        // Filter to only include keys that are in the schema
        let filtered: HashMap<String, String> = env_map
            .into_iter()
            .filter(|(k, _)| schema.contains_key(k))
            .collect();

        let result = export(&filtered, export_format).map_err(CliError::Input)?;
        output_result(&result, output)
    } else {
        let result = export(&env_map, export_format).map_err(CliError::Input)?;
        output_result(&result, output)
    }
}

fn output_result(result: &str, output: Option<&str>) -> Result<(), CliError> {
    match output {
        Some(path) => {
            fs::write(path, result)
                .map_err(|e| CliError::Input(format!("Failed to write {}: {}", path, e)))?;
            eprintln!("Exported to {}", path);
            Ok(())
        }
        None => {
            println!("{}", result);
            Ok(())
        }
    }
}

fn export(env_map: &HashMap<String, String>, format: ExportFormat) -> Result<String, String> {
    export_to_string(env_map, format)
}

/// Export as shell script (export FOO="bar")
fn export_shell(keys: &[&String], env_map: &HashMap<String, String>) -> Result<String, String> {
    let mut lines = Vec::new();
    lines.push("#!/bin/sh".to_string());
    lines.push("# Generated by zenv".to_string());
    lines.push("".to_string());

    for key in keys {
        if let Some(value) = env_map.get(*key) {
            let escaped = escape_shell_value(value);
            lines.push(format!("export {}=\"{}\"", key, escaped));
        }
    }

    Ok(lines.join("\n"))
}

/// Export as Dockerfile ENV statements
fn export_docker(keys: &[&String], env_map: &HashMap<String, String>) -> Result<String, String> {
    let mut lines = Vec::new();
    lines.push("# Generated by zenv".to_string());
    lines.push("".to_string());

    for key in keys {
        if let Some(value) = env_map.get(*key) {
            let escaped = escape_docker_value(value);
            lines.push(format!("ENV {}={}", key, escaped));
        }
    }

    Ok(lines.join("\n"))
}

/// Export as Kubernetes ConfigMap YAML
fn export_k8s(keys: &[&String], env_map: &HashMap<String, String>) -> Result<String, String> {
    let mut lines = vec![
        "# Generated by zenv".to_string(),
        "apiVersion: v1".to_string(),
        "kind: ConfigMap".to_string(),
        "metadata:".to_string(),
        "  name: app-config".to_string(),
        "data:".to_string(),
    ];

    for key in keys {
        if let Some(value) = env_map.get(*key) {
            // YAML strings need proper quoting for special characters
            let yaml_value = escape_yaml_value(value);
            lines.push(format!("  {}: {}", key, yaml_value));
        }
    }

    Ok(lines.join("\n"))
}

/// Export as JSON object
fn export_json(keys: &[&String], env_map: &HashMap<String, String>) -> Result<String, String> {
    let mut map = serde_json::Map::new();
    for key in keys {
        if let Some(value) = env_map.get(*key) {
            map.insert((*key).clone(), serde_json::Value::String(value.clone()));
        }
    }
    serde_json::to_string_pretty(&map)
        .map_err(|e| format!("JSON serialization error: {}", e))
}

/// Export as systemd Environment directives
fn export_systemd(keys: &[&String], env_map: &HashMap<String, String>) -> Result<String, String> {
    let mut lines = Vec::new();
    lines.push("# Generated by zenv".to_string());
    lines.push("# Add to [Service] section of your .service file".to_string());
    lines.push("".to_string());

    for key in keys {
        if let Some(value) = env_map.get(*key) {
            let escaped = escape_systemd_value(value);
            lines.push(format!("Environment=\"{}={}\"", key, escaped));
        }
    }

    Ok(lines.join("\n"))
}

/// Export as standard .env format
fn export_dotenv(keys: &[&String], env_map: &HashMap<String, String>) -> Result<String, String> {
    let mut lines = Vec::new();
    lines.push("# Generated by zenv".to_string());
    lines.push("".to_string());

    for key in keys {
        if let Some(value) = env_map.get(*key) {
            // Quote values that contain special characters
            if needs_quoting(value) {
                let escaped = value.replace('\\', "\\\\").replace('"', "\\\"");
                lines.push(format!("{}=\"{}\"", key, escaped));
            } else {
                lines.push(format!("{}={}", key, value));
            }
        }
    }

    Ok(lines.join("\n"))
}

/// Export as GitHub Secrets CLI commands (gh secret set)
fn export_github_secrets(keys: &[&String], env_map: &HashMap<String, String>) -> Result<String, String> {
    let mut lines = vec![
        "#!/bin/sh".to_string(),
        "# Generated by zenv".to_string(),
        "# Run this script to set GitHub repository secrets".to_string(),
        "# Requires: gh auth login".to_string(),
        "".to_string(),
    ];

    for key in keys {
        if let Some(value) = env_map.get(*key) {
            // Use heredoc for multi-line or special characters
            if value.contains('\n') || value.contains('\'') {
                lines.push(format!("gh secret set {} << 'EOF'", key));
                lines.push(value.clone());
                lines.push("EOF".to_string());
            } else {
                // Simple values can use --body
                let escaped = value.replace('\\', "\\\\").replace('\'', "'\\''");
                lines.push(format!("gh secret set {} --body '{}'", key, escaped));
            }
        }
    }

    Ok(lines.join("\n"))
}

/// Escape a value for shell script (double-quoted string)
fn escape_shell_value(value: &str) -> String {
    value
        .replace('\\', "\\\\")
        .replace('"', "\\\"")
        .replace('$', "\\$")
        .replace('`', "\\`")
        .replace('\n', "\\n")
}

/// Escape a value for Dockerfile ENV
fn escape_docker_value(value: &str) -> String {
    // Docker ENV values with spaces need quoting
    if value.contains(' ') || value.contains('"') || value.contains('$') {
        let escaped = value
            .replace('\\', "\\\\")
            .replace('"', "\\\"");
        format!("\"{}\"", escaped)
    } else {
        value.to_string()
    }
}

/// Escape a value for YAML
fn escape_yaml_value(value: &str) -> String {
    // YAML needs quoting for certain characters
    if value.contains(':') || value.contains('#') || value.contains('\n')
        || value.contains('"') || value.contains('\'') || value.is_empty()
        || value.starts_with(' ') || value.ends_with(' ')
        || value == "true" || value == "false" || value == "null"
        || value.parse::<f64>().is_ok()
    {
        // Use double quotes and escape
        let escaped = value
            .replace('\\', "\\\\")
            .replace('"', "\\\"")
            .replace('\n', "\\n");
        format!("\"{}\"", escaped)
    } else {
        value.to_string()
    }
}

/// Escape a value for systemd Environment directive
fn escape_systemd_value(value: &str) -> String {
    // Systemd uses double quotes, escape accordingly
    value
        .replace('\\', "\\\\")
        .replace('"', "\\\"")
        .replace('\n', "\\n")
}

/// Check if a value needs quoting in .env format
fn needs_quoting(value: &str) -> bool {
    value.contains(' ')
        || value.contains('"')
        || value.contains('\'')
        || value.contains('#')
        || value.contains('\n')
        || value.contains('$')
        || value.is_empty()
}

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

    fn make_env(entries: Vec<(&str, &str)>) -> HashMap<String, String> {
        entries.into_iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()
    }

    #[test]
    fn test_export_format_from_str() {
        assert_eq!("shell".parse::<ExportFormat>(), Ok(ExportFormat::Shell));
        assert_eq!("bash".parse::<ExportFormat>(), Ok(ExportFormat::Shell));
        assert_eq!("docker".parse::<ExportFormat>(), Ok(ExportFormat::Docker));
        assert_eq!("dockerfile".parse::<ExportFormat>(), Ok(ExportFormat::Docker));
        assert_eq!("k8s".parse::<ExportFormat>(), Ok(ExportFormat::K8s));
        assert_eq!("kubernetes".parse::<ExportFormat>(), Ok(ExportFormat::K8s));
        assert_eq!("configmap".parse::<ExportFormat>(), Ok(ExportFormat::K8s));
        assert_eq!("json".parse::<ExportFormat>(), Ok(ExportFormat::Json));
        assert_eq!("systemd".parse::<ExportFormat>(), Ok(ExportFormat::Systemd));
        assert_eq!("service".parse::<ExportFormat>(), Ok(ExportFormat::Systemd));
        assert_eq!("dotenv".parse::<ExportFormat>(), Ok(ExportFormat::Dotenv));
        assert_eq!("env".parse::<ExportFormat>(), Ok(ExportFormat::Dotenv));
        assert!("invalid".parse::<ExportFormat>().is_err());
    }

    #[test]
    fn test_export_shell() {
        let env = make_env(vec![("FOO", "bar"), ("BAZ", "qux")]);
        let baz = "BAZ".to_string();
        let foo = "FOO".to_string();
        let keys: Vec<&String> = vec![&baz, &foo];
        let result = export_shell(&keys, &env).unwrap();
        assert!(result.contains("#!/bin/sh"));
        assert!(result.contains("export BAZ=\"qux\""));
        assert!(result.contains("export FOO=\"bar\""));
    }

    #[test]
    fn test_export_shell_escapes() {
        let env = make_env(vec![("KEY", "value with \"quotes\" and $var")]);
        let key = "KEY".to_string();
        let keys: Vec<&String> = vec![&key];
        let result = export_shell(&keys, &env).unwrap();
        assert!(result.contains("\\\"quotes\\\""));
        assert!(result.contains("\\$var"));
    }

    #[test]
    fn test_export_docker() {
        let env = make_env(vec![("PORT", "3000"), ("NAME", "my app")]);
        let name = "NAME".to_string();
        let port = "PORT".to_string();
        let keys: Vec<&String> = vec![&name, &port];
        let result = export_docker(&keys, &env).unwrap();
        assert!(result.contains("ENV NAME=\"my app\""));
        assert!(result.contains("ENV PORT=3000"));
    }

    #[test]
    fn test_export_k8s() {
        let env = make_env(vec![("DATABASE_URL", "postgres://localhost/db")]);
        let db_url = "DATABASE_URL".to_string();
        let keys: Vec<&String> = vec![&db_url];
        let result = export_k8s(&keys, &env).unwrap();
        assert!(result.contains("apiVersion: v1"));
        assert!(result.contains("kind: ConfigMap"));
        assert!(result.contains("DATABASE_URL:"));
    }

    #[test]
    fn test_export_json() {
        let env = make_env(vec![("FOO", "bar")]);
        let foo = "FOO".to_string();
        let keys: Vec<&String> = vec![&foo];
        let result = export_json(&keys, &env).unwrap();
        assert!(result.contains("\"FOO\": \"bar\""));
    }

    #[test]
    fn test_export_systemd() {
        let env = make_env(vec![("FOO", "bar")]);
        let foo = "FOO".to_string();
        let keys: Vec<&String> = vec![&foo];
        let result = export_systemd(&keys, &env).unwrap();
        assert!(result.contains("Environment=\"FOO=bar\""));
    }

    #[test]
    fn test_export_dotenv() {
        let env = make_env(vec![("SIMPLE", "value"), ("COMPLEX", "has spaces")]);
        let complex = "COMPLEX".to_string();
        let simple = "SIMPLE".to_string();
        let keys: Vec<&String> = vec![&complex, &simple];
        let result = export_dotenv(&keys, &env).unwrap();
        assert!(result.contains("SIMPLE=value"));
        assert!(result.contains("COMPLEX=\"has spaces\""));
    }

    #[test]
    fn test_escape_yaml_special_values() {
        // Boolean-like values need quoting
        assert_eq!(escape_yaml_value("true"), "\"true\"");
        assert_eq!(escape_yaml_value("false"), "\"false\"");
        assert_eq!(escape_yaml_value("null"), "\"null\"");
        // Numbers need quoting
        assert_eq!(escape_yaml_value("123"), "\"123\"");
        assert_eq!(escape_yaml_value("3.14"), "\"3.14\"");
        // Normal strings don't need quoting
        assert_eq!(escape_yaml_value("normal"), "normal");
    }

    // =========================================================================
    // GitHub Secrets Export Tests (v0.3.8)
    // =========================================================================

    #[test]
    fn test_export_github_secrets_simple() {
        let env = make_env(vec![("API_KEY", "secret123"), ("PORT", "3000")]);
        let api_key = "API_KEY".to_string();
        let port = "PORT".to_string();
        let keys: Vec<&String> = vec![&api_key, &port];
        let result = export_github_secrets(&keys, &env).unwrap();

        assert!(result.contains("#!/bin/sh"), "Should have shebang");
        assert!(result.contains("gh secret set API_KEY --body 'secret123'"), "Should use --body for simple values");
        assert!(result.contains("gh secret set PORT --body '3000'"), "Should include PORT");
    }

    #[test]
    fn test_export_github_secrets_multiline() {
        let multiline_value = "line1\nline2\nline3";
        let env = make_env(vec![("PRIVATE_KEY", multiline_value)]);
        let key = "PRIVATE_KEY".to_string();
        let keys: Vec<&String> = vec![&key];
        let result = export_github_secrets(&keys, &env).unwrap();

        // Multiline values should use heredoc format
        assert!(result.contains("gh secret set PRIVATE_KEY << 'EOF'"), "Should use heredoc for multiline");
        assert!(result.contains("line1\nline2\nline3"), "Should preserve newlines");
        assert!(result.contains("EOF"), "Should close heredoc");
    }

    #[test]
    fn test_export_github_secrets_special_chars() {
        // Single quotes need special handling
        let env = make_env(vec![("CONFIG", "it's a test")]);
        let key = "CONFIG".to_string();
        let keys: Vec<&String> = vec![&key];
        let result = export_github_secrets(&keys, &env).unwrap();

        // Values with single quotes should use heredoc
        assert!(result.contains("gh secret set CONFIG << 'EOF'"), "Should use heredoc for quotes");
    }

    #[test]
    fn test_export_github_secrets_escapes_backslashes() {
        let env = make_env(vec![("PATH_VAR", "C:\\Users\\test")]);
        let key = "PATH_VAR".to_string();
        let keys: Vec<&String> = vec![&key];
        let result = export_github_secrets(&keys, &env).unwrap();

        // Should escape backslashes
        assert!(result.contains("gh secret set PATH_VAR"), "Should include key");
        assert!(result.contains("--body") || result.contains("EOF"), "Should have body or heredoc");
    }

    #[test]
    fn test_export_github_secrets_header_comments() {
        let env = make_env(vec![("FOO", "bar")]);
        let foo = "FOO".to_string();
        let keys: Vec<&String> = vec![&foo];
        let result = export_github_secrets(&keys, &env).unwrap();

        assert!(result.contains("#!/bin/sh"), "Should have shebang");
        assert!(result.contains("# Generated by zenv"), "Should have generator comment");
        assert!(result.contains("gh auth login"), "Should mention auth requirement");
    }

    #[test]
    fn test_export_github_secrets_format_alias() {
        // Test all format aliases parse correctly
        assert_eq!("github-secrets".parse::<ExportFormat>(), Ok(ExportFormat::GithubSecrets));
        assert_eq!("gh-secrets".parse::<ExportFormat>(), Ok(ExportFormat::GithubSecrets));
        assert_eq!("github".parse::<ExportFormat>(), Ok(ExportFormat::GithubSecrets));
    }
}