-
Notifications
You must be signed in to change notification settings - Fork 0
/
VenvManager-functional.py
359 lines (261 loc) · 9.37 KB
/
VenvManager-functional.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
from subprocess import run
from platform import system
from sys import stdout
from os import remove, mkdir, getcwd
from re import compile
from os.path import join, exists
from logging import Logger, StreamHandler, Formatter, INFO
from json import load, dumps
# For coloring log outputs
class CustomFormatter(Formatter):
grey = "\x1b[38;21m"
blue = "\x1b[38;5;39m"
yellow = "\x1b[38;5;226m"
red = "\x1b[38;5;196m"
bold_red = "\x1b[31;1m"
reset = "\x1b[0m"
def __init__(self, fmt):
from logging import DEBUG, WARNING, ERROR, CRITICAL
super().__init__()
self.fmt = fmt
self.FORMATS = {
DEBUG: self.grey + self.fmt + self.reset,
INFO: self.blue + self.fmt + self.reset,
WARNING: self.yellow + self.fmt + self.reset,
ERROR: self.red + self.fmt + self.reset,
CRITICAL: self.bold_red + self.fmt + self.reset,
}
def format(self, record):
logFormat = self.FORMATS.get(record.levelno)
formatter = Formatter(logFormat)
return formatter.format(record)
VENV_FILENAME = "venv"
VENVLOG_FILENAME = "venvLog.txt"
PATHS_FILENAME = "paths.json"
OS_NAME = system()
CURRENT_DIR = getcwd()
"""
Check functions
"""
def CheckPython(self) -> None:
streamdata, isExist = self.RunCommand("python --version")
if isExist:
self.logger.info(f"Using {streamdata}")
else:
self.logger.error("Python is not exists")
exit(1)
def CheckGit(self) -> bool:
streamdata, isExist = self.RunCommand("git --version")
if isExist:
self.logger.info(f"Using {streamdata}")
else:
self.logger.error("Cant found git")
return isExist
"""
Running Functions
"""
def CheckCommand(
logger: Logger, terminalData: tuple, successMsg: str, failureMsg: str
) -> None:
_, isSuccess = terminalData
if isSuccess:
logger.info(successMsg)
else:
logger.error(failureMsg)
logger.error("ERROR OCCURED!!! Check venvLog file")
exit(1)
def RunScript(logger: Logger, paths: dict, filename: str, args: str = "") -> None:
script_filename = filename
if filename.endswith(".py"):
script_filename = script_filename[:-3]
logger.info(
f"Running {script_filename}.py with [{', '.join(args.split(' '))}] args"
)
command = f"{paths['python']} {script_filename}.py {args}"
process = run(command, shell=True, check=True)
if process.returncode == 0:
logger.info(f"{script_filename}.py run successfully")
else:
logger.error(f"Cant run {script_filename}.py file")
def RunCommand(command: str, isCheck: bool = True) -> tuple:
process = run(command, shell=True, check=isCheck, capture_output=True)
streamdata = process.stdout
streamdata = streamdata.decode("UTF-8")
streamdata = streamdata.strip()
with open(PATHS_FILENAME, "a") as file:
if streamdata != "":
file.write(f"{'-'*200}\n")
file.write(f"Command : {command}\n")
file.write(f"Output :\n{streamdata}\n")
return (streamdata, True) if process.returncode == 0 else (streamdata, False)
"""
Logger and envrionment functions
"""
def SetLogger(logger: Logger, loggerLevel) -> None:
logger.setLevel(loggerLevel)
handler = StreamHandler(stdout)
handler.setLevel(INFO)
logFormat = "[%(asctime)s] /_\ %(levelname)-8s /_\ %(message)s"
if OS_NAME == "Windows":
formatter = Formatter(logFormat)
else:
formatter = CustomFormatter(logFormat)
handler.setFormatter(formatter)
logger.addHandler(handler)
def CreateEnv(logger: Logger):
file = open(VENV_FILENAME, "w")
file.close()
logger.info(f"{VENVLOG_FILENAME} file is created")
CheckPython()
if exists(VENV_FILENAME):
logger.info(f"Using {VENV_FILENAME} virtual environment")
else:
logger.info(f"Creating {VENV_FILENAME}")
CheckCommand(
RunCommand("python -m venv venv"),
f"{VENV_FILENAME} is created",
"Cant create virtual environment",
)
def CreateRequirementsFile(paths: dict) -> None:
command = f"{paths['pip']} freeze > requirements.txt"
CheckCommand(
RunCommand(command),
"requirements.txt file is updated",
"Cant create requirements file",
)
def CheckPackages(logger: Logger, paths: dict, filename: str) -> tuple:
logger.info("Checking Packages")
command = f"{paths['pip']} freeze > temp_requirements.txt"
RunCommand(command)
envPackages = []
with open("temp_requirements.txt", "r") as envFile:
envPackages = set(envFile.readlines())
# deleting the temp_requirements file
remove("temp_requirements.txt")
wantedPackages = []
with open(filename, "r") as wantedFile:
wantedPackages = set(wantedFile.readlines())
# union function from set value type
notIncludedPackages = wantedPackages - envPackages
return (notIncludedPackages, wantedPackages.issubset(envPackages))
def InstallWRequirements(
logger: Logger, paths: dict, filename: str = "requirements.txt"
) -> None:
needToDownload, isContains = CheckPackages(filename)
if isContains:
logger.info("Requirements are already installed")
return
for package in needToDownload:
package = package.strip()
command = f"{paths['pip']} install {package}"
logger.info(f"Installing {package}")
RunCommand(command)
CreateRequirementsFile()
"""
Path functions
"""
def GetPaths() -> dict:
paths = {}
if exists(PATHS_FILENAME):
with open(PATHS_FILENAME, "r") as pathFile:
paths = load(pathFile)
for key, path in paths:
if exists(path) is False:
del paths[key]
else:
winPath = f"{VENV_FILENAME}\\Scripts"
if OS_NAME == "Windows":
paths["python"] = f"{winPath}\\python.exe"
paths["pip"] = f"{winPath}\\pip.exe"
paths["activate"] = f"{winPath}\\activate.bat"
paths["deactivate"] = f"{winPath}\\deactivate.bat"
elif OS_NAME == "Linux":
paths["activate"] = f"source {VENV_FILENAME}/bin/activate"
paths["python"] = f"{paths['activate']} && python3"
paths["pip"] = f"{paths['activate']} && pip3"
paths["deactivate"] = ""
return paths
def SavePaths(paths: dict) -> None:
with open(PATHS_FILENAME, "w") as file:
jsonObject = dumps(paths, indent=4)
file.write(jsonObject)
"""
Git functions
"""
def GetRepositoryName(repoLink: str) -> str:
regexPattern = "([^/]+)\\.git$"
pattern = compile(regexPattern)
matcher = pattern.search(repoLink)
return matcher.group(1)
def CloneRepository(
logger: Logger, paths: dict, repoLink: str, repoKey: str, parentFolder: str = ""
) -> None:
if CheckGit() is False:
logger.error("Cannot detect git")
return
repoName = GetRepositoryName(repoLink)
realRepoKey = repoKey + "-repo"
if realRepoKey in paths.keys():
logger.info(f"{repoName} is exists")
return
paths[realRepoKey] = join(parentFolder, repoName)
SavePaths()
if exists(join(CURRENT_DIR, parentFolder)) is False:
mkdir(join(CURRENT_DIR, parentFolder))
if parentFolder == "":
command = f"git clone --recursive {repoLink}"
else:
command = (
f"cd {parentFolder} && git clone --recursive {repoLink} && cd {CURRENT_DIR}"
)
logger.info(f"Cloning {repoLink}")
RunCommand(command)
def UpdateRepository(logger: Logger, paths: dict, repoKey: str) -> None:
if CheckGit() is False:
logger.error("Cannot detect git")
return
realRepoKey = repoKey + "-repo"
if realRepoKey not in paths.keys():
logger.info(f"{repoKey} is not exists")
return
command = f"cd {paths[realRepoKey]} && git pull && cd {CURRENT_DIR}"
logger.info(f"Updating {repoKey}")
RunCommand(command)
def UpdateAllRepositories(logger: Logger, paths: dict) -> None:
if CheckGit() is False:
logger.error("Cannot detect git")
return
for key in paths.keys():
if "-repo" not in key:
continue
UpdateRepository(key[:-5])
def RunScriptInsideRepository(
logger: Logger, paths: dict, repoKey: str, repoCommand: str
) -> None:
realRepoKey = repoKey + "-repo"
if realRepoKey not in paths.keys():
logger.info(f"{repoKey} is not exists")
return
command = ""
if OS_NAME == "Windows":
command = f"cd {paths[realRepoKey]} && {join(CURRENT_DIR, paths['python'])} {repoCommand} && cd {CURRENT_DIR}"
elif OS_NAME == "Linux":
command = f"{paths['activate']} && cd {paths[realRepoKey]} && python3 {repoCommand} && cd {CURRENT_DIR}"
logger.info(f"Running {repoCommand}")
RunCommand(command)
def InstallRequirementsFromRepository(
logger: Logger, paths: dict, repoKey: str, file: str = "requirements.txt"
) -> None:
realRepoKey = repoKey + "-repo"
if realRepoKey not in paths.keys():
logger.info(f"{repoKey} is not exists")
return
InstallWRequirements(join(paths[realRepoKey], file))
def InstallRequirementsFromAllRepositories(logger: Logger, paths: dict) -> None:
if CheckGit() is False:
logger.error("Cannot detect git")
return
for key in paths.keys():
if "-repo" not in key:
continue
InstallRequirementsFromRepository(key[:-5])