-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit_commit_stats.py
More file actions
265 lines (225 loc) · 9.26 KB
/
Copy pathgit_commit_stats.py
File metadata and controls
265 lines (225 loc) · 9.26 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
#!/usr/bin/env python3
"""
Git Commit Stats - Analyze git commit patterns and generate statistics
"""
import subprocess
import sys
import argparse
import json
from datetime import datetime, timedelta
from collections import defaultdict, Counter
from pathlib import Path
class GitCommitStats:
def __init__(self, repo_path='.', days=365, author=None):
self.repo_path = Path(repo_path)
self.days = days
self.author = author
self.stats = {}
def run_git_command(self, cmd):
"""Execute git command and return output"""
try:
result = subprocess.run(
cmd,
cwd=self.repo_path,
capture_output=True,
text=True,
check=True
)
return result.stdout.strip()
except subprocess.CalledProcessError as e:
print(f"Error running git command: {e}", file=sys.stderr)
return ""
def get_commits(self):
"""Get commit log with details"""
since_date = (datetime.now() - timedelta(days=self.days)).strftime('%Y-%m-%d')
cmd = [
'git', 'log',
f'--since={since_date}',
'--pretty=format:%H|%an|%ae|%ad|%s',
'--date=iso',
'--numstat'
]
if self.author:
cmd.append(f'--author={self.author}')
return self.run_git_command(cmd)
def parse_commits(self, log_output):
"""Parse git log output into structured data"""
commits = []
current_commit = None
for line in log_output.split('\n'):
if not line:
continue
if '|' in line and len(line.split('|')) == 5:
# New commit line
if current_commit:
commits.append(current_commit)
hash_id, author, email, date, subject = line.split('|')
current_commit = {
'hash': hash_id,
'author': author,
'email': email,
'date': datetime.fromisoformat(date.rsplit(' ', 1)[0]),
'subject': subject,
'files_changed': [],
'additions': 0,
'deletions': 0
}
elif current_commit and '\t' in line:
# File change line
parts = line.split('\t')
if len(parts) == 3:
additions, deletions, filename = parts
try:
adds = int(additions) if additions != '-' else 0
dels = int(deletions) if deletions != '-' else 0
current_commit['additions'] += adds
current_commit['deletions'] += dels
current_commit['files_changed'].append(filename)
except ValueError:
pass
if current_commit:
commits.append(current_commit)
return commits
def analyze(self):
"""Analyze commits and generate statistics"""
log_output = self.get_commits()
commits = self.parse_commits(log_output)
if not commits:
return {
'total_commits': 0,
'message': 'No commits found in the specified period'
}
# Basic stats
total_commits = len(commits)
total_additions = sum(c['additions'] for c in commits)
total_deletions = sum(c['deletions'] for c in commits)
# Author stats
authors = Counter(c['author'] for c in commits)
# Time-based stats
hours = Counter(c['date'].hour for c in commits)
weekdays = Counter(c['date'].strftime('%A') for c in commits)
months = Counter(c['date'].strftime('%Y-%m') for c in commits)
# File type stats
file_types = Counter()
for commit in commits:
for file in commit['files_changed']:
ext = Path(file).suffix or 'no-extension'
file_types[ext] += 1
self.stats = {
'repository': self.repo_path.name,
'period_days': self.days,
'total_commits': total_commits,
'total_additions': total_additions,
'total_deletions': total_deletions,
'top_contributors': [
{'author': author, 'commits': count, 'percentage': round(count/total_commits*100, 1)}
for author, count in authors.most_common(10)
],
'commits_by_hour': dict(sorted(hours.items())),
'commits_by_weekday': dict(weekdays),
'commits_by_month': dict(sorted(months.items())),
'top_file_types': dict(file_types.most_common(10)),
'avg_additions_per_commit': round(total_additions / total_commits, 1),
'avg_deletions_per_commit': round(total_deletions / total_commits, 1)
}
return self.stats
def format_text(self):
"""Format statistics as readable text"""
if not self.stats or self.stats.get('total_commits', 0) == 0:
return self.stats.get('message', 'No data available')
output = []
output.append("\n📊 Git Commit Statistics")
output.append("━" * 80)
output.append(f"\nRepository: {self.stats['repository']}")
output.append(f"Period: Last {self.stats['period_days']} days")
output.append(f"Total Commits: {self.stats['total_commits']:,}")
output.append(f"Lines Added: +{self.stats['total_additions']:,}")
output.append(f"Lines Deleted: -{self.stats['total_deletions']:,}")
output.append("\n\n👥 Top Contributors")
output.append("━" * 80)
for i, contrib in enumerate(self.stats['top_contributors'][:5], 1):
bar = "█" * int(contrib['percentage'] / 5)
output.append(f"{i}. {contrib['author']:<20} {bar:<20} {contrib['commits']} commits ({contrib['percentage']}%)")
output.append("\n\n⏰ Most Active Hours")
output.append("━" * 80)
hours_sorted = sorted(self.stats['commits_by_hour'].items(), key=lambda x: x[1], reverse=True)[:5]
max_hour_commits = max(h[1] for h in hours_sorted) if hours_sorted else 1
for hour, count in hours_sorted:
bar = "█" * int(count / max_hour_commits * 20)
output.append(f"{hour:02d}:00-{hour+1:02d}:00 {bar:<20} {count} commits")
output.append("\n\n📅 Commits by Day of Week")
output.append("━" * 80)
weekday_order = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
weekday_data = [(day, self.stats['commits_by_weekday'].get(day, 0)) for day in weekday_order]
max_day_commits = max(d[1] for d in weekday_data) if weekday_data else 1
for day, count in weekday_data:
bar = "█" * int(count / max_day_commits * 20)
output.append(f"{day:<12} {bar:<20} {count} commits")
output.append("\n\n📁 Top File Types")
output.append("━" * 80)
for ext, count in list(self.stats['top_file_types'].items())[:5]:
output.append(f"{ext:<15} {count} changes")
output.append("\n")
return "\n".join(output)
def format_json(self):
"""Format statistics as JSON"""
return json.dumps(self.stats, indent=2)
def main():
parser = argparse.ArgumentParser(
description='Analyze git commit patterns and generate statistics'
)
parser.add_argument(
'repo_path',
nargs='?',
default='.',
help='Path to git repository (default: current directory)'
)
parser.add_argument(
'--days',
type=int,
default=365,
help='Number of days to analyze (default: 365)'
)
parser.add_argument(
'--author',
help='Filter commits by author name'
)
parser.add_argument(
'--format',
choices=['text', 'json'],
default='text',
help='Output format (default: text)'
)
parser.add_argument(
'--export',
help='Export results to file'
)
args = parser.parse_args()
# Check if git is available
try:
subprocess.run(['git', '--version'], capture_output=True, check=True)
except (subprocess.CalledProcessError, FileNotFoundError):
print("Error: git is not installed or not in PATH", file=sys.stderr)
sys.exit(1)
# Check if path is a git repository
repo_path = Path(args.repo_path)
if not (repo_path / '.git').exists():
print(f"Error: {repo_path} is not a git repository", file=sys.stderr)
sys.exit(1)
# Analyze commits
analyzer = GitCommitStats(str(repo_path), args.days, args.author)
analyzer.analyze()
# Format output
if args.format == 'json':
output = analyzer.format_json()
else:
output = analyzer.format_text()
# Print or export
if args.export:
with open(args.export, 'w') as f:
f.write(output)
print(f"Results exported to {args.export}")
else:
print(output)
if __name__ == '__main__':
main()