forked from mazen160/GithubCloner
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithubcloner.py
More file actions
executable file
·413 lines (349 loc) · 14.2 KB
/
githubcloner.py
File metadata and controls
executable file
·413 lines (349 loc) · 14.2 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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
#!/usr/bin/env python3
# coding=utf-8
# *******************************************************************
# *** GithubCloner ***
# * Description:
# A script that clones public Github repositories
# of users and organizations automatically.
# * Version:
# v0.3
# * Homepage:
# https://github.com/mazen160/GithubCloner
# * Author:
# Mazin Ahmed <Mazin AT MazinAhmed DOT net>
# *******************************************************************
# Modules
import argparse
import git
import json
import os
import queue
import requests
import threading
import time
class getReposURLs(object):
def __init__(self):
self.user_agent = "GithubCloner (https://github.com/mazen160/GithubCloner)"
self.headers = {'User-Agent': self.user_agent, 'Accept': '*/*'}
self.timeout = 3
def UserGists(self, user, username=None, token=None):
"""
Returns a list of GIT URLs for accessible gists.
Input:-
user: Github user.
Optional Input:-
username: Github username.
token: Github token or password.
Output:-
a list of Github gist repositories URLs.
"""
URLs = []
API = "https://api.github.com/users/{}/gists".format(user)
if (username or token) is None:
resp = requests.get(API, headers=self.headers, timeout=self.timeout).text
else:
resp = requests.get(API, headers=self.headers, timeout=self.timeout, auth=(username, token)).text
resp = json.loads(resp)
try:
if (resp["message"] == "Not Found"):
return([]) # The organization does not exist. Returning an empty list.
except TypeError:
pass
for i in range(len(resp)):
URLs.append(resp[i]["git_pull_url"])
return(URLs)
def AuthenticatedGists(self, username, token):
"""
Returns a list of gists of an authenticated user.
Input:-
username: Github username.
token: Github token or password.
Output:-
a list of Github gist repositories URLs.
"""
URLs = []
API = "https://api.github.com/gists"
resp = requests.get(API, headers=self.headers, timeout=self.timeout, auth=(username, token)).text
resp = json.loads(resp)
for i in range(len(resp)):
URLs.append(resp[i]["git_pull_url"])
return(URLs)
def fromUser(self, user, username=None, token=None, include_gists=False):
"""
Retrieves a list of repositories for a Github user.
Input:-
user: Github username.
Optional Input:-
username: Github username.
token: Github token or password.
Output:-
a list of Github repositories URLs.
"""
URLs = []
API = "https://api.github.com/users/{}/repos?per_page=40000000".format(user)
if (username or token) is None:
resp = requests.get(API, headers=self.headers, timeout=self.timeout).text
else:
resp = requests.get(API, headers=self.headers, timeout=self.timeout, auth=(username, token)).text
resp = json.loads(resp)
try:
if (resp["message"] == "Not Found"):
return([]) # The user does not exist. Returning an empty list.
except TypeError:
pass
for i in range(len(resp)):
URLs.append(resp[i]["git_url"])
if include_gists is True:
URLs.extend(self.UserGists(user, username=username, token=token))
return(URLs)
def fromOrg(self, org_name, username=None, token=None):
"""
Retrieves a list of repositories for a Github organization.
Input:-
org_name: Github organization name.
Optional Input:-
username: Github username.
token: Github token or password.
Output:-
a list of Github repositories URLs.
"""
URLs = []
API = "https://api.github.com/orgs/{}/repos?per_page=40000000".format(org_name)
if (username or token) is None:
resp = requests.get(API, headers=self.headers, timeout=self.timeout).text
else:
resp = requests.get(API, headers=self.headers, timeout=self.timeout, auth=(username, token)).text
resp = json.loads(resp)
try:
if (resp["message"] == "Not Found"):
return([]) # The organization does not exist. Returning an empty list.
except TypeError:
pass
for i in range(len(resp)):
URLs.append(resp[i]["git_url"])
return(URLs)
def fromOrgIncludeUsers(self, org_name, username=None, token=None, include_gists=False):
"""
Retrieves a list of repositories for a Github organization
and repositories of the Github organization's members.
Input:-
org_name: Github organization name.
Optional Input:-
username: Github username.
token: Github token or password.
Output:-
a list of Github repositories URLs.
"""
URLs = []
members = []
URLs.extend(self.fromOrg(org_name, username=username, token=token))
API = "https://api.github.com/orgs/{}/members?per_page=40000000".format(org_name)
if (username or token) is None:
resp = requests.get(API, headers=self.headers, timeout=self.timeout).text
else:
resp = requests.get(API, headers=self.headers, timeout=self.timeout, auth=(username, token)).text
resp = json.loads(resp)
try:
if (resp["message"] == "Not Found"):
return([]) # The organization does not exist. Returning an empty list.
except TypeError:
pass
for i in range(len(resp)):
members.append(resp[i]["login"])
for member in members:
URLs.extend(self.fromUser(member, username=username, token=token, include_gists=include_gists))
return(URLs)
def checkAuthencation(self, username, token):
"""
Checks whether an authentication credentials are valid or not.
Input:-
username: Github username.
token: Github token or password.
Output:-
True: if the authentication credentials are valid.
False: if the authentication credentials are invalid.
"""
API = "https://api.github.com/user"
resp = requests.get(API, auth=(username, token), timeout=self.timeout, headers=self.headers)
if resp.status_code == 200:
return(True)
else:
return(False)
def fromAuthenticatedUser(self, username, token):
"""
Retrieves a list of Github repositories than an authenticated user
has access to.
Input:-
username: Github username.
token: Github token or password.
Output:-
a list of Github repositories URLs.
"""
URLs = []
API = "https://api.github.com/user/repos?per_page=40000000&type=all"
resp = requests.get(API, headers=self.headers, timeout=self.timeout, auth=(username, token)).text
resp = json.loads(resp)
for i in range(len(resp)):
URLs.append(resp[i]["git_url"])
return(URLs)
def cloneRepo(URL, cloningpath, username=None, token=None):
"""
Clones a single GIT repository.
Input:-
URL: GIT repository URL.
cloningPath: the directory that the repository will be cloned at.
Optional Input:-
username: Github username.
token: Github token or password.
"""
try:
try:
if not os.path.exists(cloningpath):
os.mkdir(cloningpath)
except Exception:
pass
URL = URL.replace("git://", "https://")
if (username or token) is not None:
URL = URL.replace("https://", "https://{}:{}@".format(username, token))
repopath = URL.split("/")[-2] + "_" + URL.split("/")[-1]
repopath = repopath.rstrip(".git")
if '@' in repopath:
repopath = repopath.replace(repopath[:repopath.index("@") + 1], "")
fullpath = cloningpath + "/" + repopath
with threading.Lock():
print(fullpath)
git.Repo.clone_from(URL, fullpath)
except Exception:
print("Error: There was an error in cloning [{}]".format(URL))
def cloneBulkRepos(URLs, cloningPath, threads_limit=5, username=None, token=None):
"""
Clones a bulk of GIT repositories.
Input:-
URLs: A list of GIT repository URLs.
cloningPath: the directory that the repository will be cloned at.
Optional Input:-
threads_limit: The limit of working threads.
username: Github username.
token: Github token or password.
"""
Q = queue.Queue()
threads_state = []
for URL in URLs:
Q.put(URL)
while Q.empty() is False:
if (threading.active_count() < (threads_limit + 1)):
t = threading.Thread(target=cloneRepo, args=(Q.get(), cloningPath,), kwargs={"username": username, "token": token})
t.daemon = True
t.start()
else:
time.sleep(0.5)
threads_state.append(t)
for _ in threads_state:
_.join()
def main():
"""
The main function.
"""
parser = argparse.ArgumentParser()
parser.add_argument("-u", "--user",
dest="users",
help="Github user (comma-separated input for multiple Github users).",
action='store')
parser.add_argument("-org", "--org",
dest="organizations",
help="Github organization (comma-separated input for multiple Github organizations).",
action='store')
parser.add_argument("--include-org-members",
dest="include_organization_members",
help="Include the members of a Github organization.",
action='store_true')
parser.add_argument("-o", "--output-path",
dest="output_path",
help="The directory to use in cloning Git repositories.",
action='store',
required=True)
parser.add_argument("-t", "--threads",
dest="threads_limit",
help="Threads used in cloning repositories (Default: 5).",
action='store',
default=5)
parser.add_argument("-a", "--authentication",
dest="authentication",
help="Github authentication credentials (username:token).",
action='store')
parser.add_argument("--include-authenticated-repos",
dest="include_authenticated_repos",
help="Include repositories that the authenticated Github" +
" account have access to.",
action='store_true')
parser.add_argument("--include-gists",
dest="include_gists",
help="Include gists.",
action='store_true')
args = parser.parse_args()
users = args.users if args.users else None
organizations = args.organizations if args.organizations else None
include_organization_members = args.include_organization_members if args.include_organization_members else False
output_path = args.output_path if args.output_path else None
threads_limit = int(args.threads_limit) if args.threads_limit else 5
authentication = args.authentication if args.authentication else None
include_authenticated_repos = args.include_authenticated_repos if args.include_authenticated_repos else False
include_gists = args.include_gists if args.include_gists else False
if threads_limit > 10:
print("Error: Using more than 10 threads may cause errors.\nDecrease the amount of used threads.")
print("\nExiting....")
exit(1)
if not args.output_path:
print("Error: The output path is not specified.")
print("\nExiting...")
exit(1)
if not (args.users or args.organizations):
print("Error: Both Github users and Github organizations are not specified.")
print("\nExiting...")
exit(1)
if str.isdigit(str(threads_limit)) is False:
print("Error: Specified threads specified is invalid.")
print("\nExiting...")
exit(1)
if not os.path.exists(output_path):
os.mkdir(output_path)
if authentication is not None:
if getReposURLs().checkAuthencation(authentication.split(":")[0], authentication.split(":")[1]) is False:
print("Error: authentication failed.")
print("\nExiting...")
exit(1)
else:
username = authentication.split(":")[0]
token = authentication.split(":")[1]
else:
username = None
token = None
if (include_authenticated_repos is True) and (authentication is None):
print("Error: --include-authenticated-repos is used and --authentication is not provided.")
print("\nExiting...")
exit(1)
URLs = []
if include_authenticated_repos is True:
URLs.extend(getReposURLs().fromAuthenticatedUser(username, token))
URLs.extend(getReposURLs().AuthenticatedGists(username, token))
if users is not None:
users = users.replace(" ", "").split(",")
for user in users:
URLs.extend(getReposURLs().fromUser(user, username=username, token=token, include_gists=include_gists))
if organizations is not None:
organizations = organizations.replace(" ", "").split(",")
for organization in organizations:
if include_organization_members is False:
URLs.extend(getReposURLs().fromOrg(organization, username=username, token=token))
else:
URLs.extend(getReposURLs().fromOrgIncludeUsers(organization, username=username, token=token, include_gists=include_gists))
URLs = list(set(URLs))
cloneBulkRepos(URLs, output_path, threads_limit=threads_limit, username=username, token=token)
if (__name__ == "__main__"):
try:
main()
except KeyboardInterrupt:
print('\nKeyboardInterrupt Detected.')
print('\nExiting...')
exit(0)
# *** END *** #