repotoire 0.3.47

Graph-powered code analysis CLI. 81 detectors for security, architecture, and code quality.
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
//! Long parameter list detector
//!
//! Detects functions with too many parameters, which is a code smell indicating:
//! - The function is doing too much (violates SRP)
//! - Related parameters should be grouped into objects
//! - The function has poor API design
//!
//! This is a simple, query-based detector that examines function signatures
//! stored in the code graph.

use crate::detectors::base::{Detector, DetectorConfig};
use crate::graph::GraphStore;
use crate::models::{Finding, Severity};
use anyhow::Result;
use std::collections::HashSet;
use std::path::PathBuf;
use tracing::{debug, info};
use uuid::Uuid;

/// Thresholds for long parameter list detection
#[derive(Debug, Clone)]
pub struct LongParameterThresholds {
    /// Parameters above this count are flagged
    pub max_params: usize,
    /// Parameters at this count trigger high severity
    pub high_params: usize,
    /// Parameters at this count trigger critical severity
    pub critical_params: usize,
}

impl Default for LongParameterThresholds {
    fn default() -> Self {
        Self {
            max_params: 5,
            high_params: 7,
            critical_params: 10,
        }
    }
}

/// Parameters to exclude from counting
static SKIP_PARAMS: &[&str] = &["self", "cls"];

/// Detects functions with too many parameters
pub struct LongParameterListDetector {
    config: DetectorConfig,
    thresholds: LongParameterThresholds,
    skip_params: HashSet<String>,
}

impl LongParameterListDetector {
    /// Create a new detector with default thresholds
    pub fn new() -> Self {
        Self::with_thresholds(LongParameterThresholds::default())
    }

    /// Create with custom thresholds
    pub fn with_thresholds(thresholds: LongParameterThresholds) -> Self {
        let skip_params: HashSet<String> = SKIP_PARAMS.iter().map(|s| s.to_string()).collect();

        Self {
            config: DetectorConfig::new(),
            thresholds,
            skip_params,
        }
    }

    /// Create with custom config
    pub fn with_config(config: DetectorConfig) -> Self {
        let thresholds = LongParameterThresholds {
            max_params: config.get_option_or("max_params", 5),
            high_params: config.get_option_or("high_params", 7),
            critical_params: config.get_option_or("critical_params", 10),
        };

        let skip_params: HashSet<String> = SKIP_PARAMS.iter().map(|s| s.to_string()).collect();

        Self {
            config,
            thresholds,
            skip_params,
        }
    }

    /// Extract meaningful parameter names (excluding self/cls)
    fn get_meaningful_params(&self, params: &[serde_json::Value]) -> Vec<String> {
        params
            .iter()
            .filter_map(|p| {
                let name = if p.is_string() {
                    p.as_str().map(|s| s.to_string())
                } else if let Some(obj) = p.as_object() {
                    obj.get("name").and_then(|n| n.as_str()).map(|s| s.to_string())
                } else {
                    None
                };

                name.filter(|n| !self.skip_params.contains(n))
            })
            .collect()
    }

    /// Calculate severity based on parameter count
    fn calculate_severity(&self, param_count: usize) -> Severity {
        if param_count >= self.thresholds.critical_params {
            Severity::Critical
        } else if param_count >= self.thresholds.high_params {
            Severity::High
        } else if param_count > self.thresholds.max_params {
            Severity::Medium
        } else {
            Severity::Low
        }
    }

    /// Generate a suggested config class name
    fn suggest_config_name(&self, func_name: &str, params: &[String]) -> String {
        // Try to derive from function name
        if let Some(base) = func_name.strip_prefix("create_") {
            return format!("{}Config", to_pascal_case(base));
        }
        if let Some(base) = func_name.strip_prefix("init_") {
            return format!("{}Options", to_pascal_case(base));
        }
        if let Some(base) = func_name.strip_prefix("initialize_") {
            return format!("{}Options", to_pascal_case(base));
        }
        if let Some(base) = func_name.strip_prefix("process_") {
            return format!("{}Params", to_pascal_case(base));
        }
        if let Some(base) = func_name.strip_prefix("configure_") {
            return format!("{}Config", to_pascal_case(base));
        }

        // Look for common parameter patterns
        let param_set: HashSet<&str> = params.iter().map(|s| s.as_str()).collect();

        if param_set.contains("host") && param_set.contains("port") {
            return "ConnectionConfig".to_string();
        }
        if param_set.contains("url") && param_set.contains("timeout") {
            return "ConnectionConfig".to_string();
        }
        if param_set.contains("username") && param_set.contains("password") {
            return "Credentials".to_string();
        }
        if param_set.contains("width") && param_set.contains("height") {
            return "Dimensions".to_string();
        }
        if param_set.contains("x") && param_set.contains("y") {
            return "Position".to_string();
        }
        if param_set.contains("start") && param_set.contains("end") {
            return "Range".to_string();
        }

        // Default: use function name
        format!("{}Config", to_pascal_case(func_name))
    }

    /// Generate refactoring suggestion
    fn generate_suggestion(&self, func_name: &str, params: &[String]) -> String {
        let config_name = self.suggest_config_name(func_name, params);
        
        let mut lines = vec![
            "**Refactoring Options:**\n".to_string(),
            "**1. Introduce Parameter Object:**".to_string(),
            "```python".to_string(),
            "from dataclasses import dataclass".to_string(),
            String::new(),
            "@dataclass".to_string(),
            format!("class {}:", config_name),
        ];

        // Add parameters as fields (first 6)
        for p in params.iter().take(6) {
            lines.push(format!("    {}: Any  # TODO: add type", p));
        }
        if params.len() > 6 {
            lines.push(format!("    # ... and {} more fields", params.len() - 6));
        }

        lines.push(String::new());
        lines.push(format!("def {}(config: {}):", func_name, config_name));
        lines.push("    ...".to_string());
        lines.push("```".to_string());
        lines.push(String::new());

        // Option 2: Builder pattern (for many params)
        if params.len() >= 8 {
            let builder_name = format!("{}Builder", to_pascal_case(func_name));
            lines.push("**2. Use Builder Pattern:**".to_string());
            lines.push("```python".to_string());
            lines.push(format!("class {}:", builder_name));
            if let Some(p) = params.first() {
                lines.push(format!("    def with_{}(self, value): ...", p));
            }
            if let Some(p) = params.get(1) {
                lines.push(format!("    def with_{}(self, value): ...", p));
            }
            lines.push("    # ... more setters".to_string());
            lines.push(format!("    def build(self): return {}(...)", func_name));
            lines.push("```".to_string());
            lines.push(String::new());
        }

        // Option 3: Split function
        let option_num = if params.len() >= 8 { "3" } else { "2" };
        lines.push(format!("**{}. Split Into Smaller Functions:**", option_num));
        lines.push(format!(
            "- Break `{}` into functions with focused responsibilities",
            func_name
        ));
        lines.push("- Each function handles a subset of the original task".to_string());

        lines.join("\n")
    }

    /// Estimate effort based on parameter count
    fn estimate_effort(&self, param_count: usize) -> String {
        if param_count >= 12 {
            "Large (1-2 days)".to_string()
        } else if param_count >= 8 {
            "Medium (4-8 hours)".to_string()
        } else if param_count >= 6 {
            "Small (2-4 hours)".to_string()
        } else {
            "Small (1 hour)".to_string()
        }
    }

    /// Create a finding for a function with long parameter list
    fn create_finding(
        &self,
        _qualified_name: String,
        func_name: String,
        file_path: String,
        line_start: Option<u32>,
        params: Vec<String>,
    ) -> Finding {
        let param_count = params.len();
        let severity = self.calculate_severity(param_count);

        // Format parameters for display
        let mut params_display = params.iter().take(8).cloned().collect::<Vec<_>>().join(", ");
        if params.len() > 8 {
            params_display.push_str(&format!(" ... ({} total)", params.len()));
        }

        let description = if param_count >= self.thresholds.critical_params {
            format!(
                "Function `{}` has {} parameters: `{}`\n\n\
                 **Threshold**: >{} parameters\n\n\
                 This is a critical issue. Such long parameter lists:\n\
                 - Are nearly impossible to use correctly\n\
                 - Indicate the function is doing way too much\n\
                 - Should be split into multiple smaller functions",
                func_name, param_count, params_display, self.thresholds.max_params
            )
        } else if param_count >= self.thresholds.high_params {
            format!(
                "Function `{}` has {} parameters: `{}`\n\n\
                 **Threshold**: >{} parameters\n\n\
                 Consider refactoring to:\n\
                 - Group related parameters into a data class\n\
                 - Split the function into smaller functions\n\
                 - Use the Builder pattern for complex construction",
                func_name, param_count, params_display, self.thresholds.max_params
            )
        } else {
            format!(
                "Function `{}` has {} parameters: `{}`\n\n\
                 **Threshold**: >{} parameters\n\n\
                 Consider whether some parameters can be grouped \
                 into a single configuration object or data class.",
                func_name, param_count, params_display, self.thresholds.max_params
            )
        };

        Finding {
            id: Uuid::new_v4().to_string(),
            detector: "LongParameterListDetector".to_string(),
            severity,
            title: format!("Long parameter list: {} ({} params)", func_name, param_count),
            description,
            affected_files: vec![PathBuf::from(&file_path)],
            line_start,
            line_end: None,
            suggested_fix: Some(self.generate_suggestion(&func_name, &params)),
            estimated_effort: Some(self.estimate_effort(param_count)),
            category: Some("code_smell".to_string()),
            cwe_id: None,
            why_it_matters: Some(
                "Long parameter lists make functions difficult to use correctly. \
                 Callers must remember the order and meaning of each parameter, \
                 leading to errors. They also indicate that a function may be \
                 doing too much and should be split."
                    .to_string(),
            ),
            ..Default::default()
        }
    }
}

impl Default for LongParameterListDetector {
    fn default() -> Self {
        Self::new()
    }
}

impl Detector for LongParameterListDetector {
    fn name(&self) -> &'static str {
        "LongParameterListDetector"
    }

    fn description(&self) -> &'static str {
        "Detects functions with too many parameters"
    }

    fn category(&self) -> &'static str {
        "code_smell"
    }

    fn config(&self) -> Option<&DetectorConfig> {
        Some(&self.config)
    }

    fn detect(&self, graph: &GraphStore) -> Result<Vec<Finding>> {
        let mut findings = Vec::new();
        
        for func in graph.get_functions() {
            let param_count = func.param_count().unwrap_or(0) as usize;
            
            // Use configured thresholds instead of hardcoded values
            if param_count > self.thresholds.max_params {
                let severity = self.calculate_severity(param_count);
                
                findings.push(Finding {
                    id: Uuid::new_v4().to_string(),
                    detector: "LongParameterListDetector".to_string(),
                    severity,
                    title: format!("Long parameter list: {}", func.name),
                    description: format!(
                        "Function '{}' has {} parameters (threshold: {}). Consider using a config object.",
                        func.name, param_count, self.thresholds.max_params
                    ),
                    affected_files: vec![func.file_path.clone().into()],
                    line_start: Some(func.line_start),
                    line_end: Some(func.line_end),
                    suggested_fix: Some("Group related parameters into a configuration object or class".to_string()),
                    estimated_effort: Some(self.estimate_effort(param_count)),
                    category: Some("quality".to_string()),
                    cwe_id: None,
                    why_it_matters: Some("Long parameter lists make functions hard to call and understand".to_string()),
                    ..Default::default()
                });
            }
        }
        
        Ok(findings)
    }
}

/// Convert snake_case to PascalCase
fn to_pascal_case(s: &str) -> String {
    s.split('_')
        .map(|word| {
            let mut chars = word.chars();
            match chars.next() {
                None => String::new(),
                Some(first) => first.to_uppercase().chain(chars).collect(),
            }
        })
        .collect()
}

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

    #[test]
    fn test_default_thresholds() {
        let detector = LongParameterListDetector::new();
        assert_eq!(detector.thresholds.max_params, 5);
        assert_eq!(detector.thresholds.high_params, 7);
        assert_eq!(detector.thresholds.critical_params, 10);
    }

    #[test]
    fn test_severity_calculation() {
        let detector = LongParameterListDetector::new();

        assert_eq!(detector.calculate_severity(5), Severity::Low);
        assert_eq!(detector.calculate_severity(6), Severity::Medium);
        assert_eq!(detector.calculate_severity(7), Severity::High);
        assert_eq!(detector.calculate_severity(10), Severity::Critical);
    }

    #[test]
    fn test_meaningful_params() {
        let detector = LongParameterListDetector::new();

        let params = vec![
            serde_json::json!("self"),
            serde_json::json!("x"),
            serde_json::json!("y"),
            serde_json::json!({"name": "cls"}),
            serde_json::json!({"name": "config"}),
        ];

        let meaningful = detector.get_meaningful_params(&params);
        assert_eq!(meaningful, vec!["x", "y", "config"]);
    }

    #[test]
    fn test_to_pascal_case() {
        assert_eq!(to_pascal_case("hello_world"), "HelloWorld");
        assert_eq!(to_pascal_case("create_user"), "CreateUser");
        assert_eq!(to_pascal_case("x"), "X");
    }

    #[test]
    fn test_suggest_config_name() {
        let detector = LongParameterListDetector::new();

        assert_eq!(
            detector.suggest_config_name("create_user", &[]),
            "UserConfig"
        );
        assert_eq!(
            detector.suggest_config_name(
                "connect",
                &["host".to_string(), "port".to_string()]
            ),
            "ConnectionConfig"
        );
        assert_eq!(
            detector.suggest_config_name(
                "login",
                &["username".to_string(), "password".to_string()]
            ),
            "Credentials"
        );
    }
}