-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit_candlestick.py
More file actions
364 lines (312 loc) · 10 KB
/
git_candlestick.py
File metadata and controls
364 lines (312 loc) · 10 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
#!/usr/bin/env python3
"""
Git Commit Candlestick Chart
============================
コミット履歴をローソク足チャートで可視化する
各コミットを1本のローソク足として表現:
- 始値 (Open): コミット前の総行数
- 終値 (Close): コミット後の総行数
- 高値 (High): 始値 + 追加行数
- 安値 (Low): 始値 - 削除行数
"""
import argparse
import subprocess
import re
import fnmatch
from datetime import datetime
from pathlib import Path
import pandas as pd
import plotly.graph_objects as go
def run_git(repo_path: str, *args: str) -> str:
"""gitコマンドを実行"""
result = subprocess.run(
["git", "-C", repo_path, *args],
capture_output=True,
text=True,
check=True,
)
return result.stdout
def get_commits(
repo_path: str,
branch: str | None = None,
since: str | None = None,
until: str | None = None,
) -> list[dict]:
"""コミット一覧を取得(古い順)"""
args = [
"log",
"--reverse",
"--format=%H|%s|%ai|%an",
]
if branch:
args.append(branch)
if since:
args.append(f"--since={since}")
if until:
args.append(f"--until={until}")
output = run_git(repo_path, *args)
commits = []
for line in output.strip().split("\n"):
if not line:
continue
parts = line.split("|", 3)
if len(parts) >= 4:
commits.append({
"hash": parts[0],
"message": parts[1],
"date": parts[2],
"author": parts[3],
})
return commits
def get_commit_stats(
repo_path: str,
commit_hash: str,
file_pattern: str | None = None,
) -> tuple[int, int]:
"""コミットの追加/削除行数を取得"""
try:
output = run_git(repo_path, "show", "--numstat", "--format=", commit_hash)
except subprocess.CalledProcessError:
return 0, 0
added = 0
deleted = 0
for line in output.strip().split("\n"):
if not line:
continue
parts = line.split("\t")
if len(parts) < 3:
continue
# バイナリファイルは "-" になる
if parts[0] == "-" or parts[1] == "-":
continue
file_path = parts[2]
# ファイルパターンでフィルタ
if file_pattern and not fnmatch.fnmatch(file_path, file_pattern):
continue
try:
added += int(parts[0])
deleted += int(parts[1])
except ValueError:
continue
return added, deleted
def build_candlestick_data(
repo_path: str,
commits: list[dict],
file_pattern: str | None = None,
) -> pd.DataFrame:
"""ローソク足データを構築"""
data = []
total_lines = 0
for i, commit in enumerate(commits):
added, deleted = get_commit_stats(repo_path, commit["hash"], file_pattern)
open_val = total_lines
close_val = total_lines + added - deleted
high_val = total_lines + added
low_val = total_lines - deleted
data.append({
"index": i,
"hash": commit["hash"][:8],
"full_hash": commit["hash"],
"message": commit["message"][:50],
"full_message": commit["message"],
"date": commit["date"],
"author": commit["author"],
"open": open_val,
"high": high_val,
"low": low_val,
"close": close_val,
"added": added,
"deleted": deleted,
})
total_lines = close_val
# 進捗表示
if (i + 1) % 50 == 0 or i + 1 == len(commits):
print(f"Processing: {i + 1}/{len(commits)} commits")
return pd.DataFrame(data)
def create_chart(
df: pd.DataFrame,
title: str = "Git Commit Candlestick Chart",
hide_message: bool = False,
):
"""ローソク足チャートを作成"""
# ホバーテキストを作成
hover_texts = []
for _, row in df.iterrows():
if hide_message:
text = (
f"<b>{row['hash']}</b><br>"
f"Date: {row['date']}<br>"
f"─────────────<br>"
f"Added: +{row['added']}<br>"
f"Deleted: -{row['deleted']}<br>"
f"Net: {row['close'] - row['open']:+d}<br>"
f"─────────────<br>"
f"Total: {row['open']} → {row['close']}"
)
else:
text = (
f"<b>{row['hash']}</b><br>"
f"{row['full_message']}<br>"
f"─────────────<br>"
f"Date: {row['date']}<br>"
f"Author: {row['author']}<br>"
f"─────────────<br>"
f"Added: +{row['added']}<br>"
f"Deleted: -{row['deleted']}<br>"
f"Net: {row['close'] - row['open']:+d}<br>"
f"─────────────<br>"
f"Total: {row['open']} → {row['close']}"
)
hover_texts.append(text)
# 色を決定(陽線=緑、陰線=赤)
colors = ["#26a69a" if row["close"] >= row["open"] else "#ef5350" for _, row in df.iterrows()]
fig = go.Figure()
# ローソク足を描画
fig.add_trace(go.Candlestick(
x=df["index"],
open=df["open"],
high=df["high"],
low=df["low"],
close=df["close"],
increasing=dict(line=dict(color="#26a69a"), fillcolor="#26a69a"),
decreasing=dict(line=dict(color="#ef5350"), fillcolor="#ef5350"),
hoverinfo="text",
hovertext=hover_texts,
name="Commits",
))
# レイアウト設定
fig.update_layout(
title=dict(
text=title,
font=dict(size=20),
),
xaxis=dict(
title="Commit (chronological order)",
rangeslider=dict(visible=True, thickness=0.05),
tickmode="linear",
dtick=max(1, len(df) // 20),
),
yaxis=dict(
title="Lines of Code",
gridcolor="rgba(128, 128, 128, 0.2)",
),
plot_bgcolor="white",
hovermode="x unified",
showlegend=False,
)
# X軸のラベルをコミットハッシュに
fig.update_xaxes(
ticktext=df["hash"].tolist(),
tickvals=df["index"].tolist(),
)
return fig
def main():
parser = argparse.ArgumentParser(
description="Git Commit Candlestick Chart - コミット履歴をローソク足で可視化"
)
parser.add_argument(
"repo_path",
nargs="?",
default=".",
help="Gitリポジトリのパス (default: current directory)",
)
parser.add_argument(
"-b", "--branch",
help="対象ブランチ (default: current branch)",
)
parser.add_argument(
"-s", "--since",
help="開始日 (e.g., '2024-01-01', '1 month ago')",
)
parser.add_argument(
"-u", "--until",
help="終了日 (e.g., '2024-12-31', 'yesterday')",
)
parser.add_argument(
"-p", "--pattern",
help="ファイルパターン (e.g., '*.py', 'src/*.ts')",
)
parser.add_argument(
"-o", "--output",
help="出力HTMLファイル (指定しない場合はブラウザで表示)",
)
parser.add_argument(
"-n", "--limit",
type=int,
help="最新N件のコミットのみ",
)
parser.add_argument(
"--hide-message",
action="store_true",
help="コミットメッセージと作者を非表示",
)
parser.add_argument(
"--cdn",
action="store_true",
help="plotly.jsをCDNから読み込む(HTMLファイル軽量化)",
)
args = parser.parse_args()
repo_path = str(Path(args.repo_path).resolve())
# リポジトリ確認
try:
run_git(repo_path, "rev-parse", "--git-dir")
except subprocess.CalledProcessError:
print(f"Error: '{repo_path}' is not a git repository")
return 1
print(f"Repository: {repo_path}")
if args.branch:
print(f"Branch: {args.branch}")
if args.pattern:
print(f"File pattern: {args.pattern}")
if args.since:
print(f"Since: {args.since}")
if args.until:
print(f"Until: {args.until}")
# コミット取得
print("\nFetching commits...")
commits = get_commits(repo_path, args.branch, args.since, args.until)
if not commits:
print("No commits found")
return 1
if args.limit:
commits = commits[-args.limit:]
print(f"Found {len(commits)} commits")
# ローソク足データ構築
print("\nBuilding candlestick data...")
df = build_candlestick_data(repo_path, commits, args.pattern)
if df.empty:
print("No data to display")
return 1
# チャート作成
title = f"Git Candlestick: {Path(repo_path).name}"
if args.pattern:
title += f" ({args.pattern})"
fig = create_chart(df, title, hide_message=args.hide_message)
# 出力
if args.output:
# CDNオプション: plotly.jsをCDNから読み込み(約3MB→数KB)
include_plotlyjs = "cdn" if args.cdn else True
fig.write_html(
args.output,
include_plotlyjs=include_plotlyjs,
full_html=True,
config={
"displayModeBar": True,
"responsive": True,
},
)
print(f"\nChart saved to: {args.output}")
if args.cdn:
print("(Using CDN for plotly.js - requires internet connection)")
else:
print("\nOpening chart in browser...")
fig.show()
# サマリー
print(f"\n=== Summary ===")
print(f"Total commits: {len(df)}")
print(f"Initial lines: {df.iloc[0]['open']}")
print(f"Final lines: {df.iloc[-1]['close']}")
print(f"Net change: {df.iloc[-1]['close'] - df.iloc[0]['open']:+d}")
return 0
if __name__ == "__main__":
exit(main())