-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetchgithubfiles.py
More file actions
218 lines (149 loc) · 5.84 KB
/
fetchgithubfiles.py
File metadata and controls
218 lines (149 loc) · 5.84 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
import requests
import sys
import base64
import json
import os
import argparse
from pathlib import Path
# GLOBAL VARIABLES
language = ""
fileExtension = ""
apiToken = None
maxRepos = 100
directory = Path("./fetchedfiles")
topic = None
keywords = None
#####################################################################
# COMMAND LINE ARGUMENTS AND OPTIONS PARSING
parser = argparse.ArgumentParser()
# Positional arguments
parser.add_argument(
"Language", help="Set the programming language you want to search for")
parser.add_argument(
"FileExtension", help="Set the extension (without .) you want to search for")
# Options
parser.add_argument("-apitoken", "--ApiToken", help="Set your GitHub API token")
parser.add_argument("-mr", "--MaxRepos",
help="Set max number of repos pages to be fetched")
parser.add_argument("-d", "--Directory",
help="Set the directory where downloaded files will be stored")
parser.add_argument("-t", "--Topic", help="Filter repositories by topic")
parser.add_argument("-k", "--Keywords", nargs='+',
help="Filter repositories by keywords")
args = parser.parse_args()
if args.ApiToken != None:
apiToken = args.ApiToken
if args.MaxRepos != None:
maxRepos = abs(int(args.MaxRepos))
if args.Language != None:
language = (args.Language).lower()
if args.FileExtension != None:
fileExtension = (args.FileExtension).lower()
if args.Directory != None:
directory = Path(args.Directory)
if args.Topic != None:
topic = (args.Topic).lower()
if args.Keywords != None:
keywords = args.Keywords
keywords = '+'.join(keywords)
#####################################################################
# FUNCTIONS
def getAPIToken():
global apiToken
if apiToken != None:
return
if "GHScraperAPIToken" in os.environ:
apiToken = str(os.environ["GHScraperAPIToken"])
return
print("Error! API token not provided neither via option nor via environment variable")
sys.exit()
def checkAPIRateExceeded(JSONresponse):
if "message" in JSONresponse and "API rate limit exceeded" in JSONresponse["message"]:
print("API Rate Exceeded")
sys.exit()
def printJSONLog(log):
with open("log.json", "w") as o:
o.write(json.dumps(log))
o.close()
def fetchRepos(page, reposPerPage, headers):
queryString = "https://api.github.com/search/repositories?q="
if keywords != None:
queryString = queryString + keywords
if topic != None:
queryString = queryString + "+topic:" + str(topic)
queryString = queryString + "+language:" + str(language)
queryString = queryString + "&order=desc&page=" + \
str(page) + "&per_page=" + str(reposPerPage)
response = requests.get(queryString, headers=headers)
JSONresponse = response.json()
if not ("items" in JSONresponse):
checkAPIRateExceeded(JSONresponse)
printJSONLog(JSONresponse)
return None
print("Fetched " + str(len(JSONresponse["items"])) + " " + str(
language) + " language repos (page " + str(page) + ")")
return JSONresponse["items"]
def fetchRepoFiles(repoFullName, headers):
request = requests.get("https://api.github.com/search/code?q=extension:" +
str(fileExtension) + "+repo:" + str(repoFullName) + "&per_page=100", headers=headers)
JSONresponse = request.json()
if not ("items" in JSONresponse):
checkAPIRateExceeded(JSONresponse)
printJSONLog(JSONresponse)
return None
print("\tFetched " + str(len(JSONresponse["items"])
) + " files for " + str(repoFullName) + " repo")
return JSONresponse["items"]
def fetchSingleFile(repoFullName, fileName, filePath, headers):
request = requests.get("https://api.github.com/repos/" +
str(repoFullName) + "/contents/" + str(filePath), headers=headers)
JSONresponse = request.json()
if not ("content" in JSONresponse):
checkAPIRateExceeded(JSONresponse)
print("\t\tFetched file " + str(fileName) + " ... ", end="")
return JSONresponse["content"]
def decodeFileContent(fileContent):
return base64.b64decode(fileContent).decode()
def downloadSingleFile(repoName, fileName, fileContent):
print("Downloading ... ", end="")
with open(directory / (str(repoName) + "_" + str(fileName)), "w") as o:
o.write(fileContent)
o.close()
print("Done!")
return
#####################################################################
# MAIN
getAPIToken()
headers = {
'Accept': 'application/vnd.github.preview.text-match+json',
'Authorization': "token " + str(apiToken)
}
# Create directory where files will be downloaded
os.makedirs(directory, exist_ok=True)
page = 1
countFetchedRepos = 0
reposPerPage = maxRepos % 100
while countFetchedRepos <= maxRepos:
fetchedRepos = fetchRepos(page, reposPerPage, headers)
if fetchedRepos == None:
break
for repo in fetchedRepos: # For each repo, fetch files in that repo
if repo["fork"] == True:
continue
repoName = repo["name"]
repoFullName = repo["full_name"]
fetchedFilesList = fetchRepoFiles(repoFullName, headers)
if fetchedFilesList == None:
break
for file in fetchedFilesList: # Download each file in fetchedFiles
fileName = file["name"]
filePath = file["path"]
fetchedFile = fetchSingleFile(
repoFullName, fileName, filePath, headers)
if fetchedFile == None:
break
fileContent = decodeFileContent(fetchedFile)
downloadSingleFile(repoName, fileName, fileContent)
page = page + 1 # Next page
print("############## END OF FETCHED FILES ##############")
#####################################################################