-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaverage-time.py
193 lines (136 loc) · 5.57 KB
/
average-time.py
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
from dotenv import load_dotenv
import os
import requests
from datetime import datetime, time, timedelta
load_dotenv()
working_hours_start = time(int(os.environ.get("WORKING_HOURS_START", 7)), 0)
working_hours_end = time(int(os.environ.get("WORKING_HOURS_END", 20)), 0)
def get_required_env_variable():
access_token = os.environ.get("GITHUB_ACCESS_TOKEN")
repo_owner = os.environ.get("GITHUB_REPO_OWNER")
repo_name = os.environ.get("GITHUB_REPO_NAME")
return access_token, repo_owner, repo_name
def check_env_variables():
access_token, repo_owner, repo_name = get_required_env_variable()
if not access_token or not repo_owner or not repo_name:
print(
"Please set GITHUB_ACCESS_TOKEN, GITHUB_REPO_OWNER, and GITHUB_REPO_NAME environment variables."
)
exit()
def calculate_working_hours(
start_time, end_time, working_hours_start, working_hours_end
):
start_of_working_hours = max(
start_time, datetime.combine(start_time.date(), working_hours_start)
)
end_of_working_hours = min(
end_time, datetime.combine(end_time.date(), working_hours_end)
)
return max(
0, (end_of_working_hours - start_of_working_hours).total_seconds() / 3600
)
def get_approval_time_for_pr(pr_number):
access_token, repo_owner, repo_name = get_required_env_variable()
url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/pulls/{pr_number}/reviews"
headers = {"Authorization": f"Bearer {access_token}"}
response = requests.get(url, headers=headers)
if not response.status_code == 200:
return None
timeline_data = response.json()
for event in timeline_data:
if event["state"] == "APPROVED":
return datetime.strptime(event["submitted_at"], "%Y-%m-%dT%H:%M:%SZ")
def filter_pull_requests_by_date(pull_requests):
filtered_pull_requests = []
latest_date = datetime.strptime(
os.environ.get("LATEST_DATE", "2022-12-31"), "%Y-%m-%d"
)
for pr in pull_requests:
created_at = datetime.strptime(pr["created_at"], "%Y-%m-%dT%H:%M:%SZ")
if created_at >= latest_date:
filtered_pull_requests.append(pr)
return filtered_pull_requests, len(pull_requests) > len(filtered_pull_requests)
def get_all_pull_requests():
access_token, repo_owner, repo_name = get_required_env_variable()
print("Retrieving pull requests...")
url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/pulls"
params = {
"state": "closed",
"per_page": 100,
"page": 1,
"sort": "created",
"direction": "desc",
}
headers = {"Authorization": f"Bearer {access_token}"}
all_pull_requests = []
while True:
response = requests.get(url, params=params, headers=headers)
if not response.status_code == 200:
print(
f"Failed to retrieve pull requests. Status code: {response.status_code}"
)
break
pull_requests = response.json()
if not pull_requests:
break
filtered_pull_requests, removed_old_pull_requests = (
filter_pull_requests_by_date(pull_requests)
)
all_pull_requests.extend(filtered_pull_requests)
print(f"{len(all_pull_requests)} PRs retrieved", end="\r", flush=True)
if removed_old_pull_requests:
break
params["page"] += 1
print(f"Retrieved {len(all_pull_requests)} pull requests")
return all_pull_requests
check_env_variables()
# Accumulate approval times across all pages
total_approval_times = {}
pull_requests = get_all_pull_requests()
analyzed_prs = 0
for pr in pull_requests:
created_at = datetime.strptime(pr["created_at"], "%Y-%m-%dT%H:%M:%SZ")
author = pr["user"]["login"]
if not pr["merged_at"]:
continue # Skip if the pull request has not been merged
pr_number = pr["number"]
approval_time = get_approval_time_for_pr(pr_number)
if not approval_time:
continue
# Initialize adjusted approval duration
approval_duration = 0
# Iterate through days between submission and approval
current_day = created_at.date()
while current_day <= approval_time.date():
# Determine the relevant working hours for the current day
current_start_time = max(
created_at, datetime.combine(current_day, working_hours_start)
)
current_end_time = min(
approval_time, datetime.combine(current_day, working_hours_end)
)
# Calculate the time spent within working hours for the current day
current_duration = calculate_working_hours(
current_start_time,
current_end_time,
working_hours_start,
working_hours_end,
)
# Add the time spent on the current day to the total approval
# duration
approval_duration += current_duration
# Move to the next day
current_day += timedelta(days=1)
analyzed_prs += 1
print(f"{analyzed_prs} PRs analyzed", end="\r", flush=True)
if author not in total_approval_times:
total_approval_times[author] = []
total_approval_times[author].append(approval_duration)
print(f"Analyzed {analyzed_prs}")
for author, approval_times in total_approval_times.items():
average_approval_time = sum(approval_times) / len(approval_times)
hours, remainder = divmod(average_approval_time * 3600, 3600)
minutes, seconds = divmod(remainder, 60)
print(
f"Author: {author}, Total Average Approval Time: {int(hours)} hours {int(minutes)} minutes {int(seconds)} seconds"
)