-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
240 lines (179 loc) · 5.55 KB
/
main.py
File metadata and controls
240 lines (179 loc) · 5.55 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
try:
# --- Importing external dependencies ---
from os import system as shell
from os.path import basename
from platform import system
from re import split
from sys import argv, version_info
if(version_info.major < 3):
raise(RuntimeError)
if(system() == "Linux"): # Dependencies for Linux
import readline
# --- Importing internal dependencies ---
from core import INFO, REGEX_ARGS
from core import helper, launch, sortTools, splash, version
from core.colors import Colors
from core.config import Config, getConfig, setConfig
from core.generate import Generate
from core.icons import Icons
# --- Importing the tool registry ---
from tools import TOOLS
except(RuntimeError) as e:
print("/!\\ - Program must be run with Python 3")
exit()
except(ModuleNotFoundError) as e:
print("[ ERROR ]: " + e.msg)
exit()
def arg(cfg: Config) -> bool:
""" Launch method in argument mode
Args:
cfg (Config): the user config instance
Returns:
bool: True value when exiting, False on exception
"""
__args = dict({
"prefix": tuple[tuple[tuple[str], str]]((
(("-g", "--generate"), ""),
(("-l", "--list"), ""),
(("-s", "--set"), "<prop> <value>"),
(("-t", "--tool"), "<tool>"),
(("-h", "--help"), ""),
(("-D", "--debug"), ""),
(("-v", "--version"), "")
)),
"desc": tuple[str | tuple[str]]((
"Generate a tool with interactive inputs",
"List all registered python tools",
("Apply new configuration value on property", "prop: colors|encode|splash"),
"Start a selected tools by name",
"Show the helper commands menu",
"Launch the script in debug mod",
"Show version of script"
))
})
try:
if(argv[1] in __args["prefix"][0][0]): # -g, --generate
Generate()
elif(argv[1] in __args["prefix"][1][0]): # -l, --list
sortTools(TOOLS)
elif(argv[1] in __args["prefix"][2][0]): # -s, --set
setConfig(cfg, argv[2], argv[3])
elif(argv[1] in __args["prefix"][3][0]): # -t, --tool
for tool in TOOLS:
if(argv[2] in tool.command[0]):
launch(tool, argv[2:len(argv)])
elif(argv[1] in __args["prefix"][-3][0]): # -h, --help
__table = list[str]([
f"{INFO['name']} by {INFO['author']}",
f"Github: {INFO['github']}\n",
f"Usage: python {basename(__file__)} <argument>\n",
f"Arguments:{' '*(34-len('Arguments:'))}Descriptions:"
])
for i, arg in enumerate(__args["prefix"]):
__left = f"{arg[0][0]}, {arg[0][1]} {arg[1]}"
__desc = f"\n{' '*35}* ".join(__args['desc'][i]) if(isinstance(__args['desc'][i], tuple)) else __args['desc'][i]
__table.append("".join([
f"{__left}{' '*(34-len(__left))}{__desc}",
"\n"*(1 if(i in (len(__args['desc'])-4, len(__args['desc'])-1)) else 0)
]))
print("\n".join([ f" {t}" for t in __table ]))
elif(argv[1] in __args["prefix"][-2][0]): # -D, --debug
__isLinux = bool(system() == "Linux")
while(True):
shell("clear" if(__isLinux) else "cls")
print(f"{Icons.info}Lanched in debug mod")
shell(f"python{'3' if(__isLinux) else ''} main.py")
input(f"{Icons.info}Press any keys to continue...")
elif(argv[1] in __args["prefix"][-1][0]): # -v, --version
version()
except(IndexError, KeyError):
print(f"{Icons.warn}Insufficient arguments !")
return(False)
return(True)
def config(cfg: Config) -> bool:
""" Config function to apply user settings
Args:
cfg (Config): the user config instance
Returns:
bool: True value when exiting
"""
__cmds = list[tuple]([
(("set", "s"), "(s)et"),
(("get", "g"), "(g)et"),
(("help", "h"), "(h)elp"),
(("back", "b"), "(b)ack")
])
helper(__cmds)
while(True):
prompt = str(input(f"({Colors.green}{INFO['name']}{Colors.end})[{Colors.purple}settings{Colors.end}]> {Colors.cyan}"))
print(end=Colors.end)
__args = list[str](split(REGEX_ARGS, prompt))
if(__args[0] in __cmds[0][0]):
try:
setConfig(cfg, __args[1], __args[2])
except(IndexError):
print(f"{Icons.warn}No value was entered !")
except(Exception) as e:
print(f"{Icons.err}{e}")
elif(__args[0] in __cmds[1][0]):
try:
getConfig(cfg, __args[1])
except(IndexError):
print(f"{Icons.warn}No value was entered !")
elif(__args[0] in __cmds[-2][0]):
helper(__cmds)
elif(__args[0] in __cmds[-1][0]):
break
elif(not __args[0]):
pass
else:
print(f"{Icons.warn}Uknown command !")
return(True)
def main(cfg: Config) -> bool:
""" Main launch method
Args:
cfg (Config): the user config instance
Returns:
bool: True value when exiting
"""
__cmds = list[tuple]([ tool.command for tool in TOOLS ] + [
(("settings", "s"), "(s)ettings"),
(("version", "v"), "(v)ersion"),
(("help", "h"), "(h)elp"),
(("quit", "q"), "(q)uit")
])
if(cfg.getSplash()):
splash()
helper(__cmds)
while(True):
prompt = str(input(f"({Colors.green}{INFO['name']}{Colors.end})> {Colors.cyan}"))
print(end=Colors.end)
__args = list[str](split(REGEX_ARGS, prompt))
__f = bool(False)
for i, command in enumerate(__cmds[0:len(__cmds)-4]):
if(__args[0] in command[0]):
try:
__f = bool(True)
launch(TOOLS[i], __args)
break
except:
print(f'{Icons.err}"{command[0][0]}" not implemented !')
if(not __f):
if(__args[0] in __cmds[-4][0]):
config(cfg)
elif(__args[0] in __cmds[-3][0]):
version()
elif(__args[0] in __cmds[-2][0]):
helper(__cmds)
elif(__args[0] in __cmds[-1][0]):
break
elif((not __args[0]) or __f):
pass
else:
print(f"{Icons.warn}Uknown command !")
return(True)
if(__name__ == "__main__"):
__cfg = Config()
arg(__cfg) if(len(argv) > 1) else main(__cfg)