-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodemetrics.py
More file actions
executable file
·1693 lines (1428 loc) · 56.8 KB
/
Copy pathcodemetrics.py
File metadata and controls
executable file
·1693 lines (1428 loc) · 56.8 KB
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CodeMetrics - 代码度量分析工具
一个功能丰富的代码度量工具,提供:
- 目录树结构展示
- 代码行/注释行/空行统计
- 多语言支持
- COCOMO 成本估算
- 代码健康度分析
Author: CodeMetrics Team
License: MIT
Version: 1.1.0
"""
import os
import sys
import argparse
import json
from dataclasses import dataclass, field, asdict
from typing import List, Dict, Optional, Tuple
from pathlib import Path
from collections import defaultdict
import time
import fnmatch
from datetime import datetime
# ============================================================================
# 版本信息
# ============================================================================
__version__ = "1.1.0"
__author__ = "CodeMetrics Team"
# ============================================================================
# 默认配置
# ============================================================================
DEFAULT_CONFIG = {
"name": "CodeMetrics 配置文件",
"version": "1.0",
# 输出设置
"output": {
"dir": "codemetrics_output", # 输出目录名
"formats": ["terminal", "json", "markdown", "html"], # 输出格式
"auto_open": False, # 是否自动打开 HTML 报告
},
# 排除规则
"exclude": {
"patterns": [
"docs/*",
"*.md",
"*.json",
"*.html",
"*.txt",
"*.pdf",
"*.png",
"*.jpg",
"*.gif",
],
"dirs": [
".git",
".svn",
"node_modules",
"__pycache__",
"build",
"dist",
".venv",
"venv",
],
},
# COCOMO 设置
"cocomo": {
"project_type": "semi-detached", # organic / semi-detached / embedded
"cost_per_month_usd": 5000,
"cost_per_month_cny": 30000,
},
# 健康度阈值
"health": {
"comment_ratio_min": 0.15,
"comment_ratio_max": 0.30,
"avg_file_lines_min": 100,
"avg_file_lines_max": 500,
"large_file_threshold": 800,
"low_comment_threshold": 0.05,
},
# 显示选项
"display": {
"show_tree": True,
"show_cocomo": True,
"show_health": True,
"top_n": 10,
"use_colors": True,
},
}
CONFIG_FILENAME = ".codemetrics.json"
GLOBAL_CONFIG_FILENAME = "config.json" # 工具目录下的全局配置
# ============================================================================
# 颜色定义 (ANSI)
# ============================================================================
class Colors:
"""终端颜色"""
RESET = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"
# 前景色
RED = "\033[31m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
BLUE = "\033[34m"
MAGENTA = "\033[35m"
CYAN = "\033[36m"
WHITE = "\033[37m"
# 亮色
BRIGHT_RED = "\033[91m"
BRIGHT_GREEN = "\033[92m"
BRIGHT_YELLOW = "\033[93m"
BRIGHT_BLUE = "\033[94m"
BRIGHT_MAGENTA = "\033[95m"
BRIGHT_CYAN = "\033[96m"
# 是否启用颜色
USE_COLORS = sys.stdout.isatty()
def color(text: str, c: str) -> str:
"""给文本添加颜色"""
if USE_COLORS:
return f"{c}{text}{Colors.RESET}"
return text
# ============================================================================
# 语言定义
# ============================================================================
LANGUAGE_EXTENSIONS = {
# 系统编程
'.c': 'C',
'.h': 'C/C++ Header',
'.cpp': 'C++',
'.cc': 'C++',
'.cxx': 'C++',
'.hpp': 'C++ Header',
'.hxx': 'C++ Header',
'.rs': 'Rust',
'.go': 'Go',
'.asm': 'Assembly',
'.s': 'Assembly',
'.S': 'Assembly',
# 脚本语言
'.py': 'Python',
'.pyw': 'Python',
'.rb': 'Ruby',
'.pl': 'Perl',
'.pm': 'Perl',
'.sh': 'Shell',
'.bash': 'Bash',
'.zsh': 'Zsh',
'.fish': 'Fish',
'.lua': 'Lua',
'.tcl': 'Tcl',
'.awk': 'AWK',
# Web 前端
'.js': 'JavaScript',
'.mjs': 'JavaScript',
'.ts': 'TypeScript',
'.jsx': 'React JSX',
'.tsx': 'React TSX',
'.html': 'HTML',
'.htm': 'HTML',
'.css': 'CSS',
'.scss': 'SCSS',
'.sass': 'Sass',
'.less': 'Less',
'.vue': 'Vue',
'.svelte': 'Svelte',
# JVM
'.java': 'Java',
'.kt': 'Kotlin',
'.kts': 'Kotlin',
'.scala': 'Scala',
'.groovy': 'Groovy',
'.clj': 'Clojure',
# .NET
'.cs': 'C#',
'.fs': 'F#',
'.vb': 'Visual Basic',
# 函数式
'.hs': 'Haskell',
'.ml': 'OCaml',
'.mli': 'OCaml',
'.erl': 'Erlang',
'.ex': 'Elixir',
'.exs': 'Elixir',
# 配置
'.json': 'JSON',
'.yaml': 'YAML',
'.yml': 'YAML',
'.toml': 'TOML',
'.xml': 'XML',
'.ini': 'INI',
'.cfg': 'Config',
'.conf': 'Config',
'.properties': 'Properties',
# 文档
'.md': 'Markdown',
'.markdown': 'Markdown',
'.rst': 'reStructuredText',
'.txt': 'Text',
'.tex': 'LaTeX',
# 数据库
'.sql': 'SQL',
# DevOps
'.dockerfile': 'Dockerfile',
'.tf': 'Terraform',
'.hcl': 'HCL',
# 其他
'.r': 'R',
'.R': 'R',
'.m': 'MATLAB/Objective-C',
'.swift': 'Swift',
'.dart': 'Dart',
'.php': 'PHP',
'.proto': 'Protocol Buffers',
'.thrift': 'Thrift',
}
# 特殊文件名
SPECIAL_FILES = {
'Makefile': 'Makefile',
'makefile': 'Makefile',
'GNUmakefile': 'Makefile',
'Dockerfile': 'Dockerfile',
'dockerfile': 'Dockerfile',
'Kconfig': 'Kconfig',
'CMakeLists.txt': 'CMake',
'meson.build': 'Meson',
'BUILD': 'Bazel',
'BUILD.bazel': 'Bazel',
'WORKSPACE': 'Bazel',
'Cargo.toml': 'Cargo',
'go.mod': 'Go Module',
'package.json': 'npm',
'requirements.txt': 'pip',
'Gemfile': 'Ruby Gems',
'.gitignore': 'Git Config',
'.gitattributes': 'Git Config',
}
# 注释风格
COMMENT_STYLES = {
'C': {'line': '//', 'block_start': '/*', 'block_end': '*/'},
'C/C++ Header': {'line': '//', 'block_start': '/*', 'block_end': '*/'},
'C++': {'line': '//', 'block_start': '/*', 'block_end': '*/'},
'C++ Header': {'line': '//', 'block_start': '/*', 'block_end': '*/'},
'Java': {'line': '//', 'block_start': '/*', 'block_end': '*/'},
'JavaScript': {'line': '//', 'block_start': '/*', 'block_end': '*/'},
'TypeScript': {'line': '//', 'block_start': '/*', 'block_end': '*/'},
'Go': {'line': '//', 'block_start': '/*', 'block_end': '*/'},
'Rust': {'line': '//', 'block_start': '/*', 'block_end': '*/'},
'Swift': {'line': '//', 'block_start': '/*', 'block_end': '*/'},
'Kotlin': {'line': '//', 'block_start': '/*', 'block_end': '*/'},
'Scala': {'line': '//', 'block_start': '/*', 'block_end': '*/'},
'C#': {'line': '//', 'block_start': '/*', 'block_end': '*/'},
'PHP': {'line': '//', 'block_start': '/*', 'block_end': '*/'},
'Dart': {'line': '//', 'block_start': '/*', 'block_end': '*/'},
'Python': {'line': '#', 'block_start': '"""', 'block_end': '"""'},
'Ruby': {'line': '#', 'block_start': '=begin', 'block_end': '=end'},
'Shell': {'line': '#', 'block_start': None, 'block_end': None},
'Bash': {'line': '#', 'block_start': None, 'block_end': None},
'Perl': {'line': '#', 'block_start': '=pod', 'block_end': '=cut'},
'R': {'line': '#', 'block_start': None, 'block_end': None},
'YAML': {'line': '#', 'block_start': None, 'block_end': None},
'TOML': {'line': '#', 'block_start': None, 'block_end': None},
'Makefile': {'line': '#', 'block_start': None, 'block_end': None},
'Dockerfile': {'line': '#', 'block_start': None, 'block_end': None},
'Kconfig': {'line': '#', 'block_start': None, 'block_end': None},
'HTML': {'line': None, 'block_start': '<!--', 'block_end': '-->'},
'XML': {'line': None, 'block_start': '<!--', 'block_end': '-->'},
'CSS': {'line': None, 'block_start': '/*', 'block_end': '*/'},
'SCSS': {'line': '//', 'block_start': '/*', 'block_end': '*/'},
'SQL': {'line': '--', 'block_start': '/*', 'block_end': '*/'},
'Lua': {'line': '--', 'block_start': '--[[', 'block_end': ']]'},
'Haskell': {'line': '--', 'block_start': '{-', 'block_end': '-}'},
'Lisp': {'line': ';', 'block_start': None, 'block_end': None},
'Clojure': {'line': ';', 'block_start': None, 'block_end': None},
'Assembly': {'line': ';', 'block_start': None, 'block_end': None},
}
# 默认注释风格
DEFAULT_COMMENT_STYLE = {'line': '#', 'block_start': None, 'block_end': None}
# ============================================================================
# COCOMO 模型参数
# ============================================================================
COCOMO_PARAMS = {
'organic': {'a': 2.4, 'b': 1.05, 'c': 2.5, 'd': 0.38, 'desc': '简单项目'},
'semi-detached': {'a': 3.0, 'b': 1.12, 'c': 2.5, 'd': 0.35, 'desc': '中等项目'},
'embedded': {'a': 3.6, 'b': 1.20, 'c': 2.5, 'd': 0.32, 'desc': '复杂/嵌入式'},
}
COST_PER_PERSON_MONTH_USD = 5000
COST_PER_PERSON_MONTH_CNY = 30000
# ============================================================================
# 数据结构
# ============================================================================
@dataclass
class FileStats:
"""单个文件的统计信息"""
path: str
name: str
language: str
size: int
total_lines: int
code_lines: int
comment_lines: int
blank_lines: int
@dataclass
class DirStats:
"""目录的汇总统计"""
path: str
name: str
file_count: int = 0
dir_count: int = 0
total_size: int = 0
total_lines: int = 0
code_lines: int = 0
comment_lines: int = 0
blank_lines: int = 0
children: List = field(default_factory=list)
@dataclass
class LanguageStats:
"""按语言的汇总统计"""
language: str
file_count: int = 0
total_lines: int = 0
code_lines: int = 0
comment_lines: int = 0
blank_lines: int = 0
total_size: int = 0
# ============================================================================
# 核心功能
# ============================================================================
def detect_language(file_path: str) -> str:
"""检测文件的编程语言"""
name = os.path.basename(file_path)
# 检查特殊文件名
if name in SPECIAL_FILES:
return SPECIAL_FILES[name]
# 检查扩展名
ext = os.path.splitext(name)[1].lower()
if ext in LANGUAGE_EXTENSIONS:
return LANGUAGE_EXTENSIONS[ext]
# 检查 shebang
try:
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
first_line = f.readline()
if first_line.startswith('#!'):
if 'python' in first_line:
return 'Python'
elif 'bash' in first_line or 'sh' in first_line:
return 'Shell'
elif 'ruby' in first_line:
return 'Ruby'
elif 'perl' in first_line:
return 'Perl'
elif 'node' in first_line:
return 'JavaScript'
except:
pass
return 'Unknown'
def count_lines(file_path: str, language: str) -> Tuple[int, int, int, int]:
"""
统计文件行数
Returns:
(total_lines, code_lines, comment_lines, blank_lines)
"""
style = COMMENT_STYLES.get(language, DEFAULT_COMMENT_STYLE)
total = 0
code = 0
comment = 0
blank = 0
in_block_comment = False
try:
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
for line in f:
total += 1
stripped = line.strip()
# 空行
if not stripped:
blank += 1
continue
# 块注释处理
if in_block_comment:
comment += 1
if style['block_end'] and style['block_end'] in stripped:
in_block_comment = False
continue
# 检查块注释开始
if style['block_start'] and style['block_start'] in stripped:
# 检查是否同行结束
if style['block_end'] and style['block_end'] in stripped:
# 同行开始和结束,如 /* comment */
idx_start = stripped.find(style['block_start'])
idx_end = stripped.find(style['block_end'])
if idx_end > idx_start:
# 检查块注释外是否有代码
before = stripped[:idx_start].strip()
after = stripped[idx_end + len(style['block_end']):].strip()
if before or after:
code += 1
else:
comment += 1
continue
else:
in_block_comment = True
# 检查块注释开始前是否有代码
idx = stripped.find(style['block_start'])
if stripped[:idx].strip():
code += 1
else:
comment += 1
continue
# 行注释
if style['line'] and stripped.startswith(style['line']):
comment += 1
continue
# 代码行
code += 1
except Exception as e:
# 无法读取的文件
pass
return total, code, comment, blank
def get_file_size(file_path: str) -> int:
"""获取文件大小"""
try:
return os.path.getsize(file_path)
except:
return 0
def format_size(size: int) -> str:
"""格式化文件大小"""
if size < 1024:
return f"{size} B"
elif size < 1024 * 1024:
return f"{size / 1024:.1f} KB"
elif size < 1024 * 1024 * 1024:
return f"{size / (1024 * 1024):.1f} MB"
else:
return f"{size / (1024 * 1024 * 1024):.1f} GB"
def format_number(num: int) -> str:
"""格式化数字,添加千位分隔符"""
return f"{num:,}"
def should_ignore(path: str, ignore_patterns: List[str]) -> bool:
"""检查路径是否应该被忽略"""
name = os.path.basename(path)
# 默认忽略
default_ignore = [
'.git', '.svn', '.hg', '.bzr',
'__pycache__', '.pytest_cache', '.mypy_cache',
'node_modules', 'bower_components',
'.idea', '.vscode', '.vs',
'venv', '.venv', 'env', '.env',
'build', 'dist', 'target', 'out',
'*.pyc', '*.pyo', '*.o', '*.obj', '*.ko',
'*.so', '*.dll', '*.dylib', '*.a', '*.lib',
'*.exe', '*.bin',
'*.jpg', '*.jpeg', '*.png', '*.gif', '*.ico',
'*.pdf', '*.doc', '*.docx',
'*.zip', '*.tar', '*.gz', '*.rar',
]
all_patterns = default_ignore + ignore_patterns
for pattern in all_patterns:
if fnmatch.fnmatch(name, pattern):
return True
return False
def is_text_file(file_path: str) -> bool:
"""检查是否是文本文件"""
# 通过扩展名快速判断
ext = os.path.splitext(file_path)[1].lower()
if ext in LANGUAGE_EXTENSIONS:
return True
name = os.path.basename(file_path)
if name in SPECIAL_FILES:
return True
# 尝试读取
try:
with open(file_path, 'rb') as f:
chunk = f.read(1024)
if b'\x00' in chunk: # 二进制文件
return False
return True
except:
return False
def scan_file(file_path: str) -> Optional[FileStats]:
"""扫描单个文件"""
if not is_text_file(file_path):
return None
language = detect_language(file_path)
if language == 'Unknown':
return None
size = get_file_size(file_path)
total, code, comment, blank = count_lines(file_path, language)
return FileStats(
path=file_path,
name=os.path.basename(file_path),
language=language,
size=size,
total_lines=total,
code_lines=code,
comment_lines=comment,
blank_lines=blank,
)
def scan_directory(dir_path: str, ignore_patterns: List[str] = None) -> DirStats:
"""递归扫描目录"""
if ignore_patterns is None:
ignore_patterns = []
dir_stats = DirStats(
path=dir_path,
name=os.path.basename(dir_path) or dir_path,
)
try:
entries = sorted(os.listdir(dir_path))
except PermissionError:
return dir_stats
for entry in entries:
entry_path = os.path.join(dir_path, entry)
if should_ignore(entry_path, ignore_patterns):
continue
if os.path.isdir(entry_path):
# 递归扫描子目录
sub_stats = scan_directory(entry_path, ignore_patterns)
if sub_stats.file_count > 0: # 只保留有文件的目录
dir_stats.children.append(sub_stats)
dir_stats.dir_count += 1 + sub_stats.dir_count
dir_stats.file_count += sub_stats.file_count
dir_stats.total_size += sub_stats.total_size
dir_stats.total_lines += sub_stats.total_lines
dir_stats.code_lines += sub_stats.code_lines
dir_stats.comment_lines += sub_stats.comment_lines
dir_stats.blank_lines += sub_stats.blank_lines
else:
# 扫描文件
file_stats = scan_file(entry_path)
if file_stats:
dir_stats.children.append(file_stats)
dir_stats.file_count += 1
dir_stats.total_size += file_stats.size
dir_stats.total_lines += file_stats.total_lines
dir_stats.code_lines += file_stats.code_lines
dir_stats.comment_lines += file_stats.comment_lines
dir_stats.blank_lines += file_stats.blank_lines
return dir_stats
def collect_by_language(dir_stats: DirStats) -> Dict[str, LanguageStats]:
"""按语言收集统计"""
lang_stats = defaultdict(lambda: LanguageStats(language=''))
def collect(node):
if isinstance(node, FileStats):
lang = node.language
if not lang_stats[lang].language:
lang_stats[lang].language = lang
lang_stats[lang].file_count += 1
lang_stats[lang].total_lines += node.total_lines
lang_stats[lang].code_lines += node.code_lines
lang_stats[lang].comment_lines += node.comment_lines
lang_stats[lang].blank_lines += node.blank_lines
lang_stats[lang].total_size += node.size
elif isinstance(node, DirStats):
for child in node.children:
collect(child)
collect(dir_stats)
return dict(lang_stats)
def collect_all_files(dir_stats: DirStats) -> List[FileStats]:
"""收集所有文件"""
files = []
def collect(node):
if isinstance(node, FileStats):
files.append(node)
elif isinstance(node, DirStats):
for child in node.children:
collect(child)
collect(dir_stats)
return files
def calculate_cocomo(code_lines: int, project_type: str = 'semi-detached') -> Dict:
"""计算 COCOMO 估算"""
if code_lines == 0:
return {
'kloc': 0,
'person_months': 0,
'duration_months': 0,
'team_size': 0,
'cost_usd': 0,
'cost_cny': 0,
'project_type': project_type,
}
kloc = code_lines / 1000
params = COCOMO_PARAMS.get(project_type, COCOMO_PARAMS['semi-detached'])
person_months = params['a'] * (kloc ** params['b'])
duration_months = params['c'] * (person_months ** params['d'])
team_size = person_months / duration_months if duration_months > 0 else 0
return {
'kloc': round(kloc, 2),
'person_months': round(person_months, 1),
'duration_months': round(duration_months, 1),
'team_size': round(team_size, 1),
'cost_usd': int(person_months * COST_PER_PERSON_MONTH_USD),
'cost_cny': int(person_months * COST_PER_PERSON_MONTH_CNY),
'project_type': project_type,
'project_type_desc': params['desc'],
}
def calculate_health(dir_stats: DirStats, all_files: List[FileStats]) -> Dict:
"""计算代码健康度指标"""
metrics = {}
# 注释率
if dir_stats.code_lines > 0:
ratio = dir_stats.comment_lines / dir_stats.code_lines
metrics['comment_ratio'] = {
'value': round(ratio * 100, 1),
'unit': '%',
'status': 'good' if 0.15 <= ratio <= 0.30 else
'warning' if 0.10 <= ratio <= 0.40 else 'bad',
'desc': '注释率 (建议 15-30%)',
}
# 平均文件行数
if dir_stats.file_count > 0:
avg = dir_stats.total_lines / dir_stats.file_count
metrics['avg_file_lines'] = {
'value': int(avg),
'unit': '行',
'status': 'good' if 100 <= avg <= 500 else
'warning' if 50 <= avg <= 800 else 'bad',
'desc': '平均文件行数 (建议 100-500)',
}
# 代码密度
if dir_stats.total_lines > 0:
density = dir_stats.code_lines / dir_stats.total_lines
metrics['code_density'] = {
'value': round(density * 100, 1),
'unit': '%',
'status': 'info',
'desc': '代码密度 (代码行/总行)',
}
# 大文件警告
large_files = [f for f in all_files if f.code_lines > 800]
metrics['large_files'] = {
'value': len(large_files),
'unit': '个',
'status': 'warning' if large_files else 'good',
'desc': '大文件 (>800行代码)',
'files': [{'path': f.path, 'lines': f.code_lines} for f in large_files[:5]],
}
# 低注释文件
low_comment_files = [f for f in all_files
if f.code_lines > 100 and
f.comment_lines / f.code_lines < 0.05 if f.code_lines > 0]
metrics['low_comment_files'] = {
'value': len(low_comment_files),
'unit': '个',
'status': 'warning' if low_comment_files else 'good',
'desc': '低注释文件 (<5%注释)',
'files': [{'path': f.path, 'ratio': round(f.comment_lines/f.code_lines*100, 1) if f.code_lines > 0 else 0}
for f in low_comment_files[:5]],
}
return metrics
# ============================================================================
# 输出格式化
# ============================================================================
def generate_tree_text(node, prefix: str = "", is_last: bool = True) -> List[str]:
"""生成目录树的纯文本(用于保存到文件)"""
lines = []
connector = "└── " if is_last else "├── "
if isinstance(node, DirStats):
# 目录
stats = f"[{node.file_count} files | {format_number(node.code_lines)} code | {format_size(node.total_size)}]"
lines.append(f"{prefix}{connector}📁 {node.name}/ {stats}")
# 子项
new_prefix = prefix + (" " if is_last else "│ ")
children = node.children
for i, child in enumerate(children):
lines.extend(generate_tree_text(child, new_prefix, i == len(children) - 1))
else:
# 文件
stats = f"[{node.code_lines}|{node.comment_lines}|{node.blank_lines}]"
lines.append(f"{prefix}{connector}📄 {node.name} [{node.language}] {stats} {format_size(node.size)}")
return lines
def print_tree(node, prefix: str = "", is_last: bool = True, show_details: bool = True):
"""打印目录树"""
connector = "└── " if is_last else "├── "
if isinstance(node, DirStats):
# 目录
icon = "📁"
name = color(node.name + "/", Colors.BRIGHT_BLUE + Colors.BOLD)
stats = color(f"[{node.file_count} files | {format_number(node.code_lines)} code | {format_size(node.total_size)}]", Colors.DIM)
print(f"{prefix}{connector}{icon} {name} {stats}")
# 子项
new_prefix = prefix + (" " if is_last else "│ ")
children = node.children
for i, child in enumerate(children):
print_tree(child, new_prefix, i == len(children) - 1, show_details)
else:
# 文件
icon = "📄"
name = node.name
lang = color(f"[{node.language}]", Colors.CYAN)
if show_details:
stats = color(f"[{node.code_lines}|{node.comment_lines}|{node.blank_lines}]", Colors.DIM)
size = color(format_size(node.size), Colors.DIM)
print(f"{prefix}{connector}{icon} {name} {lang} {stats} {size}")
else:
print(f"{prefix}{connector}{icon} {name} {lang}")
def print_language_table(lang_stats: Dict[str, LanguageStats]):
"""打印语言统计表格(简洁版)"""
# 排序:按代码行数降序
sorted_langs = sorted(lang_stats.values(), key=lambda x: x.code_lines, reverse=True)
# 计算总计
total = LanguageStats(language='Total')
for ls in sorted_langs:
total.file_count += ls.file_count
total.total_lines += ls.total_lines
total.code_lines += ls.code_lines
total.comment_lines += ls.comment_lines
total.blank_lines += ls.blank_lines
total.total_size += ls.total_size
print()
print(color("Language Statistics", Colors.BOLD + Colors.CYAN))
print(color("=" * 95, Colors.DIM))
# 表头
header = f"{'Language':<18} {'Files':>8} {'Code':>12} {'Comment':>12} {'Blank':>10} {'Total':>12} {'Size':>12}"
print(color(header, Colors.BOLD))
print(color("-" * 95, Colors.DIM))
# 数据行
for ls in sorted_langs:
row = f"{ls.language:<18} {ls.file_count:>8} {ls.code_lines:>12,} {ls.comment_lines:>12,} {ls.blank_lines:>10,} {ls.total_lines:>12,} {format_size(ls.total_size):>12}"
print(row)
# 总计行
print(color("-" * 95, Colors.DIM))
total_row = f"{total.language:<18} {total.file_count:>8} {total.code_lines:>12,} {total.comment_lines:>12,} {total.blank_lines:>10,} {total.total_lines:>12,} {format_size(total.total_size):>12}"
print(color(total_row, Colors.BOLD + Colors.GREEN))
print(color("=" * 95, Colors.DIM))
def print_cocomo(cocomo: Dict):
"""打印 COCOMO 估算"""
print()
print(color("COCOMO Cost Estimation", Colors.BOLD + Colors.YELLOW))
print(color("=" * 60, Colors.DIM))
print(f" Code Size: {cocomo['kloc']:,.2f} KLOC ({int(cocomo['kloc'] * 1000):,} lines)")
print(f" Project Type: {cocomo['project_type_desc']} ({cocomo['project_type']})")
print(color("-" * 60, Colors.DIM))
print(f" Duration: {cocomo['duration_months']:.1f} months")
print(f" Team Size: {cocomo['team_size']:.1f} persons")
print(f" Person-Months: {cocomo['person_months']:.1f} PM")
print(color("-" * 60, Colors.DIM))
print(color(f" Cost (USD): ${cocomo['cost_usd']:,}", Colors.GREEN))
print(color(f" Cost (CNY): {cocomo['cost_cny']:,} CNY", Colors.GREEN))
print(color("=" * 60, Colors.DIM))
def print_health(health: Dict):
"""打印健康度指标"""
print()
print(color("Code Health Metrics", Colors.BOLD + Colors.MAGENTA))
print(color("=" * 60, Colors.DIM))
status_icons = {'good': '[OK]', 'warning': '[WARN]', 'bad': '[BAD]', 'info': '[INFO]'}
status_colors = {'good': Colors.GREEN, 'warning': Colors.YELLOW, 'bad': Colors.RED, 'info': Colors.CYAN}
for key, metric in health.items():
icon = status_icons[metric['status']]
clr = status_colors[metric['status']]
line = f" {icon:<8} {metric['desc']}: {metric['value']} {metric['unit']}"
print(color(line, clr))
if key in ['large_files', 'low_comment_files'] and metric['value'] > 0:
for f in metric.get('files', [])[:3]:
if 'lines' in f:
file_line = f" - {os.path.basename(f['path'])} ({f['lines']} lines)"
else:
file_line = f" - {os.path.basename(f['path'])} ({f['ratio']}%)"
print(color(file_line, Colors.DIM))
print(color("=" * 60, Colors.DIM))
def print_top_files(all_files: List[FileStats], n: int = 10):
"""打印 Top N 文件"""
print()
print(color(f"Top {n} Files (by code lines)", Colors.BOLD))
print(color("=" * 80, Colors.DIM))
sorted_files = sorted(all_files, key=lambda x: x.code_lines, reverse=True)[:n]
for i, f in enumerate(sorted_files, 1):
ratio = f.comment_lines / f.code_lines * 100 if f.code_lines > 0 else 0
print(f" {i:2}. {os.path.basename(f.path)}")
print(color(f" {f.language} | {f.code_lines:,} 代码行 | {f.comment_lines:,} 注释行 ({ratio:.1f}%) | {format_size(f.size)}", Colors.DIM))
def generate_json(dir_stats: DirStats, lang_stats: Dict, cocomo: Dict, health: Dict) -> str:
"""生成 JSON 输出"""
def node_to_dict(node):
if isinstance(node, FileStats):
return asdict(node)
elif isinstance(node, DirStats):
d = {
'path': node.path,
'name': node.name,
'type': 'directory',
'file_count': node.file_count,
'dir_count': node.dir_count,
'total_size': node.total_size,
'total_lines': node.total_lines,
'code_lines': node.code_lines,
'comment_lines': node.comment_lines,
'blank_lines': node.blank_lines,
'children': [node_to_dict(c) for c in node.children],
}
return d
result = {
'tree': node_to_dict(dir_stats),
'by_language': {k: asdict(v) for k, v in lang_stats.items()},
'cocomo': cocomo,
'health': health,
}
return json.dumps(result, indent=2, ensure_ascii=False)
def generate_markdown(dir_stats: DirStats, lang_stats: Dict, cocomo: Dict, health: Dict, all_files: List[FileStats] = None) -> str:
"""生成 Markdown 输出"""
lines = []
lines.append(f"# 📊 代码统计报告: {dir_stats.name}")
lines.append("")
lines.append(f"> 生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
lines.append("")
lines.append("## 📋 概览")
lines.append("")
lines.append(f"| 指标 | 数值 |")
lines.append(f"|------|------|")
lines.append(f"| 文件数 | {dir_stats.file_count} |")
lines.append(f"| 代码行 | {dir_stats.code_lines:,} |")
lines.append(f"| 注释行 | {dir_stats.comment_lines:,} |")
lines.append(f"| 空行 | {dir_stats.blank_lines:,} |")
lines.append(f"| 总行数 | {dir_stats.total_lines:,} |")
lines.append(f"| 总大小 | {format_size(dir_stats.total_size)} |")
lines.append("")
# 目录树
lines.append("## 📂 目录结构")
lines.append("")
lines.append("> 📖 图例: `[代码行|注释行|空行]`")
lines.append("")
lines.append("```")
tree_lines = generate_tree_text(dir_stats)
lines.extend(tree_lines)
lines.append("```")
lines.append("")
# 语言统计
lines.append("## 📊 语言统计")
lines.append("")
lines.append("| 语言 | 文件 | 代码行 | 注释行 | 空行 | 总大小 |")
lines.append("|------|------|--------|--------|------|--------|")
sorted_langs = sorted(lang_stats.values(), key=lambda x: x.code_lines, reverse=True)
for ls in sorted_langs:
lines.append(f"| {ls.language} | {ls.file_count} | {ls.code_lines:,} | {ls.comment_lines:,} | {ls.blank_lines:,} | {format_size(ls.total_size)} |")
# 总计
lines.append(f"| **总计** | **{dir_stats.file_count}** | **{dir_stats.code_lines:,}** | **{dir_stats.comment_lines:,}** | **{dir_stats.blank_lines:,}** | **{format_size(dir_stats.total_size)}** |")
lines.append("")
# COCOMO
lines.append("## 💰 开发成本估算 (COCOMO)")
lines.append("")
lines.append(f"| 指标 | 数值 |")
lines.append(f"|------|------|")
lines.append(f"| 代码规模 | {cocomo['kloc']:.2f} KLOC ({int(cocomo['kloc']*1000):,} 行) |")
lines.append(f"| 项目类型 | {cocomo['project_type_desc']} ({cocomo['project_type']}) |")
lines.append(f"| 预估工期 | {cocomo['duration_months']:.1f} 个月 |")
lines.append(f"| 建议团队 | {cocomo['team_size']:.1f} 人 |")
lines.append(f"| 总人月数 | {cocomo['person_months']:.1f} 人月 |")
lines.append(f"| 成本 (USD) | ${cocomo['cost_usd']:,} |")
lines.append(f"| 成本 (CNY) | ¥{cocomo['cost_cny']:,} |")
lines.append("")
# 健康度
lines.append("## 🏥 代码健康度")
lines.append("")
lines.append("| 指标 | 数值 | 状态 |")
lines.append("|------|------|------|")