-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
254 lines (225 loc) · 7.91 KB
/
Copy pathcli.py
File metadata and controls
254 lines (225 loc) · 7.91 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
"""CodeHeat CLI 진입점: `codeheat scan|own <path>`."""
from __future__ import annotations
import argparse
import json
import sys
from .insights import generate_insights
from .ownership import build_ownership_reports, list_tracked_files
from .static_scan import build_smell_reports
def _cmd_scan(args: argparse.Namespace) -> int:
reports = build_smell_reports(
args.repo_path,
compute_todo_age=not args.no_todo_age,
compute_dup=not args.no_duplication,
)
payload = {
"repo_path": args.repo_path,
"file_count": len(reports),
"files": [r.to_dict() for r in reports],
}
with open(args.output, "w", encoding="utf-8") as fh:
json.dump(payload, fh, indent=2, ensure_ascii=False)
print(f"Files analyzed: {len(reports)}")
if reports:
top = reports[0]
hotspot = f", hotspot={top.hotspot_function}()" if top.hotspot_function else ""
print(
f"Riskiest file: {top.file} "
f"(smell={top.smell_score}, max CCN={top.complexity}, "
f"nesting={top.max_nesting_depth}, params={top.max_param_count}{hotspot})"
)
print(f"Report saved: {args.output}")
return 0
def _resolve_files(args: argparse.Namespace) -> list[str]:
"""오너십 분석 대상 파일 목록 결정.
--from-report 가 있으면 1단계 리포트의 파일을(복잡도 내림차순) 사용,
없으면 git 추적 파일 전체. 둘 다 --limit 로 상한.
"""
if args.from_report:
with open(args.from_report, "r", encoding="utf-8") as fh:
report = json.load(fh)
files = [f["file"] for f in report.get("files", [])]
else:
files = list_tracked_files(args.repo_path)
if args.limit and args.limit > 0:
files = files[: args.limit]
return files
def _cmd_own(args: argparse.Namespace) -> int:
files = _resolve_files(args)
if not files:
print("No files to analyze. (Check it's a git repo and the --from-report path is correct.)")
return 1
reports = build_ownership_reports(
args.repo_path,
files,
top_n=args.top,
use_complexity_delta=not args.churn_only,
complexity_commit_limit=args.complexity_limit,
)
payload = {
"repo_path": args.repo_path,
"weighting": "churn" if args.churn_only else "complexity_delta",
"file_count": len(reports),
"files": [r.to_dict() for r in reports],
}
with open(args.output, "w", encoding="utf-8") as fh:
json.dump(payload, fh, indent=2, ensure_ascii=False)
analyzed = sum(1 for r in reports if r.total_commits > 0)
print(f"Files analyzed: {len(reports)} (with git history: {analyzed})")
for r in reports[:3]:
if r.top_contributors:
top = r.top_contributors[0]
print(
f" {r.file} → {top.name} "
f"(score={top.score}, commits={top.commit_count}, "
f"last={top.last_commit_days}d ago)"
)
print(f"Report saved: {args.output}")
return 0
def _cmd_insights(args: argparse.Namespace) -> int:
try:
result = generate_insights(
smell_path=args.smell_report,
ownership_path=args.ownership_report,
backend=args.backend,
model=args.model,
top_k=args.top_k,
ollama_host=args.ollama_host,
dry_run=args.dry_run,
)
except (RuntimeError, ValueError) as e:
print(f"Failed to generate insights: {e}")
return 1
except FileNotFoundError as e:
print(f"Input report not found: {e}")
return 1
if args.dry_run:
print("[dry-run] prompt that would be sent to the LLM:\n")
print(result["prompt"])
return 0
with open(args.output, "w", encoding="utf-8") as fh:
json.dump(result, fh, indent=2, ensure_ascii=False)
print(f"Backend: {result['backend']} (model={result['model']})")
if result.get("summary"):
print(f"Summary: {result['summary']}")
for ins in result["insights"][:5]:
print(f" [{ins['risk']}] {ins['file']} → {ins['ask_who']}")
print(f" ↳ {ins['ask_what']}")
print(f"Report saved: {args.output}")
return 0
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="codeheat",
description="Rank refactor priorities from code complexity + git history",
)
sub = parser.add_subparsers(dest="command", required=True)
scan = sub.add_parser("scan", help="run static analysis (complexity + TODO)")
scan.add_argument("repo_path", help="repository/directory path to analyze")
scan.add_argument(
"--output",
default="smell_report.json",
help="output JSON path (default: smell_report.json)",
)
scan.add_argument(
"--no-todo-age",
action="store_true",
help="skip git-based TODO-age calculation (faster)",
)
scan.add_argument(
"--no-duplication",
action="store_true",
help="skip duplication_ratio calculation (faster)",
)
scan.set_defaults(func=_cmd_scan)
own = sub.add_parser(
"own", help="run ownership analysis (match contributors to complexity spikes)"
)
own.add_argument("repo_path", help="git repository path to analyze")
own.add_argument(
"--from-report",
default=None,
help="path to a stage-1 smell_report.json; analyze only its files",
)
own.add_argument(
"--output",
default="ownership_report.json",
help="output JSON path (default: ownership_report.json)",
)
own.add_argument(
"--top",
type=int,
default=2,
help="top contributors per file (default: 2)",
)
own.add_argument(
"--limit",
type=int,
default=30,
help="cap on the number of files analyzed (default: 30, 0 for unlimited)",
)
own.add_argument(
"--churn-only",
action="store_true",
help="skip the complexity delta, weight by churn (changed lines) only (faster)",
)
own.add_argument(
"--complexity-limit",
type=int,
default=200,
help="cap the newest-N commits for per-file function-level complexity "
"(guards I/O on large repos, default: 200, 0 for unlimited)",
)
own.set_defaults(func=_cmd_own)
ins = sub.add_parser(
"insights",
help="generate stage-3 AI insights (refactor priority + who to ask)",
)
ins.add_argument(
"smell_report",
help="path to stage-1 smell_report.json (complexity/TODO)",
)
ins.add_argument(
"--ownership-report",
default=None,
help="path to stage-2 ownership_report.json (used for owner matching if given)",
)
ins.add_argument(
"--backend",
choices=["ollama", "anthropic"],
default="ollama",
help="LLM backend (default: ollama, free and local)",
)
ins.add_argument(
"--model",
default=None,
help="model name (default per backend: ollama=llama3.1, anthropic=claude-opus-4-8)",
)
ins.add_argument(
"--top-k",
type=int,
default=10,
help="number of top files to send to the LLM (default: 10)",
)
ins.add_argument(
"--ollama-host",
default="http://localhost:11434",
help="Ollama server address (default: http://localhost:11434)",
)
ins.add_argument(
"--output",
default="insights_report.json",
help="output JSON path (default: insights_report.json)",
)
ins.add_argument(
"--dry-run",
action="store_true",
help="print the assembled prompt only, no LLM call (no key/network needed)",
)
ins.set_defaults(func=_cmd_insights)
return parser
def main(argv: list[str] | None = None) -> int:
parser = build_parser()
args = parser.parse_args(argv)
return args.func(args)
if __name__ == "__main__":
sys.exit(main())