-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodeboard.py
More file actions
executable file
·3458 lines (3051 loc) · 138 KB
/
codeboard.py
File metadata and controls
executable file
·3458 lines (3051 loc) · 138 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
"""CodeBoard — Git repository dashboard for your local codebase."""
__version__ = "0.2.0"
import argparse
import json
import locale
import os
import shutil
import signal
import subprocess
import sys
import time
import tomllib
from collections import Counter
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timezone
from pathlib import Path
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.text import Text
from rich import box
# ── Configuration ──────────────────────────────────────────────────────────────
CONFIG_DIR = Path.home() / ".config" / "codeboard"
CONFIG_FILE = CONFIG_DIR / "config.toml"
_DEFAULT_CONFIG = {
"scan_dir": str(Path.home() / "Code"),
"extra_repos": [],
"lang": "auto",
"obsidian_vault": "",
"gitnexus_bin": "",
}
def _load_config() -> dict:
cfg = dict(_DEFAULT_CONFIG)
if CONFIG_FILE.is_file():
with open(CONFIG_FILE, "rb") as f:
cfg.update(tomllib.load(f))
return cfg
def _generate_default_config() -> str:
return """\
# CodeBoard configuration
# See: https://github.com/shaoyiyang/codeboard
# Directory to scan for git repositories
scan_dir = "~/Code"
# Additional individual repos to include (outside scan_dir)
extra_repos = []
# UI language: "auto", "en", or "zh"
lang = "auto"
# Path to Obsidian vault (for 'doc' command, optional)
# obsidian_vault = "~/Documents/Obsidian Vault"
# Path to gitnexus binary (for 'graph' command, optional)
# gitnexus_bin = ""
"""
CFG = _load_config()
# Derive globals from config
DEFAULT_CODE_DIR = Path(CFG["scan_dir"]).expanduser()
EXTRA_REPOS = [Path(p).expanduser() for p in CFG["extra_repos"]]
OBSIDIAN_VAULT = Path(CFG["obsidian_vault"]).expanduser() if CFG["obsidian_vault"] else Path.home() / "Documents" / "Obsidian Vault"
GITNEXUS_BIN = CFG["gitnexus_bin"] or ""
# ── i18n ───────────────────────────────────────────────────────────────────────
_I18N: dict[str, dict[str, str]] = {
"en": {
# relative time
"just_now": "just now", "secs_ago": "{n}s ago", "mins_ago": "{n}m ago",
"hours_ago": "{n}h ago", "days_ago": "{n}d ago", "months_ago": "{n}mo ago",
"years_ago": "{n}y ago", "no_commits": "no commits",
# dashboard
"col_name": "Name", "col_branch": "Branch", "col_last_commit": "Last Commit",
"col_status": "Status", "col_language": "Language", "col_commits": "Commits",
"col_remote": "Remote", "dashboard_sub": "● = uncommitted ✓ = clean",
# activity
"col_time": "Time", "col_repo": "Repo", "col_author": "Author", "col_message": "Message",
# health
"health_dirty": " ⚠ Uncommitted changes", "health_ahead": " ⚠ Unpushed commits",
"health_behind": " ⚠ Behind remote", "health_no_remote": " ○ No remote",
"health_inactive": " ○ Inactive >30d", "health_ok": " ✓ All clean",
# detail
"lbl_path": "Path", "lbl_remote": "Remote", "lbl_branch": "Branch", "lbl_tags": "Tags",
"lbl_commits": "Commits", "lbl_contribs": "Contributors", "lbl_lang": "Language",
"lbl_status": "Status", "lbl_recent": "Recent commits", "lbl_activity": "Activity",
"none": "none", "this_week": "this week", "this_month": "this month",
# stats
"total_repos": "Total repos", "active_30d": "Active(30d)", "has_remote": "Has remote",
"total_commits": "Total commits", "lang_dist": "Language distribution",
"week_top": "Weekly top", "remote_dist": "Remote distribution",
# dirty / each
"all_clean": "All repos are clean", "col_changes": "Changes",
"dirty_title": "Repos with uncommitted changes ({n})",
"dirty_prompt": "Enter number to open with lazygit, Enter to exit",
"invalid_num": "Invalid number",
"processing_n": "Processing {n} dirty repos one by one",
"each_hint": "Close lazygit → next repo, Ctrl+C to exit",
"interrupted": "Interrupted", "all_done": "All done",
# pull / push
"no_remote_repos": "No repos with remote configured",
"pull_prep": "Pulling {n} repos with remote",
"updated_n": " ✓ Updated ({n})", "failed_n": " ✗ Failed ({n})",
"up_to_date_n": " ─ Up to date ({n})",
"no_push_needed": "No repos need pushing",
"confirm_push": "Confirm push {n} repos above? [y/N]",
"cancelled": "Cancelled", "push_done": "Push complete",
# commit / stash
"missing_msg": "Missing commit message, use -m",
"tree_clean": "{name}: working tree clean",
"n_changes": "{name} — {n} changed files:",
"n_more": " ... {n} more files",
"commit_msg_lbl": "Commit message", "confirm_commit": "Confirm git add -A && commit? [y/N]",
"committed": "✓ Committed", "commit_fail": "✗ Commit failed:",
"no_stash_needed": "{name}: working tree clean, nothing to stash",
"stash_ok": "✓ {name}: stashed {n} changes", "stash_fail": "✗ Stash failed:",
"stash_pop_ok": "✓ {name}: stash pop succeeded", "stash_pop_fail": "✗ Stash pop failed:",
# grep
"no_match": "No matches: {pattern}",
# find_repo / require
"multi_match": "Multiple matches: {hints}",
"match_hint": "Hint: use full path to distinguish",
"repo_not_found": "Repo not found: {name}",
"lazygit_missing": "lazygit not installed", "gitnexus_missing": "gitnexus not found",
"expected_path": "Expected path: {path}",
# doc
"gen_doc": "Generating doc: {name}", "cannot_scan": "Cannot scan: {name}",
"doc_ok": "✓ Generated: {path}", "doc_stats": "{imgs} diagrams | {commits} commit records",
"copying": "Copy: {path}",
"doc_none": "none",
"doc_clean": "clean", "doc_dirty": "{n} uncommitted changes",
"doc_info": "Basic Info", "doc_attr": "Attribute", "doc_value": "Value",
"doc_path": "Path", "doc_remote": "Remote", "doc_branch": "Branch",
"doc_language": "Language", "doc_commits_week_month": "**{commits}** commits (this week {week} / this month {month})",
"doc_contribs": "Contributors", "doc_tags": "Tags",
"doc_status": "Status",
"doc_overview": "Overview",
"doc_arch": "Architecture",
"doc_arch_full": "Full architecture in CLAUDE.md ({n} lines)",
"doc_diagrams": "Key Diagrams", "doc_source_tree": "Source Structure",
"doc_docs_index": "Documentation Index", "doc_recent": "Recent Activity",
# graph report markdown templates
"rpt_title": "Code Graph",
"rpt_info": "Data Source",
"rpt_gen_by": "Auto-generated by [GitNexus](https://github.com/nicobailon/gitnexus) knowledge graph engine.",
"rpt_regen": "Regenerate: `cb graph {name} report`",
"rpt_metric": "Metric", "rpt_value": "Value",
"rpt_nodes": "Nodes", "rpt_edges": "Edges",
"rpt_communities_label": "Communities",
"rpt_processes_label": "Processes", "rpt_files_label": "Files",
"rpt_idx_time": "Index Time",
"rpt_related": "Related: [[{name}]]",
"rpt_overview": "Graph Overview",
"rpt_overview_desc": "The knowledge graph contains **{nodes:,}** nodes and **{edges:,}** edges, covering {files} source files.",
"rpt_node_top3": "Nodes are primarily composed of {top3}.",
"rpt_node_dist": "Node Type Distribution",
"rpt_edge_dist": "Edge Type Distribution",
"rpt_module_dist": "Module File Distribution",
"rpt_pie_title": "Files by Module",
"rpt_module": "Module", "rpt_file_count": "Files", "rpt_pct": "Pct",
"rpt_cross_deps": "Cross-module Dependencies (Hot Calls)",
"rpt_cross_desc": "File-level CALLS edges ranked by frequency, reflecting inter-module coupling:",
"rpt_caller_file": "Caller File", "rpt_callee_file": "Callee File", "rpt_call_count": "Calls",
"rpt_imports": "Module Import Relations",
"rpt_hubs": "Hub Nodes (High References)",
"rpt_hubs_desc": "Functions and classes referenced most by other symbols — the **core API** of the codebase:",
"rpt_symbol": "Symbol", "rpt_file": "File", "rpt_refs": "References", "rpt_type": "Type",
"rpt_top_callers": "Top Callers",
"rpt_top_callers_desc": "Symbols that call the most other functions, typically **entry points or core dispatchers**:",
"rpt_function": "Function", "rpt_call_n": "Calls",
"rpt_proc_flows": "Process Flows",
"rpt_proc_desc": "GitNexus detected **{n}** process flows via call chain tracing. Top {m}:",
"rpt_file_index": "Key File Index",
"rpt_file_index_desc": "AI navigation guide: files ranked by number of defined symbols, for quick understanding of each file's role.",
"rpt_file_col": "File", "rpt_sym_count": "Symbols", "rpt_main_defs": "Main Definitions",
"rpt_inherit": "Class Inheritance",
"rpt_inherit_desc": "{n} inheritance relations, {m} base classes:",
"rpt_parent": "Base Class", "rpt_child": "Subclasses",
"rpt_structs": "Core Data Structures (Struct)",
"rpt_structs_desc": "Indexed {n} Structs, by module:",
"rpt_enums": "Enum Types",
"rpt_namespaces": "Namespace Structure",
"rpt_community_struct": "Community Structure (Leiden Clustering)",
"rpt_community_desc": "Leiden algorithm detected **{n}** communities. Top communities by symbol count:",
"rpt_involved_files": "Involved Files",
"rpt_core_symbols": "Core Symbols",
"rpt_comm_overview": "Community Overview",
"rpt_comm_col": "Community", "rpt_domain": "Domain",
"rpt_sym_n": "Symbols", "rpt_cohesion": "Cohesion",
"rpt_edge_stats": "Edge Relation Statistics",
"rpt_edge_type": "Edge Type", "rpt_meaning": "Meaning", "rpt_count": "Count",
"rpt_edge_calls": "Function call", "rpt_edge_defines": "File defines symbol",
"rpt_edge_imports": "File/module import", "rpt_edge_contains": "Directory contains file",
"rpt_edge_member": "Namespace member", "rpt_edge_step": "Process step",
"rpt_edge_extends": "Class inheritance",
"rpt_code_graph_doc": "Code Graph",
"rpt_xref_label": "GitNexus Code Graph",
# graph
"graph_ok": "✓ Generated: {path}",
"graph_stats": "{nodes:,} nodes | {edges:,} edges | {communities} communities | {processes} processes",
"xref_added": " Added cross-reference to {name}.md",
"graph_specify_repo": "Please specify a repo name",
"graph_already_indexed": "⟳ {name} already indexed, will rebuild",
"graph_cpp_warn": "⚠ C/C++ projects may take longer or be unstable to index",
"graph_indexing": "Indexing: {name}",
"graph_index_ok": "✓ Indexing complete: {name}",
"graph_index_fail": "✗ Indexing failed (exit {code})",
"graph_index_timeout": "✗ Indexing timed out (>180s)",
"graph_not_indexed": "Not yet indexed, run first: cb graph {name} index",
"graph_idx_time": "Index time: {time}",
"graph_unknown": "unknown",
"graph_node_stats": "Node Statistics",
"graph_edge_stats": "Edge Statistics",
"graph_type": "Type", "graph_count": "Count",
"graph_total_nodes": "Total nodes: {n}",
"graph_total_edges": "Total edges: {n}",
"graph_communities_n": "Communities: {n} (Leiden clustering)",
"graph_top_callers": "Top Callers",
"graph_function": "Function", "graph_file": "File", "graph_calls": "Calls",
"graph_code_graph": "Code Graph",
"graph_query_fail": "Query failed or no results",
"graph_processes": "Processes ({n})",
"graph_proc_id": "ID", "graph_proc_summary": "Summary",
"graph_proc_steps": "Steps", "graph_proc_type": "Type",
"graph_definitions": "Definitions ({n})",
"graph_def_name": "Name", "graph_def_line": "Line",
"graph_proc_symbols": "Process Symbols ({n})",
"graph_sym_module": "Module", "graph_sym_process": "Process",
"graph_no_results": "No matching results",
"graph_n_results": "{n} results total",
"graph_cross_deps": "Cross-module Dependencies (CALLS)",
"graph_caller": "Caller", "graph_callee": "Callee",
"graph_no_cross_calls": "No cross-module call edges",
"graph_n_cross_calls": "{n} cross-file call relations",
"graph_leiden_community": "Leiden Communities",
"graph_no_community": "No community data",
"graph_comm_id": "ID", "graph_comm_domain": "Domain",
"graph_comm_symbols": "Symbols", "graph_comm_cohesion": "Cohesion",
"graph_comm_members": "Members (sampled)",
"graph_n_communities": "{n} communities total",
"graph_module_dist": "Module File Distribution",
"graph_module": "Module", "graph_files": "Files",
"graph_pct": "Pct", "graph_no_files": "No file nodes",
"graph_n_files_modules": "{files} files, {modules} modules total",
"graph_hub_nodes": "Hub Nodes",
"graph_symbol": "Symbol", "graph_refs": "Refs",
"graph_no_data": "No data",
"graph_n_hubs": "{n} high-reference symbols",
"graph_hierarchy": "Class Hierarchy",
"graph_no_hierarchy": "No class inheritance found",
"graph_n_subclasses": "{n} subclasses",
"graph_n_inherit": "{edges} inheritance relations, {bases} base classes",
"graph_generating": "Generating code graph: {name}",
# watch
"watch_ft": "Refresh every {n}s | Took {t:.1f}s | Ctrl+C to exit",
},
"zh": {
"just_now": "刚刚", "secs_ago": "{n}秒前", "mins_ago": "{n}分钟前",
"hours_ago": "{n}小时前", "days_ago": "{n}天前", "months_ago": "{n}月前",
"years_ago": "{n}年前", "no_commits": "无提交",
"col_name": "名称", "col_branch": "分支", "col_last_commit": "最后提交",
"col_status": "状态", "col_language": "语言", "col_commits": "提交数",
"col_remote": "远程", "dashboard_sub": "● = 未提交变更 ✓ = 干净",
"col_time": "时间", "col_repo": "仓库", "col_author": "作者", "col_message": "提交信息",
"health_dirty": " ⚠ 未提交变更", "health_ahead": " ⚠ 未推送提交",
"health_behind": " ⚠ 落后远程", "health_no_remote": " ○ 无远程仓库",
"health_inactive": " ○ 长期未活跃 >30天", "health_ok": " ✓ 一切正常",
"lbl_path": "路径", "lbl_remote": "远程", "lbl_branch": "分支", "lbl_tags": "标签",
"lbl_commits": "提交", "lbl_contribs": "贡献者", "lbl_lang": "语言",
"lbl_status": "状态", "lbl_recent": "最近提交", "lbl_activity": "活跃度",
"none": "无", "this_week": "本周", "this_month": "本月",
"total_repos": "总仓库", "active_30d": "活跃(30天)", "has_remote": "有远程",
"total_commits": "总提交", "lang_dist": "语言分布",
"week_top": "本周活跃 Top", "remote_dist": "远程分布",
"all_clean": "所有仓库都是干净的", "col_changes": "变更",
"dirty_title": "有未提交变更的仓库 ({n})",
"dirty_prompt": "输入序号用 lazygit 打开,直接回车退出",
"invalid_num": "无效序号",
"processing_n": "逐个处理 {n} 个有变更的仓库",
"each_hint": "关闭 lazygit 后自动跳到下一个,Ctrl+C 退出",
"interrupted": "已中断", "all_done": "全部处理完毕",
"no_remote_repos": "没有配置远程仓库的项目",
"pull_prep": "准备 pull {n} 个有远程的仓库",
"updated_n": " ✓ 已更新 ({n})", "failed_n": " ✗ 失败 ({n})",
"up_to_date_n": " ─ 已是最新 ({n})",
"no_push_needed": "没有需要推送的仓库",
"confirm_push": "确认推送以上 {n} 个仓库? [y/N]",
"cancelled": "已取消", "push_done": "推送完成",
"missing_msg": "缺少提交信息,请用 -m 指定",
"tree_clean": "{name}: 工作区干净,无需提交",
"n_changes": "{name} — {n} 个变更文件:",
"n_more": " ... 还有 {n} 个文件",
"commit_msg_lbl": "提交信息", "confirm_commit": "确认 git add -A && commit? [y/N]",
"committed": "✓ 已提交", "commit_fail": "✗ 提交失败:",
"no_stash_needed": "{name}: 工作区干净,无需 stash",
"stash_ok": "✓ {name}: stash 了 {n} 个变更", "stash_fail": "✗ stash 失败:",
"stash_pop_ok": "✓ {name}: stash pop 成功", "stash_pop_fail": "✗ stash pop 失败:",
"no_match": "未找到匹配: {pattern}",
"multi_match": "多个匹配: {hints}",
"match_hint": "提示: 用完整路径区分",
"repo_not_found": "未找到仓库: {name}",
"lazygit_missing": "未安装 lazygit", "gitnexus_missing": "未找到 gitnexus",
"expected_path": "期望路径: {path}",
"gen_doc": "生成文档: {name}", "cannot_scan": "无法扫描: {name}",
"doc_ok": "✓ 已生成: {path}", "doc_stats": "{imgs} 张图表 | {commits} 条提交记录",
"copying": "复制: {path}",
"doc_none": "无",
"doc_clean": "干净", "doc_dirty": "{n} 未提交变更",
"doc_info": "基本信息", "doc_attr": "属性", "doc_value": "值",
"doc_path": "路径", "doc_remote": "远程", "doc_branch": "分支",
"doc_language": "语言", "doc_commits_week_month": "**{commits}** commits (本周 {week} / 本月 {month})",
"doc_contribs": "贡献者", "doc_tags": "标签",
"doc_status": "状态",
"doc_overview": "项目概述",
"doc_arch": "架构",
"doc_arch_full": "完整架构详见 CLAUDE.md ({n} 行)",
"doc_diagrams": "关键图表", "doc_source_tree": "源码结构",
"doc_docs_index": "文档索引", "doc_recent": "最近活动",
"rpt_title": "代码图谱",
"rpt_info": "数据来源",
"rpt_gen_by": "由 [GitNexus](https://github.com/nicobailon/gitnexus) 知识图谱引擎自动生成。",
"rpt_regen": "重新生成: `cb graph {name} report`",
"rpt_metric": "指标", "rpt_value": "值",
"rpt_nodes": "节点", "rpt_edges": "边",
"rpt_communities_label": "社区",
"rpt_processes_label": "流程", "rpt_files_label": "文件",
"rpt_idx_time": "索引时间",
"rpt_related": "相关文档: [[{name}]]",
"rpt_overview": "图谱总览",
"rpt_overview_desc": "知识图谱包含 **{nodes:,}** 个节点和 **{edges:,}** 条边,覆盖 {files} 个源文件。",
"rpt_node_top3": "节点主要由 {top3} 组成。",
"rpt_node_dist": "节点类型分布",
"rpt_edge_dist": "边类型分布",
"rpt_module_dist": "模块文件分布",
"rpt_pie_title": "文件数按模块",
"rpt_module": "模块", "rpt_file_count": "文件数", "rpt_pct": "占比",
"rpt_cross_deps": "跨模块依赖 (热点调用)",
"rpt_cross_desc": "文件间 CALLS 调用边按频次排名,反映模块间耦合关系:",
"rpt_caller_file": "调用方文件", "rpt_callee_file": "被调用文件", "rpt_call_count": "调用次数",
"rpt_imports": "模块间导入关系",
"rpt_hubs": "高引用度符号 (Hub Nodes)",
"rpt_hubs_desc": "被其他符号引用次数最多的函数和类,是代码库的**核心 API**:",
"rpt_symbol": "符号", "rpt_file": "文件", "rpt_refs": "引用次数", "rpt_type": "类型",
"rpt_top_callers": "顶级调用者 (Top Callers)",
"rpt_top_callers_desc": "主动调用其他函数次数最多的符号,通常是**入口函数或核心调度器**:",
"rpt_function": "函数", "rpt_call_n": "调用次数",
"rpt_proc_flows": "执行流程 (Process Flows)",
"rpt_proc_desc": "GitNexus 通过调用链追踪检测到 **{n}** 条执行流程。以下为最重要的 {m} 条:",
"rpt_file_index": "关键文件索引",
"rpt_file_index_desc": "AI 导航指南:按文件定义的符号数排列,快速了解每个文件的职责。",
"rpt_file_col": "文件", "rpt_sym_count": "符号数", "rpt_main_defs": "主要定义",
"rpt_inherit": "类继承体系",
"rpt_inherit_desc": "{n} 条继承关系,{m} 个基类:",
"rpt_parent": "基类", "rpt_child": "子类",
"rpt_structs": "核心数据结构 (Struct)",
"rpt_structs_desc": "共索引到 {n} 个 Struct,按模块分布:",
"rpt_enums": "枚举类型 (Enum)",
"rpt_namespaces": "命名空间结构",
"rpt_community_struct": "社区结构 (Leiden Clustering)",
"rpt_community_desc": "Leiden 算法检测到 **{n}** 个社区,以下为符号数最多的社区:",
"rpt_involved_files": "涉及文件",
"rpt_core_symbols": "核心符号",
"rpt_comm_overview": "社区总览",
"rpt_comm_col": "社区", "rpt_domain": "域",
"rpt_sym_n": "符号数", "rpt_cohesion": "凝聚度",
"rpt_edge_stats": "边关系统计",
"rpt_edge_type": "边类型", "rpt_meaning": "含义", "rpt_count": "数量",
"rpt_edge_calls": "函数调用", "rpt_edge_defines": "文件定义符号",
"rpt_edge_imports": "文件/模块导入", "rpt_edge_contains": "目录包含文件",
"rpt_edge_member": "命名空间成员", "rpt_edge_step": "流程步骤",
"rpt_edge_extends": "类继承",
"rpt_code_graph_doc": "代码图谱",
"rpt_xref_label": "GitNexus 代码图谱",
"graph_ok": "✓ 已生成: {path}",
"graph_stats": "{nodes:,} 节点 | {edges:,} 边 | {communities} 社区 | {processes} 流程",
"xref_added": " 已添加交叉引用到 {name}.md",
"graph_specify_repo": "请指定仓库名称",
"graph_already_indexed": "⟳ {name} 已有索引,将重新构建",
"graph_cpp_warn": "⚠ C/C++ 项目索引可能耗时较长或不稳定",
"graph_indexing": "索引: {name}",
"graph_index_ok": "✓ 索引完成: {name}",
"graph_index_fail": "✗ 索引失败 (exit {code})",
"graph_index_timeout": "✗ 索引超时 (>180s)",
"graph_not_indexed": "尚未建立图索引,请先运行: cb graph {name} index",
"graph_idx_time": "索引时间: {time}",
"graph_unknown": "未知",
"graph_node_stats": "节点统计",
"graph_edge_stats": "边统计",
"graph_type": "类型", "graph_count": "数量",
"graph_total_nodes": "总节点: {n}",
"graph_total_edges": "总边: {n}",
"graph_communities_n": "社区数: {n} (Leiden 聚类)",
"graph_top_callers": "Top 调用者",
"graph_function": "函数", "graph_file": "文件", "graph_calls": "调用数",
"graph_code_graph": "代码图谱",
"graph_query_fail": "查询失败或无结果",
"graph_processes": "执行流 ({n})",
"graph_proc_id": "ID", "graph_proc_summary": "摘要",
"graph_proc_steps": "步数", "graph_proc_type": "类型",
"graph_definitions": "符号定义 ({n})",
"graph_def_name": "名称", "graph_def_line": "行号",
"graph_proc_symbols": "流程符号 ({n})",
"graph_sym_module": "模块", "graph_sym_process": "流程",
"graph_no_results": "无匹配结果",
"graph_n_results": "共 {n} 条结果",
"graph_cross_deps": "跨模块依赖 (CALLS)",
"graph_caller": "调用方", "graph_callee": "被调用方",
"graph_no_cross_calls": "无跨模块调用边",
"graph_n_cross_calls": "{n} 条跨文件调用关系",
"graph_leiden_community": "Leiden 社区",
"graph_no_community": "无社区数据",
"graph_comm_id": "ID", "graph_comm_domain": "域",
"graph_comm_symbols": "符号数", "graph_comm_cohesion": "凝聚度",
"graph_comm_members": "成员 (采样)",
"graph_n_communities": "共 {n} 个社区",
"graph_module_dist": "模块文件分布",
"graph_module": "模块", "graph_files": "文件数",
"graph_pct": "占比", "graph_no_files": "无文件节点",
"graph_n_files_modules": "共 {files} 个文件, {modules} 个模块",
"graph_hub_nodes": "Hub Nodes",
"graph_symbol": "符号", "graph_refs": "引用数",
"graph_no_data": "无数据",
"graph_n_hubs": "{n} 个高引用符号",
"graph_hierarchy": "类继承",
"graph_no_hierarchy": "无类继承关系",
"graph_n_subclasses": "{n} 子类",
"graph_n_inherit": "{edges} 条继承关系, {bases} 个基类",
"graph_generating": "生成代码图谱: {name}",
"watch_ft": "每 {n}s 刷新 | 耗时 {t:.1f}s | Ctrl+C 退出",
},
}
_ui_lang = CFG["lang"] # "auto", "en", or "zh"
def _detect_lang() -> str:
try:
loc = locale.getlocale()[0] or ""
except ValueError:
loc = ""
return "zh" if loc.startswith("zh") else "en"
def T(key: str, **kw) -> str:
"""Get translated UI string."""
lang = _ui_lang if _ui_lang != "auto" else _detect_lang()
table = _I18N.get(lang, _I18N["en"])
s = table.get(key, _I18N["en"].get(key, key))
return s.format(**kw) if kw else s
console = Console()
LANG_MAP = {
".py": "Python", ".pyx": "Python", ".pyi": "Python",
".js": "JavaScript", ".mjs": "JavaScript", ".cjs": "JavaScript",
".ts": "TypeScript", ".tsx": "TypeScript",
".jsx": "React",
".c": "C", ".h": "C/C++",
".cpp": "C++", ".cc": "C++", ".cxx": "C++", ".hpp": "C++",
".java": "Java",
".go": "Go",
".rs": "Rust",
".rb": "Ruby",
".php": "PHP",
".swift": "Swift",
".kt": "Kotlin",
".scala": "Scala",
".jl": "Julia",
".r": "R", ".R": "R",
".lua": "Lua",
".sh": "Shell", ".bash": "Shell", ".zsh": "Shell",
".html": "HTML", ".htm": "HTML",
".css": "CSS", ".scss": "CSS", ".less": "CSS",
".vue": "Vue",
".svelte": "Svelte",
".dart": "Dart",
".ex": "Elixir", ".exs": "Elixir",
".zig": "Zig",
".nim": "Nim",
".f90": "Fortran", ".f95": "Fortran", ".f03": "Fortran",
".m": "MATLAB/ObjC",
".tex": "LaTeX",
".md": "Markdown",
".sql": "SQL",
".proto": "Protobuf",
}
IGNORE_EXTS = {
".json", ".yaml", ".yml", ".toml", ".xml", ".lock", ".sum",
".txt", ".csv", ".log", ".gitignore", ".dockerignore",
".png", ".jpg", ".jpeg", ".gif", ".svg", ".ico",
".woff", ".woff2", ".ttf", ".eot",
".pdf", ".zip", ".tar", ".gz",
".map", ".min.js", ".min.css",
}
def run_git(repo_path: Path, *args: str, timeout: int = 10) -> str:
"""执行 git 命令并返回 stdout"""
try:
r = subprocess.run(
["git", "-C", str(repo_path)] + list(args),
capture_output=True, text=True, timeout=timeout,
)
return r.stdout.strip()
except (subprocess.TimeoutExpired, FileNotFoundError):
return ""
def relative_time(dt: datetime) -> str:
"""Convert datetime to human-readable relative time."""
now = datetime.now(timezone.utc)
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
diff = now - dt
seconds = int(diff.total_seconds())
if seconds < 0:
return T("just_now")
if seconds < 60:
return T("secs_ago", n=seconds)
minutes = seconds // 60
if minutes < 60:
return T("mins_ago", n=minutes)
hours = minutes // 60
if hours < 24:
return T("hours_ago", n=hours)
days = hours // 24
if days < 30:
return T("days_ago", n=days)
months = days // 30
if months < 12:
return T("months_ago", n=months)
years = days // 365
return T("years_ago", n=years)
def detect_remote_type(url: str) -> str:
"""从 remote URL 判断类型"""
if not url:
return "none"
url_lower = url.lower()
if "github.com" in url_lower:
return "github"
if "gitlab" in url_lower:
return "gitlab"
if "gitee.com" in url_lower:
return "gitee"
if "bitbucket" in url_lower:
return "bitbucket"
return "other"
def detect_language(repo_path: Path) -> str:
"""检测仓库主要语言 (快速版)"""
output = run_git(repo_path, "ls-files")
if not output:
return "-"
counter = Counter()
for f in output.split("\n"):
ext = Path(f).suffix.lower()
if ext in IGNORE_EXTS or not ext:
continue
lang = LANG_MAP.get(ext)
if lang:
counter[lang] += 1
if not counter:
return "-"
return counter.most_common(1)[0][0]
def detect_language_detail(repo_path: Path) -> list[tuple[str, int]]:
"""检测仓库语言占比 (详细版)"""
output = run_git(repo_path, "ls-files")
if not output:
return []
counter = Counter()
for f in output.split("\n"):
ext = Path(f).suffix.lower()
if ext in IGNORE_EXTS or not ext:
continue
lang = LANG_MAP.get(ext)
if lang:
counter[lang] += 1
return counter.most_common()
SCAN_SCRIPT_BASE = r"""
cd "$1" || exit 1
echo "%%BRANCH%%$(git branch --show-current 2>/dev/null || git rev-parse --short HEAD 2>/dev/null)"
echo "%%LOG%%$(git log -1 --format='%aI|%s' 2>/dev/null)"
echo "%%DIRTY%%$(git status --porcelain 2>/dev/null | wc -l | tr -d ' ')"
echo "%%COUNT%%$(git rev-list --count HEAD 2>/dev/null)"
echo "%%REMOTE%%$(git remote get-url origin 2>/dev/null)"
echo "%%AB%%$(git rev-list --left-right --count HEAD...@{upstream} 2>/dev/null)"
"""
SCAN_SCRIPT_FULL = SCAN_SCRIPT_BASE + r"""
echo "%%LANG%%$(git ls-files 2>/dev/null)"
"""
def scan_repo(repo_path: Path, full: bool = False) -> dict | None:
"""扫描单个仓库 (单次 shell 调用)"""
if not (repo_path / ".git").is_dir():
return None
name = repo_path.name
script = SCAN_SCRIPT_FULL if full else SCAN_SCRIPT_BASE
try:
r = subprocess.run(
["sh", "-c", script, "--", str(repo_path)],
capture_output=True, text=True, timeout=15,
)
output = r.stdout
except (subprocess.TimeoutExpired, FileNotFoundError):
return None
def extract(tag: str) -> str:
marker = f"%%{tag}%%"
for line in output.split("\n"):
if line.startswith(marker):
return line[len(marker):]
return ""
branch = extract("BRANCH") or "?"
log_line = extract("LOG")
last_time = None
last_msg = ""
if log_line and "|" in log_line:
parts = log_line.split("|", 1)
last_msg = parts[1]
try:
last_time = datetime.fromisoformat(parts[0])
except ValueError:
pass
dirty_str = extract("DIRTY")
dirty_count = int(dirty_str) if dirty_str.isdigit() else 0
commit_str = extract("COUNT")
commit_count = int(commit_str) if commit_str.isdigit() else 0
remote_url = extract("REMOTE")
remote_type = detect_remote_type(remote_url)
ahead, behind = 0, 0
ab = extract("AB")
if ab and "\t" in ab:
parts = ab.split("\t")
ahead = int(parts[0]) if parts[0].isdigit() else 0
behind = int(parts[1]) if parts[1].isdigit() else 0
lang = ""
if full:
# 语言检测:复用已获取的 ls-files 输出
lang_marker = "%%LANG%%"
lang_output = ""
idx = output.find(lang_marker)
if idx >= 0:
lang_output = output[idx + len(lang_marker):]
if lang_output:
counter = Counter()
for f in lang_output.split("\n"):
ext = Path(f).suffix.lower()
if ext in IGNORE_EXTS or not ext:
continue
l = LANG_MAP.get(ext)
if l:
counter[l] += 1
lang = counter.most_common(1)[0][0] if counter else "-"
else:
lang = "-"
info = {
"name": name,
"path": str(repo_path),
"branch": branch,
"last_time": last_time,
"last_time_rel": relative_time(last_time) if last_time else T("no_commits"),
"last_time_ts": last_time.timestamp() if last_time else 0,
"last_msg": last_msg,
"dirty": dirty_count,
"commits": commit_count,
"remote_url": remote_url,
"remote_type": remote_type,
"ahead": ahead,
"behind": behind,
"lang": lang,
}
return info
def list_git_repos(code_dir: Path, filter_kw: str = "") -> list[Path]:
"""列出所有 git 仓库路径(含 EXTRA_REPOS)"""
if not code_dir.is_dir():
console.print(f"[red]Directory not found: {code_dir}[/red]")
return []
repos = [d for d in code_dir.iterdir() if d.is_dir() and (d / ".git").is_dir()]
for extra in EXTRA_REPOS:
if extra.is_dir() and (extra / ".git").is_dir() and extra.parent != code_dir:
repos.append(extra)
repos.sort(key=lambda p: p.name.lower())
if filter_kw:
repos = [r for r in repos if filter_kw.lower() in r.name.lower()]
return repos
def scan_all(code_dir: Path, full: bool = True, filter_kw: str = "") -> list[dict]:
"""并行扫描所有仓库"""
repos = list_git_repos(code_dir, filter_kw)
results = []
with ThreadPoolExecutor(max_workers=8) as pool:
futures = {pool.submit(scan_repo, r, full): r for r in repos}
for future in as_completed(futures):
info = future.result()
if info:
results.append(info)
return results
def sort_repos(repos: list[dict], sort_key: str = "activity") -> list[dict]:
"""排序仓库列表"""
if sort_key == "name":
return sorted(repos, key=lambda r: r["name"].lower())
if sort_key == "commits":
return sorted(repos, key=lambda r: r["commits"], reverse=True)
if sort_key == "changes":
return sorted(repos, key=lambda r: r["dirty"], reverse=True)
# default: activity (最近活跃在前)
return sorted(repos, key=lambda r: r["last_time_ts"], reverse=True)
def cmd_dashboard(args):
"""主仪表盘"""
code_dir = Path(args.path).expanduser()
repos = scan_all(code_dir, full=True, filter_kw=args.filter)
repos = sort_repos(repos, args.sort)
if args.json:
for r in repos:
r.pop("last_time", None)
print(json.dumps(repos, ensure_ascii=False, indent=2))
return
table = Table(box=box.ROUNDED, show_lines=False, padding=(0, 1))
table.add_column(T("col_name"), style="bold cyan", no_wrap=True, max_width=20)
table.add_column(T("col_branch"), style="magenta", no_wrap=True, max_width=15)
table.add_column(T("col_last_commit"), no_wrap=True, max_width=10)
table.add_column(T("col_status"), no_wrap=True, justify="center")
table.add_column(T("col_language"), no_wrap=True, max_width=12)
table.add_column(T("col_commits"), justify="right")
table.add_column(T("col_remote"), no_wrap=True)
for r in repos:
# Color based on timestamp, not by parsing the relative time string
rel = r["last_time_rel"]
ts = r["last_time_ts"]
if ts == 0:
time_text = Text(T("no_commits"), style="dim")
else:
age_days = (time.time() - ts) / 86400
if age_days < 1:
time_text = Text(rel, style="green")
elif age_days <= 7:
time_text = Text(rel, style="green")
elif age_days <= 30:
time_text = Text(rel, style="yellow")
else:
time_text = Text(rel, style="dim red")
# 状态
if r["dirty"] > 0:
status = Text(f"●{r['dirty']}", style="yellow")
else:
status = Text("✓", style="green")
# 远程
rt = r["remote_type"]
if rt == "github":
remote_text = Text("github", style="bright_white")
elif rt == "gitlab":
remote_text = Text("gitlab", style="bright_red")
elif rt == "gitee":
remote_text = Text("gitee", style="bright_red")
elif rt == "none":
remote_text = Text("local", style="dim")
else:
remote_text = Text(rt, style="dim")
# ahead/behind 标记
if r["ahead"] > 0 or r["behind"] > 0:
markers = []
if r["ahead"] > 0:
markers.append(f"↑{r['ahead']}")
if r["behind"] > 0:
markers.append(f"↓{r['behind']}")
remote_text.append(f" {' '.join(markers)}", style="yellow")
# 非默认目录的仓库加路径标注
display_name = Text(r["name"], style="bold cyan")
if Path(r["path"]).parent != code_dir:
short_parent = str(Path(r["path"]).parent).replace(str(Path.home()), "~")
display_name.append(f" ({short_parent})", style="dim")
table.add_row(
display_name,
r["branch"],
time_text,
status,
r["lang"] or "-",
str(r["commits"]),
remote_text,
)
title = f"CodeBoard ── {code_dir} ── {len(repos)} repos"
panel = Panel(table, title=title, subtitle=T("dashboard_sub"), border_style="blue")
console.print(panel)
def cmd_activity(args):
"""跨仓库活动时间线"""
code_dir = Path(args.path).expanduser()
limit = args.limit
repos = list_git_repos(code_dir, filter_kw=args.filter)
all_commits = []
def get_recent_commits(repo_path: Path):
output = run_git(repo_path, "log", "--all", f"--max-count={limit}", "--format=%aI|%an|%s")
if not output:
return []
entries = []
for line in output.split("\n"):
if "|" not in line:
continue
parts = line.split("|", 2)
if len(parts) < 3:
continue
try:
dt = datetime.fromisoformat(parts[0])
except ValueError:
continue
entries.append({
"time": dt,
"time_ts": dt.timestamp(),
"time_rel": relative_time(dt),
"author": parts[1],
"message": parts[2],
"repo": repo_path.name,
})
return entries
with ThreadPoolExecutor(max_workers=8) as pool:
futures = {pool.submit(get_recent_commits, r): r for r in repos}
for future in as_completed(futures):
all_commits.extend(future.result())
all_commits.sort(key=lambda c: c["time_ts"], reverse=True)
all_commits = all_commits[:limit]
if args.json:
for c in all_commits:
c.pop("time", None)
print(json.dumps(all_commits, ensure_ascii=False, indent=2))
return
table = Table(box=box.SIMPLE, show_header=True, padding=(0, 1))
table.add_column(T("col_time"), style="dim", no_wrap=True, max_width=10)
table.add_column(T("col_repo"), style="bold cyan", no_wrap=True, max_width=20)
table.add_column(T("col_author"), style="magenta", no_wrap=True, max_width=12)
table.add_column(T("col_message"), max_width=60)
for c in all_commits:
msg = c["message"]
if len(msg) > 60:
msg = msg[:57] + "..."
# 根据提交类型着色
if msg.startswith("feat"):
msg_text = Text(msg, style="green")
elif msg.startswith("fix"):
msg_text = Text(msg, style="yellow")
elif msg.startswith("refactor") or msg.startswith("chore"):
msg_text = Text(msg, style="dim")
else:
msg_text = Text(msg)
table.add_row(c["time_rel"], c["repo"], c["author"], msg_text)
panel = Panel(table, title=f"Recent Activity ── {len(all_commits)} commits", border_style="blue")
console.print(panel)
def cmd_health(args):
"""健康检查报告"""
code_dir = Path(args.path).expanduser()
repos = scan_all(code_dir, full=False, filter_kw=args.filter)
if args.json:
for r in repos:
r.pop("last_time", None)
print(json.dumps(repos, ensure_ascii=False, indent=2))
return
# 分类
dirty_repos = [r for r in repos if r["dirty"] > 0]
ahead_repos = [r for r in repos if r["ahead"] > 0]
behind_repos = [r for r in repos if r["behind"] > 0]
no_remote = [r for r in repos if r["remote_type"] == "none"]
now_ts = datetime.now(timezone.utc).timestamp()
inactive = [r for r in repos if r["last_time_ts"] > 0 and (now_ts - r["last_time_ts"]) > 30 * 86400]
inactive.sort(key=lambda r: r["last_time_ts"])
clean = [r for r in repos if r["dirty"] == 0 and r["ahead"] == 0 and r["behind"] == 0
and r["remote_type"] != "none" and (now_ts - r["last_time_ts"]) <= 30 * 86400]
lines = []
if dirty_repos:
dirty_repos.sort(key=lambda r: r["dirty"], reverse=True)
items = " | ".join(f"{r['name']} ({r['dirty']})" for r in dirty_repos)
lines.append(Text.assemble(
(T("health_dirty"), "bold yellow"),
(f" ({len(dirty_repos)} repos)\n", "yellow"),
(f" {items}\n", ""),
))
if ahead_repos:
items = " | ".join(f"{r['name']} (↑{r['ahead']})" for r in ahead_repos)
lines.append(Text.assemble(
(T("health_ahead"), "bold yellow"),
(f" ({len(ahead_repos)} repos)\n", "yellow"),
(f" {items}\n", ""),
))
if behind_repos:
items = " | ".join(f"{r['name']} (↓{r['behind']})" for r in behind_repos)
lines.append(Text.assemble(
(T("health_behind"), "bold red"),
(f" ({len(behind_repos)} repos)\n", "red"),
(f" {items}\n", ""),
))
if no_remote:
items = " | ".join(r["name"] for r in no_remote)
lines.append(Text.assemble(
(T("health_no_remote"), "bold dim"),
(f" ({len(no_remote)} repos)\n", "dim"),
(f" {items}\n", ""),
))
if inactive:
items = " | ".join(f"{r['name']} ({r['last_time_rel']})" for r in inactive)
lines.append(Text.assemble(
(T("health_inactive"), "bold dim"),
(f" ({len(inactive)} repos)\n", "dim"),
(f" {items}\n", ""),
))
if clean:
lines.append(Text.assemble(
(T("health_ok"), "bold green"),
(f" ({len(clean)} repos)\n", "green"),
))
content = Text()
for line in lines:
content.append_text(line)
content.append("\n")
panel = Panel(content, title="Health Report", border_style="blue")
console.print(panel)
def cmd_detail(args):
"""单个仓库详情"""
code_dir = Path(args.path).expanduser()
repo_path = find_repo(code_dir, args.repo)
if not repo_path:
return
repo_name = repo_path.name
info = scan_repo(repo_path, full=True)
if not info: