homeboy 0.76.0

CLI for multi-component deployment and development workflow automation
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
//! Structural complexity analysis — detect god files, high item counts,
//! and other structural issues that convention-based analysis can't catch.
//!
//! Plugs into the audit pipeline as an additional findings source.

use std::collections::HashMap;
use std::path::Path;

use super::conventions::AuditFinding;
use super::findings::{Finding, Severity};

/// Thresholds for structural findings.
const GOD_FILE_LINE_THRESHOLD: usize = 1000;
const HIGH_ITEM_COUNT_THRESHOLD: usize = 15;
const DIRECTORY_SPRAWL_FILE_THRESHOLD: usize = 25;

/// Known source file extensions for structural analysis.
/// Matches the walker's known extensions so we analyze the same files.
const SOURCE_EXTENSIONS: &[&str] = &[
    "rs", "php", "js", "ts", "jsx", "tsx", "mjs", "py", "go", "java", "rb", "swift", "kt", "c",
    "cpp", "h",
];

/// Directories to skip during structural analysis.
const SKIP_DIRS: &[&str] = &[
    "node_modules",
    "vendor",
    ".git",
    "build",
    "dist",
    "target",
    ".svn",
    ".hg",
    "cache",
    "tmp",
];

/// Run structural analysis on all source files under a root directory.
///
/// Returns findings for files that exceed structural thresholds.
pub(crate) fn analyze_structure(root: &Path) -> Vec<Finding> {
    let mut findings = Vec::new();
    let mut stack = vec![root.to_path_buf()];
    let mut dir_source_counts: HashMap<String, usize> = HashMap::new();

    while let Some(dir) = stack.pop() {
        let entries = match std::fs::read_dir(&dir) {
            Ok(e) => e,
            Err(_) => continue,
        };

        for entry in entries.flatten() {
            let path = entry.path();

            if path.is_dir() {
                let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
                if !SKIP_DIRS.contains(&name) {
                    stack.push(path);
                }
                continue;
            }

            let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
            if !SOURCE_EXTENSIONS.contains(&ext) {
                continue;
            }

            let parent_rel = path
                .parent()
                .and_then(|p| p.strip_prefix(root).ok())
                .map(|p| p.to_string_lossy().to_string())
                .unwrap_or_default();
            *dir_source_counts.entry(parent_rel).or_insert(0) += 1;

            let content = match std::fs::read_to_string(&path) {
                Ok(c) => c,
                Err(_) => continue,
            };

            let relative = path
                .strip_prefix(root)
                .map(|p| p.to_string_lossy().to_string())
                .unwrap_or_else(|_| path.to_string_lossy().to_string());

            // Check line count
            let line_count = content.lines().count();
            if line_count > GOD_FILE_LINE_THRESHOLD {
                let suggestion = "Consider decomposing into focused modules.                      Use `homeboy refactor move` to extract related groups of items.".to_string();
                findings.push(Finding {
                    convention: "structural".to_string(),
                    severity: Severity::Warning,
                    file: relative.clone(),
                    description: format!(
                        "File has {} lines (threshold: {})",
                        line_count, GOD_FILE_LINE_THRESHOLD
                    ),
                    suggestion,
                    kind: AuditFinding::GodFile,
                });
            }

            // Count top-level items (functions, structs, enums, consts, etc.)
            let item_count = count_top_level_items(&content, ext);
            if item_count > HIGH_ITEM_COUNT_THRESHOLD {
                findings.push(Finding {
                    convention: "structural".to_string(),
                    severity: Severity::Info,
                    file: relative,
                    description: format!(
                        "File has {} top-level items (threshold: {})",
                        item_count, HIGH_ITEM_COUNT_THRESHOLD
                    ),
                    suggestion: "Group related items and extract into focused modules".to_string(),
                    kind: AuditFinding::HighItemCount,
                });
            }
        }
    }

    for (dir, count) in dir_source_counts {
        if count <= DIRECTORY_SPRAWL_FILE_THRESHOLD {
            continue;
        }

        let dir_label = if dir.is_empty() { ".".to_string() } else { dir };
        findings.push(Finding {
            convention: "structural".to_string(),
            severity: Severity::Info,
            file: dir_label,
            description: format!(
                "Directory has {} source files (threshold: {})",
                count, DIRECTORY_SPRAWL_FILE_THRESHOLD
            ),
            suggestion:
                "Directory sprawl detected — group related files into focused subdirectories"
                    .to_string(),
            kind: AuditFinding::DirectorySprawl,
        });
    }

    // Sort by file path for deterministic output
    findings.sort_by(|a, b| a.file.cmp(&b.file));
    findings
}

/// Count top-level items in a source file.
///
/// Uses lightweight pattern matching rather than full parsing — we just need
/// approximate counts for threshold detection, not exact ASTs.
fn count_top_level_items(content: &str, ext: &str) -> usize {
    match ext {
        "rs" => count_rust_items(content),
        "php" => count_php_items(content),
        "js" | "jsx" | "mjs" | "ts" | "tsx" => count_js_items(content),
        _ => 0, // Unknown languages get no item count findings
    }
}

/// Count top-level items in Rust source.
///
/// Matches: fn, struct, enum, const, static, type, trait, impl at zero indentation.
fn count_rust_items(content: &str) -> usize {
    let mut count = 0;
    let mut in_test_module = false;

    for line in content.lines() {
        let trimmed = line.trim();

        // Skip items inside test modules (everything after #[cfg(test)])
        if trimmed == "#[cfg(test)]" {
            in_test_module = true;
            continue;
        }
        if in_test_module {
            continue;
        }

        // Only count items at top level (zero indentation)
        let indent = line.len() - line.trim_start().len();
        if indent > 0 {
            continue;
        }

        if is_rust_item_declaration(trimmed) {
            count += 1;
        }
    }

    count
}

/// Check if a trimmed line starts a Rust item declaration.
fn is_rust_item_declaration(trimmed: &str) -> bool {
    // Strip visibility prefix
    let rest = if let Some(r) = trimmed.strip_prefix("pub(crate) ") {
        r
    } else if let Some(r) = trimmed.strip_prefix("pub(super) ") {
        r
    } else if let Some(r) = trimmed.strip_prefix("pub ") {
        r
    } else {
        trimmed
    };

    // Strip async/unsafe/const modifiers for functions
    let rest = if let Some(r) = rest.strip_prefix("async ") {
        r
    } else {
        rest
    };
    let rest = if let Some(r) = rest.strip_prefix("unsafe ") {
        r
    } else {
        rest
    };

    rest.starts_with("fn ")
        || rest.starts_with("struct ")
        || rest.starts_with("enum ")
        || rest.starts_with("const ")
        || rest.starts_with("static ")
        || rest.starts_with("type ")
        || rest.starts_with("trait ")
        || rest.starts_with("impl ")
        || rest.starts_with("impl<")
}

/// Count top-level items in PHP source.
///
/// Matches: function, class, interface, trait, const at zero indentation.
fn count_php_items(content: &str) -> usize {
    let mut count = 0;

    for line in content.lines() {
        let trimmed = line.trim();
        let indent = line.len() - line.trim_start().len();
        if indent > 0 {
            continue;
        }

        // Strip visibility
        let rest = trimmed
            .strip_prefix("public ")
            .or_else(|| trimmed.strip_prefix("protected "))
            .or_else(|| trimmed.strip_prefix("private "))
            .unwrap_or(trimmed);
        let rest = rest
            .strip_prefix("static ")
            .or_else(|| rest.strip_prefix("abstract "))
            .or_else(|| rest.strip_prefix("final "))
            .unwrap_or(rest);

        if rest.starts_with("function ")
            || rest.starts_with("class ")
            || rest.starts_with("interface ")
            || rest.starts_with("trait ")
            || rest.starts_with("const ")
        {
            count += 1;
        }
    }

    count
}

/// Count top-level items in JavaScript/TypeScript source.
///
/// Matches: function, class, const, let, var, export at zero indentation.
fn count_js_items(content: &str) -> usize {
    let mut count = 0;

    for line in content.lines() {
        let trimmed = line.trim();
        let indent = line.len() - line.trim_start().len();
        if indent > 0 {
            continue;
        }

        let rest = trimmed
            .strip_prefix("export default ")
            .or_else(|| trimmed.strip_prefix("export "))
            .unwrap_or(trimmed);

        if rest.starts_with("function ")
            || rest.starts_with("class ")
            || rest.starts_with("const ")
            || rest.starts_with("let ")
            || rest.starts_with("var ")
            || rest.starts_with("interface ")
            || rest.starts_with("type ")
            || rest.starts_with("enum ")
        {
            count += 1;
        }
    }

    count
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn count_rust_items_basic() {
        let content = r#"
use std::path::Path;

pub struct Foo {
    name: String,
}

fn helper() -> bool {
    true
}

pub fn main_logic() {
    // ...
}

impl Foo {
    pub fn new() -> Self {
        Self { name: String::new() }
    }
}

const MAX: usize = 100;

#[cfg(test)]
mod tests {
    fn test_something() {}
    fn test_another() {}
}
"#;
        // Should count: struct Foo, fn helper, pub fn main_logic, impl Foo, const MAX = 5
        // Should NOT count: use, items inside #[cfg(test)]
        let count = count_rust_items(content);
        assert_eq!(count, 5, "Expected 5 top-level items");
    }

    #[test]
    fn count_rust_items_with_visibility() {
        let content = r#"
pub(crate) fn internal() {}
pub struct Public {}
pub(super) const X: i32 = 1;
pub async fn async_handler() {}
"#;
        assert_eq!(count_rust_items(content), 4);
    }

    #[test]
    fn count_php_items_basic() {
        let content = r#"<?php
namespace App\Models;

class User {
    public function getName() {}
    public function getEmail() {}
}

function helper() {}

interface Cacheable {
    public function cache();
}
"#;
        // class User, function helper, interface Cacheable = 3
        // Methods inside class are indented, so not counted
        assert_eq!(count_php_items(content), 3);
    }

    #[test]
    fn count_js_items_basic() {
        let content = r#"
import { foo } from './bar';

export function processData() {}

export class DataProcessor {
    transform() {}
}

const CONFIG = {};

export default function main() {}
"#;
        // export function, export class, const CONFIG, export default function = 4
        assert_eq!(count_js_items(content), 4);
    }

    #[test]
    fn god_file_detected() {
        let dir = std::env::temp_dir().join("homeboy_structural_god_test");
        let _ = std::fs::create_dir_all(&dir);

        // Create a file with 1100 lines (above 1000-line threshold)
        let mut content = String::new();
        for i in 0..1100 {
            content.push_str(&format!("fn func_{}() {{}}\n", i));
        }
        std::fs::write(dir.join("big.rs"), &content).unwrap();

        // Create a small file (under threshold)
        std::fs::write(dir.join("small.rs"), "fn tiny() {}\n").unwrap();

        let findings = analyze_structure(&dir);
        let god_findings: Vec<&Finding> = findings
            .iter()
            .filter(|f| f.kind == AuditFinding::GodFile)
            .collect();

        assert_eq!(god_findings.len(), 1, "Should flag big.rs as god file");
        assert_eq!(god_findings[0].file, "big.rs");
        assert!(god_findings[0].description.contains("1100 lines"));

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn skips_non_source_files() {
        let dir = std::env::temp_dir().join("homeboy_structural_skip_test");
        let _ = std::fs::create_dir_all(&dir);

        // A big non-source file should not be flagged
        let mut content = String::new();
        for _ in 0..1000 {
            content.push_str("some data line\n");
        }
        std::fs::write(dir.join("data.csv"), &content).unwrap();
        std::fs::write(dir.join("readme.md"), &content).unwrap();

        let findings = analyze_structure(&dir);
        assert!(
            findings.is_empty(),
            "Non-source files should not produce findings"
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn skips_vendor_directories() {
        let dir = std::env::temp_dir().join("homeboy_structural_vendor_test");
        let vendor = dir.join("vendor");
        let _ = std::fs::create_dir_all(&vendor);

        let mut content = String::new();
        for i in 0..600 {
            content.push_str(&format!("fn func_{}() {{}}\n", i));
        }
        std::fs::write(vendor.join("big.rs"), &content).unwrap();

        let findings = analyze_structure(&dir);
        assert!(findings.is_empty(), "Files in vendor/ should be skipped");

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn under_threshold_no_findings() {
        let dir = std::env::temp_dir().join("homeboy_structural_clean_test");
        let _ = std::fs::create_dir_all(&dir);

        // A reasonable 100-line file with 5 items
        let mut content = String::new();
        for i in 0..5 {
            content.push_str(&format!("/// Doc for func_{}\n", i));
            content.push_str(&format!("pub fn func_{}() {{\n", i));
            for j in 0..15 {
                content.push_str(&format!("    let x{} = {};\n", j, j));
            }
            content.push_str("}\n\n");
        }
        std::fs::write(dir.join("clean.rs"), &content).unwrap();

        let findings = analyze_structure(&dir);
        assert!(
            findings.is_empty(),
            "Clean files should produce no findings"
        );

        let _ = std::fs::remove_dir_all(&dir);
    }
}