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
//! Developer environment health checker.
//!
//! Runs checks for common developer tools (Git, Node.js, Rust, Python, Docker),
//! disk space, and SSH keys. Reports pass/warn/fail status for each check.

use std::io;
use std::path::PathBuf;
use std::process::Command;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;

use colored::Colorize;
use serde::Serialize;
use thiserror::Error;

/// Errors specific to the doctor module.
#[derive(Error, Debug)]
pub enum DoctorError {
    /// IO error during check execution
    #[error("IO error: {0}")]
    Io(#[from] io::Error),

    /// One or more health checks failed
    #[error("{fail} check(s) failed ({pass} passed, {warn} warning(s))")]
    ChecksFailed {
        pass: u32,
        warn: u32,
        fail: u32,
    },
}

/// Status of a single health check.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum CheckStatus {
    Pass,
    Warn,
    Fail,
}

/// Result of a single health check.
#[derive(Debug, Serialize)]
pub struct CheckResult {
    /// Name of the tool or check
    pub name: String,
    /// Pass, warn, or fail
    pub status: CheckStatus,
    /// Version string if available
    pub version: Option<String>,
    /// Additional detail (e.g., "pip not found", "2 keys found")
    pub detail: String,
}

/// Run a command with a timeout, returning stdout as a trimmed string.
/// Returns None if the command fails or times out.
fn run_cmd_with_timeout(cmd: &str, args: &[&str], timeout_secs: u64) -> Option<String> {
    let cmd_owned = cmd.to_string();
    let args_owned: Vec<String> = args.iter().map(|s| s.to_string()).collect();

    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let result = Command::new(&cmd_owned).args(&args_owned).output();
        let _ = tx.send(result);
    });

    match rx.recv_timeout(Duration::from_secs(timeout_secs)) {
        Ok(Ok(output)) if output.status.success() => {
            let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
            Some(stdout)
        }
        _ => None,
    }
}

/// Extract a version number from a tool's --version output.
/// Looks for patterns like "git version 2.43.0" → "2.43.0".
fn extract_version(output: &str) -> String {
    // Take the first line only
    let first_line = output.lines().next().unwrap_or(output);

    // Common patterns: "tool version X.Y.Z", "tool X.Y.Z", "vX.Y.Z"
    for word in first_line.split_whitespace().rev() {
        let clean = word.trim_start_matches('v');
        if clean.contains('.') && clean.chars().next().is_some_and(|c| c.is_ascii_digit()) {
            return clean.to_string();
        }
    }

    first_line.to_string()
}

/// Check if Git is installed and configured.
fn check_git() -> CheckResult {
    let version = run_cmd_with_timeout("git", &["--version"], 3);
    match version {
        Some(output) => {
            let ver = extract_version(&output);
            let user = run_cmd_with_timeout("git", &["config", "user.name"], 3);
            let detail = match user {
                Some(ref name) if !name.is_empty() => format!("user.name = {name}"),
                _ => "user.name not configured".to_string(),
            };
            let status = if user.is_some() && !user.as_deref().unwrap_or_default().is_empty() {
                CheckStatus::Pass
            } else {
                CheckStatus::Warn
            };
            CheckResult {
                name: "Git".to_string(),
                status,
                version: Some(ver),
                detail,
            }
        }
        None => CheckResult {
            name: "Git".to_string(),
            status: CheckStatus::Fail,
            version: None,
            detail: "not installed".to_string(),
        },
    }
}

/// Check if Node.js and npm are installed.
fn check_node() -> CheckResult {
    let node_ver = run_cmd_with_timeout("node", &["--version"], 3);
    match node_ver {
        Some(output) => {
            let ver = extract_version(&output);
            let npm = run_cmd_with_timeout("npm", &["--version"], 3);
            let detail = match npm {
                Some(ref npm_ver) => format!("npm {}", npm_ver.trim()),
                None => "npm not found".to_string(),
            };
            let status = if npm.is_some() {
                CheckStatus::Pass
            } else {
                CheckStatus::Warn
            };
            CheckResult {
                name: "Node.js".to_string(),
                status,
                version: Some(ver),
                detail,
            }
        }
        None => CheckResult {
            name: "Node.js".to_string(),
            status: CheckStatus::Fail,
            version: None,
            detail: "not installed".to_string(),
        },
    }
}

/// Check if Rust toolchain is installed.
fn check_rust() -> CheckResult {
    let rustc_ver = run_cmd_with_timeout("rustc", &["--version"], 3);
    match rustc_ver {
        Some(output) => {
            let ver = extract_version(&output);
            let cargo = run_cmd_with_timeout("cargo", &["--version"], 3);
            let detail = match cargo {
                Some(ref c) => format!("cargo {}", extract_version(c)),
                None => "cargo not found".to_string(),
            };
            let status = if cargo.is_some() {
                CheckStatus::Pass
            } else {
                CheckStatus::Warn
            };
            CheckResult {
                name: "Rust".to_string(),
                status,
                version: Some(ver),
                detail,
            }
        }
        None => CheckResult {
            name: "Rust".to_string(),
            status: CheckStatus::Fail,
            version: None,
            detail: "not installed".to_string(),
        },
    }
}

/// Check if Python is installed with pip.
fn check_python() -> CheckResult {
    // Try python3 first, then python, then py (Windows)
    let candidates = ["python3", "python", "py"];
    let mut python_output = None;
    let mut python_cmd = "";

    for cmd in &candidates {
        if let Some(output) = run_cmd_with_timeout(cmd, &["--version"], 3) {
            python_output = Some(output);
            python_cmd = cmd;
            break;
        }
    }

    match python_output {
        Some(output) => {
            let ver = extract_version(&output);
            // Check for pip
            let pip = run_cmd_with_timeout("pip3", &["--version"], 3)
                .or_else(|| run_cmd_with_timeout("pip", &["--version"], 3));
            let detail = match pip {
                Some(_) => format!("pip available (via {python_cmd})"),
                None => "pip not found".to_string(),
            };
            let status = if pip.is_some() {
                CheckStatus::Pass
            } else {
                CheckStatus::Warn
            };
            CheckResult {
                name: "Python".to_string(),
                status,
                version: Some(ver),
                detail,
            }
        }
        None => CheckResult {
            name: "Python".to_string(),
            status: CheckStatus::Fail,
            version: None,
            detail: "not installed".to_string(),
        },
    }
}

/// Check if Docker is installed and the daemon is running.
fn check_docker() -> CheckResult {
    let docker_ver = run_cmd_with_timeout("docker", &["--version"], 3);
    match docker_ver {
        Some(output) => {
            let ver = extract_version(&output);
            // Check if daemon is running (docker info is fast if daemon is up)
            let info = run_cmd_with_timeout("docker", &["info"], 5);
            let (status, detail) = match info {
                Some(_) => (CheckStatus::Pass, "daemon running".to_string()),
                None => (CheckStatus::Warn, "daemon not running".to_string()),
            };
            CheckResult {
                name: "Docker".to_string(),
                status,
                version: Some(ver),
                detail,
            }
        }
        None => CheckResult {
            name: "Docker".to_string(),
            status: CheckStatus::Fail,
            version: None,
            detail: "not installed".to_string(),
        },
    }
}

/// Check available disk space on the current drive.
fn check_disk() -> CheckResult {
    use sysinfo::Disks;

    let disks = Disks::new_with_refreshed_list();

    // Find the disk for the current directory
    let cwd = std::env::current_dir().ok();
    let mut best_match: Option<(String, u64)> = None;

    for disk in disks.list() {
        let mount = disk.mount_point().to_string_lossy().to_string();
        let available = disk.available_space();

        // On Windows, match drive letter; on Unix, match longest mount prefix
        if let Some(ref dir) = cwd {
            let dir_str = dir.to_string_lossy();
            if dir_str.starts_with(&mount) {
                match &best_match {
                    Some((prev_mount, _)) if mount.len() > prev_mount.len() => {
                        best_match = Some((mount.clone(), available));
                    }
                    None => {
                        best_match = Some((mount.clone(), available));
                    }
                    _ => {}
                }
            }
        }
    }

    // Fallback: just use the first disk
    let (mount, available) = best_match.unwrap_or_else(|| {
        disks
            .list()
            .first()
            .map(|d| {
                (
                    d.mount_point().to_string_lossy().to_string(),
                    d.available_space(),
                )
            })
            .unwrap_or_else(|| ("unknown".to_string(), 0))
    });

    let gb = available as f64 / 1_073_741_824.0;
    let detail = format!("{gb:.0} GB free on {mount}");

    let status = if gb >= 10.0 {
        CheckStatus::Pass
    } else if gb >= 5.0 {
        CheckStatus::Warn
    } else {
        CheckStatus::Fail
    };

    CheckResult {
        name: "Disk".to_string(),
        status,
        version: None,
        detail,
    }
}

/// Check if SSH keys exist in ~/.ssh/.
fn check_ssh() -> CheckResult {
    let home = dirs_from_env();
    let ssh_dir = home.join(".ssh");

    if !ssh_dir.exists() {
        return CheckResult {
            name: "SSH".to_string(),
            status: CheckStatus::Warn,
            version: None,
            detail: "~/.ssh not found".to_string(),
        };
    }

    // Count key files (id_rsa, id_ed25519, id_ecdsa, etc.)
    let key_count = std::fs::read_dir(&ssh_dir)
        .map(|entries| {
            entries
                .filter_map(|e| e.ok())
                .filter(|e| {
                    let name = e.file_name().to_string_lossy().to_string();
                    name.starts_with("id_") && !name.ends_with(".pub")
                })
                .count()
        })
        .unwrap_or(0);

    if key_count > 0 {
        CheckResult {
            name: "SSH".to_string(),
            status: CheckStatus::Pass,
            version: None,
            detail: format!("{key_count} key(s) found"),
        }
    } else {
        CheckResult {
            name: "SSH".to_string(),
            status: CheckStatus::Warn,
            version: None,
            detail: "no keys found in ~/.ssh".to_string(),
        }
    }
}

/// Get the user's home directory from environment variables.
fn dirs_from_env() -> PathBuf {
    #[cfg(windows)]
    {
        std::env::var("USERPROFILE")
            .map(PathBuf::from)
            .unwrap_or_else(|_| PathBuf::from("C:\\"))
    }
    #[cfg(not(windows))]
    {
        std::env::var("HOME")
            .map(PathBuf::from)
            .unwrap_or_else(|_| PathBuf::from("/"))
    }
}

/// Collect all health check results in parallel without printing.
/// Uses `std::thread::scope` to run all 7 checks concurrently.
/// Used by the TUI dashboard and the CLI `run()` function.
pub fn collect_checks() -> Result<Vec<CheckResult>, DoctorError> {
    let mut results = Vec::with_capacity(7);
    std::thread::scope(|s| {
        let handles: Vec<_> = vec![
            s.spawn(|| check_git()),
            s.spawn(|| check_node()),
            s.spawn(|| check_rust()),
            s.spawn(|| check_python()),
            s.spawn(|| check_docker()),
            s.spawn(|| check_disk()),
            s.spawn(|| check_ssh()),
        ];
        for handle in handles {
            results.push(handle.join().expect("doctor check thread panicked"));
        }
    });
    Ok(results)
}

/// Run all doctor checks and display results.
pub fn run(json: bool) -> Result<(), DoctorError> {
    let checks = collect_checks()?;

    if json {
        let json_str = serde_json::to_string_pretty(&checks).map_err(io::Error::other)?;
        println!("{json_str}");
        return Ok(());
    }

    // Colored terminal output
    println!();
    println!(
        "  {} {} {} {} {}",
        "devpulse".bold(),
        "──".dimmed(),
        "Doctor".bold(),
        "──".dimmed(),
        "Environment Health".dimmed()
    );
    println!();

    let mut pass_count = 0;
    let mut warn_count = 0;
    let mut fail_count = 0;

    for check in &checks {
        let status_str = match check.status {
            CheckStatus::Pass => {
                pass_count += 1;
                "[PASS]".green().bold().to_string()
            }
            CheckStatus::Warn => {
                warn_count += 1;
                "[WARN]".yellow().bold().to_string()
            }
            CheckStatus::Fail => {
                fail_count += 1;
                "[FAIL]".red().bold().to_string()
            }
        };

        let version_str = check.version.as_deref().unwrap_or("").to_string();

        println!(
            "  {}  {:<12} {:<10} {}",
            status_str,
            check.name.bold(),
            version_str,
            check.detail.dimmed()
        );
    }

    println!();
    println!(
        "  Result: {} passed, {} warning(s), {} failure(s)",
        pass_count.to_string().green().bold(),
        warn_count.to_string().yellow().bold(),
        fail_count.to_string().red().bold()
    );
    println!();

    // Return error if any checks failed — caller maps this to a non-zero exit code
    if fail_count > 0 {
        return Err(DoctorError::ChecksFailed {
            pass: pass_count,
            warn: warn_count,
            fail: fail_count,
        });
    }

    Ok(())
}

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

    #[test]
    fn test_extract_version_git() {
        assert_eq!(extract_version("git version 2.43.0"), "2.43.0");
    }

    #[test]
    fn test_extract_version_node() {
        assert_eq!(extract_version("v22.1.0"), "22.1.0");
    }

    #[test]
    fn test_extract_version_rustc() {
        assert_eq!(
            extract_version("rustc 1.77.0 (aedd173a2 2024-03-17)"),
            "1.77.0"
        );
    }

    #[test]
    fn test_extract_version_fallback() {
        assert_eq!(extract_version("unknown"), "unknown");
    }

    #[test]
    fn test_check_status_serialization() {
        let result = CheckResult {
            name: "Test".to_string(),
            status: CheckStatus::Pass,
            version: Some("1.0".to_string()),
            detail: "all good".to_string(),
        };
        let json = serde_json::to_string(&result).unwrap();
        assert!(json.contains("\"pass\""));
        assert!(json.contains("\"Test\""));
    }

    #[test]
    fn test_dirs_from_env_returns_path() {
        let home = dirs_from_env();
        // Should always return a non-empty path
        assert!(!home.as_os_str().is_empty());
    }
}