crabmate 0.5.0

Rust AI agent: OpenAI-compatible chat/completions, function calling, HTTP serve, ops CLI
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
490
491
492
493
494
495
496
497
498
//! 代码度量与分析工具:行数统计(可选 tokei / 内置 walk)、依赖图、覆盖率报告解析

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

use super::output_util;
use super::tool_param_types::{
    CodeStatsArgs, CodeStatsFormat, CoverageReportArgs, CoverageReportFormat,
};
use crate::cm_tools::project_metrics;

pub(super) const MAX_OUTPUT_LINES: usize = 600;

// ── code_stats:代码行数统计 ────────────────────────────────

pub fn code_stats(args_json: &str, workspace_root: &Path, max_output_len: usize) -> String {
    let v = match crate::cm_tools::tools::parse_args_json(args_json) {
        Ok(v) => v,
        Err(e) => return e,
    };
    let args: CodeStatsArgs = match serde_json::from_value(v) {
        Ok(a) => a,
        Err(e) => return format!("参数 JSON 与 code_stats 形状不一致: {e}"),
    };
    let path = args
        .path
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .unwrap_or(".");
    if path.contains("..") || path.starts_with('/') {
        return "错误:path 不安全(禁止 .. 与绝对路径)".to_string();
    }
    let target = workspace_root.join(path);
    if !target.exists() {
        return format!("错误:路径 {} 不存在", path);
    }

    let format = match args.format.unwrap_or_default() {
        CodeStatsFormat::Table => "table",
        CodeStatsFormat::Json => "json",
    };

    let stats = project_metrics::gather_workspace_code_stats(
        &target,
        project_metrics::DEFAULT_EXCLUDED_DIRS,
    );
    if stats.languages.is_empty() {
        return format!("路径 {} 下未找到可识别的源码文件", path);
    }

    if format == "json" {
        return format_code_stats_json(&stats, max_output_len);
    }
    format_code_stats_table(&stats, path, max_output_len)
}

fn format_code_stats_json(stats: &project_metrics::WorkspaceCodeStats, max_output_len: usize) -> String {
    let entries: Vec<serde_json::Value> = stats
        .languages
        .iter()
        .map(|lang| {
            serde_json::json!({
                "language": lang.language,
                "files": lang.files,
                "lines": lang.total_lines(),
                "blank": lang.blanks,
                "comment": lang.comments,
                "code": lang.code
            })
        })
        .collect();
    let result = serde_json::json!({
        "total_files": stats.total_files(),
        "total_lines": stats.total_lines(),
        "total_code": stats.total_code(),
        "total_comments": stats.total_comments(),
        "total_blanks": stats.total_blanks(),
        "languages": entries
    });
    match serde_json::to_string_pretty(&result) {
        Ok(s) => output_util::truncate_output_lines(&s, max_output_len, MAX_OUTPUT_LINES),
        Err(e) => format!("JSON 序列化错误:{}", e),
    }
}

fn format_code_stats_table(
    stats: &project_metrics::WorkspaceCodeStats,
    path: &str,
    max_output_len: usize,
) -> String {
    let source_label = if cfg!(feature = "project_metrics") {
        "tokei 库"
    } else {
        "内置扩展名统计"
    };
    let mut out = String::new();
    out.push_str(&format!("代码统计({}):{}\n", source_label, path));
    out.push_str(&format!(
        "{:<20} {:>6} {:>10} {:>8} {:>8} {:>8}\n",
        "Language", "Files", "Lines", "Blank", "Comment", "Code"
    ));
    out.push_str(&"-".repeat(64));
    out.push('\n');
    for lang in &stats.languages {
        out.push_str(&format!(
            "{:<20} {:>6} {:>10} {:>8} {:>8} {:>8}\n",
            lang.language,
            lang.files,
            lang.total_lines(),
            lang.blanks,
            lang.comments,
            lang.code
        ));
    }
    out.push_str(&"-".repeat(64));
    out.push('\n');
    out.push_str(&format!(
        "{:<20} {:>6} {:>10} {:>8} {:>8} {:>8}\n",
        "Total",
        stats.total_files(),
        stats.total_lines(),
        stats.total_blanks(),
        stats.total_comments(),
        stats.total_code()
    ));

    output_util::truncate_output_lines(&out, max_output_len, MAX_OUTPUT_LINES)
}

#[path = "code_metrics_dependency_graph.rs"]
mod code_metrics_dependency_graph;

pub use code_metrics_dependency_graph::dependency_graph;

// ── coverage_report:覆盖率报告解析 ────────────────────────

pub fn coverage_report(args_json: &str, workspace_root: &Path, max_output_len: usize) -> String {
    let v = match crate::cm_tools::tools::parse_args_json(args_json) {
        Ok(v) => v,
        Err(e) => return e,
    };
    let args: CoverageReportArgs = match serde_json::from_value(v) {
        Ok(a) => a,
        Err(e) => return format!("参数 JSON 与 coverage_report 形状不一致: {e}"),
    };
    let path = match args.path.as_deref().map(str::trim) {
        Some(p) if !p.is_empty() => p.to_string(),
        _ => {
            return auto_detect_coverage(workspace_root, max_output_len);
        }
    };
    if path.contains("..") || path.starts_with('/') {
        return "错误:path 不安全(禁止 .. 与绝对路径)".to_string();
    }

    let format = coverage_format_str(args.format.unwrap_or_default());
    run_coverage_parse(&path, &workspace_root.join(&path), format, max_output_len)
}

/// 读取覆盖率文件并按格式解析;未知格式时输出前 50 行预览。
fn run_coverage_parse(path: &str, full: &Path, format: &str, max_output_len: usize) -> String {
    if !full.is_file() {
        return format!("错误:覆盖率文件 {} 不存在", path);
    }

    let content = match std::fs::read_to_string(full) {
        Ok(c) => c,
        Err(e) => return format!("读取覆盖率文件失败:{}", e),
    };

    let actual_format = if format != "auto" {
        format.to_string()
    } else {
        detect_coverage_format(path, &content)
    };

    if let Some(result) = parse_coverage_by_format(&actual_format, &content, max_output_len) {
        return result;
    }
    let preview = output_util::truncate_output_lines(&content, max_output_len / 2, 50);
    format!(
        "覆盖率文件 {}(格式:{})前 50 行:\n{}",
        path, actual_format, preview
    )
}

fn coverage_format_str(format: CoverageReportFormat) -> &'static str {
    match format {
        CoverageReportFormat::Auto => "auto",
        CoverageReportFormat::Lcov => "lcov",
        CoverageReportFormat::Tarpaulin => "tarpaulin",
        CoverageReportFormat::TarpaulinJson => "tarpaulin_json",
        CoverageReportFormat::Cobertura => "cobertura",
    }
}

/// 按格式分派覆盖率解析(`coverage_report` / `auto_detect_coverage` 共用);未知格式返回 `None`。
fn parse_coverage_by_format(fmt: &str, content: &str, max_output_len: usize) -> Option<String> {
    match fmt {
        "lcov" => Some(parse_lcov(content, max_output_len)),
        "tarpaulin" | "tarpaulin_json" => Some(parse_tarpaulin_json(content, max_output_len)),
        "cobertura" => Some(parse_cobertura_summary(content, max_output_len)),
        _ => None,
    }
}

fn auto_detect_coverage(workspace_root: &Path, max_output_len: usize) -> String {
    let candidates = [
        "lcov.info",
        "coverage/lcov.info",
        "coverage.json",
        "tarpaulin-report.json",
        "coverage/tarpaulin-report.json",
        "coverage/cobertura.xml",
        "cobertura.xml",
        "coverage/coverage.json",
    ];
    for c in &candidates {
        let full = workspace_root.join(c);
        if full.is_file() {
            let content = match std::fs::read_to_string(&full) {
                Ok(s) => s,
                Err(_) => continue,
            };
            let fmt = detect_coverage_format(c, &content);
            let result = match parse_coverage_by_format(&fmt, &content, max_output_len) {
                Some(r) => r,
                None => continue,
            };
            return format!("自动检测覆盖率文件:{}\n{}", c, result);
        }
    }
    "未找到覆盖率文件。支持的文件:lcov.info、tarpaulin-report.json、cobertura.xml。请用 path 参数指定路径。".to_string()
}

fn detect_coverage_format(path: &str, content: &str) -> String {
    let lower = path.to_lowercase();
    if lower.ends_with(".info") || content.starts_with("TN:") || content.starts_with("SF:") {
        return "lcov".to_string();
    }
    if lower.ends_with(".xml") && (content.contains("<coverage") || content.contains("cobertura")) {
        return "cobertura".to_string();
    }
    if lower.ends_with(".json")
        && content.contains("\"covered\"")
        && content.contains("\"coverable\"")
    {
        return "tarpaulin".to_string();
    }
    "unknown".to_string()
}

fn parse_lcov(content: &str, max_output_len: usize) -> String {
    let mut files = parse_lcov_records(content);

    if files.is_empty() {
        return "LCOV 文件为空或解析无结果".to_string();
    }

    let total_found: usize = files.iter().map(|(_, f, _)| f).sum();
    let total_hit: usize = files.iter().map(|(_, _, h)| h).sum();
    let pct = coverage_pct(total_hit, total_found, 0.0);

    let mut out = format!(
        "LCOV 覆盖率摘要:{:.1}%({}/{} 行)\n\n",
        pct, total_hit, total_found
    );
    out.push_str(&format!(
        "{:<50} {:>8} {:>8} {:>8}\n",
        "File", "Lines", "Hit", "Pct"
    ));
    out.push_str(&"-".repeat(78));
    out.push('\n');

    files.sort_by(|a, b| {
        coverage_pct(a.2, a.1, 100.0)
            .partial_cmp(&coverage_pct(b.2, b.1, 100.0))
            .unwrap_or(std::cmp::Ordering::Equal)
    });

    for (file, found, hit) in &files {
        let fp = coverage_pct(*hit, *found, 100.0);
        let short = if file.len() > 48 {
            let suffix: String = file
                .chars()
                .rev()
                .take(45)
                .collect::<Vec<_>>()
                .into_iter()
                .rev()
                .collect();
            format!("...{}", suffix)
        } else {
            file.clone()
        };
        out.push_str(&format!(
            "{:<50} {:>8} {:>8} {:>7.1}%\n",
            short, found, hit, fp
        ));
    }

    output_util::truncate_output_lines(&out, max_output_len, MAX_OUTPUT_LINES)
}

/// 覆盖率百分比;`found == 0` 时返回 `none_default`。
fn coverage_pct(hit: usize, found: usize, none_default: f64) -> f64 {
    if found > 0 {
        hit as f64 / found as f64 * 100.0
    } else {
        none_default
    }
}

/// 解析 LCOV 的 `SF:` / `LF:` / `LH:` / `end_of_record` 记录,返回 (文件, 总行数, 命中行数)。
fn parse_lcov_records(content: &str) -> Vec<(String, usize, usize)> {
    let mut files = Vec::new();
    let mut current_file = String::new();
    let mut lines_found = 0usize;
    let mut lines_hit = 0usize;
    for line in content.lines() {
        if let Some(sf) = line.strip_prefix("SF:") {
            current_file = sf.trim().to_string();
        } else if let Some(lf) = line.strip_prefix("LF:") {
            lines_found = lf.trim().parse().unwrap_or(0);
        } else if let Some(lh) = line.strip_prefix("LH:") {
            lines_hit = lh.trim().parse().unwrap_or(0);
        } else if line == "end_of_record" {
            if !current_file.is_empty() {
                files.push((current_file.clone(), lines_found, lines_hit));
            }
            current_file.clear();
            lines_found = 0;
            lines_hit = 0;
        }
    }
    files
}

fn parse_tarpaulin_json(content: &str, max_output_len: usize) -> String {
    let v: serde_json::Value = match serde_json::from_str(content) {
        Ok(v) => v,
        Err(e) => return format!("Tarpaulin JSON 解析失败:{}", e),
    };
    let file_stats = match parse_tarpaulin_files(&v) {
        Some(fs) if !fs.is_empty() => fs,
        Some(_) => return "Tarpaulin JSON:无文件级覆盖数据".to_string(),
        None => {
            // 单文件模式:顶层 covered / coverable 直接出摘要。
            let Some(covered) = v.get("covered").and_then(|c| c.as_u64()) else {
                return "Tarpaulin JSON:无文件级覆盖数据".to_string();
            };
            let coverable = v.get("coverable").and_then(|c| c.as_u64()).unwrap_or(0);
            let pct = coverage_pct(covered as usize, coverable as usize, 0.0);
            return format!(
                "Tarpaulin 覆盖率:{:.1}%({}/{} 行)",
                pct, covered, coverable
            );
        }
    };

    let total_coverable: usize = file_stats.values().map(|(c, _)| c).sum();
    let total_covered: usize = file_stats.values().map(|(_, h)| h).sum();
    let pct = coverage_pct(total_covered, total_coverable, 0.0);

    let mut out = format!(
        "Tarpaulin 覆盖率摘要:{:.1}%({}/{} 行)\n\n",
        pct, total_covered, total_coverable
    );
    let mut sorted: Vec<_> = file_stats.into_iter().collect();
    sorted.sort_by(|a, b| {
        coverage_pct(a.1.1, a.1.0, 100.0)
            .partial_cmp(&coverage_pct(b.1.1, b.1.0, 100.0))
            .unwrap_or(std::cmp::Ordering::Equal)
    });

    for (file, (coverable, covered)) in &sorted {
        let fp = coverage_pct(*covered, *coverable, 100.0);
        let short = if file.len() > 48 {
            let suffix: String = file
                .chars()
                .rev()
                .take(45)
                .collect::<Vec<_>>()
                .into_iter()
                .rev()
                .collect();
            format!("...{}", suffix)
        } else {
            file.clone()
        };
        out.push_str(&format!("{:<50} {:.1}%\n", short, fp));
    }

    output_util::truncate_output_lines(&out, max_output_len, MAX_OUTPUT_LINES)
}

/// 从 Tarpaulin JSON 提取(path → (coverable, covered));顶层无 `files` 数组时返回 `None`。
fn parse_tarpaulin_files(v: &serde_json::Value) -> Option<HashMap<String, (usize, usize)>> {
    let files = v.get("files")?.as_array()?;
    let mut file_stats = HashMap::new();
    for f in files {
        let path = f.get("path").and_then(|p| p.as_str()).unwrap_or("?");
        let covered = f.get("covered").and_then(|c| c.as_u64()).unwrap_or(0) as usize;
        let coverable = f.get("coverable").and_then(|c| c.as_u64()).unwrap_or(0) as usize;
        file_stats.insert(path.to_string(), (coverable, covered));
    }
    Some(file_stats)
}

fn parse_cobertura_summary(content: &str, max_output_len: usize) -> String {
    let mut line_rate = None;
    let mut branch_rate = None;

    for line in content.lines().take(20) {
        if line.contains("line-rate=")
            && let Some(val) = extract_xml_attr(line, "line-rate")
        {
            line_rate = val.parse::<f64>().ok();
        }
        if line.contains("branch-rate=")
            && let Some(val) = extract_xml_attr(line, "branch-rate")
        {
            branch_rate = val.parse::<f64>().ok();
        }
        if line_rate.is_some() {
            break;
        }
    }

    match (line_rate, branch_rate) {
        (Some(lr), Some(br)) => {
            format!(
                "Cobertura 覆盖率:行覆盖 {:.1}%,分支覆盖 {:.1}%",
                lr * 100.0,
                br * 100.0
            )
        }
        (Some(lr), None) => {
            format!("Cobertura 覆盖率:行覆盖 {:.1}%", lr * 100.0)
        }
        _ => {
            let preview = output_util::truncate_output_lines(content, max_output_len / 2, 30);
            format!(
                "Cobertura XML 未找到 line-rate 属性,前 30 行:\n{}",
                preview
            )
        }
    }
}

fn extract_xml_attr<'a>(line: &'a str, attr: &str) -> Option<&'a str> {
    let needle = format!("{}=\"", attr);
    let start = line.find(&needle)? + needle.len();
    let rest = &line[start..];
    let end = rest.find('"')?;
    Some(&rest[..end])
}

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

    #[test]
    fn test_detect_lcov() {
        assert_eq!(detect_coverage_format("lcov.info", "TN:\nSF:foo"), "lcov");
        assert_eq!(detect_coverage_format("x.info", "SF:bar"), "lcov");
    }

    #[test]
    fn test_detect_tarpaulin() {
        let content = r#"{"covered":10,"coverable":20}"#;
        assert_eq!(detect_coverage_format("report.json", content), "tarpaulin");
    }

    #[test]
    fn test_parse_lcov_basic() {
        let lcov = "TN:\nSF:src/main.rs\nLF:100\nLH:80\nend_of_record\n";
        let result = parse_lcov(lcov, 10000);
        assert!(result.contains("80.0%"));
        assert!(result.contains("main.rs"));
    }

    #[test]
    fn test_extract_xml_attr() {
        let line = r#"<coverage line-rate="0.85" branch-rate="0.70">"#;
        assert_eq!(extract_xml_attr(line, "line-rate"), Some("0.85"));
        assert_eq!(extract_xml_attr(line, "branch-rate"), Some("0.70"));
    }

    #[test]
    fn test_cobertura_summary() {
        let xml = r#"<?xml version="1.0"?><coverage line-rate="0.85" branch-rate="0.70">"#;
        let result = parse_cobertura_summary(xml, 10000);
        assert!(result.contains("85.0%"));
        assert!(result.contains("70.0%"));
    }
}