-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecurrent_classes.py
463 lines (406 loc) · 17.3 KB
/
recurrent_classes.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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
import inspect
import os
import sys
import json
import tkinter
from tkinter import filedialog
from datetime import datetime
class bcolors:
with open("startup.acpl-ini", "r", encoding="utf-8") as startup_file:
for line in startup_file.readlines():
if line.startswith("use-colors: "):
line = line.replace("use-colors: ", "")
line = line.replace("\n", "")
if line.lower() == "true":
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
ITALICS = '\x1B[3m'
else:
HEADER = ''
OKBLUE = ''
OKGREEN = ''
WARNING = ''
FAIL = ''
ENDC = ''
BOLD = ''
UNDERLINE = ''
ITALICS = ''
startup_file.close()
colors_used = HEADER != ''
class Text():
def __init__(self, texts):
self.texts = texts
self.console = self.texts["console"]
self.console_modify_ini = self.console["modify-ini"]
self.console_help = self.console["help"]
self.critic_errors = self.texts["critic-errors"]
self.statement_errors = self.texts["statement-errors"]
self.updates = self.texts["update-checker"]
self.errors = self.texts["errors"]
self.compiler = self.texts["compiler"]
self.ide = self.texts["ide"]
self.main = self.texts["main"]
self.acpl_debugger = self.main["acpl_debugger"]
def get(self, key):
return self.texts.get(key)
class CriticError(Exception):
def __init__(self, *args):
if args:
self.message = args[0]
else:
self.message = None
def __str__(self):
if self.message:
return "CriticError : {0}".format(self.message)
else:
return "CriticError error has been raised."
def error(line_number, error_type, message=None, *args, quit=True):
if args:
for arg in args:
message += arg
if message != None:
print(f"{bcolors.FAIL}{error_type} {texts.statement_errors['on-line']} {line_number+1} : {message}{bcolors.ENDC}")
else:
print(f"{bcolors.FAIL}{error_type} {texts.statement_errors['has-been-raised']} {line_number+1}{bcolors.ENDC}")
if quit is True:
sys.exit()
def lineno():
"""
Returns the current line number where the function is called.
"""
return inspect.currentframe().f_back.f_lineno
def split(word:str):
"""
Splits a string into a list.
Parameter 'word' (str) : The string to split.
"""
return list(word)
def debug(entry_type, line, level, message, *args):
"""
Debug function.
Parameter 'entry_type' (str) : in, out, or other.
Parameter 'line' (int) : The line where the debug is placed.
Parameter 'message' (str) and '*args' : The message to display.
Parameter 'level' (int) : corresponds to the level of importance of the debug message
"""
global debug_const
global date_format
if debug_const >= level:
if entry_type.lower() == "in":
entry = "\n>>>"
elif entry_type.lower() == "out":
entry = "<<<"
else:
entry = "==="
if args:
for arg in args:
message += str(arg)
debug_msg_plain_text = entry + "\t" + "(" + str(line) + ")\t" + str(message) + "\n"
debug_msg = bcolors.ITALICS + bcolors.OKBLUE + entry + "\t" + "(" + str(line) + ")\t" + str(message) + bcolors.ENDC + "\n"
if not os.path.exists("/DEBUG/"):
try:
os.mkdir(os.getcwd()+"/DEBUG/")
except FileExistsError:
pass
with open(f"DEBUG/debug_{date_format}.log", "a", encoding="utf-8") as debug_file:
debug_file.write(debug_msg_plain_text)
if entry == "<<<":
debug_file.write("\n")
debug_file.close()
print(debug_msg)
if len([name for name in os.listdir(os.getcwd()+"/DEBUG/")]) > 5:
for file in os.listdir(os.getcwd()+"/DEBUG")[:5]:
os.remove(os.getcwd()+'/DEBUG/'+file)
class StatementError(Exception):
def __init__(self, *args):
if args:
self.message = args[0]
else:
self.message = None
def __str__(self):
if self.message:
return "StatementError : {0}".format(self.message)
else:
return "StatementError error has been raised."
def replace_line(file_name:str, line_num:int, text:str):
"""
Replaces a line of a file with a given string.
Parameter 'file_name' (str) : The path to the file.
Parameter 'line_num' (int) : The line to replace.
Parameter 'text' (str) : The text that will replace the current line.
"""
lines = open(file_name, 'r').readlines()
try:
lines[int(line_num)] = text
except IndexError:
lines = [text]
out = open(file_name, 'w')
out.writelines(lines)
out.close()
def delete_line(file_name:str, line_number:int, condition:bool=True):
"""
Deletes one line in a file.
Parameter 'file_name' (str) : The path to the file.
Parameter 'line_number' (int) : The line to delete.
Parameter 'condition' (bool, Default : True) : Will only delete the file if the condition is True.
"""
if condition is True: # If the condition is verified
file = open(file_name, "r", encoding="utf-8") # Opens the file once
lines = file.readlines() # Reads its lines and stores them in a list
file.close() # Closes the file
lines.pop(line_number) # Removes the specified line from the list
file = open(file_name, "w", encoding="utf-8") # Re-opens the file, and erases its content
file.writelines(lines) # Rewrites the file with the new content (old + deleted line)
file.close() # Closes the file
def insert_line(path_to_file:str, index:int, value:str):
"""
Inserts a line in a specified file, at a specific index.
Parameter 'path_to_file' (str) : The path to the file.
Parameter 'index' (int) : The line number where the text has to be inserted.
Parameter 'value' (str) : The text to insert.
"""
file = open(path_to_file, "r", encoding="utf-8") # Opens the file
contents = file.readlines() # Stores the content in a list
file.close() # Closes the file
contents.insert(index, value) # Inserts the correct text at the index (creates a new line)
file = open(path_to_file, "w", encoding="utf-8") # Re-opens the file, and erases its content
file.writelines(contents) # Rewrites everything, with the modified line
file.close() # Closes the file again
def remove_suffix(variable:str, condition:bool=True, chars_amount:int=1):
"""
Removes the suffix of a string.
Parameter 'variable' (str) : The text where the suffix has to be removed.
Parameter 'chars_amount' (int) : Default : 1. Number of chars to remove.
Parameter 'condition' (bool) : Default : True. Will only remove if the condition is True.
"""
if condition is True: # If the condition is respected
return variable[:-chars_amount] # Suffix gets removed
return variable
def remove_prefix(variable:str, condition:bool=True, chars_amount:int=1):
"""
Removes the prefix of a string.
Parameter 'variable' (str) : The text where the prefix has to be removed.
Parameter 'chars_amount' (int) : Default : 1. Number of chars to remove.
Parameter 'condition' (bool) : Default : True. Will only remove if the condition is True.
"""
if condition is True: # If the condition is respected
return variable[chars_amount:len(variable)] # Prefix gets removed
return variable
def add_suffix(variable:str, suffix:str, condition:bool=True):
"""
Removes the suffix of a string.
Parameter 'variable' (str) : The text where the suffix has to be added.
Parameter 'suffix' (int) : Default : 1. The suffix to add.
Parameter 'condition' (bool) : Default : True. Will only add if the condition is True.
"""
if condition is True:
variable += suffix
return variable
def recreate_string(variable:list, char_in_between:str=""):
"""
Recreates a string from a list.
Parameter 'variable' (list) : The list to put together to a string.
Parameter 'char_in_between' (str) : The char to put between the elements to recompose. Nothing by default.
"""
temp_str = ""
for element in variable:
temp_str += str(element) + char_in_between
return temp_str
#def increment_variable(variable:(int, float), count:(int, float)=1, condition:bool=True, condition_is_false:function=None)
def remove_from_string(variable:str, strs_to_remove:(list, tuple), condition:bool=True):
"""
Removes all the specified strings from a string.
Parameter 'variable' (str) : The string in which to replace.
Parameter 'str_sto_remove' (list, tuple) : The strings that will be removed.
Parameter 'condition' (bool, Default : True) : Will only execute the function if this parameter is set to True.
"""
if condition is True:
for element in strs_to_remove:
variable = variable.replace(str(element), "")
return variable
def open_file_dialog(extensions:(list, tuple, str)=""):
"""
Opens a "open file dialog".
:extensions: If left empty, any extensions are accepted. If not, if the extension is not in the list,
the function will return None.
:return: The filename.
"""
root = tkinter.Tk()
root.geometry("1x1")
root.title("Open")
filename = filedialog.askopenfilename()
root.withdraw()
if extensions != "":
if isinstance(extensions, str):
if not filename.endswith("."+extensions):
return None
else:
correct_extension = False
for element in extensions:
if filename.endswith("."+element):
correct_extension = True
break
if correct_extension is False:
return None
return filename
def md_format(lines:(str, list)):
"""
Formats markdown text or list.
:param lines: The lines to format.
:return: The formatted text, as string.
"""
if isinstance(lines, list):
lines = recreate_string(lines)
while "**" in lines:
lines = lines.replace("**", bcolors.BOLD, 1)
lines = lines.replace("**", bcolors.ENDC, 1)
while "*" in lines:
lines = lines.replace("*", bcolors.ITALICS, 1)
lines = lines.replace("*", bcolors.ENDC, 1)
while "```" in lines:
lines = lines.replace("```", bcolors.WARNING, 1)
lines = lines.replace("```", bcolors.ENDC, 1)
while "`" in lines:
lines = lines.replace("`", bcolors.WARNING, 1)
lines = lines.replace("`", bcolors.ENDC, 1)
""""while "####" in lines:
header = lines[lines.find("####") + 1:lines.find("\n")]
print(header)
lines = lines.replace(f"#{header}\n", f"{bcolors.HEADER}{bcolors.ITALICS}{header.replace('#', '')}{bcolors.ENDC}\n")
while "###" in lines:
header = lines[lines.find("###") + 1:lines.find("\n")]
print(header)
lines = lines.replace(f"#{header}\n", f"{bcolors.HEADER}{bcolors.BOLD}{header.replace('#', '')}{bcolors.ENDC}\n")
while "##" in lines:
header = lines[lines.find("##") + 1:lines.find("\n")]
print(header)
lines = lines.replace(f"#{header}\n", f"{bcolors.HEADER}{bcolors.BOLD}{bcolors.UNDERLINE}{header.replace('#', '')}{bcolors.ENDC}\n")
"""
return lines
def launch_py_file(filename:str):
if not filename.endswith(".py"):
filename += ".py"
file_to_launch = open(filename, "r")
exec(file_to_launch.read())
file_to_launch.close()
def var_type_as_str(var):
"""
Returns a string containing the type of the inputted variable.
:param var: A variable.
:return: A string containing the type of the inputted variable.
"""
temp = str(type(var))
temp = temp.replace("<class '", "")
temp = temp.replace("'>", "")
return temp
def print_dir(extensions:(str, list, tuple)="*"):
"""
Prints a view of the whole directory.
:param extensions: A list of extensions that can be displayed. Default : All
"""
import os
from rich.tree import Tree
from rich.console import Console
console = Console()
# If the extensions list is a string, turn it to list.
if isinstance(extensions, str):
extensions = [extensions]
# Initialize tree
tree = Tree(f":open_file_folder: [link file://{os.getcwd()}]{os.getcwd()}")
# Get directory contents and sort it
dir_contents = os.listdir()
directories = []
files = []
for element in dir_contents:
if os.path.isdir(element):
directories.append(element)
else:
# Checking authorized extensions, appending only if wanted
try:
if extensions == ["*"] or element.split(".")[1] in extensions:
files.append(element)
except IndexError:
# Ignoring files without extensions
pass
dir_contents = [] # Reset 'dir_contents'
# Appending folders first, then files
for element in directories:
dir_contents.append(element)
for element in files:
dir_contents.append(element)
# Deletion of 'directories' and 'files'
del directories
del files
# Build tree
for element in dir_contents:
# Add little icons depending on extension
if os.path.isdir(element):
element = f":file_folder: {element}"
else:
element = f":page_facing_up: {element}"
# Add element to tree
tree.add(element)
# Print tree
console.print(tree)
try:
startup_file = open("startup.acpl-ini", "r+", encoding="utf-8")
except FileNotFoundError:
print("Unable to load startup.acpl-ini !")
sys.exit()
startup = startup_file.readlines()
date_format = datetime.now().strftime("%Y_%m_%d__%H_%M_%S")
for lines in startup:
if lines.endswith("\n"):
lines = lines.replace("\n", "")
if lines.startswith("debug-state: "):
lines = lines.replace("debug-state: ", "")
debug_const = int(lines)
if str(lines).startswith("lang: "):
with open("startup.acpl-ini", "r", encoding="utf-8") as startup_file:
lines = startup_file.readlines()
lines = lines[1]
lines = str(lines).replace("lang: ", "")
lines = lines.replace("\n", "")
language = lines
try:
with open("trad_" + language + ".json", "r", encoding="utf-8") as json_file:
texts = json.load(json_file)
json_file.close()
texts = Text(texts)
except NameError:
raise CriticError(texts.critic_errors["NameError_LanguageFile"])
ide_forbidden_files = ["main.py", "console.py", "ide.py", "compiler.py", "setup.py", "updater_main.py", "updater_others.py"]
with open("startup.acpl-ini", "r", encoding="utf-8") as startup_file:
for line in startup_file.readlines():
if line.startswith("use-colors: "):
line = line.replace("use-colors: ", "")
line = line.replace("\n", "")
use_colors = line.lower() != "false"
elif line.startswith("process-time-round-numbers: "):
line = line.replace("process-time-round-numbers: ", "")
process_time_round_numbers = int(remove_suffix(line, line.endswith("\n")))
elif line.startswith("open-compiled-file: "):
line = remove_suffix(line.replace("open-compiled-file: ", ""), line.endswith("\n"))
open_compiled_file = line.lower() != "false"
elif line.startswith("leave-comments-at-compiling: "):
line = line.replace("leave-comments-at-compiling: ", "")
line = remove_suffix(line, line.endswith("\n"))
leave_comments_at_compiling = line.lower() == "true"
elif line.startswith("startup-check-update: "):
line = line.replace("startup-check-update: ", "")
line = remove_suffix(line, line.endswith("\n"))
startup_check_update = line.lower() != "false"
elif line.startswith("compiling-style: "):
line = line.replace("compiling-style: ", "")
line = remove_suffix(line, line.endswith("\n"))
compiling_style = line
elif line.startswith("compile-ask-for-replace: "):
line = line.replace("compile-ask-for-replace: ", "")
line = remove_suffix(line, line.endswith("\n"))
compile_ask_for_replace = line.lower() != "false"