Skip to content

Commit eebb379

Browse files
committed
refactor: cmd exec system
Replaced side func Handler with build in __init__. Avoided self passing to cmd. Cleaned code from similar lines and names.
1 parent 959d1b3 commit eebb379

8 files changed

Lines changed: 133 additions & 144 deletions

File tree

scr/commands/basic/dependencies.py

Lines changed: 25 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -18,27 +18,6 @@ class Dependencies(Command):
1818
"--update": False,
1919
}
2020

21-
def Handler(self):
22-
dependencies = ["cryptography", "pycryptodome", "cython", "nuitka", "colorama", "setuptools"]
23-
24-
if self.options["--show"]:
25-
string = ""
26-
for dep in dependencies:
27-
string+=f"\n {dep}"
28-
Log.Custom(f"Project's dependencies:{string}")
29-
30-
if self.options["--install"]:
31-
for dep in dependencies:
32-
system(f"pip install {f" --log {Log.logFile}" if Log.logFile else ""}{ "--quiet" if Log.quiet else ""}{ "--no-input" if Log.noInput else ""} {dep}")
33-
34-
if self.options["--uninstall"]:
35-
for dep in dependencies:
36-
system(f"pip uninstall {f" --log {Log.logFile}" if Log.logFile else ""}{ "--quiet" if Log.quiet else ""}{ "--no-input" if Log.noInput else ""} {dep}")
37-
38-
if self.options["--update"]:
39-
for dep in dependencies:
40-
system(f"pip install --upgrade {f" --log {Log.logFile}" if Log.logFile else ""}{ "--quiet" if Log.quiet else ""}{ "--no-input" if Log.noInput else ""} {dep}")
41-
4221
help = f'''
4322
Usage:
4423
py-shield dependencies [options]
@@ -59,4 +38,28 @@ def Handler(self):
5938
--show*` -> show all dependencies of the program.
6039
--install*` -> install all dependencies of the program.
6140
--uninstall*` -> uninstall all dependencies of the program.
62-
--update*` -> update all dependencies of the program'''
41+
--update*` -> update all dependencies of the program'''
42+
43+
def __init__(self):
44+
dependencies = ["cryptography", "pycryptodome", "cython", "nuitka", "colorama", "setuptools"]
45+
46+
if self.options["--show"]:
47+
string = ""
48+
for dep in dependencies:
49+
string+=f"\n {dep}"
50+
Log.Custom(f"Project's dependencies:{string}")
51+
52+
if self.options["--install"]:
53+
for dep in dependencies:
54+
system(f"pip install {f" --log {Log.logFile}" if Log.logFile else ""}{ "--quiet" if Log.quiet else ""}{ "--no-input" if Log.noInput else ""} {dep}")
55+
Log.Success("Dependencies installed")
56+
57+
if self.options["--uninstall"]:
58+
for dep in dependencies:
59+
system(f"pip uninstall {f" --log {Log.logFile}" if Log.logFile else ""}{ "--quiet" if Log.quiet else ""}{ "--no-input" if Log.noInput else ""} {dep}")
60+
Log.Success("Dependencies uninstalled")
61+
62+
if self.options["--update"]:
63+
for dep in dependencies:
64+
system(f"pip install --upgrade {f" --log {Log.logFile}" if Log.logFile else ""}{ "--quiet" if Log.quiet else ""}{ "--no-input" if Log.noInput else ""} {dep}")
65+
Log.Success("Dependencies updated")

scr/commands/basic/help.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,6 @@ class Help(Command):
66
requiredOptions = []
77
options = {}
88

9-
def Handler(command: Command = None):
10-
Log.Custom(command.help)
11-
129
help = f'''
1310
Usage:
1411
py-shield <command> [options]
@@ -27,4 +24,9 @@ def Handler(command: Command = None):
2724
--quiet -> give less output.
2825
--log <path> -> write all logs to a file.
2926
--no-color -> suppress colored output.
30-
--no-input -> disable prompting for input.'''
27+
--no-input -> disable prompting for input.'''
28+
29+
def __init__(self, command: Command = None):
30+
if command == None:
31+
command = self
32+
Log.Custom(command.help)

scr/commands/basic/info.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -15,19 +15,6 @@ class Info(Command):
1515
"--description": False,
1616
}
1717

18-
def Handler(self):
19-
if self.options["--all"]:
20-
Log.Custom(f"{NAME} version {VERSION}\nby {AUTHOR}\n{DESCRIPTION}\nRepo: {Fore.BLUE if Log.colored else ""}{URL}{Fore.RESET}")
21-
22-
elif self.options["--version"]:
23-
Log.Custom(f"{NAME} version {VERSION}")
24-
25-
elif self.options["--url"]:
26-
Log.Custom(f"Repo: {Fore.BLUE if Log.colored else ""}{URL}{Fore.RESET}")
27-
28-
elif self.options["--description"]:
29-
Log.Custom(f"{DESCRIPTION}")
30-
3118
help = f'''
3219
Usage:
3320
py-shield info [options]
@@ -47,3 +34,16 @@ def Handler(self):
4734
--version*` -> show version of the program.
4835
--url*` -> show URL of program's github repo.
4936
--description*` -> show description of the program.'''
37+
38+
def __init__(self):
39+
if self.options["--all"]:
40+
Log.Custom(f"{NAME} version {VERSION}\nby {AUTHOR}\n{DESCRIPTION}\nRepo: {Fore.BLUE if Log.colored else ""}{URL}{Fore.RESET}")
41+
42+
elif self.options["--version"]:
43+
Log.Custom(f"{NAME} version {VERSION}")
44+
45+
elif self.options["--url"]:
46+
Log.Custom(f"Repo: {Fore.BLUE if Log.colored else ""}{URL}{Fore.RESET}")
47+
48+
elif self.options["--description"]:
49+
Log.Custom(f"{DESCRIPTION}")

scr/commands/obfuscation/obfuscate.py

Lines changed: 47 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,6 @@ class Obfuscate(Command):
3030
"entrypoint": ""
3131
}
3232

33-
def Handler(self):
34-
PerformObfuscation(self)
35-
3633
help = f'''
3734
Usage:
3835
py-shield obfuscate [options] main.py
@@ -64,36 +61,38 @@ def Handler(self):
6461
--output <path> -> output dir.
6562
--follow-imports -> add all imports to the protected script.'''
6663

67-
class PerformObfuscation:
68-
def __init__(self, this: Command):
69-
self.this = this
70-
self.workingDir = getcwd()
71-
self.imports = []
64+
def __init__(self):
65+
self.InitVars()
7266
self.CheckOptions()
7367
self.ObfuscateFiles()
74-
self.obfuscation.CreateExecutor(self.this.options["--output"])
68+
self.obfuscation.CreateExecutor(self.options["--output"])
69+
Log.Success("Obfuscation compleated")
70+
71+
def InitVars(self):
72+
self.workingDir = getcwd()
73+
self.imports = []
7574

7675
def CheckOptions(self):
77-
Log.Info("Obfuscation.")
78-
if self.this.options["--recursive"] < 0:
76+
Log.Info("Obfuscation")
77+
if self.options["--recursive"] < 0:
7978
raise Exception("Invalid --recursive value.")
8079

81-
if not self.this.options["--output"]:
82-
self.this.options["--output"] = "obfuscated"
80+
if not self.options["--output"]:
81+
self.options["--output"] = "obfuscated"
8382

84-
if path.exists(self.this.options["--output"]):
85-
Log.Warning(f"Output directory already exists: \"{self.this.options['--output']}\".")
83+
if path.exists(self.options["--output"]):
84+
Log.Warning(f"Output directory already exists: \"{self.options['--output']}\".")
8685
responce = ""
8786
while responce != "y" or responce != "n" or responce != "ignore":
8887
responce = Log.Question("Override directory? (y/n)").lower()
8988

9089
match responce:
9190
case "ignore":
92-
rmtree(self.this.options["--output"])
91+
rmtree(self.options["--output"])
9392
Log.Info("Directory overridden.")
9493
break
9594
case "y":
96-
rmtree(self.this.options["--output"])
95+
rmtree(self.options["--output"])
9796
Log.Success("Directory overridden.")
9897
break
9998
case "n":
@@ -103,51 +102,51 @@ def CheckOptions(self):
103102
Log.Fail("Invalid response. Please enter 'y' or 'n'.")
104103
print()
105104

106-
self.entryPoint = self.this.options["entrypoint"]
105+
self.entryPoint = self.options["entrypoint"]
107106
if not path.exists(self.entryPoint) or not path.isfile(self.entryPoint) or not self.entryPoint.endswith(".py"):
108107
raise Exception(f"Invalid entrypoint path: \"{self.entryPoint}\".")
109108
if path.isabs(self.entryPoint):
110109
raise Exception(f"Abs path is unsupported: \"{self.entryPoint}\"")
111110

112-
for file in self.this.options["--files"]:
111+
for file in self.options["--files"]:
113112
if not path.exists(file) or not path.isfile(file) or not file.endswith(".py"):
114113
raise Exception(f"Invalid file path: \"{file}\".")
115114
if path.isabs(file):
116115
raise Exception(f"Abs path is unsupported: \"{file}\"")
117116

118-
for dir in self.this.options["--dirs"]:
117+
for dir in self.options["--dirs"]:
119118
if not path.exists(dir) or not path.isdir(dir):
120119
raise Exception(f"Invalid directory path: \"{dir}\".")
121120
if path.isabs(dir):
122121
raise Exception(f"Abs path is unsupported: \"{dir}\"")
123122

124123
Log.Info(f"Entrypoint file: {self.entryPoint}")
125-
if self.this.options["--files"]:
126-
Log.Info(f"Included files: {self.this.options["--files"]}")
127-
if self.this.options["--dirs"]:
128-
Log.Info(f"Included dirs: {self.this.options["--dirs"]}")
124+
if self.options["--files"]:
125+
Log.Info(f"Included files: {self.options["--files"]}")
126+
if self.options["--dirs"]:
127+
Log.Info(f"Included dirs: {self.options["--dirs"]}")
129128

130-
methods = f"{"hashdata, " if self.this.options["--hashdata"] else ""}{"fernet, " if self.this.options["--fernet"] else ""}{"aes, " if self.this.options["--aes"] else ""}{"chacha20, " if self.this.options["--chacha"] else ""}{"salsa20, " if self.this.options["--salsa"] else ""}{"base64, " if self.this.options["--base64"] else ""}{f"recursive<{self.this.options["--recursive"]}>, " if self.this.options["--recursive"]>0 else ""}"[:-2]
129+
methods = f"{"hashdata, " if self.options["--hashdata"] else ""}{"fernet, " if self.options["--fernet"] else ""}{"aes, " if self.options["--aes"] else ""}{"chacha20, " if self.options["--chacha"] else ""}{"salsa20, " if self.options["--salsa"] else ""}{"base64, " if self.options["--base64"] else ""}{f"recursive<{self.options["--recursive"]}>, " if self.options["--recursive"]>0 else ""}"[:-2]
131130
if methods:
132131
Log.Info(f"Obfuscation methods: {methods}")
133132

134-
options = f"{"follow-imports, " if self.this.options["--follow-imports"] else ""}{"no-protect, " if self.this.options["--no-protect"] else ""}"[:-2]
133+
options = f"{"follow-imports, " if self.options["--follow-imports"] else ""}{"no-protect, " if self.options["--no-protect"] else ""}"[:-2]
135134
if options:
136135
Log.Info(f"Additional options: {options}")
137-
Log.Info(f"output dir: {self.this.options["--output"]}\n")
136+
Log.Info(f"output dir: {self.options["--output"]}\n")
138137

139138
def ObfuscateFiles(self):
140-
self.obfuscation = MainObfuscation(self.this.options["--hashdata"],
141-
self.this.options["--fernet"],
142-
self.this.options["--aes"],
143-
self.this.options["--chacha"],
144-
self.this.options["--salsa"],
145-
self.this.options["--base64"],
146-
self.this.options["--recursive"],
147-
self.this.options["--no-protect"],
148-
self.this.options["--enc-exec"])
149-
150-
for file in self.this.options["--files"]:
139+
self.obfuscation = MainObfuscation(self.options["--hashdata"],
140+
self.options["--fernet"],
141+
self.options["--aes"],
142+
self.options["--chacha"],
143+
self.options["--salsa"],
144+
self.options["--base64"],
145+
self.options["--recursive"],
146+
self.options["--no-protect"],
147+
self.options["--enc-exec"])
148+
149+
for file in self.options["--files"]:
151150
with open(file, "r", encoding="utf-8") as pyFile:
152151
context = pyFile.read()
153152
if not context:
@@ -165,9 +164,9 @@ def ObfuscateFiles(self):
165164
context = self.obfuscation.Wrap(context)
166165

167166
self.SaveFile(filename, filepath, context)
168-
self.obfuscation.ProtectFile(self.this.options["--output"], filepath+sep+filename)
167+
self.obfuscation.ProtectFile(self.options["--output"], filepath+sep+filename)
169168

170-
for dir in self.this.options["--dirs"]:
169+
for dir in self.options["--dirs"]:
171170
for dirpath, dirnames, filenames in walk(dir):
172171
for filename in filenames:
173172

@@ -187,7 +186,7 @@ def ObfuscateFiles(self):
187186
context = self.obfuscation.Wrap(context)
188187

189188
self.SaveFile(filename , dirpath, context)
190-
self.obfuscation.ProtectFile(self.this.options["--output"], dirpath+sep+filename)
189+
self.obfuscation.ProtectFile(self.options["--output"], dirpath+sep+filename)
191190

192191
with open(self.entryPoint, "r", encoding="utf-8") as pyFile:
193192
context = pyFile.read()
@@ -205,15 +204,15 @@ def ObfuscateFiles(self):
205204
context = self.obfuscation.Wrap(context)
206205

207206
self.SaveFile(filename, filepath, context, entrypoint = True)
208-
self.obfuscation.ProtectFile(self.this.options["--output"], filepath+sep+filename)
207+
self.obfuscation.ProtectFile(self.options["--output"], filepath+sep+filename)
209208

210209
def SaveFile(self, filename, filepath, content, entrypoint = False):
211210
if entrypoint:
212211
imports = ""
213212
for module in self.imports:
214213
imports+=f"import {module}\n"
215214

216-
filepath = self.this.options["--output"]+sep+filepath
215+
filepath = self.options["--output"]+sep+filepath
217216
makedirs(filepath, exist_ok=True)
218217

219218
with open(filepath+sep+filename, "w", encoding="utf-8") as file:
@@ -224,20 +223,20 @@ def SaveFile(self, filename, filepath, content, entrypoint = False):
224223
Log.Info(f"{filename} saved in {filepath[:-1]}")
225224

226225
def FollowImports(self, content):
227-
if self.this.options["--follow-imports"]:
226+
if self.options["--follow-imports"]:
228227
modules = GetImports(content)
229228

230-
if not self.this.options["--no-protect"]:
229+
if not self.options["--no-protect"]:
231230
modules.append("hashlib")
232231
modules.append("os")
233232

234-
if self.this.options["--chacha"] or self.this.options["--salsa"]:
233+
if self.options["--chacha"] or self.options["--salsa"]:
235234
modules.append("Crypto.Cipher")
236235

237-
if self.this.options["--aes"]:
236+
if self.options["--aes"]:
238237
modules.append("cryptography.hazmat.primitives.ciphers.aead")
239238

240-
if self.this.options["--fernet"]:
239+
if self.options["--fernet"]:
241240
modules.append("cryptography.fernet")
242241

243242
modules.append("sys")

0 commit comments

Comments
 (0)