- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmake_data.py
More file actions
Latest commit
executable file
·295 lines (245 loc) · 9.91 KB
/
Copy pathmake_data.py
File metadata and controls
executable file
·295 lines (245 loc) · 9.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
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
""" Module provide functions to make data """
importos
importre
fromtypingimportList, Callable, Tuple, TypeVar
importrequests
importpygit2
importpandasaspd
frombs4importBeautifulSoup
frommarkdownimportmarkdown
fromsettingsimportROOTDIR, HEADERS, VALID_RN_NUM, VALID_LINK_NUM, CM, PR, IS
Time=TypeVar("Time")
Markdown=TypeVar("Markdown")
classMyRemoteCallbacks(pygit2.RemoteCallbacks):
""" Define function to show state of cloning process """
deftransfer_progress(self, stats):
print(f'{stats.indexed_objects}/{stats.total_objects}')
defcrawl_repos(result_path: str) ->None:
""" Crawl Github repo with highest star number
(Assume that the higher star number the higher project quality)
Store result in result_path """
result= []
foriinrange(50):
print(i+1)
resp=requests.get(f"https://gitstar-ranking.com/repositories?page={i+1}")
soup=BeautifulSoup(resp.text, "html.parser")
repos_container=soup.find("div", {"class": "row"})
repos=repos_container.find_all('a')
forrepoinrepos:
result.append('/'.join(repo["href"].split('/')[-2:]))
result=pd.DataFrame({"Repo": result})
result.to_csv(result_path)
deftraverse_repos(repo_list_path: str, func: Callable[[str, str], None]) ->None:
""" This function do func in range of all repositories in repo list file"""
repos=pd.read_csv(repo_list_path)
error_log=open("error_log.txt", "a+")
forrepoinrepos["Repo"]:
try:
func(repo)
exceptExceptionase:
error_log.write((f"Repo {repo} encounter error: {e.messageifhasattr(e, 'message') elsee} "
f"in function {func.__name__}\n"))
error_log.close()
defgithub_api(repo: str, component: str, func: Callable, params: str="") ->List[str]:
""" Get all specific component of element has type is type using github_api """
page=1
all_els= []
whileTrue:
url=f"https://api.github.com/repos/{repo}/{component}?{params}&per_page=100&page={page}"
try:
response=requests.get(url, headers=HEADERS)
response.raise_for_status()
exceptrequests.HTTPError:
ifresponse.status_code==422:
break
else:
raiseIOError("Http Error")
exceptrequests.Timeout:
raiseIOError("Timeout Error")
els=response.json()
els_per_page= [func(el) forelinels]
all_els+=els_per_page
# 100 is the limit of per_page param in github api
iflen(els) <100:
break
page+=1
returnall_els
defcrawl_rn(repo: str) ->Callable[[str, str, str, Callable], List[str]]:
""" Crawl all release notes at repo"""
print(repo)
returngithub_api(repo, component="releases", func=lambdael: el)
defcrawl_pr(repo: str) ->Callable[[str, str, str, Callable], List[str]]:
""" Crawl all pull requests of repo """
print(repo)
returngithub_api(repo, component="pulls", params="state=all", func=lambdael: el)
defcrawl_issue(repo: str) ->Callable[[str, str, str, Callable], List[str]]:
""" Crawl all issues of repo """
print(repo)
returngithub_api(repo, component="issues", params="state=all", func=lambdael: el)
defcrawl_cm(repo: str) ->List[str]:
""" Crawl all commits in repo """
folder=repo.replace('/', '_')
path=os.path.join(ROOTDIR, "repos", folder)
assertos.path.exists(path)
cmd=f""" cd {path}
git branch -a"""
all_branches=os.popen(cmd).read().split('\n')[:-1]
all_branches= [branch.strip() forbranchinall_branchesif"HEAD ->"notinbranch]
all_commit_shas=set()
forbranchinall_branches[1:]:
try:
cmd=f"""cd {path}
git rev-list {branch}"""
commit_shas=os.popen(cmd).read()
# Each line is a commit sha and the last line is empty line
commit_shas=commit_shas.split('\n')[:-1]
all_commit_shas.update(commit_shas)
exceptException:
continue
repo=pygit2.Repository(path)
# Get commit message from commit sha
commits= [repo.revparse_single(commit_sha) forcommit_shainall_commit_shas]
# Get all commit message and commit sha
commits= [
{
"message": commit.message,
"sha": commit.hex,
"author": commit.author,
"commit_time": commit.commit_time,
"committer": commit.committer
}
forcommitincommits
]
commits=pd.DataFrame(commits)
returncommits
defcm_spliter(message: str) ->Tuple[str, str]:
""" Split commit into commit summary (the first line) and follow by commit description """
try:
# Convert markdown into html
html=markdown(message)
soup=BeautifulSoup(html, "html.parser")
lines= [p.text.strip() forpinsoup.find_all('p')]
summary=lines[0]
description="<.> ".join(lines[1:])
returnsummary, description
exceptException:
returnNone, None
defclone_repos(repo: str) ->None:
""" Clone github repository """
folder=repo.replace('/', '_')
path=os.path.join(ROOTDIR, "repos", folder)
ifos.path.exists(path):
returnNone
print(repo)
pygit2.clone_repository(f"https://github.com/{repo}", path, callbacks=MyRemoteCallbacks())
defbuild_rn_info(repo: str) ->None:
""" Get information of release notes at repo and store into a csv file at data/[repo] """
folder=repo.replace('/', '_')
print("Repo:",repo)
folder_path=os.path.join(ROOTDIR, "data", folder)
ifnotos.path.exists(folder_path):
os.mkdir(folder_path)
rn_info_path=os.path.join(folder_path, "rn_info.csv")
# Release note info path exists mean that this repo is processed so pass it
ifos.path.exists(rn_info_path):
returnNone
try:
# Crawl changelogs
print("Start crawl release notes")
rn_info=crawl_rn(repo)
print("Crawl release notes done")
assertrn_infoisnotNone
rn_info=pd.DataFrame(rn_info)
rn_info.to_csv(rn_info_path)
exceptExceptionase:
print("Wrong implement at build_rn_info")
raisee
defbuild_cm_info(repo: str) ->None:
""" Get information of commits at repo and store into a csv file at data/[repo] """
folder=repo.replace('/', '_')
print("Repo:", repo)
folder_path=os.path.join(ROOTDIR, "data", folder)
ifnotos.path.exists(folder_path):
os.mkdir(folder_path)
commit_path=os.path.join(folder_path, "commit.csv")
# Commit path exists mean that this repo is processed so pass it
# if os.path.exists(commit_path):
# return None
try:
print("Start load commits")
commits=crawl_cm(repo)
print("Commits loaded")
assertcommitsisnotNone
# Get commit messages and commit descriptions
summa_des= [cm_spliter(commit)
forcommitincommits.loc[:, "message"]]
summaries, descriptions=zip(*summa_des)
commit_df=pd.DataFrame({
"Summary": summaries,
"Description": descriptions,
"Sha": commits["sha"],
"Author": commits["author"],
"Committer": commits["committer"],
"Commit Time": commits["commit_time"]
})
# Check commit messages
print("Num commit messages:", len(commit_df))
print("\n")
print("==============================================")
print("\n")
commit_df.to_csv(commit_path)
exceptExceptionase:
print("Wrong implemen at build_cm_info function")
raisee
defbuild_pr_info(repo: str) ->None:
""" Get information of pull requests at repo and store into a csv file at data/[repo] """
folder=repo.replace('/', '_')
print("Repo:", repo)
folder_path=os.path.join(ROOTDIR, "data", folder)
ifnotos.path.exists(folder_path):
os.mkdir(folder_path)
pr_info_path=os.path.join(folder_path, "pr_info.csv")
# Pull request info path exists mean that this repo is processed so pass it
ifos.path.exists(pr_info_path):
returnNone
try:
# Crawl changelogs
print("Start crawl pull requests")
pr_info=crawl_pr(repo)
print("Crawl pull requests done")
assertpr_infoisnotNone
pr_info=pd.DataFrame(pr_info)
pr_info.to_csv(pr_info_path)
exceptExceptionase:
print("Wrong implement at build_pr_info function")
raisee
defbuild_issue_info(repo: str) ->None:
""" Get information of release notes at repo and store into a csv file at data/[repo] """
folder=repo.replace('/', '_')
print("Repo",repo)
folder_path=os.path.join(ROOTDIR, "data", folder)
ifnotos.path.exists(folder_path):
os.mkdir(folder_path)
issue_info_path=os.path.join(folder_path, "issue_info.csv")
# Issue info path exists mean that this repo is processed so pass it
ifos.path.exists(issue_info_path):
returnNone
try:
# Crawl changelogs
print("Start crawl issues")
issue_info=crawl_issue(repo)
print("Crawl issues done")
issue_info=pd.DataFrame(issue_info)
issue_info.to_csv(issue_info_path)
exceptExceptionase:
print("Wrong implement at build_issue_info function")
raisee
defmake_data() ->None:
""" This function define a pipeline to get data from top repositories in Github (sort by stars) that statisfy
some rule for specific problem """
# crawl_repos("raw_repos.csv")
# traverse_repos("valid_repos.csv", clone_repos)
# traverse_repos("valid_repos.csv", build_rn_info)
# traverse_repos("valid_repos.csv", build_cm_info)
# traverse_repos("valid_repos.csv", build_pr_info)
# traverse_repos("valid_repos.csv", build_issue_info)