-
Notifications
You must be signed in to change notification settings - Fork 2
/
SusyGen
executable file
·1031 lines (883 loc) · 34.3 KB
/
SusyGen
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import os
import os.path
import io
import tempfile
import subprocess
import difflib
import json
import re
import sys
import urllib.request
import mimetypes
import datetime
import stat
import shutil
import time
import threading
import math
CONFIG = None
################################################################################
# Log and Control
fail = False
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def print_header(msg):
global fail
if fail:
print("\n" + bcolors.FAIL + "Erros encontrados" + bcolors.ENDC)
exit()
print(bcolors.HEADER + "---------------------------------")
print(msg + bcolors.ENDC)
def print_ok(msg=" OK "):
print(bcolors.OKBLUE + msg + bcolors.ENDC)
def print_error(msg=None):
global fail
fail = True
if msg:
print(bcolors.FAIL + "ERRO -", msg + bcolors.ENDC)
else:
print(bcolors.FAIL + "ERRO" + bcolors.ENDC)
def print_warning(msg):
print(bcolors.WARNING + msg + bcolors.ENDC)
def print_check(msg):
print(msg+": ", end="")
################################################################################
# Defines
CC = ["gcc"]
CPPFLAGS = []
CFLAGS = ["-O3", "-std=c99", "-Werror", "-Wall", "-Wextra", "-pedantic", "-Wunused-result", "-Wno-error=unused-result"]
LDFLAGS = []
LDLIBS = ["-lm"]
HTML_HEADER = """<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html; charset=utf-8'>
<title>Laboratório !ID!</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link href='https://fonts.googleapis.com/css?family=Noto+Sans:400,700,400italic' rel='stylesheet' type='text/css'>
<link rel='stylesheet' href='https://sindresorhus.com/github-markdown-css/github-markdown.css'>
<style>
.markdown-body {
box-sizing: border-box;
min-width: 200px;
max-width: 980px;
margin: 0 auto;
padding: 45px;
font-family: 'Noto Sans', sans-serif;
}
.markdown-body h6 { margin-bottom: 0; }
.markdown-body h6 + ul li {
display: inline-block;
width: 100%;
max-width: 426px;
vertical-align: top;
}
.markdown-body h6 + ul li pre {
max-height: 400px;
}
</style>
</head>
<body>
<article class='markdown-body'>
"""
HTML_TAIL = """
</article>
</body>
</html>
"""
################################################################################
# Timer Process
class TimerPopen:
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
self.process = None
self.elapsed = 0
self.returncode = -1
def run(self):
self.thread = threading.Thread(target=self.processthread)
self.thread.start()
def wait(self):
self.thread.join()
def processthread(self):
start = time.time()
self.process = subprocess.Popen(*self.args, **self.kwargs)
try:
self.process.wait(timeout=10)
except TimeoutExpired:
self.process.kill()
self.process.wait()
done = time.time()
self.elapsed = done - start
self.returncode = self.process.returncode
################################################################################
# Languages
class Language:
def __init__(self, srcdir, tmpdir, config):
self.srcdir = srcdir
self.tmpdir = tmpdir
self.config = config
self.source = list()
def compile(self):
pass
def run(self, stdin, stdout, stderr, args):
pass
def copy(self, target):
for file in self.source:
shutil.copy(os.path.join(self.srcdir, file), target)
class LanguageC(Language):
def __init__(self, srcdir, tmpdir, config):
Language.__init__(self, srcdir, tmpdir, config)
global CONFIG
self.executable = os.path.join(tmpdir, CONFIG["submissions"]["basename"])
self.header = list()
def compile(self):
Language.compile(self)
print_check("Compilando C")
self.source = list()
for file in os.listdir(self.srcdir):
if file.endswith(".c"):
self.source.append(file)
elif file.endswith(".h"):
self.header.append(file)
if not self.source:
print_error("Falta código da solução.")
command = list()
command.extend(CC)
command.extend(CPPFLAGS)
command.extend(CFLAGS)
command.extend(LDFLAGS)
command.extend(self.source)
command.extend(LDLIBS)
command.append("-o"+self.executable)
comp = subprocess.Popen(command, cwd=self.srcdir, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
comp.wait()
if comp.returncode:
print_error("Compilação da solução falhou.")
print(str(comp.stdout.read(), 'utf-8'))
print_ok()
def run(self, stdin, stdout, stderr, args):
Language.run(self, stdin, stdout, stderr, args)
Args = [self.executable]
if args:
Args.extend(args)
p = TimerPopen(Args, stdin=stdin, stdout=stdout, stderr=stderr)
p.run()
return p
def copy(self, target):
Language.copy(self, target)
for file in self.header:
shutil.copy(os.path.join(self.srcdir, file), target)
class LanguagePY3(Language):
def __init__(self, srcdir, tmpdir, config):
Language.__init__(self, srcdir, tmpdir, config)
global CONFIG
self.executable = CONFIG["submissions"]["basename"]+".py"
if "main" in self.config:
self.executable = self.config["main"]
def compile(self):
Language.compile(self)
print_check("Compilando PY3")
self.source = list()
for file in os.listdir(self.srcdir):
if file.endswith(".py"):
self.source.append(file)
shutil.copy(os.path.join(self.srcdir, file), self.tmpdir)
if not self.source:
print_error("Falta código da solução.")
elif self.executable not in self.source:
print_error("Falta código da main: {0:s}".format(self.executable))
else:
print_ok()
def run(self, stdin, stdout, stderr, args):
Language.run(self, stdin, stdout, stderr, args)
Args = ["python3", os.path.join(self.tmpdir, self.executable)]
if args:
Args.extend(args)
p = TimerPopen(Args, stdin=stdin, stdout=stdout, stderr=stderr)
p.run()
return p
def getLanguage(lang, srcdir, tmpdir, config):
L = "Language" + lang
if L not in globals():
print_error("Language error: " + lang)
return
Lang = globals()[L]
if not os.path.isdir(tmpdir):
os.mkdir(tmpdir)
return Lang(srcdir, tmpdir, config)
################################################################################
# Init
# Get the directory of this script
script_dir = os.path.dirname(os.path.realpath(__file__))
cur_dir = os.getcwd()
# Arguments
import argparse
parser = argparse.ArgumentParser(description='Gerador do enunciado para o Susy.')
parser.add_argument('directory', metavar='directory', type=str, nargs='?',
default=cur_dir,
help='Diretório do enunciado')
parser.add_argument('--keep', action='store_true',
help='Não excluir arquivos temporários')
parser.add_argument('--new', action='store_true',
help='Sobreescreve testes com gerador')
parser.add_argument('--seq', action='store_true',
help='Executar sequencialmente')
parser.add_argument('--quiet', action='store_true',
help='Evitar saidas')
args = parser.parse_args()
################################################################################
# Configs
workdir = os.path.realpath(args.directory)
print_header("Trabalhando o Enunciado")
print_ok(workdir)
print_check("Configuração")
config_file = open(os.path.join(workdir, 'config.json'))
CONFIG = json.load(config_file)
config_file.close()
print_ok()
#Default Values
if "limits" not in CONFIG:
CONFIG["limits"] = dict()
if "cpu" not in CONFIG["limits"]:
CONFIG["limits"]["cpu"] = 5
if "input" not in CONFIG["solution"]:
CONFIG["solution"]["input"] = dict()
if "std" not in CONFIG["solution"]["input"]:
CONFIG["solution"]["input"]["std"] = True
if "extensions" not in CONFIG["solution"]["input"]:
CONFIG["solution"]["input"]["extensions"] = ["in"]
if "output" not in CONFIG["solution"]:
CONFIG["solution"]["output"] = dict()
if "std" not in CONFIG["solution"]["output"]:
CONFIG["solution"]["output"]["std"] = True
if "extensions" not in CONFIG["solution"]["output"]:
CONFIG["solution"]["output"]["extensions"] = ["out"]
elif len(CONFIG["solution"]["output"]["extensions"]) > 1:
print_error(msg="Susy somente suporta um arquivo de saída")
if "filter" not in CONFIG["solution"]["output"]:
CONFIG["solution"]["output"]["filter"] = None
if "stderr" not in CONFIG["solution"]:
CONFIG["solution"]["stderr"] = dict()
if "std" not in CONFIG["solution"]["stderr"]:
CONFIG["solution"]["stderr"]["std"] = True
if "extension" not in CONFIG["solution"]["stderr"]:
CONFIG["solution"]["stderr"]["extension"] = "err"
cmd = dict()
cmd["id"] = CONFIG["task"]["id"]
CONFIG["submissions"]["basename"] = CONFIG["submissions"]["basename"] % cmd
# Detecting testes
tests = dict()
tests["open"] = list()
tests["gopen"] = list()
d = os.path.join(workdir, "tests", "open")
if os.path.isdir(d):
for file in os.listdir(d):
filename, file_extension = os.path.splitext(file)
if not filename.startswith("arq") or not file_extension.startswith("."):
print("Ignoring open test:", file)
filename = filename[3:]
file_extension = file_extension[1:]
if file_extension == "pre":
tests["gopen"].append(filename)
elif file_extension == CONFIG["solution"]["input"]["extensions"][0]:
tests["open"].append(filename)
if args.new:
tests["open"] = [name for name in tests["open"] if name not in tests["gopen"]]
else:
tests["gopen"] = [name for name in tests["gopen"] if name not in tests["open"]]
tests["hidden"] = list()
tests["ghidden"] = list()
d = os.path.join(workdir, "tests", "hidden")
if os.path.isdir(d):
for file in os.listdir(d):
filename, file_extension = os.path.splitext(file)
if not filename.startswith("arq") or not file_extension.startswith("."):
print("Ignoring hidden test:", file)
filename = filename[3:]
file_extension = file_extension[1:]
if filename in tests["open"] or filename in tests["gopen"]:
print("Atenção: O teste fechado", filename, "será inogrado.")
elif file_extension == "pre":
tests["ghidden"].append(filename)
elif file_extension == CONFIG["solution"]["input"]["extensions"][0]:
tests["hidden"].append(filename)
if args.new:
tests["hidden"] = [name for name in tests["hidden"] if name not in tests["ghidden"]]
else:
tests["ghidden"] = [name for name in tests["ghidden"] if name not in tests["hidden"]]
for key, value in tests.items():
value.sort()
#print(tests)
print("Testes estáticos encontrados")
print_check("Abertos")
print_ok(",".join(tests["open"]))
print_check("Fechados")
print_ok(",".join(tests["hidden"]))
print("Testes encontrados")
print_check("Abertos")
print_ok(",".join(tests["gopen"]))
print_check("Fechados")
print_ok(",".join(tests["ghidden"]))
################################################################################
# Temporary Directory
print_header("Diretório Temporário")
if args.keep:
tmpdir = tempfile.gettempdir()
tmpdir = os.path.join(tmpdir, "SusyTools_" + CONFIG["task"]["id"])
if os.path.isdir(tmpdir):
shutil.rmtree(tmpdir, ignore_errors=True)
os.mkdir(tmpdir)
print_ok(tmpdir)
print_warning("Não será excluído")
else:
tmpdir_obj = tempfile.TemporaryDirectory(prefix="SusyTools_")
tmpdir = tmpdir_obj.name
print_ok(tmpdir)
# Creator
if tests["gopen"] or tests["ghidden"]:
gen = "PY3"
gen_data = None
if "generator" in CONFIG:
if "language" in CONFIG["generator"]:
gen = CONFIG["generator"]["language"]
gen_data = CONFIG["generator"]
gen_src = os.path.join(workdir, "tests", "generator")
gen_tmp = os.path.join(tmpdir, "generator")
Gen = getLanguage(gen, gen_src, gen_tmp, gen_data)
Gen.compile()
# Tests
d = os.path.join(tmpdir, "tests")
os.mkdir(d)
if tests["open"] or tests["hidden"]:
print_check("Copiando testes estáticos")
for type in ["open", "hidden"]:
target = os.path.join(workdir, "tests", type)
for filename in tests[type]:
exts = CONFIG["solution"]["input"]["extensions"] + CONFIG["solution"]["output"]["extensions"]
exts.append(CONFIG["solution"]["stderr"]["extension"])
for ext in exts:
filepath = os.path.join(target, "arq{0:s}.{1:s}".format(filename, ext))
if os.path.isfile(filepath):
shutil.copy(filepath, d)
print_ok()
def wait_gentest(p, data):
print_check("Teste " + data["filename"])
p.wait()
if p.returncode:
print_error()
else:
print_ok()
print(str(p.process.stdout.read(), 'utf-8'))
def run_gentest(t, filename, wait_list):
global Gen
global CONFIG
params = list()
params.append(os.path.join(workdir, "tests", t, "arq" + filename + ".pre"))
params.extend([os.path.join(d, "arq{0:s}.{1:s}".format(filename, ext)) for ext in CONFIG["solution"]["input"]["extensions"]])
params.extend([os.path.join(d, "arq{0:s}.{1:s}".format(filename, ext)) for ext in CONFIG["solution"]["output"]["extensions"]])
params.append(os.path.join(d, "arq{0:s}.{1:s}".format(filename, CONFIG["solution"]["stderr"]["extension"])))
p = Gen.run(None, subprocess.PIPE, subprocess.STDOUT, params)
data = dict()
data["filename"] = filename
data["files"] = params
if args.seq:
wait_gentest(p, data)
else:
wait_list.append((p, data))
if tests["gopen"] or tests["ghidden"]:
print_header("Gerando testes")
wait_list = list()
for filename in tests["gopen"]:
run_gentest("open", filename, wait_list)
tests["open"].append(filename)
tests["open"].sort()
for filename in tests["ghidden"]:
run_gentest("hidden", filename, wait_list)
tests["hidden"].append(filename)
tests["hidden"].sort()
for p in wait_list:
wait_gentest(*p)
################################################################################
# Solution
print_header("Solução")
x = os.path.join(tmpdir, "solution")
os.mkdir(x)
langs = None
if "languages" in CONFIG["solution"]:
langs = CONFIG["solution"]["languages"].keys()
if not langs:
langs = [CONFIG["solution"]["language"]]
Langs = dict()
for lang in langs:
L = "Language" + lang
if L not in globals():
print_error("Language error: " + lang)
continue
Lang = globals()[L]
src = os.path.join(workdir, "solution", lang)
if not os.path.isdir(src):
src = os.path.join(workdir, "solution")
tmp = os.path.join(tmpdir, "solution", lang)
os.mkdir(tmp)
dt = None
if "languages" in CONFIG["solution"] and lang in CONFIG["solution"]["languages"]:
dt = CONFIG["solution"]["languages"][lang]
Langs[lang] = Lang(src, tmp, dt)
Langs[lang].compile()
################################################################################
# Run tests
def wait_test(p, data):
print_check("Teste "+data["filename"])
p.wait()
data["stdin"].close()
data["stdout"].close()
data["stderr"].close()
if p.returncode:
print_error("Erro na execução ({0:d})".format(p.returncode))
return
for d in data["difflist"]:
result = os.path.join(data["cwd"], d)
reference = os.path.join(data["swd"], d)
if os.path.isfile(reference):
res = open(result)
ref = open(reference)
diff = list(difflib.unified_diff(ref.readlines(), res.readlines(), fromfile='Correto', tofile='Executado'))
res.close()
ref.close()
if diff:
print_error("Diferenças encontradas no {0:s}".format(d))
global args
if not args.quiet:
sys.stdout.writelines(diff)
return
else:
shutil.copy(result, reference)
elapsed = math.ceil(10 * p.elapsed)
if elapsed > data["config"]["limits"]["cpu"]:
data["config"]["limits"]["cpu"] = elapsed
print_warning(" OK {0:.3f}s".format(p.elapsed))
else:
print_ok(" OK {0:.3f}s".format(p.elapsed))
d = os.path.join(tmpdir, "tests")
for lang, L in Langs.items():
print_header("Rodando os testes para solução em "+lang)
wait_list = list()
for filename in sorted(tests["open"]+tests["hidden"]):
ld = os.path.join(d, "arq" + filename + "_" + lang)
os.mkdir(ld)
test_args = list()
tmp_args = [os.path.join(d, "arq{0:s}.{1:s}".format(filename, ext)) for ext in CONFIG["solution"]["input"]["extensions"]]
if CONFIG["solution"]["input"]["std"]:
stdin = open(tmp_args.pop(0), "r")
else:
stdin = open(os.devnull, "r")
test_args.extend(tmp_args)
tmp_args = [os.path.join(ld, "arq{0:s}.{1:s}".format(filename, ext)) for ext in CONFIG["solution"]["output"]["extensions"]]
if CONFIG["solution"]["output"]["std"]:
stdout = open(tmp_args.pop(0), "w")
else:
stdout = open(os.devnull, "w")
test_args.extend(tmp_args)
tmp_args = os.path.join(ld, "arq{0:s}.{1:s}".format(filename, CONFIG["solution"]["stderr"]["extension"]))
if CONFIG["solution"]["stderr"]["std"]:
stderr = open(tmp_args, "w")
else:
stderr = open(os.devnull, "w")
test_args.append(tmp_args)
difflist = list()
difflist.extend(["arq{0:s}.{1:s}".format(filename, ext) for ext in CONFIG["solution"]["output"]["extensions"]])
difflist.append("arq{0:s}.{1:s}".format(filename, CONFIG["solution"]["stderr"]["extension"]))
p = L.run(stdin, stdout, stderr, test_args)
data = dict()
data["filename"] = filename
data["swd"] = d
data["cwd"] = ld
data["stdin"] = stdin
data["stdout"] = stdout
data["stderr"] = stderr
data["difflist"] = difflist
data["config"] = CONFIG
if args.seq:
wait_test(p, data)
else:
wait_list.append((p, data))
for p in wait_list:
wait_test(*p)
# Checando resultados:
print_header("Limites")
print_check("Verificando limite de CPU")
if CONFIG["limits"]["cpu"] > 10:
print_warning("{0:d}s! Limite do Susy: {1:d}s".format(CONFIG["limits"]["cpu"], 10))
CONFIG["limits"]["cpu"] = 10
else:
print_ok(" OK {0:d}s".format(CONFIG["limits"]["cpu"]))
# Salvando Testes
if args.new:
print_header("Salvando Testes")
for t in ["open", "hidden"]:
target = os.path.join(workdir, "tests", t)
print_check("Copiando testes para tests/{0:s}".format(t))
for filename in tests["g"+t]:
args = list()
args.extend([os.path.join(d, "arq{0:s}.{1:s}".format(filename, ext)) for ext in CONFIG["solution"]["input"]["extensions"]])
args.extend([os.path.join(d, "arq{0:s}.{1:s}".format(filename, ext)) for ext in CONFIG["solution"]["output"]["extensions"]])
args.append(os.path.join(d, "arq{0:s}.{1:s}".format(filename, CONFIG["solution"]["stderr"]["extension"])))
for file in args:
shutil.copy(file, target)
print_ok()
# Check Images
print_header("Enunciado")
print_check("Imagens")
imgs = list()
mimetypes.init()
for filename in os.listdir(workdir):
m = mimetypes.guess_type(filename)
if m[0] and m[0].startswith("image/"):
imgs.append(filename)
print_ok(",".join(imgs))
# Markdown
load_test_re = re.compile('(?P<pre>.*)!TESTE!(?P<file>\d+)!(?P<pos>.*)')
include_re = re.compile('(?P<pre>.*)include\(\"(?P<file>[^\"]+)\"\)(?P<pos>.*)')
def parse_md(input, output):
while input:
line = input.pop(0)
m = load_test_re.match(line)
if m:
line = m.group('pre')
input.insert(0,m.group('pos'))
input.insert(0," ```\n\n")
input.insert(0,'include("tests/arq'+m.group('file')+'.out")\n')
input.insert(0," ```\n")
input.insert(0,"* [Saída](dados/arq"+m.group('file')+".res)\n\n")
input.insert(0," ```\n\n")
input.insert(0,'include("tests/arq'+m.group('file')+'.in")\n')
input.insert(0," ```\n")
input.insert(0,"* [Entrada](dados/arq"+m.group('file')+".in)\n\n")
input.insert(0,"###### Teste "+m.group('file')+"\n\n")
m = include_re.match(line)
if m:
line = m.group('pre')
input.insert(0,m.group('pos'))
f = os.path.join(tmpdir, m.group('file'))
if not os.path.isfile(f):
f = os.path.join(workdir, m.group('file'))
f = open(f)
flines = f.readlines()
f.close()
while flines:
input.insert(0, flines.pop())
output.append(line)
print_check("Carregando Markdown")
md = os.path.join(workdir, "enunciado.md")
md = open(md)
mdlines = md.readlines()
md.close()
print_ok()
print_check("Parseando Markdown")
mdo = list()
parse_md(mdlines, mdo)
print_ok()
print_check("Salvando Markdown")
md = os.path.join(tmpdir, "enunciado.md")
md = open(md, "w")
md.writelines(mdo)
md.close()
md = ''.join(mdo)
print_ok()
print_check("Markdown para HTML")
req = urllib.request.Request(url='https://api.github.com/markdown/raw',
data=md.encode('utf-8'))
req.add_header('Content-Type', 'text/x-markdown')
html = ""
with urllib.request.urlopen(req) as response:
html = response.read().decode('utf-8')
md = os.path.join(tmpdir, "enunciado.html")
md = open(md, "w")
md.write(HTML_HEADER)
md.write(html)
md.write(HTML_TAIL)
md.close()
md = HTML_HEADER.splitlines(keepends=True)
md.extend(html.splitlines(keepends=True))
md.extend(HTML_TAIL.splitlines(keepends=True))
html = md
print_ok()
cmd_re = re.compile('(?P<pre>.*)!(?P<cmd>[A-Z_]+)!(?P<pos>.*)')
def parse_html(input, output, data):
while input:
line = input.pop(0)
m = cmd_re.match(line)
if m:
line = ""
tag = m.group('cmd').lower()
if tag in data:
input.insert(0,m.group('pos'))
input.insert(0,data[tag])
input.insert(0,m.group('pre'))
else:
input.insert(0,"!"+m.group('pos'))
input.insert(0,m.group('cmd'))
input.insert(0,m.group('pre')+"!")
continue
output.append(line)
def write_cfg(filename, data):
cfg = '''##||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
# Tarefa
VERSION: 9.6 # Versão do sistema
TASKID: %(id)s # Identificação da tarefa (tratada como identificador)
TASK_COMMENT: %(title)s # Título da tarefa
# Data de início do prazo de submissão
START_TIME: %(start_time)s
START_DATE: %(start_date)s
# Data de fim do prazo de submissão
FINAL_TIME: %(final_time)s
FINAL_DATE: %(final_date)s
PROCESSOR: [%(languages)s] # Processador a ser usado na instalação da tarefa
IMPLEMENTATION_PROCESSOR: %(language)s
MAIN_PROG_NAME: %(basename)s
SELECT_PROCESSOR: False
SUBMIT_FILES: ["*"] # Submissão de um único arquivo, com nome próprio
MAX_SUBMISSIONS: %(max_submissions)s
CORE_LIMIT: 0 # Tamanho máximo do arquivo core (bytes) 0/0
CPU_LIMIT: %(cpu_limit)s # Tempo maximo de processamento em segundos 1/10
DATA_LIMIT: %(data_limit)s # Limite de tamanho do segmento de dados (kbytes) 100/1000
FILE_LIMIT: %(file_limit)s # Tamanho máximo de arquivos gerados (blocos) 100/2000
NOFILE_LIMIT: 10 # Número máximo de arquivos abertos num programa submetido 10/20
NPROC_LIMIT: 10 # Número máximo de processos criados num programa submetido 10/10
STACK_LIMIT: %(stack_limit)s # Tamanho máximo da pilha de execução (bytes) 1000/10000
INPUTPART: %(input_part)s
OUTPUTPART: %(output_part)s
ERRORPART: %(error_part)s
%(suffix)s
OUTPUT_FILTER: %(output_filter)s
TEST_CASES: [%(open_tests)s] # Testes abertos
HIDDEN_TEST_CASES: [%(hidden_tests)s] # Testes fechados
EXHIBIT_AUX_FILES: [%(aux_files)s]
SYM_LINKS: [%(sym_links)s] # Aux presentes na execução
KEEP: %(keep)s # Número de submissões a preservar de cada aluno
TASK_DESCRIPTION_PAGE: enunciado.html
##||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
''' % data
filename.write(cfg)
print_check("HTML de referência")
cmd = dict()
cmd["id"] = CONFIG["task"]["id"]
cmd["max_submissions"] = str(CONFIG["submissions"]["maximum"])
cmd["deadline"] = "%d/%m/%Y %H:%M:%S"
cmd["title"] = CONFIG["task"]["title"]
cmd["basename"] = CONFIG["submissions"]["basename"] % cmd
rhtml = list()
parse_html(html[:], rhtml, cmd)
desc = open(os.path.join(workdir, "enunciado.html"), "w")
desc.writelines(rhtml)
desc.close()
print_ok()
rdir = os.path.join(workdir, "releases")
shutil.rmtree(rdir, ignore_errors=True)
os.mkdir(rdir)
for release in CONFIG["releases"]:
print_header("Instalador "+release["name"])
print_check("Criando diretório")
d = os.path.join(tmpdir, release["name"])
rdirr = os.path.join(rdir, release["name"])
try:
os.mkdir(d)
os.mkdir(rdirr)
except FileExistsError:
print_error("Diretório " + d +" já existe")
continue
ds = os.path.join(d, CONFIG["task"]["id"])
os.mkdir(ds)
print_ok()
release["start_time"] = datetime.datetime.strptime(release["start_time"], "%Y-%m-%d %H:%M:%S")
release["end_time"] = datetime.datetime.strptime(release["end_time"], "%Y-%m-%d %H:%M:%S")
if "description" not in release or release["description"]:
print_check("Editando HTML")
cmd = dict()
cmd["id"] = CONFIG["task"]["id"]
cmd["max_submissions"] = str(CONFIG["submissions"]["maximum"])
cmd["deadline"] = release["end_time"].strftime("%d/%m/%Y %H:%M:%S")
cmd["title"] = CONFIG["task"]["title"]
cmd["basename"] = CONFIG["submissions"]["basename"] % cmd
rhtml = list()
parse_html(html[:], rhtml, cmd)
print_ok()
print_check("Salvando HTML")
desc = open(os.path.join(ds, "enunciado.html"), "w")
desc.writelines(rhtml)
desc.close()
for img in imgs:
shutil.copy(os.path.join(workdir, img), ds)
print_ok()
print_check("Copiando testes")
dt = os.path.join(ds, "dados")
os.mkdir(dt)
for t in ["open", "hidden"]:
if t+"_tests" not in release or release[t+"_tests"]:
for filename in tests[t]:
for ext in CONFIG["solution"]["input"]["extensions"]:
shutil.copy(os.path.join(tmpdir, "tests", "arq{0:s}.{1:s}".format(filename, ext)), dt)
print_ok()
saux = os.path.join(workdir, "aux")
daux = os.path.join(ds, "aux")
os.mkdir(daux)
exib_aux = list()
if os.path.isdir(saux) and ("aux" not in release or release["aux"] != False):
print_check("Copiando Auxiliares")
for filename in os.listdir(saux):
shutil.copy(os.path.join(saux, filename), daux)
if "aux" in release and release["aux"] == True:
exib_aux.append(filename)
print_ok()
print_check("Copiando solução")
dsols = os.path.join(ds, "sols")
os.mkdir(dsols)
sym_links = list()
for lang, L in Langs.items():
if lang == CONFIG["solution"]["language"]:
L.copy(dsols)
if L.config and "public" in L.config:
for filename in L.config["public"]:
shutil.copy(os.path.join(workdir, "solution", lang, filename), daux)
sym_links.append(filename)
if "aux" in release and release["aux"] == True:
exib_aux.append(filename)
print_ok()
print_check("Gerando tarefa.cfg")
cfgd = dict()
cfgd["id"] = CONFIG["task"]["id"]
if release["title"]:
cfgd["title"] = CONFIG["task"]["title"]
else:
cfgd["title"] = "Unknown"
cfgd["start_time"] = release["start_time"].strftime("%H:%M:%S")
cfgd["start_date"] = release["start_time"].strftime("%Y/%m/%d")
cfgd["final_time"] = release["end_time"].strftime("%H:%M:%S")
cfgd["final_date"] = release["end_time"].strftime("%Y/%m/%d")
cfgd["hidden_tests"] = ""
if "hidden_tests" not in release or (release["hidden_tests"] and release["hidden_tests"] != "open"):
if "open_tests" in release and release["open_tests"] == "hidden":
cfgd["hidden_tests"] = '"' + '","'.join(x for x in sorted(tests[ "open"] +tests["hidden"])) + '"'
else:
cfgd["hidden_tests"] = '"' + '","'.join(x for x in tests["hidden"]) + '"'
cfgd["open_tests"] = ""
if "open_tests" not in release or (release["open_tests"] and release["open_tests"] != "hidden"):
if "hidden_tests" in release and release["hidden_tests"] == "open":
cfgd["open_tests"] = '"' + '","'.join(x for x in sorted(tests[ "open"] +tests["hidden"])) + '"'
else:
cfgd["open_tests"] = '"' + '","'.join(x for x in tests["open"]) + '"'
cfgd["language"] = CONFIG["solution"]["language"]
cfgd["languages"] = '"' + '","'.join(x for x in CONFIG["submissions"]["languages"].keys()) + '"'
cfgd["cpu_limit"] = str(CONFIG["limits"]["cpu"])
cfgd["data_limit"] = str(CONFIG["limits"]["data"])
cfgd["file_limit"] = str(CONFIG["limits"]["file"])
cfgd["stack_limit"] = str(CONFIG["limits"]["stack"])
cfgd["keep"] = str(CONFIG["submissions"]["keep"])
cfgd["max_submissions"] = str(CONFIG["submissions"]["maximum"])
cfgd["basename"] = CONFIG["submissions"]["basename"] % cfgd
cfgd["sym_links"] = ''
if sym_links:
cfgd["sym_links"] = '"' + '","'.join(x for x in sym_links) + '"'
cfgd["aux_files"] = ''
if exib_aux:
cfgd["aux_files"] = '"' + '","'.join(x for x in exib_aux) + '"'
cfgd["suffix"] = ""
cfgd["input_part"] = ""
if CONFIG["solution"]["input"]["std"]:
cfgd["input_part"] += " <"
for i, ext in enumerate(CONFIG["solution"]["input"]["extensions"]):
cfgd["input_part"] += " arq%(test)s.{0:s}".format(ext)
I = ""
if i:
I = str(i)
cfgd["suffix"] += "INPUT_SUFFIX{1:s}: '.{0:s}'\n".format(ext, I)
cfgd["output_part"] = ""
if CONFIG["solution"]["output"]["std"]:
cfgd["output_part"] += " >"
for i, ext in enumerate(CONFIG["solution"]["output"]["extensions"]):
cfgd["output_part"] += " arq%(test)s.{0:s}".format(ext)
I = ""
if i:
I = str(i)
cfgd["suffix"] += "OUTPUT_SUFFIX{1:s}: '.{0:s}'\n".format(ext, I)
cfgd["error_part"] = ""
if CONFIG["solution"]["stderr"]["std"]:
cfgd["error_part"] += " 2>"
cfgd["error_part"] += " arq%(test)s.{0:s}".format(CONFIG["solution"]["stderr"]["extension"])
cfgd["suffix"] += "ERROR_SUFFIX: '.{0:s}'\n".format(CONFIG["solution"]["stderr"]["extension"])
cfgd["output_filter"] = ""
if CONFIG["solution"]["output"]["filter"] is not None and CONFIG["solution"]["output"]["filter"].lower() == "tokenize":
cfgd["output_filter"] = "TOKENIZER"
cfg = open(os.path.join(ds, "tarefa.cfg"), "w")
write_cfg(cfg, cfgd)
cfg.close()
print_ok()
print_check("Compactando")
shutil.make_archive(os.path.join(rdirr, str(CONFIG["task"]["id"])), 'zip', root_dir=d, base_dir=str(CONFIG["task"]["id"]))
print_ok()
if "shareable" in release:
print_header("Enunciado "+release["name"])
shareable = release["shareable"]
print_check("Criando diretório")
dshare = os.path.join(d, "enunciado_" + str(CONFIG["task"]["id"]))
os.mkdir(dshare)
print_ok()
print_check("Copiando testes")
dt = os.path.join(dshare, "testes")
os.mkdir(dt)
for t in ["open", "hidden"]:
if t+"_tests" in shareable and shareable[t+"_tests"]:
for filename in tests[t]:
args = list()
args.extend(CONFIG["solution"]["input"]["extensions"])
args.extend(CONFIG["solution"]["output"]["extensions"])
args.append(CONFIG["solution"]["stderr"]["extension"])
for ext in args:
shutil.copy(os.path.join(tmpdir, "tests", "arq{0:s}.{1:s}".format(filename, ext)), dt)
print_ok()
if "aux" in shareable and shareable["aux"]:
print_check("Copiando Aux")
saux = os.path.join(workdir, "aux")
daux = os.path.join(dshare, "aux")
os.mkdir(daux)
if os.path.isdir(saux):
for filename in os.listdir(saux):
shutil.copy(os.path.join(saux, filename), daux)
for lang, L in Langs.items():
if L.config and "public" in L.config:
for filename in L.config["public"]: