-
Notifications
You must be signed in to change notification settings - Fork 0
/
collect_commit_data_pr.py
215 lines (188 loc) · 8.91 KB
/
collect_commit_data_pr.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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
#!/usr/bin/env python
# coding: utf-8
# In[322]:
import sys
sys.executable
# In[381]:
import ast
import pandas as pd
import numpy as np
from pygit2 import Object, Repository, GIT_SORT_TIME
from pygit2 import init_repository, Patch
from colorama import Fore
from tqdm import tqdm
import swifter
from pandarallel import pandarallel
import subprocess
import warnings
from joblib import Parallel, delayed
import os
import multiprocessing
import time
import random
# In[388]:
def createCommitGroup(commit_list, parent_commit):
try:
if type(commit_list) != list and type(commit_list) != type(pd.Series()) and type(commit_list) != np.ndarray:
commit_list = ast.literal_eval(commit_list)
if len(commit_list) == 0:
return [[]]
elif len(commit_list) == 1:
return [[parent_commit, commit_list[0]]]
else:
avail_commits = len(commit_list)
lst_result = [[parent_commit, commit_list[0]]]
for i in range(avail_commits-1):
lst_result.append([commit_list[i], commit_list[i+1]])
return lst_result
except:
return [[]]
def getHead(commit_list, pull_number, repo_loc):
try:
if type(commit_list) != list and type(commit_list) != type(pd.Series()) and type(commit_list) != np.ndarray:
commit = ast.literal_eval(commit_list)[0]
else:
commit = commit_list[0]
pull_fetch = subprocess.Popen(["git","fetch", "origin", f"pull/{pull_number}/head"], cwd = f"{repo_loc}",
shell=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).wait()
result = subprocess.run(["git","show", f"{commit}^"], cwd = f"{repo_loc}", capture_output = True, text = True).stdout[7:47]
return result
except Exception as e:
return []
# In[390]:
def returnCommitStats(x):
try:
if len(x) < 2:
return []
if x[0] == [] or x[1] == []:
return []
commit_parent_sha = x[0]
commit_head_sha = x[1]
commit_parent = repo.get(commit_parent_sha)
commit_head = repo.get(commit_head_sha)
if type(commit_parent) != type(None) and type(commit_head) != type(None):
diff = repo.diff(commit_parent, commit_head, context_lines=0, interhunk_lines=0)
commit_sha = commit_head_sha
commit_author_name = commit_head.author.name
commit_author_email = commit_head.author.email
committer_author_name = commit_head.committer.name
committer_author_email = commit_head.committer.email
commit_message = commit_head.message
commit_additions = diff.stats.insertions
commit_deletions = diff.stats.deletions
commit_changes_total = commit_additions + commit_deletions
commit_files_changed_count = diff.stats.files_changed
commit_time = commit_head.commit_time
commit_file_changes = []
for obj in diff:
if type(obj) == Patch:
additions = 0
deletions = 0
for hunk in obj.hunks:
for line in hunk.lines:
# The new_lineno represents the new location of the line after the patch. If it's -1, the line has been deleted.
if line.new_lineno == -1:
deletions += 1
# Similarly, if a line did not previously have a place in the file, it's been added fresh.
if line.old_lineno == -1:
additions += 1
commit_file_changes.append({'file':obj.delta.new_file.path,
'additions': additions,
'deletions': deletions,
'total': additions + deletions})
return [commit_sha, commit_author_name, commit_author_email, committer_author_name, committer_author_email,
commit_message, commit_additions, commit_deletions, commit_changes_total, commit_files_changed_count,
commit_file_changes, commit_time]
return []
except:
return []
def cleanCommitData(library, repo_loc, partition, num_partitions = 20):
# In[386]:
df_library = df_pr[df_pr['repo_name'] == library]
if partition < num_partitions:
df_library = df_library.head(partition * int(df_library.shape[0]/num_partitions)).tail(int(df_library.shape[0]/num_partitions))
else:
df_library = df_library.tail(df_library.shape[0] - (num_partitions - 1) * int(df_library.shape[0]/num_partitions))
# In[387]:
global repo
repo = Repository(repo_loc)
df_library['parent_commit'] = df_library.parallel_apply(lambda x: getHead(x['commit_list'], x['pr_number'], repo_loc), axis = 1)
print(f"finished getting parent commits for {library}")
df_library['commit_groups'] = \
df_library.parallel_apply(lambda x: createCommitGroup(x['commit_list'], x['parent_commit']), axis = 1)
df_commit_groups = df_library[['pr_number', 'repo_id', 'repo_name', 'actor_id', 'actor_login',
'org_id', 'org_login', 'pr_state', 'commit_groups']].explode('commit_groups')
df_commit_groups = df_commit_groups[df_commit_groups['commit_groups'].apply(lambda x: len(x)>0)]
commit_data = df_commit_groups['commit_groups'].parallel_apply(lambda x: returnCommitStats(x))
# In[ ]:
df_commit = pd.DataFrame(commit_data.tolist(),
columns = ['commit sha', 'commit author name', 'commit author email', 'committer name',
'commmitter email', 'commit message', 'commit additions', 'commit deletions',
'commit changes total', 'commit files changed count', 'commit file changes',
'commit time'])
# In[ ]:
df_commit_final = pd.concat([df_commit_groups.reset_index(drop = True), df_commit], axis = 1)
for col in ['pr_number', 'repo_id', 'actor_id']:
df_commit_final[col] = pd.to_numeric(df_commit_final[col])
return df_commit_final
def getCommitData(library, partition, num_partitions, folder):
# download repo
lib_p2 = library.split("/")[1]
lib_ren = library.replace("/","___")
if f'commits_pr_{lib_ren}.parquet' not in os.listdir(f'data/github_commits/parquet/{folder}'):
try:
print(f"Starting {library}")
start = time.time()
if lib_ren not in os.listdir("repos2"):
subprocess.Popen(["git", "clone", f"git@github.com:{library}.git", f"{lib_ren}"], cwd = "repos2").communicate()
else:
return
print(f"Finished cloning {library}")
df_lib = cleanCommitData(library, f"repos2/{lib_ren}", partition, num_partitions)
if partition == 1 and num_partitions == 1:
df_lib.to_parquet(f'data/github_commits/parquet/{folder}/commits_pr_{lib_ren}.parquet',
engine='fastparquet')
else:
df_lib.to_parquet(f'data/github_commits/parquet/{folder}/commits_pr_{lib_ren}_p{partition}.parquet',
engine='fastparquet')
end = time.time()
subprocess.Popen(["rm", "-rf", f"{lib_ren}"], cwd = "repos2").communicate()
print(f"{library} completed in {start - end}")
return "success"
except Exception as e:
return f"failure, {str(e)}"
return 'success'
if __name__ == '__main__':
# In[382]:
pandarallel.initialize(progress_bar=True)
warnings.filterwarnings("ignore")
folder = sys.argv[1]
# In[385]:
# import all pull request data
df_pr = pd.DataFrame()
commit_urls = []
for val in np.arange(0, 500, 1):
if int(val) < 10:
val = f"0{val}"
if int(val) < 100:
val = f"0{val}"
try:
df_part = pd.read_csv(f'data/github_clean/{folder}/prEventCommits000000000{val}.csv', index_col = 0)
df_part['partition'] = val
df_pr = pd.concat([df_pr, df_part])
except:
print(f'data/github_clean/{folder}/prEventCommits000000000{val}.csv not found')
repos = df_pr['repo_name'].unique().tolist()
repos = [ele for ele in repos if "/" in ele]
random.shuffle(repos)
results = []
#repos = ['lablup/backend.ai']
#repos = ['Azure/azure-sdk-for-python']
for r in repos:
if r not in ["ansible/ansible", "apache/airflow", "apache/spark", "pandas-dev/pandas", "pytorch/pytorch"]:
result = getCommitData(r,1,1, folder)
#for i in np.arange(1, 21, 1):
# result = getCommitData(r,i, 20, folder)
# print(r, result)
results.append(result)
print("Done!")