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
//! Build artifact scanner and cleaner.
//!
//! Walks a directory tree looking for known build artifact directories
//! (node_modules, target, __pycache__, etc.), calculates their sizes,
//! and presents an interactive colored table for selective or bulk deletion.

use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};

use colored::Colorize;
use serde::Serialize;

use crate::utils::format_size;
use thiserror::Error;
use walkdir::WalkDir;

/// Errors specific to the sweep module.
#[derive(Error, Debug)]
pub enum SweepError {
    /// The specified scan path does not exist or is inaccessible
    #[error("Path not found: {0}")]
    PathNotFound(String),

    /// IO error during scanning or deletion
    #[error("IO error: {0}")]
    Io(#[from] io::Error),

    /// Error walking the directory tree
    #[error("Walk error: {0}")]
    Walk(String),
}

/// Known build artifact directory names and their language/framework label.
const ARTIFACT_DIRS: &[(&str, &str)] = &[
    ("node_modules", "Node.js"),
    ("target", "Rust/Cargo"),
    ("__pycache__", "Python"),
    (".cache", "Cache"),
    (".gradle", "Gradle"),
    (".next", "Next.js"),
    (".nuxt", "Nuxt"),
    ("venv", "Python venv"),
    (".venv", "Python venv"),
    ("build", "Build output"),
    ("dist", "Distribution"),
    (".tox", "Python Tox"),
];

/// A single discovered artifact directory with metadata.
#[derive(Debug, Clone, Serialize)]
pub struct ArtifactEntry {
    /// Full path to the artifact directory
    pub path: String,
    /// Size in bytes
    pub size_bytes: u64,
    /// Human-readable size string
    pub size_human: String,
    /// Language/framework type label
    pub artifact_type: String,
}

/// Scan results containing all found artifacts and a total.
#[derive(Debug, Clone, Serialize)]
pub struct ScanResult {
    /// List of found artifact directories
    pub entries: Vec<ArtifactEntry>,
    /// Total reclaimable bytes
    pub total_bytes: u64,
    /// Human-readable total
    pub total_human: String,
}

/// JSON-serializable output wrapper.
#[derive(Debug, Serialize)]
struct JsonOutput {
    entries: Vec<ArtifactEntry>,
    total_bytes: u64,
    total_human: String,
    count: usize,
}

/// Parse a human-readable size string (e.g., "1M", "500K", "2G") into bytes.
/// Returns 0 for invalid input. Case-insensitive.
pub fn parse_min_size(s: &str) -> u64 {
    let s = s.trim().to_uppercase();
    if s.is_empty() {
        return 0;
    }

    let (num_str, multiplier) = if let Some(n) = s.strip_suffix('G') {
        (n, 1_073_741_824u64)
    } else if let Some(n) = s.strip_suffix('M') {
        (n, 1_048_576u64)
    } else if let Some(n) = s.strip_suffix('K') {
        (n, 1024u64)
    } else {
        (s.as_str(), 1u64)
    };

    num_str
        .parse::<f64>()
        .map(|n| (n * multiplier as f64) as u64)
        .unwrap_or(0)
}

/// Calculate total size of all files inside a directory.
fn dir_size(path: &Path) -> u64 {
    WalkDir::new(path)
        .into_iter()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_type().is_file())
        .filter_map(|e| e.metadata().ok())
        .map(|m| m.len())
        .sum()
}

/// Check if a directory name matches any known artifact directory.
fn is_artifact_dir(name: &str) -> Option<&'static str> {
    for &(dir_name, label) in ARTIFACT_DIRS {
        if name == dir_name {
            return Some(label);
        }
    }
    None
}

/// Scan a root directory for build artifacts, skipping into artifact dirs themselves.
pub fn scan(root: &Path, min_bytes: u64) -> Result<ScanResult, SweepError> {
    if !root.exists() {
        return Err(SweepError::PathNotFound(root.display().to_string()));
    }

    let mut entries = Vec::new();

    // Walk with filter_entry to avoid recursing INTO artifact directories (performance critical)
    let walker = WalkDir::new(root).follow_links(false).into_iter();
    let filtered = walker.filter_entry(|entry| {
        // If this entry is a directory matching an artifact name, let it through
        // but don't recurse into it (we'll handle that below)
        if entry.file_type().is_dir() {
            let name = entry.file_name().to_string_lossy();
            // Skip hidden directories (except our artifact patterns like .next, .venv, etc.)
            if name.starts_with('.') && is_artifact_dir(&name).is_none() && entry.depth() > 0 {
                return false;
            }
        }
        true
    });

    for entry in filtered {
        let entry = entry.map_err(|e| SweepError::Walk(e.to_string()))?;

        if !entry.file_type().is_dir() || entry.depth() == 0 {
            continue;
        }

        let name = entry.file_name().to_string_lossy();
        if let Some(label) = is_artifact_dir(&name) {
            let path = entry.path();
            let size = dir_size(path);

            if size >= min_bytes {
                entries.push(ArtifactEntry {
                    path: path.display().to_string(),
                    size_bytes: size,
                    size_human: format_size(size),
                    artifact_type: label.to_string(),
                });
            }
        }
    }

    // Sort by size descending (largest first)
    entries.sort_by(|a, b| b.size_bytes.cmp(&a.size_bytes));

    let total_bytes: u64 = entries.iter().map(|e| e.size_bytes).sum();

    Ok(ScanResult {
        total_human: format_size(total_bytes),
        total_bytes,
        entries,
    })
}

/// Run the sweep command: scan, display results, optionally prompt for deletion.
pub fn run(
    path: Option<&Path>,
    yes: bool,
    min_size_str: &str,
    json: bool,
) -> Result<(), SweepError> {
    let root = path.unwrap_or_else(|| Path::new("."));
    let canonical = root
        .canonicalize()
        .map_err(|_| SweepError::PathNotFound(root.display().to_string()))?;
    let min_bytes = parse_min_size(min_size_str);
    let result = scan(&canonical, min_bytes)?;

    if json {
        return print_json(&result);
    }

    if result.entries.is_empty() {
        println!();
        println!(
            "  {} {} {} {} {}",
            "devpulse".bold(),
            "──".dimmed(),
            "Sweep".bold(),
            "──".dimmed(),
            canonical.display().to_string().dimmed()
        );
        println!();
        println!(
            "  No build artifacts found above {} threshold.",
            min_size_str
        );
        println!();
        return Ok(());
    }

    // Print colored table
    println!();
    println!(
        "  {} {} {} {} {}",
        "devpulse".bold(),
        "──".dimmed(),
        "Sweep".bold(),
        "──".dimmed(),
        canonical.display().to_string().dimmed()
    );
    println!();
    println!(
        "  {:<4} {:<11} {:<13} {}",
        "#".bold(),
        "Size".bold(),
        "Type".bold(),
        "Path".bold()
    );
    println!("  {}", "─".repeat(60).dimmed());

    for (i, entry) in result.entries.iter().enumerate() {
        let size_colored = color_by_size(&entry.size_human, entry.size_bytes);
        println!(
            "  {:<4} {:<11} {:<13} {}",
            (i + 1).to_string().bold(),
            size_colored,
            entry.artifact_type.dimmed(),
            entry.path
        );
    }

    println!("  {}", "─".repeat(60).dimmed());
    println!(
        "  {:<4} {:<11} {} ({} directories)",
        "",
        color_by_size(&result.total_human, result.total_bytes),
        "total reclaimable".bold(),
        result.entries.len()
    );
    println!();

    // Deletion prompt
    if yes {
        delete_entries(
            &result.entries,
            &(0..result.entries.len()).collect::<Vec<_>>(),
        )?;
    } else {
        prompt_and_delete(&result.entries)?;
    }

    Ok(())
}

/// Color a size string based on the byte count.
fn color_by_size(human: &str, bytes: u64) -> String {
    if bytes >= 1_073_741_824 {
        human.red().bold().to_string()
    } else if bytes >= 104_857_600 {
        human.yellow().bold().to_string()
    } else if bytes >= 10_485_760 {
        human.green().to_string()
    } else {
        human.white().to_string()
    }
}

/// Interactive prompt: ask user which entries to delete.
fn prompt_and_delete(entries: &[ArtifactEntry]) -> Result<(), SweepError> {
    print!("  Delete all? [y/N/1,3,5]: ");
    io::stdout().flush()?;

    let mut input = String::new();
    io::stdin().read_line(&mut input)?;
    let input = input.trim().to_lowercase();

    if input == "y" || input == "yes" {
        let indices: Vec<usize> = (0..entries.len()).collect();
        delete_entries(entries, &indices)?;
    } else if input == "n" || input == "no" || input.is_empty() {
        println!("  Cancelled.");
    } else {
        // Parse comma-separated indices
        let indices: Vec<usize> = input
            .split(',')
            .filter_map(|s| s.trim().parse::<usize>().ok())
            .filter(|&i| i >= 1 && i <= entries.len())
            .map(|i| i - 1) // convert to 0-based
            .collect();

        if indices.is_empty() {
            println!("  No valid selections. Cancelled.");
        } else {
            delete_entries(entries, &indices)?;
        }
    }

    Ok(())
}

/// Delete the specified artifact directories by index.
fn delete_entries(entries: &[ArtifactEntry], indices: &[usize]) -> Result<(), SweepError> {
    for &idx in indices {
        if let Some(entry) = entries.get(idx) {
            let path = PathBuf::from(&entry.path);
            match fs::remove_dir_all(&path) {
                Ok(()) => {
                    println!(
                        "  {} {} ({})",
                        "Deleted".green().bold(),
                        entry.path,
                        entry.size_human
                    );
                }
                Err(e) => {
                    eprintln!("  {} {} — {}", "Failed".red().bold(), entry.path, e);
                }
            }
        }
    }
    Ok(())
}

/// Print scan results as JSON.
fn print_json(result: &ScanResult) -> Result<(), SweepError> {
    let output = JsonOutput {
        count: result.entries.len(),
        total_bytes: result.total_bytes,
        total_human: result.total_human.clone(),
        entries: result
            .entries
            .iter()
            .map(|e| ArtifactEntry {
                path: e.path.clone(),
                size_bytes: e.size_bytes,
                size_human: e.size_human.clone(),
                artifact_type: e.artifact_type.clone(),
            })
            .collect(),
    };
    let json_str =
        serde_json::to_string_pretty(&output).map_err(|e| SweepError::Io(io::Error::other(e)))?;
    println!("{json_str}");
    Ok(())
}

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

    #[test]
    fn test_parse_min_size_megabytes() {
        assert_eq!(parse_min_size("1M"), 1_048_576);
        assert_eq!(parse_min_size("10M"), 10_485_760);
    }

    #[test]
    fn test_parse_min_size_kilobytes() {
        assert_eq!(parse_min_size("500K"), 512_000);
    }

    #[test]
    fn test_parse_min_size_gigabytes() {
        assert_eq!(parse_min_size("2G"), 2_147_483_648);
    }

    #[test]
    fn test_parse_min_size_case_insensitive() {
        assert_eq!(parse_min_size("1m"), 1_048_576);
        assert_eq!(parse_min_size("1g"), 1_073_741_824);
    }

    #[test]
    fn test_parse_min_size_invalid() {
        assert_eq!(parse_min_size("abc"), 0);
        assert_eq!(parse_min_size(""), 0);
    }

    #[test]
    fn test_format_size_bytes() {
        assert_eq!(format_size(500), "500 B");
    }

    #[test]
    fn test_format_size_kb() {
        assert_eq!(format_size(2048), "2.0 KB");
    }

    #[test]
    fn test_format_size_mb() {
        assert_eq!(format_size(5_242_880), "5.0 MB");
    }

    #[test]
    fn test_format_size_gb() {
        assert_eq!(format_size(2_147_483_648), "2.00 GB");
    }

    #[test]
    fn test_is_artifact_dir_node_modules() {
        assert_eq!(is_artifact_dir("node_modules"), Some("Node.js"));
    }

    #[test]
    fn test_is_artifact_dir_target() {
        assert_eq!(is_artifact_dir("target"), Some("Rust/Cargo"));
    }

    #[test]
    fn test_is_artifact_dir_unknown() {
        assert_eq!(is_artifact_dir("src"), None);
    }

    #[test]
    fn test_scan_nonexistent_path() {
        let result = scan(Path::new("/nonexistent/path/that/should/not/exist"), 0);
        assert!(result.is_err());
    }

    #[test]
    fn test_scan_with_tempdir() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();

        // Create fake project structure with a node_modules dir
        let nm = root.join("project").join("node_modules");
        fs::create_dir_all(&nm).unwrap();

        // Create a file inside so it has nonzero size
        let file = nm.join("package.json");
        fs::write(&file, r#"{"name":"test"}"#).unwrap();

        let result = scan(root, 0).unwrap();
        assert!(!result.entries.is_empty());
        assert_eq!(result.entries[0].artifact_type, "Node.js");
    }
}