-
Notifications
You must be signed in to change notification settings - Fork 1
/
hermesold(very).py
468 lines (351 loc) · 15.6 KB
/
hermesold(very).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
464
465
466
467
468
import json, os, sys
import colorama
import time
from hashlib import sha1
cwd = os.getcwd()
start = time.time()
superverbose = '-vv' in sys.argv
verbose = ('-v' in sys.argv) or superverbose
finalcommand = []
windowsglobal = "C:\\hermes"
linuxglobal = "/etc/hermes/"
macglobal = ""
if 'win32' in sys.platform : gfolder = windowsglobal
elif 'linux' in sys.platform : gfolder = linuxglobal
else : gfolder = macglobal
template = {
"compiler" : "",
"inputs" : [],
"includes" : [],
# "output" : "",
"run" : False,
"flags" : [],
}
#-----------------------------------------------------
#dealing with the global commands and stuff
if "global" in sys.argv:
index = sys.argv.index('global')
try:
op = sys.argv[index + 1]
if op != 'show':
key = sys.argv[index + 2]
if key == 'output':
print(colorama.Fore.RED + colorama.Style.BRIGHT +
'"output" is not a valid key for global config!' + colorama.Style.RESET_ALL)
sys.exit(1)
if op != 'show':
value = sys.argv[index + 3]
if value == '.':
if type(template[key]) == str: value = ""
elif type(template[key]) == list: value = []
elif type(template[key]) == bool: value = 'False'
except IndexError:
print(sys.argv)
print(colorama.Fore.RED + colorama.Style.BRIGHT +
"Invalid syntax for changing globals!" + colorama.Style.RESET_ALL)
sys.exit(1)
try:
with open(f"{gfolder}/globals.json", 'r') as file:
try : original = json.load(file)
except Exception as e:
# print(e)
original = {
"compiler" : "",
"inputs" : [],
"includes" : [],
# "output" : "",
"run" : False,
"flags" : [],
}
with open(f"{gfolder}/globals.json", 'w') as file:
if (op == 'change'):
if type(original[key]) == str : original[key] = value
elif type(original[key]) == list : original[key] = [value] if type(value) != list else value
elif type(original[key]) == bool : original[key] = ('true' == value.lower())
file.write(json.dumps(original, indent=4))
print(colorama.Fore.GREEN + colorama.Style.BRIGHT +
"Value changed successfully" + colorama.Style.RESET_ALL)
sys.exit(0)
elif (op == 'append'):
try:
original[key].append(value)
file.write(json.dumps(original, indent=4))
print(colorama.Fore.GREEN + colorama.Style.BRIGHT +
"Value appended successfully" + colorama.Style.RESET_ALL)
sys.exit(0)
except AttributeError as e:
print(e)
print(colorama.Fore.RED + colorama.Style.BRIGHT +
"Appending not supported on the given key!" + colorama.Style.RESET_ALL)
sys.exit(1)
elif (op == 'show'):
print(json.dumps(original, indent = 4))
file.write(json.dumps(original, indent = 4))
sys.exit(0)
except FileNotFoundError as e:
print(f"Globals folder does not exist yet, generating at {gfolder}...")
os.mkdir(gfolder)
with open(f"{gfolder}/globals.json", 'w') as newfile:
newfile.write(json.dumps({
"compiler" : "",
"inputs" : [],
"includes" : [],
# "output" : "",
"run" : False,
"flags" : [],
}, indent=4))
print(colorama.Fore.GREEN + colorama.Style.BRIGHT +
"Globals folder generated successfully" + colorama.Style.RESET_ALL)
sys.exit(0)
#load/generate hermes.json
try:
with open(f"{cwd}/hermes.json", 'r') as file:
config = json.load(file)
except FileNotFoundError as e:
print("Generating hermes.json...")
with open(f"{cwd}/hermes.json", 'w') as file:
file.write(json.dumps({
"compiler" : "",
"inputs" : [],
"includes" : [],
"output" : "",
"run" : False,
"flags" : [],
}, indent=4))
try:
os.mkdir(f"{cwd}/.hermes")
os.mkdir(f"{cwd}/.hermes/objs")
with open(f"{cwd}/.hermes/tracker.json", 'w') as file:
json.dump({"objs":dict(), "headers":dict()}, file, indent = 4)
except FileExistsError: pass
print(colorama.Fore.LIGHTGREEN_EX + colorama.Style.BRIGHT +
"Project config JSON file successfully generated! Hermes project initialized." + colorama.Style.RESET_ALL)
sys.exit(0)
#-----------------------------------------------------------------------
#filtering config file
for prop in config.keys():
if type(config[prop]) == list:
config[prop] = list(filter(lambda x:x, config[prop]))
#-----------------------------------------------------------------------
#-----------------------------------------------------------------------------------------
# dealing with default config values
# - default compiler is c++
# - default output file is *firstinputfilename*_output
defaults = None
try:
with open(f"{gfolder}/globals.json", 'r') as file:
defaults = json.load(file)
except FileNotFoundError:
if verbose : print("Globals not found! Resorting to classic default values...")
run = config.pop('run', False if defaults is None else defaults['run'])
if 'flags' not in config.keys(): config['flags'] = []
if defaults is not None: config['flags'] += defaults['flags']
if 'includes' not in config.keys(): config['includes'] = []
if defaults is not None: config['includes'] += defaults['includes']
if not(config['inputs']):
print("No input files given!")
sys.exit(1)
if defaults is not None: config['inputs'] += defaults['inputs']
if not(config['includes']):
pass
if not(config['compiler']): config['compiler'] = ('c++' if defaults is None else defaults['compiler'])
if not(config['compiler']): config['compiler'] = 'c++'
if not(config['output']):
ffile = config['inputs'][0].split('/')[-1].split('\\')[-1].split('.')[0]
config['output'] = f"{ffile}_output"
config['output'] = f"{cwd}/debug/{config['output']}"
if verbose:pinp = colorama.Fore.LIGHTCYAN_EX + f"Input Files : {' '.join(config['inputs'])}" + colorama.Style.RESET_ALL
config['inputs'] = list(map(
lambda x: f"{cwd}/{x[2:]}" if (x[:2] == './' and x[-1] != '*') else x,
# lambda x: f"{cwd}/{x[2:]}" if (x[:2] == './') else x,
config['inputs']))
breakable = True
while breakable:
breakable = False
for i, each in enumerate(config['inputs']):
if each[-1] == '*':
folder = f"{cwd}/{each[2:-1]}" if each[:2] == './' else f"{each[:-1]}"
files = os.listdir(folder)
for file in files:
if '.' in file:
config['inputs'].append(f"{folder}{file}")
else:
config['inputs'].append(f"{folder}{file}/*")
breakable = True
del config['inputs'][i]
try:
os.mkdir(f"{cwd}/debug")
print(colorama.Fore.GREEN + "Created `debug` folder" + colorama.Style.RESET_ALL)
except FileExistsError as e:
pass
#-----------------------------------------------------------------------------------------
#----------------------------------------------------
#file tracking stuff
changes = []
tracks = None
try:
with open(f'{cwd}/.hermes/tracker.json', 'r') as file : tracks = json.load(file)
except:
tracks = {"objs" : dict(), "headers" : dict()}
if superverbose:
print("File tracking hashes:")
for each in tracks['objs'].keys():
print(each, tracks[each])
for eachfile in config['inputs']:
if eachfile in tracks['objs'].keys():
with open(eachfile, 'r') as file:
code = sha1(file.read().strip().encode()).hexdigest()
if code != tracks['objs'][eachfile]:
changes.append(eachfile)
if superverbose: print(f"Changes in {eachfile}")
tracks['objs'][eachfile] = code
else:
changes.append(eachfile)
if superverbose: print(f"Changes in {eachfile}")
with open(eachfile, 'r') as file:
tracks['objs'][eachfile] = sha1(file.read().strip().encode()).hexdigest()
#TODO:
#- Implement header file tracking.
#writing tracks back to json file
try:
with open(f'{cwd}/.hermes/tracker.json', 'w') as file:
file.write(json.dumps(tracks, indent=4))
except FileNotFoundError:
os.mkdir(f"{cwd}/.hermes")
os.mkdir(f"{cwd}/.hermes/objs")
with open(f'{cwd}/.hermes/tracker.json', 'w') as file:
file.write(json.dumps(tracks, indent=4))
# for eachchange in changes:
# filename = eachchange.split('\\')[-1].split('/')[-1]
# filename = filename.split('.')[0]
# if superverbose: print(filename)
# os.system()
if '-redo' in sys.argv : changes = config['inputs']
#----------------------------------------------------
#adding build optimizations
opt = 0
if '-b' in sys.argv : opt = 1
if '-bb' in sys.argv : opt = 2
if '-bbb' in sys.argv : opt = 3
argflags = {
'includes' : '-I',
'inputs' : '',
'output' : '-o',
'flags' : '',
}
#--------------------------------------------------------------------------------------------------
#obj stuff
includesection = ""
for each in config['includes']:
includesection += f'-I"{each}" '
if superverbose:print(f"Include section:\n{includesection}")
objsnames = []
for eachchange in changes:
filename = eachchange.split('\\')[-1].split('/')[-1].split('.')[0]
if verbose:
print(colorama.Fore.GREEN +
f"Updating objects for `{filename}`" + colorama.Style.RESET_ALL)
if filename in objsnames: filename = f"{filename}1"
objsnames.append(filename)
objcomm = (f"{config['compiler']} -c {eachchange} -o {cwd}/.hermes/objs/{filename}.o {includesection} " +
f"{['-O1', '-O2', '-O3'][opt - 1] if opt > 0 else ('-Ofast' if '-saikyou' in sys.argv else '')}")
if superverbose:print(objcomm)
if os.system(objcomm):
end = time.time()
print(colorama.Style.BRIGHT + colorama.Fore.RED +
f"Compilation Failed! Error in `{filename}` Build failed in {str(end - start)[:4]}s" + colorama.Style.RESET_ALL)
sys.exit(1)
#--------------------------------------------------------------------------------------------------
if verbose:
print(colorama.Fore.LIGHTBLUE_EX + f"Compiler : {config['compiler']}" + colorama.Style.RESET_ALL)
print(pinp)
print(colorama.Fore.LIGHTYELLOW_EX + f"Include Files : {' '.join(config['includes'])}" + colorama.Style.RESET_ALL)
print(colorama.Fore.LIGHTMAGENTA_EX + f"Output file : {config['output']}" + colorama.Style.RESET_ALL)
print(colorama.Fore.LIGHTRED_EX + f"Auto launch : {run}" + colorama.Style.RESET_ALL)
print(colorama.Fore.LIGHTCYAN_EX + f"Additional flags : {' '.join(config['flags'])}" + colorama.Style.RESET_ALL)
print()
#------------------------------------------------------------------------------------------------------------------------------------------------
#force rebuilding the whole thing
if ('-f' in sys.argv) or ('-force' in sys.argv) or ('-release' in sys.argv):
print(colorama.Style.BRIGHT + colorama.Fore.YELLOW +
"Release mode, building application..." + colorama.Style.RESET_ALL)
for each in config:
if superverbose : print(each, config[each])
if each == 'compiler':
finalcommand.append(config[each])
continue
if config[each]:
finalcommand.append(" ")
finalcommand.append(argflags[each])
if type(config[each]) == list:
for i, val in enumerate(config[each]):
if i: finalcommand.append(argflags[each])
if each != 'flags' : finalcommand.append(f"\"{val}\"")
else : finalcommand.append(f"{val}")
else : finalcommand.append(f"\"{config[each]}\"")
finalcommand = list(filter(lambda x:x, finalcommand))
#--------------------------------------------------------------
#build optimizations
if opt:
print(colorama.Style.BRIGHT + colorama.Fore.YELLOW +
f"\nOptimizations O{opt} enabled! Building application..." + colorama.Style.RESET_ALL)
finalcommand.append(f'-O{opt}')
if ('-saikyou' in sys.argv) or ('-release' in sys.argv):
print(
colorama.Style.BRIGHT + colorama.Fore.BLUE +
f"\nApplying fastest possible optimizations! Building application..." + colorama.Style.RESET_ALL
)
finalcommand.append('-Ofast')
#--------------------------------------------------------------
if superverbose:
print()
print(finalcommand)
finalcommand = " ".join(finalcommand)
if os.system(finalcommand) == 0:
end = time.time()
print(colorama.Fore.GREEN + colorama.Style.BRIGHT + f"Compilation successful! Build completed in {str(end - start)[:4]}s" + colorama.Style.RESET_ALL)
else:
end = time.time()
print(colorama.Fore.RED + f"Compilation Failed! Build failed in {str(end - start)[:4]}s" + colorama.Style.RESET_ALL)
sys.exit(1)
#------------------------------------------------------------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------------------
#compiling all objects into final executable
#{cwd}/.hermes/objs/*.o
foc = f"{config['compiler']} "
for eachinput in config['inputs']:
filename = eachinput.split('/')[-1].split('\\')[-1].split('.')[0]
foc += f"{cwd}/.hermes/objs/{filename}.o "
foc += f"-o {config['output']} "
for eachflag in config['flags']:
foc += f"{eachflag} "
if opt:
print(colorama.Style.BRIGHT + colorama.Fore.YELLOW +
f"\nOptimizations O{opt} enabled! Building application..." + colorama.Style.RESET_ALL)
foc += (f'-O{opt}')
if '-saikyou' in sys.argv:
print(
colorama.Style.BRIGHT + colorama.Fore.BLUE +
f"\nApplying fastest possible optimizations! Building application..." + colorama.Style.RESET_ALL
)
foc += ('-Ofast')
if superverbose:print(foc)
if os.system(foc):
end = time.time()
print(colorama.Style.BRIGHT + colorama.Fore.RED +
f"Compilation Failed! Build failed in {str(end - start)[:4]}s" + colorama.Style.RESET_ALL)
print(colorama.Style.DIM + colorama.Fore.RED +
f"This was a linker error, most likely caused by missing object (.a, .o), .dll, .lib or .cxx files.\nEnsure all headers have their corresponding declarations, and all library flags are added." + colorama.Style.RESET_ALL)
sys.exit(1)
end = time.time()
print(colorama.Style.BRIGHT + colorama.Fore.GREEN +
f"Compilation Successful! Build succeeded in {str(end - start)[:4]}s" + colorama.Style.RESET_ALL)
#---------------------------------------------------------------------------------------------------------------
if run:
print()
start = time.time()
code = os.system(f"{config['output']}.exe") if 'win32' in sys.platform else os.system(config['output'])
end = time.time()
code = (colorama.Fore.RED if code else colorama.Fore.GREEN) + f"code {code}" + colorama.Style.RESET_ALL
print(f"\nExecution finished with exit {code} in {str(end - start)[:4]}s")
if 'win32' in sys.platform : os.system("pause")