pmat 3.11.0

PMAT - Zero-config AI context generation and code quality toolkit (CLI, MCP, HTTP)
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
// Churn handlers - extracted for file health (CB-040)

pub async fn handle_analyze_churn(
    project_path: PathBuf,
    days: u32,
    format: crate::models::churn::ChurnOutputFormat,
    output: Option<PathBuf>,
    top_files: usize,
) -> Result<()> {
    use crate::services::git_analysis::GitAnalysisService;

    eprintln!("📊 Analyzing code churn for the last {days} days...");

    // Analyze code churn
    let mut analysis = GitAnalysisService::analyze_code_churn(&project_path, days)
        .map_err(|e| anyhow::anyhow!("Churn analysis failed: {e}"))?;

    eprintln!("✅ Analyzed {} files with changes", analysis.files.len());

    // Apply filtering and sorting to analysis results
    apply_churn_file_filtering(&mut analysis, top_files);

    // Format and write output
    let content = format_churn_content(&analysis, format)?;
    write_churn_output(content, output).await?;
    Ok(())
}

// Helper function to format churn analysis as JSON
fn format_churn_as_json(analysis: &crate::models::churn::CodeChurnAnalysis) -> Result<String> {
    Ok(serde_json::to_string_pretty(analysis)?)
}

/// Format churn analysis as summary with top files display
///
/// # Examples
///
/// ```no_run
/// use pmat::models::churn::*;
/// use chrono::Utc;
/// use std::path::{Path, PathBuf};
///
/// let analysis = CodeChurnAnalysis {
///     generated_at: Utc::now(),
///     period_days: 30,
///     repository_root: PathBuf::from("."),
///     files: vec![
///         FileChurnMetrics {
///             path: PathBuf::from("src/main.rs"),
///             relative_path: "src/main.rs".to_string(),
///             commit_count: 15,
///             unique_authors: vec!["dev1".to_string(), "dev2".to_string()],
///             additions: 100,
///             deletions: 50,
///             churn_score: 0.75,
///             last_modified: Utc::now(),
///             first_seen: Utc::now(),
///         },
///         FileChurnMetrics {
///             path: PathBuf::from("src/lib.rs"),
///             relative_path: "src/lib.rs".to_string(),
///             commit_count: 8,
///             unique_authors: vec!["dev1".to_string()],
///             additions: 60,
///             deletions: 20,
///             churn_score: 0.45,
///             last_modified: Utc::now(),
///             first_seen: Utc::now(),
///         },
///     ],
///     summary: ChurnSummary {
///         total_commits: 23,
///         total_files_changed: 2,
///         hotspot_files: vec![PathBuf::from("src/main.rs")],
///         stable_files: vec![PathBuf::from("src/lib.rs")],
///         author_contributions: [("dev1".to_string(), 15), ("dev2".to_string(), 8)].iter().cloned().collect(),
///         mean_churn_score: 0.6,
///         variance_churn_score: 0.0225,
///         stddev_churn_score: 0.15,
///     },
/// };
///
/// // Testing that the data structure compiles correctly
/// assert!(analysis.files.len() == 2);
/// assert_eq!(analysis.period_days, 30);
/// assert_eq!(analysis.summary.total_files_changed, 2);
/// ```
// Helper function to format churn analysis as summary
pub fn format_churn_as_summary(
    analysis: &crate::models::churn::CodeChurnAnalysis,
) -> Result<String> {
    let mut output = String::new();

    write_summary_header(&mut output, analysis)?;
    write_summary_top_files(&mut output, analysis)?;
    write_summary_hotspot_files(&mut output, &analysis.summary)?;
    write_summary_stable_files(&mut output, &analysis.summary)?;
    write_summary_top_contributors(&mut output, &analysis.summary)?;

    Ok(output)
}

// Helper function to write summary header
fn write_summary_header(
    output: &mut String,
    analysis: &crate::models::churn::CodeChurnAnalysis,
) -> Result<()> {
    use crate::cli::colors as c;
    use std::fmt::Write;

    writeln!(output, "{}{}Code Churn Analysis Summary{}\n", c::BOLD, c::UNDERLINE, c::RESET)?;
    writeln!(output, "  {}Period:{} {}{}{}", c::BOLD, c::RESET, c::BOLD_WHITE, analysis.period_days, c::RESET)?;
    writeln!(
        output,
        "  {}Total commits:{} {}{}{}",
        c::BOLD, c::RESET, c::BOLD_WHITE, analysis.summary.total_commits, c::RESET
    )?;
    writeln!(
        output,
        "  {}Files changed:{} {}{}{}",
        c::BOLD, c::RESET, c::BOLD_WHITE, analysis.summary.total_files_changed, c::RESET
    )?;
    Ok(())
}

// Helper function to write top files by churn
fn write_summary_top_files(
    output: &mut String,
    analysis: &crate::models::churn::CodeChurnAnalysis,
) -> Result<()> {
    use crate::cli::colors as c;
    use std::fmt::Write;

    if !analysis.files.is_empty() {
        writeln!(output, "\n{}Top Files by Churn{}\n", c::BOLD, c::RESET)?;

        // Sort files by churn score or commit count (descending)
        let mut sorted_files: Vec<_> = analysis.files.iter().collect();
        sorted_files.sort_unstable_by(|a, b| {
            // Primary sort by commit count, secondary by churn score
            match b.commit_count.cmp(&a.commit_count) {
                std::cmp::Ordering::Equal => b
                    .churn_score
                    .partial_cmp(&a.churn_score)
                    .unwrap_or(std::cmp::Ordering::Equal),
                other => other,
            }
        });

        for (i, file) in sorted_files.iter().take(10).enumerate() {
            let filename = file
                .path
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or(&file.relative_path);
            let score_color = if file.churn_score > 0.5 {
                c::RED
            } else if file.churn_score > 0.3 {
                c::YELLOW
            } else {
                c::GREEN
            };
            writeln!(
                output,
                "  {}. {}{}{} - {}{}{} commits, {} authors, score: {}{:.2}{}",
                i + 1,
                c::CYAN, filename, c::RESET,
                c::BOLD_WHITE, file.commit_count, c::RESET,
                file.unique_authors.len(),
                score_color, file.churn_score, c::RESET
            )?;
        }
    }
    Ok(())
}

// Helper function to write hotspot files
fn write_summary_hotspot_files(
    output: &mut String,
    summary: &crate::models::churn::ChurnSummary,
) -> Result<()> {
    use crate::cli::colors as c;
    use std::fmt::Write;

    if !summary.hotspot_files.is_empty() {
        writeln!(output, "\n{}Hotspot Files (High Churn){}\n", c::BOLD, c::RESET)?;
        for (i, file) in summary.hotspot_files.iter().take(10).enumerate() {
            writeln!(output, "  {}. {}{}{}", i + 1, c::CYAN, file.display(), c::RESET)?;
        }
    }
    Ok(())
}

// Helper function to write stable files
fn write_summary_stable_files(
    output: &mut String,
    summary: &crate::models::churn::ChurnSummary,
) -> Result<()> {
    use crate::cli::colors as c;
    use std::fmt::Write;

    if !summary.stable_files.is_empty() {
        writeln!(output, "\n{}Stable Files (Low Churn){}\n", c::BOLD, c::RESET)?;
        for (i, file) in summary.stable_files.iter().take(10).enumerate() {
            writeln!(output, "  {}. {}{}{}", i + 1, c::CYAN, file.display(), c::RESET)?;
        }
    }
    Ok(())
}

// Helper function to write top contributors
fn write_summary_top_contributors(
    output: &mut String,
    summary: &crate::models::churn::ChurnSummary,
) -> Result<()> {
    use crate::cli::colors as c;
    use std::fmt::Write;

    if !summary.author_contributions.is_empty() {
        writeln!(output, "\n{}Top Contributors{}\n", c::BOLD, c::RESET)?;
        let mut authors: Vec<_> = summary.author_contributions.iter().collect();
        authors.sort_unstable_by(|a, b| b.1.cmp(a.1));
        for (author, files) in authors.iter().take(10) {
            writeln!(output, "  {}{}{}: {}{}{} files", c::CYAN, author, c::RESET, c::BOLD_WHITE, files, c::RESET)?;
        }
    }
    Ok(())
}

// Helper function to format churn analysis as markdown
pub fn format_churn_as_markdown(
    analysis: &crate::models::churn::CodeChurnAnalysis,
) -> Result<String> {
    let mut output = String::new();

    write_markdown_header(&mut output, analysis)?;
    write_markdown_summary_table(&mut output, &analysis.summary)?;
    write_markdown_file_details(&mut output, &analysis.files)?;
    write_markdown_author_contributions(&mut output, &analysis.summary)?;
    write_markdown_recommendations(&mut output)?;

    Ok(output)
}

// Helper function to write markdown header
fn write_markdown_header(
    output: &mut String,
    analysis: &crate::models::churn::CodeChurnAnalysis,
) -> Result<()> {
    use std::fmt::Write;

    writeln!(output, "# Code Churn Analysis Report\n")?;
    writeln!(
        output,
        "Generated: {}",
        analysis.generated_at.format("%Y-%m-%d %H:%M:%S UTC")
    )?;
    writeln!(output, "Repository: {}", analysis.repository_root.display())?;
    writeln!(output, "Analysis Period: {} days\n", analysis.period_days)?;
    Ok(())
}

// Helper function to write markdown summary table
fn write_markdown_summary_table(
    output: &mut String,
    summary: &crate::models::churn::ChurnSummary,
) -> Result<()> {
    write_markdown_table_header(output)?;
    write_summary_data_rows(output, summary)?;
    Ok(())
}

/// Write the markdown table header for summary statistics
fn write_markdown_table_header(output: &mut String) -> Result<()> {
    use std::fmt::Write;

    writeln!(output, "## Summary Statistics\n")?;
    writeln!(output, "| Metric | Value |")?;
    writeln!(output, "|--------|-------|")?;
    Ok(())
}

/// Write all summary data rows to the markdown table
fn write_summary_data_rows(
    output: &mut String,
    summary: &crate::models::churn::ChurnSummary,
) -> Result<()> {
    write_commits_row(output, summary.total_commits)?;
    write_files_changed_row(output, summary.total_files_changed)?;
    write_hotspot_files_row(output, summary.hotspot_files.len())?;
    write_stable_files_row(output, summary.stable_files.len())?;
    write_authors_row(output, summary.author_contributions.len())?;
    Ok(())
}

/// Write total commits row
fn write_commits_row(output: &mut String, total_commits: usize) -> Result<()> {
    use std::fmt::Write;
    writeln!(output, "| Total Commits | {total_commits} |")?;
    Ok(())
}

/// Write files changed row
fn write_files_changed_row(output: &mut String, files_changed: usize) -> Result<()> {
    use std::fmt::Write;
    writeln!(output, "| Files Changed | {files_changed} |")?;
    Ok(())
}

/// Write hotspot files row
fn write_hotspot_files_row(output: &mut String, hotspot_count: usize) -> Result<()> {
    use std::fmt::Write;
    writeln!(output, "| Hotspot Files | {hotspot_count} |")?;
    Ok(())
}

/// Write stable files row
fn write_stable_files_row(output: &mut String, stable_count: usize) -> Result<()> {
    use std::fmt::Write;
    writeln!(output, "| Stable Files | {stable_count} |")?;
    Ok(())
}

/// Write contributing authors row
fn write_authors_row(output: &mut String, author_count: usize) -> Result<()> {
    use std::fmt::Write;
    writeln!(output, "| Contributing Authors | {author_count} |")?;
    Ok(())
}

// Helper function to write markdown file details
fn write_markdown_file_details(
    output: &mut String,
    files: &[crate::models::churn::FileChurnMetrics],
) -> Result<()> {
    use std::fmt::Write;

    if !files.is_empty() {
        writeln!(output, "\n## File Churn Details\n")?;
        writeln!(
            output,
            "| File | Commits | Authors | Additions | Deletions | Churn Score | Last Modified |"
        )?;
        writeln!(
            output,
            "|------|---------|---------|-----------|-----------|-------------|----------------|"
        )?;

        // Sort by churn score descending
        let mut sorted_files = files.to_vec();
        sorted_files.sort_unstable_by(|a, b| {
            b.churn_score
                .partial_cmp(&a.churn_score)
                .expect("NaN values should not occur in churn scores")
        });

        for file in sorted_files.iter().take(20) {
            writeln!(
                output,
                "| {} | {} | {} | {} | {} | {:.2} | {} |",
                file.relative_path,
                file.commit_count,
                file.unique_authors.len(),
                file.additions,
                file.deletions,
                file.churn_score,
                file.last_modified.format("%Y-%m-%d")
            )?;
        }
    }
    Ok(())
}

// Helper function to write markdown author contributions
fn write_markdown_author_contributions(
    output: &mut String,
    summary: &crate::models::churn::ChurnSummary,
) -> Result<()> {
    use std::fmt::Write;

    if !summary.author_contributions.is_empty() {
        writeln!(output, "\n## Author Contributions\n")?;
        writeln!(output, "| Author | Files Modified |")?;
        writeln!(output, "|--------|----------------|")?;

        let mut authors: Vec<_> = summary.author_contributions.iter().collect();
        authors.sort_unstable_by(|a, b| b.1.cmp(a.1));

        for (author, count) in authors.iter().take(15) {
            writeln!(output, "| {author} | {count} |")?;
        }
    }
    Ok(())
}

// Helper function to write markdown recommendations
fn write_markdown_recommendations(output: &mut String) -> Result<()> {
    use std::fmt::Write;

    writeln!(output, "\n## Recommendations\n")?;
    writeln!(
        output,
        "1. **Review Hotspot Files**: Files with high churn scores may benefit from refactoring"
    )?;
    writeln!(
        output,
        "2. **Add Tests**: High-churn files should have comprehensive test coverage"
    )?;
    writeln!(
        output,
        "3. **Code Review**: Frequently modified files may indicate design issues"
    )?;
    writeln!(
        output,
        "4. **Documentation**: Document the reasons for frequent changes in hotspot files"
    )?;
    Ok(())
}

// Helper function to format churn analysis as CSV
pub fn format_churn_as_csv(analysis: &crate::models::churn::CodeChurnAnalysis) -> Result<String> {
    use std::fmt::Write;
    let mut output = String::new();

    writeln!(&mut output, "file_path,relative_path,commit_count,unique_authors,additions,deletions,churn_score,last_modified,first_seen")?;

    for file in &analysis.files {
        writeln!(
            &mut output,
            "{},{},{},{},{},{},{:.3},{},{}",
            file.path.display(),
            file.relative_path,
            file.commit_count,
            file.unique_authors.len(),
            file.additions,
            file.deletions,
            file.churn_score,
            file.last_modified.to_rfc3339(),
            file.first_seen.to_rfc3339()
        )?;
    }

    Ok(output)
}

// Helper function to write output
pub async fn write_churn_output(content: String, output: Option<PathBuf>) -> Result<()> {
    if let Some(output_path) = output {
        tokio::fs::write(&output_path, &content).await?;
        eprintln!("✅ Churn analysis written to: {}", output_path.display());
    } else {
        println!("{content}");
    }
    Ok(())
}

// Helper functions for handle_analyze_churn
// Toyota Way Extract Method: Reduce complexity by separating filtering and formatting logic

/// Applies file filtering and sorting to churn analysis results
/// Toyota Way: Extract Method - reduce complexity by extracting file processing logic
fn apply_churn_file_filtering(
    analysis: &mut crate::models::churn::CodeChurnAnalysis,
    top_files: usize,
) {
    // Apply top_files limit if specified (0 means show all)
    if top_files > 0 && analysis.files.len() > top_files {
        // Sort files by commit count descending
        analysis
            .files
            .sort_unstable_by(|a, b| b.commit_count.cmp(&a.commit_count));
        analysis.files.truncate(top_files);
    }
}

/// Formats churn analysis based on requested format
/// Toyota Way: Extract Method - reduce complexity by extracting format selection logic
fn format_churn_content(
    analysis: &crate::models::churn::CodeChurnAnalysis,
    format: crate::models::churn::ChurnOutputFormat,
) -> Result<String> {
    use crate::models::churn::ChurnOutputFormat;

    match format {
        ChurnOutputFormat::Json => format_churn_as_json(analysis),
        ChurnOutputFormat::Summary => format_churn_as_summary(analysis),
        ChurnOutputFormat::Markdown => format_churn_as_markdown(analysis),
        ChurnOutputFormat::Csv => format_churn_as_csv(analysis),
    }
}