sysmap 0.2.0

Project Mapping CLI Tool
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
use std::collections::HashMap;
use std::env;

use anyhow::Result;
use colored::Colorize;

use crate::config::{find_sysmap_root, map_path};
use crate::map::{FileNode, SystemMap};
use crate::scanner::{estimate_tokens, format_tokens};

/// Execute the summary command
pub fn execute(json: bool, yaml: bool, counts: bool) -> Result<()> {
    let cwd = env::current_dir()?;

    let root = find_sysmap_root(&cwd)
        .ok_or_else(|| anyhow::anyhow!(
            "No sysmap found. Run 'sysmap init' first."
        ))?;

    let map = SystemMap::load(&map_path(&root))?;

    if json {
        print_json_summary(&map, counts)?;
    } else if yaml {
        print_yaml_summary(&map, counts)?;
    } else {
        print_human_summary(&map, counts);
    }

    Ok(())
}

fn print_human_summary(map: &SystemMap, counts: bool) {
    // Project header
    let project_name = map.root
        .file_name()
        .map(|n| n.to_string_lossy().to_string())
        .unwrap_or_else(|| "unknown".to_string());

    // Build type string - show all languages if multiple
    let project_type = if map.project_type.languages.is_empty() {
        "Unknown".to_string()
    } else if map.project_type.languages.len() > 1 {
        let langs: Vec<String> = map.project_type.languages.iter()
            .map(|l| capitalize(l))
            .collect();
        let type_str = langs.join(", ");
        match &map.project_type.framework {
            Some(fw) => format!("{} ({})", type_str, capitalize(fw)),
            None => type_str,
        }
    } else {
        let lang = &map.project_type.languages[0];
        match &map.project_type.framework {
            Some(fw) => format!("{} ({})", capitalize(lang), capitalize(fw)),
            None => capitalize(lang),
        }
    };

    println!("{} {}", "Project:".bold(), project_name);
    println!("{} {}", "Type:".bold(), project_type);
    println!();

    // Analyze structure
    let analysis = analyze_tree(&map.tree);

    // Structure section
    println!("{}", "Structure:".bold());
    
    // Show source directories with their subdirectories
    for (dir_name, stats) in &analysis.source_dirs {
        println!("  {:<14} {} {} files{}",
            format!("{}/", dir_name),
            stats.file_count.to_string().yellow(),
            stats.primary_language.as_deref().unwrap_or(""),
            stats.lines.map(|l| format!(" ({} lines)", l)).unwrap_or_default()
        );
    }

    // Show test directories
    for (dir_name, stats) in &analysis.test_dirs {
        println!("  {:<14} {} test files",
            format!("{}/", dir_name),
            stats.file_count.to_string().yellow()
        );
    }

    // Show config files
    if !analysis.config_files.is_empty() {
        println!("  {:<14} {}",
            "Config:",
            analysis.config_files.join(", ")
        );
    }

    // Entry points
    if !analysis.entry_points.is_empty() {
        println!();
        println!("{}", "Entry points:".bold());
        for entry in &analysis.entry_points {
            println!("  {}", entry);
        }
    }

    // Key directories with interesting contents
    if !analysis.key_dirs.is_empty() {
        println!();
        println!("{}", "Key directories:".bold());
        for (dir_path, contents) in &analysis.key_dirs {
            println!("  {:<14} {}",
                format!("{}/", dir_path),
                contents.join(", ")
            );
        }
    }

    // Dependencies
    if !analysis.dependencies.is_empty() {
        println!();
        println!("{}", "Dependencies:".bold());
        println!("  {}", analysis.dependencies.join(", "));
    }
    
    // File types and purposes (metadata)
    if !analysis.purposes_found.is_empty() || !analysis.languages_found.is_empty() {
        println!();
        println!("{}", "File metadata:".bold());
        if !analysis.purposes_found.is_empty() {
            println!("  {:<14} {}",
                "Purposes:",
                analysis.purposes_found.join(", ")
            );
        }
        if !analysis.languages_found.is_empty() {
            println!("  {:<14} {}",
                "Languages:",
                analysis.languages_found.join(", ")
            );
        }
    }

    // Collapsed directories
    if !map.patterns_matched.is_empty() {
        println!();
        println!("{}", "Collapsed:".bold().dimmed());
        for pattern in &map.patterns_matched {
            println!("  {:<14} {} ({} files)",
                format!("{}/", pattern.path.display()).dimmed(),
                pattern.pattern.dimmed(),
                pattern.files_collapsed.to_string().dimmed()
            );
        }
    }

    // Show counts if requested
    if counts {
        let (total_lines, total_chars) = count_totals(&map.tree);
        let tokens = estimate_tokens(total_chars);
        println!();
        println!("{} {} lines | {} chars ({})",
            "Indexed:".bold(),
            format_number(total_lines),
            format_number(total_chars),
            format_tokens(tokens)
        );
    }
}

fn print_json_summary(map: &SystemMap, counts: bool) -> Result<()> {
    let analysis = analyze_tree(&map.tree);
    let (total_lines, total_chars) = if counts {
        count_totals(&map.tree)
    } else {
        (0, 0)
    };
    
    let summary = serde_json::json!({
        "name": map.root.file_name().map(|n| n.to_string_lossy().to_string()),
        "languages": map.project_type.languages,
        "framework": map.project_type.framework,
        "structure": {
            "source_dirs": analysis.source_dirs.iter().map(|(name, stats)| {
                serde_json::json!({
                    "path": name,
                    "files": stats.file_count,
                    "lines": stats.lines,
                    "language": stats.primary_language
                })
            }).collect::<Vec<_>>(),
            "test_dirs": analysis.test_dirs.iter().map(|(name, stats)| {
                serde_json::json!({
                    "path": name,
                    "files": stats.file_count
                })
            }).collect::<Vec<_>>(),
            "config_files": analysis.config_files
        },
        "entry_points": analysis.entry_points,
        "key_directories": analysis.key_dirs.iter().map(|(path, contents)| {
            serde_json::json!({
                "path": path,
                "contents": contents
            })
        }).collect::<Vec<_>>(),
        "dependencies": {
            "packages": analysis.dependencies
        },
        "collapsed": map.patterns_matched.iter().map(|p| {
            serde_json::json!({
                "path": p.path,
                "reason": p.pattern,
                "file_count": p.files_collapsed
            })
        }).collect::<Vec<_>>(),
        "meta": {
            "indexed_files": map.meta.indexed_files,
            "total_files": map.meta.total_files,
            "last_updated": map.scanned_at,
            "purposes_found": analysis.purposes_found,
            "file_languages": analysis.languages_found,
            "total_lines": if counts { Some(total_lines) } else { None },
            "total_chars": if counts { Some(total_chars) } else { None },
            "estimated_tokens": if counts { Some(estimate_tokens(total_chars)) } else { None }
        }
    });

    println!("{}", serde_json::to_string_pretty(&summary)?);
    Ok(())
}

fn print_yaml_summary(map: &SystemMap, counts: bool) -> Result<()> {
    // For now, just output JSON - YAML support can be added later
    // This keeps dependencies minimal for MVP
    eprintln!("{}", "YAML output not yet implemented, showing JSON:".yellow());
    print_json_summary(map, counts)
}

// ============ Analysis helpers ============

struct DirStats {
    file_count: usize,
    lines: Option<usize>,
    primary_language: Option<String>,
}

struct TreeAnalysis {
    source_dirs: Vec<(String, DirStats)>,
    test_dirs: Vec<(String, DirStats)>,
    config_files: Vec<String>,
    entry_points: Vec<String>,
    key_dirs: Vec<(String, Vec<String>)>,
    dependencies: Vec<String>,
    purposes_found: Vec<String>,
    languages_found: Vec<String>,
}

fn analyze_tree(tree: &FileNode) -> TreeAnalysis {
    let mut analysis = TreeAnalysis {
        source_dirs: Vec::new(),
        test_dirs: Vec::new(),
        config_files: Vec::new(),
        entry_points: Vec::new(),
        key_dirs: Vec::new(),
        dependencies: Vec::new(),
        purposes_found: Vec::new(),
        languages_found: Vec::new(),
    };

    // Known source directory names
    let source_dir_names = ["src", "lib", "app", "pkg", "internal", "cmd"];
    let test_dir_names = ["tests", "test", "spec", "__tests__"];
    let config_extensions = ["yaml", "yml", "toml", "json", "ini", "cfg"];
    let config_names = ["config", "settings", ".env.example", "Makefile", "Dockerfile"];
    
    // Collect all purposes and languages
    collect_metadata(tree, &mut analysis.purposes_found, &mut analysis.languages_found);

    if let FileNode::Directory { children, .. } = tree {
        for child in children {
            match child {
                FileNode::Directory { name, children: dir_children, .. } => {
                    let stats = compute_dir_stats(dir_children);

                    if source_dir_names.contains(&name.as_str()) {
                        analysis.source_dirs.push((name.clone(), stats));
                        
                        // Look for key subdirectories
                        let key_subdirs = find_key_subdirs(dir_children);
                        if !key_subdirs.is_empty() {
                            for (subdir_name, contents) in key_subdirs {
                                analysis.key_dirs.push((
                                    format!("{}/{}", name, subdir_name),
                                    contents
                                ));
                            }
                        }
                    } else if test_dir_names.contains(&name.as_str()) {
                        analysis.test_dirs.push((name.clone(), stats));
                    }
                }
                FileNode::File { name, purpose, .. } => {
                    // Check for config files
                    let is_config = config_names.iter().any(|c| name.contains(c))
                        || name.split('.').last()
                            .map(|ext| config_extensions.contains(&ext))
                            .unwrap_or(false);
                    
                    if is_config && !name.starts_with('.') {
                        analysis.config_files.push(name.clone());
                    }

                    // Check for entry points
                    if purpose.as_deref() == Some("entry") {
                        analysis.entry_points.push(name.clone());
                    }

                    // Parse dependency files
                    if name == "pyproject.toml" || name == "requirements.txt" {
                        // Would parse dependencies here in a full implementation
                    } else if name == "package.json" {
                        // Would parse dependencies here
                    } else if name == "Cargo.toml" {
                        // Would parse dependencies here
                    }
                }
                _ => {}
            }
        }
    }

    // Sort for consistent output
    analysis.config_files.sort();

    analysis
}

fn compute_dir_stats(children: &[FileNode]) -> DirStats {
    let mut file_count = 0;
    let mut total_lines = 0;
    let mut lang_counts: HashMap<String, usize> = HashMap::new();

    count_recursive(children, &mut file_count, &mut total_lines, &mut lang_counts);

    let primary_language = lang_counts
        .into_iter()
        .max_by_key(|(_, count)| *count)
        .map(|(lang, _)| lang);

    DirStats {
        file_count,
        lines: if total_lines > 0 { Some(total_lines) } else { None },
        primary_language,
    }
}

fn count_recursive(
    nodes: &[FileNode],
    file_count: &mut usize,
    total_lines: &mut usize,
    lang_counts: &mut HashMap<String, usize>,
) {
    for node in nodes {
        match node {
            FileNode::File { lines, language, .. } => {
                *file_count += 1;
                if let Some(l) = lines {
                    *total_lines += l;
                }
                if let Some(lang) = language {
                    *lang_counts.entry(lang.clone()).or_insert(0) += 1;
                }
            }
            FileNode::Directory { children, .. } => {
                count_recursive(children, file_count, total_lines, lang_counts);
            }
            FileNode::Collapsed { file_count: fc, .. } => {
                // Don't count collapsed files in detail
                *file_count += fc;
            }
        }
    }
}

fn find_key_subdirs(children: &[FileNode]) -> Vec<(String, Vec<String>)> {
    let mut result = Vec::new();
    
    // Show all subdirectories that have code files
    for child in children {
        if let FileNode::Directory { name, children: subchildren, .. } = child {
            // Skip hidden directories and common non-code directories
            if name.starts_with('.') || name == "__pycache__" {
                continue;
            }
            
            // Get file names (without extensions) for display
            let file_names: Vec<String> = subchildren
                .iter()
                .filter_map(|c| {
                    if let FileNode::File { name, .. } = c {
                        // Remove extension for cleaner display
                        let base = name.split('.').next().unwrap_or(name);
                        // Skip init/mod files
                        if base != "__init__" && base != "mod" && base != "index" {
                            return Some(base.to_string());
                        }
                    }
                    None
                })
                .collect();
            
            // Include directory if it has files
            if !file_names.is_empty() {
                result.push((name.clone(), file_names));
            }
        }
    }

    result
}

fn collect_metadata(node: &FileNode, purposes: &mut Vec<String>, languages: &mut Vec<String>) {
    match node {
        FileNode::File { purpose, language, .. } => {
            if let Some(p) = purpose {
                if !purposes.contains(p) {
                    purposes.push(p.clone());
                }
            }
            if let Some(l) = language {
                if !languages.contains(l) {
                    languages.push(l.clone());
                }
            }
        }
        FileNode::Directory { children, .. } => {
            for child in children {
                collect_metadata(child, purposes, languages);
            }
        }
        FileNode::Collapsed { .. } => {}
    }
}

fn capitalize(s: &str) -> String {
    let mut chars = s.chars();
    match chars.next() {
        None => String::new(),
        Some(c) => c.to_uppercase().chain(chars).collect(),
    }
}

/// Count total lines and chars across indexed files (excludes collapsed)
fn count_totals(node: &FileNode) -> (usize, usize) {
    let mut total_lines = 0;
    let mut total_chars = 0;
    count_totals_recursive(node, &mut total_lines, &mut total_chars);
    (total_lines, total_chars)
}

fn count_totals_recursive(node: &FileNode, lines: &mut usize, chars: &mut usize) {
    match node {
        FileNode::File { lines: l, chars: c, .. } => {
            if let Some(line_count) = l {
                *lines += line_count;
            }
            if let Some(char_count) = c {
                *chars += char_count;
            }
        }
        FileNode::Directory { children, .. } => {
            for child in children {
                count_totals_recursive(child, lines, chars);
            }
        }
        FileNode::Collapsed { .. } => {
            // Don't count collapsed directories
        }
    }
}

/// Format a number with comma separators
fn format_number(n: usize) -> String {
    let s = n.to_string();
    let mut result = String::new();
    for (i, c) in s.chars().rev().enumerate() {
        if i > 0 && i % 3 == 0 {
            result.insert(0, ',');
        }
        result.insert(0, c);
    }
    result
}