-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
432 lines (416 loc) · 19.4 KB
/
main.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
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
import config
import requests, os, re, string, shutil
from github import Github
import zipfile
g = Github(config.GITHUB_TOKEN)
turnOff = False
firstPath = os.getcwd()
def splitList(_list):
newList = []
currentList = []
x = 0
for el in _list:
if len(currentList) == 10 or x == len(_list):
newList.append(currentList)
currentList.clear()
else:
currentList.append(el)
x+=1
def search_github(keywords):
query = '+'.join(keywords) + '+in:readme+in:description'
result = g.search_repositories(query, 'stars', 'desc')
print(f'Found {result.totalCount} repo(s)')
x = 0
y = 0
for repo in result:
print(str(x) + ".", repo.clone_url, repo.stargazers_count, "stars")
x += 1
choice = ""
while choice != "exit":
text = """
\tType `page (number)` for go repository page.
\tType `exit` for leave to main menu.
\tType `all` for install all repositories from printed.
\tType id for install specific repository (eg. 1).
"""
print(text)
choice = input("Your choice: ")
try:
choice = int(choice)
print(choice, "it is")
except:
if choice == "all":
print("all it is")
def download_folder(url):
r = requests.get(url, stream = True)
zippedPath = firstPath + "/projects/zipped/"
unzippedPath = firstPath + "/projects/unzipped/"
with open(zippedPath + url.split("/")[4]+".zip", "wb") as repo:
for chunk in r.iter_content(chunk_size=1024):
if chunk:
repo.write(chunk)
with zipfile.ZipFile(zippedPath + url.split("/")[4]+".zip", 'r') as zip_ref:
zip_ref.extractall(unzippedPath)
print("Repository installed successfully.")
def checkModules(pythonFiles, path):
modules = []
for file in pythonFiles:
fileLines = open(file, "r").readlines()
for line in fileLines:
if line.startswith("#"): continue
if line.find("import ") >= 0:
if line.find("=") >= 0: continue
if line.find("from ") >= 0:
from_ = line.split("import")[0]
from_ = from_.replace("from ", "")
if from_.find(".") >= 0: from_ = from_.split(".")[0].replace(" ", "")
module = from_
alias = None
prefunctions = []
dotspl = str(str(line.split(" import ")[0]).split("from ")).split(".")
del dotspl[0]
if line.find(" as ") >= 0:
alias = str(line.split(" as ")[1].replace("\n", "")).replace(" ", "")
else:
line = line.replace("from ", "")
if line.split("import")[1].find(",")>=0:
alias = []
for submod in line.split("import")[1].split(","):
submod = str(submod.replace("\n", "")).replace(" ", "")
alias.append(submod)
else:
alias = str(line.split("import")[1].replace(" ", "")).replace("\n", "")
for dot in dotspl:
if dot.find(" as ") >= 0:
dot = dot.split(" as ")[0]
prefunctions.append(str(dot.replace(" ", "")).replace("\n", ""))
if module != "*":
if module in [x['module'] for x in modules]:
samem = [x for x in modules if x['module'] == module][0]
if type(samem['alias']) != list:
salias = samem['alias']
samem['alias'] = list()
samem['alias'].append(salias)
samem['alias'].append(alias)
else:
if type(alias) == list:
for alias in alias:
samem['alias'].append(alias)
else:
samem['alias'].append(alias)
for prefunc in range(len(prefunctions)):
for character in string.punctuation:
if character == "_": continue
prefunctions[prefunc] = prefunctions[prefunc].replace(character, '')
if samem['prefunctions'] == None:
samem['prefunctions'] = list()
samem['prefunctions'].extend(prefunctions)
else:
samem['prefunctions'].extend(prefunctions)
modules = [x for x in modules if not x['module'] == module] + [samem]
else:
arr = {"module": module, "alias": alias, "prefunctions": prefunctions}
modules.append(arr)
elif line.find(",") >= 0:
for module in str(line.split("import")[1]).split(","):
module = module.replace("\n", "")
alias = None
if module.find(" as ") >= 0:
moas = module.split(" as ")
module = str(moas[0].replace("\n", "")).replace(" ", "")
alias = str(moas[1].replace("\n", "")).replace(" ", "")
puncs = 0
for char in module:
if char in string.punctuation:
puncs += 1
if puncs > 0: continue
if module != "*":
arr = {"module": module, "alias": alias, "prefunctions": None}
modules.append(arr)
elif line.find(".") >= 0:
module = str(line.split("import")[1]).split(".")[0]
alias = None
prefunctions = []
dotspl = str(line.split("import")[1]).split(".")
del dotspl[0]
if line.find(" as ") >= 0:
moas = line.split(" as ")
module = str(str(line.split("import")[1]).split(".")[0].replace(" ", "")).replace("\n", "")
alias = str(moas[1].replace("\n", "")).replace(" ", "")
for dot in dotspl:
if dot.find(" as ") >= 0:
dot = dot.split(" as ")[0]
prefunctions.append(str(dot.replace(" ", "")).replace("\n", ""))
puncs = 0
for char in module:
if char in string.punctuation:
puncs += 1
if puncs > 0: continue
for prefunc in range(len(prefunctions)):
for character in string.punctuation:
if character == "_": continue
prefunctions[prefunc] = prefunctions[prefunc].replace(character, '')
if module != "*":
arr = {"module": module, "alias": alias, "prefunctions": prefunctions}
modules.append(arr)
else:
module = line.split("import")[-1].replace("\n", "")
alias = None
if module.find(" as ") >= 0:
moas = module.split(" as ")
module = str(moas[0].replace(" ", "")).replace("\n", "")
alias = moas[1].replace("\n", "")
puncs = 0
for char in module:
if char in string.punctuation:
puncs += 1
if puncs > 0: continue
if module != "*":
arr = {"module": module, "alias": alias, "prefunctions": None}
modules.append(arr)
return modules
def makeModuleList(modules):
moduleList = {}
for module in modules:
orgmodule = module
module = module['module'].replace(" ", "")
moduleList[module] = []
if type(orgmodule['prefunctions']) == list:
if len(orgmodule['prefunctions']) > 0:
for prefunc in orgmodule['prefunctions']:
for character in string.punctuation:
if character == "_": continue
prefunc = prefunc.replace(character, '')
moduleList[module].append(prefunc)
return moduleList
def checkFunctions(modules, pythonFiles, moduleList):
for file in pythonFiles:
fileLines = open(file, "r").readlines()
for line in fileLines:
if line.startswith("#"): continue
for module in modules:
orgmodule = module['module']
try:
if module['alias']:
modulee = module['alias']
else:
modulee = module['module']
except:
modulee = module['module']
if type(modulee) == list:
for module in modulee:
if type(module) != str: continue
if line.find(module + ".") >= 0 and line.find("import") < 0 and line.find("from") < 0:
try:
functionList = re.findall(r"{}\.(.*?)\(".format(module), line)
except:
continue
for function in functionList:
if function.find(".") >= 0:
function = function.replace(".", " -> ")
if function.find("=") >= 0: function = function.split("=")[1]
puncs = 0
for char in function:
if char != "_" and char in string.punctuation:
puncs += 1
if puncs > 0:
continue
else:
moduleList[orgmodule.replace(" ", "")].append(function)
elif line.find(orgmodule + ".") >= 0 and line.find("import ") >= 0 and line.split("import ")[1].find(".") >= 0 and line.find("from") < 0:
funt = line.split("import ")[1]
f = funt.split(".")
f[1] = f[1].replace("\n", "")
f[0] = f[0].replace(" ", "")
function = ""
if len(f) > 2:
del f[0]
x = 1
for frrom in f:
if x == len(f):
function += " " + frrom
elif x == 1:
function += frrom + " ->"
else:
function += " " + frrom + " ->"
x+=1
else:
function = f[1]
if function.find("as") >= 0: function = function.split(" as ")[0]
puncs = 0
for char in function:
if char != "_" and char in string.punctuation:
puncs += 1
if puncs > 0:
continue
moduleList[orgmodule.replace(" ", "")].append(function)
else:
module = modulee
if line.find(module + ".") >= 0 and line.find("import") < 0 and line.find("from") < 0:
functionList = re.findall(module + r"\.(.*?)\(", line)
for function in functionList:
if function.find(".") >= 0:
function = function.replace(".", " -> ")
if function.find("=") >= 0: function = function.split("=")[1]
puncs = 0
for char in function:
if char != "_" and char in string.punctuation:
puncs += 1
if puncs > 0:
continue
else:
moduleList[orgmodule.replace(" ", "")].append(function)
elif line.find(orgmodule + ".") >= 0 and line.find("import ") >= 0 and line.split("import ")[1].find(".") >= 0 and line.find("from") < 0:
funt = line.split("import ")[1]
f = funt.split(".")
f[1] = f[1].replace("\n", "")
f[0] = f[0].replace(" ", "")
function = ""
if len(f) > 2:
del f[0]
x = 1
for frrom in f:
if x == len(f):
function += " " + frrom
elif x == 1:
function += frrom + " ->"
else:
function += " " + frrom + " ->"
x+=1
else:
function = f[1]
if function.find("as") >= 0: function = function.split(" as ")[0]
puncs = 0
for char in function:
if char != "_" and char in string.punctuation:
puncs += 1
if puncs > 0:
continue
moduleList[orgmodule.replace(" ", "")].append(function)
return moduleList
def formatModuleList(modules, moduleList):
for module in modules:
module = module['module']
module = module.replace(" ", "")
moduleList[module] = list(set(moduleList[module]))
moduleList[module] = [x for x in moduleList[module] if x != ""]
return moduleList
def createTree(moduleList, path):
treePath = firstPath + "/trees/" + path.split("/")[-1] + "/"
try:
open(treePath + "tree.txt", "w")
except:
os.mkdir(treePath)
open(treePath + "tree.txt", "w")
for module in moduleList:
module = module.replace(" ", "")
agac = open(treePath + "tree.txt", "r").read()
open(treePath + "tree.txt", "w").write(agac + module + "\n")
if len(moduleList[module]) > 0:
moduleList[module] = sorted(moduleList[module])
for function in moduleList[module]:
agac = open(treePath + "tree.txt", "r").read()
open(treePath + "tree.txt", "w").write(agac + "\t" + function + "\n")
return True
def repoCheck(path):
os.chdir(path)
pythonFiles = [os.getcwd()+"/" + x for x in os.listdir(os.getcwd()) if x.endswith(".py")]
directories = [x[0] for x in os.walk(os.getcwd())]
del directories[0]
for directory in directories:
pythonFiles = pythonFiles + [directory+"/" + x for x in os.listdir(directory) if x.endswith(".py")]
pythonFiles = list(set(pythonFiles))
modules = checkModules(pythonFiles, firstPath)
moduleList = makeModuleList(modules)
moduleList = checkFunctions(modules, pythonFiles, moduleList)
moduleList = formatModuleList(modules, moduleList)
tree = createTree(moduleList, path)
os.chdir(firstPath)
return tree
def checkRepos():
repoPath = firstPath + "/projects/unzipped/"
repos = [x for x in os.listdir(repoPath) if os.path.isdir(repoPath + x) == True]
if len(repos) == 0:
print("No repositories found.")
else:
selected = ""
while selected != "exit":
x = 0
for repo in repos:
print(str(x) + ".", repo)
x+=1
text = """
\tType `exit` for return main menu.
\tType `all` for check all repositories and create tree scheme.
\tType id of repository to check specific repository.
"""
print(text)
selected = input("Your choice: ")
if selected == "all":
for repo in repos:
try:
check = repoCheck(repoPath + repo)
print("Tree creation for " + repo + "successfully finished." if check == True else "Tree couldn't created successfully for " + repo)
except Exception as e:
print("Tree couldn't created successfully for", repo)
print("Error:", e)
elif selected == "exit":
break
else:
try:
selected = int(selected)
try:
check = repoCheck(repoPath + repos[selected])
print("Tree creation for " + repos[selected] + "successfully finished." if check == True else "Tree couldn't created successfully for " + repos[selected])
except Exception as e:
print("Tree couldn't created successfully for", repos[selected])
print("Error:", e)
except Exception as e:
print("Please select choice in menu!")
def eraseData():
folders = [firstPath + "/trees", firstPath + "/projects/unzipped", firstPath + "/projects/zipped"]
for folder in folders:
for filename in os.listdir(folder):
file_path = os.path.join(folder, filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
if not file_path.find("__init__.py") >=0:
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
print("Successfully cleared path: %s" % file_path)
except Exception as e:
print('Failed to delete %s. Reason: %s' % (file_path, e))
print("Done erasing.")
def checkChoice(choice):
global turnOff
if choice == 0:
turnOff = True
elif choice == 1:
print("Under maintenance!")
#keywords = input('Enter keyword(s)[e.g python, flask, postgres]: ')
#search_github([keyword.strip() for keyword in keywords.split(',')])
elif choice == 2:
url = input('Enter folder url: ')
download_folder(url)
elif choice == 3:
checkRepos()
elif choice == 4:
eraseData()
welcomeText = f"""
\tWelcome to RepoChecker v{config.VERSION}
\n
\t0. Exit
\t1. Search with keywords. (Maintenance)
\t2. Download public repository.
\t3. Check downloaded repositories.
\t4. Erase all data.
"""
while turnOff == False:
print(welcomeText)
try:
choice = int(input("Select from menu (eg. 1): "))
except:
print("Chocie must be integer!")
continue
checkChoice(choice)