devpulse 1.0.0

Developer diagnostics: HTTP timing, build artifact cleanup, environment health checks, port scanning, PATH analysis, and config format conversion
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
//! Config format converter: JSON ↔ YAML ↔ TOML ↔ .env
//!
//! Parses a config file, detects input format (by extension or `--from` flag),
//! converts through `serde_json::Value` as universal intermediate, and writes
//! the output in the requested format.
//!
//! `.env` is flat key=value, so nested structures are dot-flattened:
//! `database.host=localhost` ↔ `{"database": {"host": "localhost"}}`

use std::collections::BTreeMap;
use std::fs;
use std::path::Path;

use colored::Colorize;
use serde_json::Value;
use thiserror::Error;

// ── Error type ───────────────────────────────────────────────────────────────

/// Errors that can occur during config conversion.
#[derive(Error, Debug)]
pub enum ConvertError {
    /// File I/O error
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),

    /// JSON parse error
    #[error("JSON parse error: {0}")]
    Json(#[from] serde_json::Error),

    /// YAML parse error
    #[error("YAML parse error: {0}")]
    Yaml(#[from] serde_yml::Error),

    /// TOML parse error
    #[error("TOML parse error: {0}")]
    TomlParse(#[from] toml::de::Error),

    /// TOML serialization error
    #[error("TOML serialization error: {0}")]
    TomlSerialize(#[from] toml::ser::Error),

    /// Unsupported format
    #[error("Unsupported format: {0}")]
    UnsupportedFormat(String),

    /// Conversion-specific error
    #[error("{0}")]
    Other(String),
}

// ── Format enum ──────────────────────────────────────────────────────────────

/// Supported config file formats.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfigFormat {
    Json,
    Yaml,
    Toml,
    Env,
}

impl ConfigFormat {
    /// Detect format from a file extension.
    pub fn from_extension(path: &Path) -> Option<Self> {
        let ext = path.extension()?.to_str()?.to_lowercase();
        match ext.as_str() {
            "json" => Some(Self::Json),
            "yaml" | "yml" => Some(Self::Yaml),
            "toml" => Some(Self::Toml),
            "env" => Some(Self::Env),
            _ => None,
        }
    }

    /// Parse format from a string label (CLI `--from` / `--to` flags).
    pub fn from_label(label: &str) -> Option<Self> {
        match label.to_lowercase().as_str() {
            "json" => Some(Self::Json),
            "yaml" | "yml" => Some(Self::Yaml),
            "toml" => Some(Self::Toml),
            "env" | "dotenv" | ".env" => Some(Self::Env),
            _ => None,
        }
    }

    /// File extension used for output.
    pub fn extension(self) -> &'static str {
        match self {
            Self::Json => "json",
            Self::Yaml => "yaml",
            Self::Toml => "toml",
            Self::Env => "env",
        }
    }

    /// Human-readable label.
    pub fn label(self) -> &'static str {
        match self {
            Self::Json => "JSON",
            Self::Yaml => "YAML",
            Self::Toml => "TOML",
            Self::Env => ".env",
        }
    }
}

// ── Conversion result for TUI / JSON output ──────────────────────────────────

/// Result of a config conversion, suitable for display or JSON output.
#[derive(Debug, Clone, serde::Serialize)]
pub struct ConvertResult {
    /// The input file path
    pub input_path: String,
    /// Detected or specified input format
    pub input_format: String,
    /// Target output format
    pub output_format: String,
    /// The converted output text
    pub output: String,
    /// Output file path (if written to disk)
    pub output_path: Option<String>,
}

// ── Core conversion logic ────────────────────────────────────────────────────

/// Parse raw text into a `serde_json::Value` given the source format.
pub fn parse_input(content: &str, format: ConfigFormat) -> Result<Value, ConvertError> {
    match format {
        ConfigFormat::Json => {
            let val: Value = serde_json::from_str(content)?;
            Ok(val)
        }
        ConfigFormat::Yaml => {
            let val: Value = serde_yml::from_str(content)?;
            Ok(val)
        }
        ConfigFormat::Toml => {
            let val: toml::Value = toml::from_str(content)?;
            // Convert toml::Value → serde_json::Value directly via serde
            let val: Value =
                serde_json::to_value(&val).map_err(|e| ConvertError::Other(e.to_string()))?;
            Ok(val)
        }
        ConfigFormat::Env => {
            let map = parse_dotenv(content);
            Ok(unflatten_map(&map))
        }
    }
}

/// Serialize a `serde_json::Value` to the target format string.
pub fn serialize_output(value: &Value, format: ConfigFormat) -> Result<String, ConvertError> {
    match format {
        ConfigFormat::Json => {
            let out = serde_json::to_string_pretty(value)?;
            Ok(out)
        }
        ConfigFormat::Yaml => {
            let out = serde_yml::to_string(value)?;
            Ok(out)
        }
        ConfigFormat::Toml => {
            // serde_json::Value implements Serialize, so toml can serialize it directly
            let out = toml::to_string_pretty(value).map_err(|e| {
                ConvertError::Other(format!(
                    "Cannot convert to TOML: {e} (TOML does not support null or mixed-type arrays)"
                ))
            })?;
            Ok(out)
        }
        ConfigFormat::Env => {
            let map = flatten_value(value, "");
            let mut lines: Vec<String> = Vec::new();
            for (k, v) in &map {
                lines.push(format!("{k}={v}"));
            }
            Ok(lines.join("\n"))
        }
    }
}

/// Full conversion: read file → parse → convert → optionally write output file.
pub fn convert_file(
    input_path: &Path,
    from_format: Option<ConfigFormat>,
    to_format: ConfigFormat,
    output_path: Option<&Path>,
) -> Result<ConvertResult, ConvertError> {
    // Detect input format
    let input_format = from_format
        .or_else(|| {
            // Special-case: files named ".env" or ".env.local" etc.
            let name = input_path
                .file_name()
                .map(|n| n.to_string_lossy().to_string())
                .unwrap_or_default();
            if name.starts_with(".env") {
                return Some(ConfigFormat::Env);
            }
            ConfigFormat::from_extension(input_path)
        })
        .ok_or_else(|| {
            ConvertError::UnsupportedFormat(format!(
                "Cannot detect format of '{}'. Use --from to specify.",
                input_path.display()
            ))
        })?;

    let content = fs::read_to_string(input_path)?;
    let value = parse_input(&content, input_format)?;
    let output = serialize_output(&value, to_format)?;

    // Write output file if path is provided
    let out_path_str = if let Some(op) = output_path {
        fs::write(op, &output)?;
        Some(op.display().to_string())
    } else {
        None
    };

    Ok(ConvertResult {
        input_path: input_path.display().to_string(),
        input_format: input_format.label().to_string(),
        output_format: to_format.label().to_string(),
        output,
        output_path: out_path_str,
    })
}

// ── .env helpers ─────────────────────────────────────────────────────────────

/// Parse a `.env` file into a flat `BTreeMap<String, String>`.
fn parse_dotenv(content: &str) -> BTreeMap<String, String> {
    let mut map = BTreeMap::new();
    for line in content.lines() {
        let trimmed = line.trim();
        // Skip comments and empty lines
        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }
        if let Some((key, val)) = trimmed.split_once('=') {
            let key = key.trim().to_string();
            // Strip optional surrounding quotes from value
            let val = val.trim();
            let val = if val.len() >= 2
                && ((val.starts_with('"') && val.ends_with('"'))
                    || (val.starts_with('\'') && val.ends_with('\'')))
            {
                val[1..val.len() - 1].to_string()
            } else {
                val.to_string()
            };
            map.insert(key, val);
        }
    }
    map
}

/// Unflatten dot-separated keys into nested JSON.  
/// `database.host=localhost` → `{"database": {"host": "localhost"}}`
fn unflatten_map(map: &BTreeMap<String, String>) -> Value {
    let mut root = serde_json::Map::new();
    for (key, val) in map {
        let parts: Vec<&str> = key.split('.').collect();
        insert_nested(&mut root, &parts, Value::String(val.clone()));
    }
    Value::Object(root)
}

/// Recursively insert a value into a nested JSON map.
fn insert_nested(map: &mut serde_json::Map<String, Value>, path: &[&str], value: Value) {
    if path.len() == 1 {
        map.insert(path[0].to_string(), value);
        return;
    }
    let entry = map
        .entry(path[0].to_string())
        .or_insert_with(|| Value::Object(serde_json::Map::new()));
    if let Value::Object(ref mut child) = entry {
        insert_nested(child, &path[1..], value);
    }
}

/// Flatten a JSON value into dot-separated key-value pairs for .env output.
fn flatten_value(value: &Value, prefix: &str) -> BTreeMap<String, String> {
    let mut map = BTreeMap::new();
    match value {
        Value::Object(obj) => {
            for (k, v) in obj {
                let new_prefix = if prefix.is_empty() {
                    k.clone()
                } else {
                    format!("{prefix}.{k}")
                };
                map.extend(flatten_value(v, &new_prefix));
            }
        }
        Value::Array(arr) => {
            for (i, v) in arr.iter().enumerate() {
                let new_prefix = format!("{prefix}.{i}");
                map.extend(flatten_value(v, &new_prefix));
            }
        }
        Value::String(s) => {
            map.insert(prefix.to_string(), s.clone());
        }
        Value::Number(n) => {
            map.insert(prefix.to_string(), n.to_string());
        }
        Value::Bool(b) => {
            map.insert(prefix.to_string(), b.to_string());
        }
        Value::Null => {
            map.insert(prefix.to_string(), String::new());
        }
    }
    map
}

// ── CLI runner ───────────────────────────────────────────────────────────────

/// Run the convert command from the CLI.
pub fn run(
    input: &str,
    to: &str,
    from: Option<&str>,
    output: Option<&str>,
    json_output: bool,
) -> Result<(), ConvertError> {
    let input_path = Path::new(input);
    let to_format = ConfigFormat::from_label(to).ok_or_else(|| {
        ConvertError::UnsupportedFormat(format!(
            "Unknown target format: '{to}'. Use: json, yaml, toml, env"
        ))
    })?;
    let from_format = from
        .map(|f| {
            ConfigFormat::from_label(f).ok_or_else(|| {
                ConvertError::UnsupportedFormat(format!(
                    "Unknown source format: '{f}'. Use: json, yaml, toml, env"
                ))
            })
        })
        .transpose()?;
    let output_path = output.map(Path::new);

    let result = convert_file(input_path, from_format, to_format, output_path)?;

    if json_output {
        let json_str =
            serde_json::to_string_pretty(&result).unwrap_or_else(|_| "{}".to_string());
        println!("{json_str}");
    } else {
        println!();
        println!(
            "  {} {} {}",
            "devpulse".bold(),
            "──".dimmed(),
            "Config Converter".bold()
        );
        println!();
        println!(
            "  {} {}{}",
            "Format:".dimmed(),
            result.input_format.cyan().bold(),
            result.output_format.green().bold()
        );
        println!(
            "  {} {}",
            "Input: ".dimmed(),
            result.input_path.white()
        );
        if let Some(ref op) = result.output_path {
            println!("  {} {}", "Output:".dimmed(), op.green());
        } else {
            // Suggest output filename using the target format extension
            let stem = Path::new(input)
                .file_stem()
                .map(|s| s.to_string_lossy().to_string())
                .unwrap_or_else(|| "output".to_string());
            let suggested = format!("{stem}.{}", to_format.extension());
            println!(
                "  {} {} (use -o to write)",
                "Hint:  ".dimmed(),
                suggested.dimmed()
            );
        }
        println!();
        println!("  {}", "── Converted Output ──".dimmed());
        println!();
        for line in result.output.lines() {
            println!("  {line}");
        }
        println!();
    }

    Ok(())
}

// ── TUI helper ───────────────────────────────────────────────────────────────

/// Run a conversion and return the result for TUI display.
pub fn convert_for_tui(
    input: &str,
    to: &str,
    from: Option<&str>,
) -> Result<ConvertResult, ConvertError> {
    let input_path = Path::new(input);
    let to_format = ConfigFormat::from_label(to).ok_or_else(|| {
        ConvertError::UnsupportedFormat(format!(
            "Unknown target format: '{to}'. Use: json, yaml, toml, env"
        ))
    })?;
    let from_format = from
        .map(|f| {
            ConfigFormat::from_label(f).ok_or_else(|| {
                ConvertError::UnsupportedFormat(format!(
                    "Unknown source format: '{f}'. Use: json, yaml, toml, env"
                ))
            })
        })
        .transpose()?;

    convert_file(input_path, from_format, to_format, None)
}

// ── Tests ────────────────────────────────────────────────────────────────────

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

    #[test]
    fn test_json_to_yaml() {
        let json = r#"{"name": "devpulse", "version": "0.1.0"}"#;
        let val = parse_input(json, ConfigFormat::Json).unwrap();
        let yaml = serialize_output(&val, ConfigFormat::Yaml).unwrap();
        assert!(yaml.contains("name: devpulse"));
        // serde_yml may quote values that look like floats (e.g. "0.1.0")
        assert!(
            yaml.contains("version: '0.1.0'")
                || yaml.contains("version: \"0.1.0\"")
                || yaml.contains("version: 0.1.0"),
            "Expected version field in YAML, got: {yaml}"
        );
    }

    #[test]
    fn test_json_to_toml() {
        let json = r#"{"name": "devpulse", "version": "0.1.0"}"#;
        let val = parse_input(json, ConfigFormat::Json).unwrap();
        let toml_out = serialize_output(&val, ConfigFormat::Toml).unwrap();
        assert!(toml_out.contains("name = \"devpulse\""));
        assert!(toml_out.contains("version = \"0.1.0\""));
    }

    #[test]
    fn test_json_to_env() {
        let json = r#"{"database": {"host": "localhost", "port": 5432}}"#;
        let val = parse_input(json, ConfigFormat::Json).unwrap();
        let env_out = serialize_output(&val, ConfigFormat::Env).unwrap();
        assert!(env_out.contains("database.host=localhost"));
        assert!(env_out.contains("database.port=5432"));
    }

    #[test]
    fn test_env_to_json() {
        let env_content = "DB_HOST=localhost\nDB_PORT=5432\n# comment\n\nAPP_NAME=test";
        let val = parse_input(env_content, ConfigFormat::Env).unwrap();
        let json = serialize_output(&val, ConfigFormat::Json).unwrap();
        assert!(json.contains("DB_HOST"));
        assert!(json.contains("localhost"));
        assert!(json.contains("DB_PORT"));
    }

    #[test]
    fn test_yaml_to_json() {
        let yaml = "name: devpulse\nversion: 0.1.0\n";
        let val = parse_input(yaml, ConfigFormat::Yaml).unwrap();
        let json = serialize_output(&val, ConfigFormat::Json).unwrap();
        assert!(json.contains("\"name\": \"devpulse\""));
    }

    #[test]
    fn test_toml_to_json() {
        let toml_input = "name = \"devpulse\"\nversion = \"0.1.0\"\n";
        let val = parse_input(toml_input, ConfigFormat::Toml).unwrap();
        let json = serialize_output(&val, ConfigFormat::Json).unwrap();
        assert!(json.contains("\"name\": \"devpulse\""));
    }

    #[test]
    fn test_dotenv_quote_stripping() {
        let env_content = "KEY1=\"quoted value\"\nKEY2='single quoted'\nKEY3=plain";
        let val = parse_input(env_content, ConfigFormat::Env).unwrap();
        let json = serialize_output(&val, ConfigFormat::Json).unwrap();
        assert!(json.contains("quoted value"));
        assert!(json.contains("single quoted"));
        assert!(json.contains("plain"));
    }

    #[test]
    fn test_nested_env_unflatten() {
        let env_content = "db.host=localhost\ndb.port=5432\napp.name=test";
        let val = parse_input(env_content, ConfigFormat::Env).unwrap();
        // Should produce nested structure
        let obj = val.as_object().unwrap();
        assert!(obj.contains_key("db"));
        assert!(obj.contains_key("app"));
        let db = obj["db"].as_object().unwrap();
        assert_eq!(db["host"].as_str().unwrap(), "localhost");
    }

    #[test]
    fn test_format_from_extension() {
        assert_eq!(ConfigFormat::from_extension(Path::new("config.json")), Some(ConfigFormat::Json));
        assert_eq!(ConfigFormat::from_extension(Path::new("config.yaml")), Some(ConfigFormat::Yaml));
        assert_eq!(ConfigFormat::from_extension(Path::new("config.yml")), Some(ConfigFormat::Yaml));
        assert_eq!(ConfigFormat::from_extension(Path::new("config.toml")), Some(ConfigFormat::Toml));
        assert_eq!(ConfigFormat::from_extension(Path::new("config.env")), Some(ConfigFormat::Env));
        assert_eq!(ConfigFormat::from_extension(Path::new("config.txt")), None);
    }

    #[test]
    fn test_format_extension_and_label() {
        assert_eq!(ConfigFormat::Json.extension(), "json");
        assert_eq!(ConfigFormat::Yaml.extension(), "yaml");
        assert_eq!(ConfigFormat::Toml.extension(), "toml");
        assert_eq!(ConfigFormat::Env.extension(), "env");
        assert_eq!(ConfigFormat::Json.label(), "JSON");
        assert_eq!(ConfigFormat::Yaml.label(), "YAML");
        assert_eq!(ConfigFormat::Toml.label(), "TOML");
        assert_eq!(ConfigFormat::Env.label(), ".env");
    }

    #[test]
    fn test_format_from_label() {
        assert_eq!(ConfigFormat::from_label("json"), Some(ConfigFormat::Json));
        assert_eq!(ConfigFormat::from_label("YAML"), Some(ConfigFormat::Yaml));
        assert_eq!(ConfigFormat::from_label("yml"), Some(ConfigFormat::Yaml));
        assert_eq!(ConfigFormat::from_label("toml"), Some(ConfigFormat::Toml));
        assert_eq!(ConfigFormat::from_label("env"), Some(ConfigFormat::Env));
        assert_eq!(ConfigFormat::from_label("dotenv"), Some(ConfigFormat::Env));
        assert_eq!(ConfigFormat::from_label("xml"), None);
    }

    #[test]
    fn test_convert_file_json_to_yaml() {
        let mut tmp = tempfile::Builder::new().suffix(".json").tempfile().unwrap();
        writeln!(tmp, r#"{{"server": "localhost", "port": 8080}}"#).unwrap();
        let result = convert_file(tmp.path(), None, ConfigFormat::Yaml, None).unwrap();
        assert_eq!(result.input_format, "JSON");
        assert_eq!(result.output_format, "YAML");
        assert!(result.output.contains("server: localhost"));
    }

    #[test]
    fn test_convert_result_serialization() {
        let result = ConvertResult {
            input_path: "test.json".into(),
            input_format: "JSON".into(),
            output_format: "YAML".into(),
            output: "key: value".into(),
            output_path: None,
        };
        let json = serde_json::to_string(&result).unwrap();
        assert!(json.contains("input_path"));
        assert!(json.contains("YAML"));
    }

    #[test]
    fn test_roundtrip_json_yaml_json() {
        let original = r#"{"alpha": "one", "beta": {"nested": true}}"#;
        let val = parse_input(original, ConfigFormat::Json).unwrap();
        let yaml = serialize_output(&val, ConfigFormat::Yaml).unwrap();
        let val2 = parse_input(&yaml, ConfigFormat::Yaml).unwrap();
        let json2 = serialize_output(&val2, ConfigFormat::Json).unwrap();
        let val3 = parse_input(&json2, ConfigFormat::Json).unwrap();
        assert_eq!(val, val3);
    }

    #[test]
    fn test_roundtrip_json_toml_json() {
        let original = r#"{"name": "test", "count": 42}"#;
        let val = parse_input(original, ConfigFormat::Json).unwrap();
        let toml_out = serialize_output(&val, ConfigFormat::Toml).unwrap();
        let val2 = parse_input(&toml_out, ConfigFormat::Toml).unwrap();
        let json2 = serialize_output(&val2, ConfigFormat::Json).unwrap();
        let val3 = parse_input(&json2, ConfigFormat::Json).unwrap();
        assert_eq!(val, val3);
    }
}