Skip to main content

tldr_cli/commands/
halstead.rs

1//! Halstead metrics command - Calculate Halstead complexity metrics per function
2//!
3//! Exposes Halstead software science metrics as a standalone command with:
4//! - Per-function granularity
5//! - Threshold-based recommendations
6//! - Optional operator/operand listing
7//! - File or directory analysis
8
9use std::path::{Path, PathBuf};
10
11use anyhow::Result;
12use clap::Args;
13use colored::Colorize;
14
15use tldr_core::metrics::halstead::{
16    analyze_halstead, merge_halstead_reports, HalsteadOptions, HalsteadReport, ThresholdStatus,
17};
18use tldr_core::metrics::{walk_source_files, WalkOptions};
19use tldr_core::{detect_or_parse_language, validate_file_path, Language};
20
21use crate::output::{common_path_prefix, strip_prefix_display, OutputFormat, OutputWriter};
22
23/// Calculate Halstead complexity metrics
24#[derive(Debug, Args)]
25pub struct HalsteadArgs {
26    /// File or directory to analyze
27    #[arg(default_value = ".")]
28    pub path: PathBuf,
29
30    /// Specific function to analyze (analyzes all if not specified)
31    #[arg(long)]
32    pub function: Option<String>,
33
34    /// Programming language (auto-detect if not specified)
35    #[arg(long, short = 'l')]
36    pub lang: Option<Language>,
37
38    /// Show list of operators found
39    #[arg(long)]
40    pub show_operators: bool,
41
42    /// Show list of operands found
43    #[arg(long)]
44    pub show_operands: bool,
45
46    /// Volume threshold for warnings (default: 1000)
47    #[arg(long, default_value = "1000")]
48    pub threshold_volume: f64,
49
50    /// Difficulty threshold for warnings (default: 20)
51    #[arg(long, default_value = "20")]
52    pub threshold_difficulty: f64,
53
54    /// Maximum functions to report (0 = all)
55    #[arg(long, default_value = "0")]
56    pub top: usize,
57
58    /// Exclude patterns (glob syntax), can be specified multiple times
59    #[arg(long, short = 'e')]
60    pub exclude: Vec<String>,
61
62    /// Include hidden files (dotfiles)
63    #[arg(long)]
64    pub include_hidden: bool,
65
66    /// Maximum files to process (0 = unlimited)
67    #[arg(long, default_value = "0")]
68    pub max_files: usize,
69}
70
71impl HalsteadArgs {
72    /// Run the halstead command
73    pub fn run(&self, format: OutputFormat, quiet: bool) -> Result<()> {
74        let writer = OutputWriter::new(format, quiet);
75
76        let options = HalsteadOptions {
77            function: self.function.clone(),
78            volume_threshold: self.threshold_volume,
79            difficulty_threshold: self.threshold_difficulty,
80            show_operators: self.show_operators,
81            show_operands: self.show_operands,
82            top: self.top,
83        };
84
85        let report = if self.path.is_file() {
86            // Single file: preserve exact current behavior
87            let validated_path = validate_file_path(self.path.to_str().unwrap_or_default(), None)?;
88            let language =
89                detect_or_parse_language(self.lang.as_ref().map(|l| l.as_str()), &validated_path)?;
90
91            writer.progress(&format!(
92                "Calculating Halstead metrics for {} ({:?})...",
93                validated_path.display(),
94                language
95            ));
96
97            analyze_halstead(&validated_path, Some(language), options)?
98        } else if self.path.is_dir() {
99            // Directory: walk -> analyze each -> merge
100            let walk_options = WalkOptions {
101                lang: self.lang,
102                exclude: self.exclude.clone(),
103                include_hidden: self.include_hidden,
104                gitignore: true,
105                max_files: self.max_files,
106            };
107
108            let (files, walk_warnings) = walk_source_files(&self.path, &walk_options)?;
109
110            writer.progress(&format!(
111                "Calculating Halstead metrics for {} files in {}...",
112                files.len(),
113                self.path.display()
114            ));
115
116            let mut reports = Vec::new();
117            let mut extra_warnings = walk_warnings;
118
119            for file in &files {
120                // Detect language per-file (walker already filtered to supported extensions)
121                let language = match Language::from_path(file) {
122                    Some(l) => l,
123                    None => {
124                        extra_warnings
125                            .push(format!("Skipping {}: unsupported language", file.display()));
126                        continue;
127                    }
128                };
129
130                // Clone options because analyze_halstead takes ownership
131                match analyze_halstead(file, Some(language), options.clone()) {
132                    Ok(report) => reports.push(report),
133                    Err(e) => {
134                        extra_warnings.push(format!("Failed to analyze {}: {}", file.display(), e));
135                    }
136                }
137            }
138
139            let mut merged = merge_halstead_reports(reports, &options);
140            let mut all_warnings = extra_warnings;
141            all_warnings.append(&mut merged.warnings);
142            merged.warnings = all_warnings;
143            merged
144        } else {
145            return Err(anyhow::anyhow!(
146                "Path does not exist: {}",
147                self.path.display()
148            ));
149        };
150
151        // Output based on format
152        if writer.is_text() {
153            self.print_text_report(&report, &writer)?;
154        } else {
155            writer.write(&report)?;
156        }
157
158        Ok(())
159    }
160
161    fn print_text_report(&self, report: &HalsteadReport, writer: &OutputWriter) -> Result<()> {
162        // Header
163        writer.write_text(&format!(
164            "\n{}\n",
165            "Halstead Metrics Report".bold().underline()
166        ))?;
167
168        // Summary
169        writer.write_text(&format!(
170            "\n{} ({} functions analyzed)\n",
171            "Summary".bold(),
172            report.summary.total_functions
173        ))?;
174        writer.write_text(&format!(
175            "  Avg Volume:     {:.2}\n",
176            report.summary.avg_volume
177        ))?;
178        writer.write_text(&format!(
179            "  Avg Difficulty: {:.2}\n",
180            report.summary.avg_difficulty
181        ))?;
182        writer.write_text(&format!(
183            "  Avg Effort:     {:.2}\n",
184            report.summary.avg_effort
185        ))?;
186        writer.write_text(&format!(
187            "  Est. Bugs:      {:.3}\n",
188            report.summary.total_estimated_bugs
189        ))?;
190
191        if report.summary.violations_count > 0 {
192            writer.write_text(&format!(
193                "  {}: {}\n",
194                "Violations".red(),
195                report.summary.violations_count
196            ))?;
197        }
198
199        // Functions table
200        writer.write_text(&format!("\n{}\n", "Functions".bold()))?;
201        writer.write_text(&format!(
202            "  {:<30} {:>8} {:>8} {:>10} {:>12} {:>10} {:>8}\n",
203            "Name", "n1", "n2", "Volume", "Difficulty", "Effort", "Status"
204        ))?;
205        writer.write_text(&format!("{}\n", "-".repeat(98)))?;
206
207        for func in &report.functions {
208            let status = format_status(&func.thresholds.volume_status);
209            let name = if func.name.len() > 30 {
210                format!("{}...", &func.name[..27])
211            } else {
212                func.name.clone()
213            };
214
215            writer.write_text(&format!(
216                "  {:<30} {:>8} {:>8} {:>10.2} {:>12.2} {:>10.0} {:>8}\n",
217                name,
218                func.metrics.n1,
219                func.metrics.n2,
220                func.metrics.volume,
221                func.metrics.difficulty,
222                func.metrics.effort,
223                status
224            ))?;
225
226            // Show operators/operands if requested
227            if let Some(ref operators) = func.operators {
228                writer.write_text(&format!(
229                    "    Operators: {}\n",
230                    operators.join(", ").dimmed()
231                ))?;
232            }
233            if let Some(ref operands) = func.operands {
234                writer.write_text(&format!("    Operands: {}\n", operands.join(", ").dimmed()))?;
235            }
236        }
237
238        // Violations with relative path display
239        if !report.violations.is_empty() {
240            // Compute common prefix for relative path display
241            let violation_paths: Vec<&Path> = report
242                .violations
243                .iter()
244                .map(|v| Path::new(v.file.as_str()))
245                .collect();
246            let prefix = if violation_paths.is_empty() {
247                PathBuf::new()
248            } else {
249                common_path_prefix(&violation_paths)
250            };
251
252            writer.write_text(&format!("\n{}\n", "Threshold Violations".red().bold()))?;
253            for violation in &report.violations {
254                let rel_path = strip_prefix_display(Path::new(&violation.file), &prefix);
255                writer.write_text(&format!(
256                    "  {} in {}: {} = {:.2} (threshold: {:.2})\n",
257                    violation.name.yellow(),
258                    rel_path,
259                    violation.metric,
260                    violation.value,
261                    violation.threshold
262                ))?;
263            }
264        }
265
266        // Warnings section
267        if !report.warnings.is_empty() {
268            writer.write_text(&format!("\n{}\n", "Warnings".yellow().bold()))?;
269            for warning in &report.warnings {
270                writer.write_text(&format!("  {}\n", warning))?;
271            }
272        }
273
274        Ok(())
275    }
276}
277
278fn format_status(status: &ThresholdStatus) -> String {
279    match status {
280        ThresholdStatus::Good => "good".green().to_string(),
281        ThresholdStatus::Warning => "warning".yellow().to_string(),
282        ThresholdStatus::Bad => "bad".red().to_string(),
283    }
284}