-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcgtest.php
2082 lines (2078 loc) · 92.6 KB
/
cgtest.php
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 php
<?php
/**
* CGTest v1.16.0 by Balint Toth [TBali]
* A multi-language offline batch test runner for CodinGame (or other) solo I/O puzzles.
*
* For usage, see:
* php cgtest.php --help
*
* Latest version: https://github.com/tbali0524/cgtest
*/
declare(strict_types=1);
namespace TBali\CGTest;
// Yes, this is a spaghetti code, I know... Don't look at it.
// I wanted a zero-dependency, single file script.
// So I skipped using OOP, and - as code repetition is low - even functions.
// And the code grew organically a bit larger than I originally planned.
// --------------------------------------------------------------------
// init counters, start global timer
$version = 'v1.16.0-dev';
$zeroLanguageStat = [
'countLanguages' => 0,
'countSkippedLanguages' => 0,
'countDirectories' => 0,
'countFiles' => 0,
'countPassedFiles' => 0,
'countRunOnlyFiles' => 0,
'countFailedFiles' => 0,
'countSkippedFiles' => 0,
'countLines' => 0,
'countTests' => 0,
'countRunOnlyTests' => 0,
'countPassedTests' => 0,
'countFailedTests' => 0,
'countSkippedTests' => 0,
'countDeletedFiles' => 0,
'startTime' => 0, // hrtime(true) in nanosec
'timeSpent' => 0, // in microsec
'timeBuilding' => 0, // in microsec
'timeRunning' => 0, // in microsec
];
$languageStats = [];
$languageStats['totals'] = $zeroLanguageStat;
$languageStats['totals']['startTime'] = intval(hrtime(true));
$languageStats['unique'] = $zeroLanguageStat;
$zeroPuzzleStat = [
'countFailedFiles' => 0,
'countRunOnlyFiles' => 0,
'countSkippedFiles' => 0,
'countTests' => 0,
'countRunOnlyTests' => 0,
'countSkippedTests' => 0,
'failedTests' => 0, //bitmap of failed tests (bit #0 = 1, if test #01 failed, etc.)
'runOnlyTests' => 0, //bitmap of runOnly tests
'skippedTests' => 0, //bitmap of skipped tests
];
$puzzleStats = [];
$directoryStats = [];
$slowTests = [];
// --------------------------------------------------------------------
// setup color mode based on terminal type
const ANSI_RED_INV = "\e[1;37;41m";
const ANSI_GREEN_INV = "\e[1;37;42m";
const ANSI_YELLOW_INV = "\e[1;37;43m";
const ANSI_GREEN = "\e[32m";
const ANSI_YELLOW = "\e[33m";
const ANSI_LIGHT_CYAN = "\e[96m";
const ANSI_RESET = "\e[0m";
$useAnsi = stream_isatty(STDOUT);
$ansiRedInv = $useAnsi ? ANSI_RED_INV : '';
$ansiGreenInv = $useAnsi ? ANSI_GREEN_INV : '';
$ansiYellowInv = $useAnsi ? ANSI_YELLOW_INV : '';
$ansiGreen = $useAnsi ? ANSI_GREEN : '';
$ansiYellow = $useAnsi ? ANSI_YELLOW : '';
$ansiLightCyan = $useAnsi ? ANSI_LIGHT_CYAN : '';
$ansiReset = $useAnsi ? ANSI_RESET : '';
$ansiVersion = $ansiGreen;
$ansiInfo = $ansiLightCyan;
$ansiWarn = $ansiYellow;
$errorTag = $ansiRedInv . '[ERROR]' . $ansiReset . ' ';
$warnTag = $ansiYellowInv . '[WARN]' . $ansiReset . ' ';
$passTag = $ansiGreenInv . '[PASS]' . $ansiReset . ' ';
$failTag = $ansiRedInv . '[FAIL]' . $ansiReset . ' ';
$infoTag = '[INFO] ';
// --------------------------------------------------------------------
// check php version
$author = 'by Balint Toth [TBali]';
$authorAnsi = 'by Balint Toth [' . $ansiInfo . 'TBali' . $ansiReset . ']';
$title = 'CGTest ' . $version . ' ' . $author . PHP_EOL;
$titleAnsi = 'CGTest ' . $ansiVersion . $version . $ansiReset . ' ' . $authorAnsi . PHP_EOL;
$titleDesc = 'A multi-language offline batch test runner for CodinGame (or other) solo I/O puzzles' . PHP_EOL;
const MIN_PHP_VERSION = '7.3.0';
if (version_compare(phpversion(), MIN_PHP_VERSION, '<')) {
echo $titleAnsi . $titleDesc . PHP_EOL;
echo $errorTag . 'Minimum required PHP version is ' . $ansiVersion . MIN_PHP_VERSION . $ansiReset
. '; you are on ' . $ansiWarn . phpversion() . $ansiReset . PHP_EOL . PHP_EOL;
// OS exit codes: 0 = OK, 1 = some tests failed, 2 = error (wrong CLI arguments, etc)
exit(2);
}
// --------------------------------------------------------------------
// default configuration
$defaultConfigFileName = '.cgtest.php';
$csprojExtension = '.csproj';
$vbprojExtension = '.vbproj';
$vbProjectName = 'vb_project';
$defaultConfig = [
'dry-run' => false,
'run-only' => false,
'ansi' => true,
'alt' => false,
'verbose' => true,
'stats' => false,
'lang-versions' => false,
'clean' => false,
'create' => '',
'test-case' => 'all',
'slowThreshold' => 5, // in seconds
'inputPath' => '.tests/input/',
'inputPattern' => '%p_i%t.txt',
'expectedPath' => '.tests/expected/',
'expectedPattern' => '%p_e%t.txt',
'outputPath' => '.tests/output/',
'outputPattern' => '%p_o%t_%l.txt',
'buildPath' => '.tests/temp/',
'debugLog' => '.tests/output/_debug_log.txt',
'buildLog' => '.tests/temp/_build_log.txt',
'languages' => ['php'],
'puzzles' => [],
'runOnlyPuzzles' => [],
// TODO: fix to work also under Windows
'bash' => [
'sourcePath' => 'bash/',
'sourceExtension' => '.sh',
'codinGameVersion' => 'GNU bash, version 5.1.16(1)',
'versionCommand' => 'bash --version',
'buildCommand' => (PHP_OS_FAMILY != 'Windows'
? 'chmod +x %s'
: ''
),
'runCommand' => '%s',
'cleanPatterns' => [],
],
'c' => [
'sourcePath' => 'c/',
'sourceExtension' => '.c',
'codinGameVersion' => 'gcc 11.2.0-20',
'versionCommand' => 'gcc --version',
// note: omitting -ldl -lcrypt from CG settings
'buildCommand' => 'gcc -std=c17 -o %b%p_%l.exe %s -lm -lpthread',
'runCommand' => '%b%p_%l.exe',
'altVersionCommand' => (PHP_OS_FAMILY != 'Windows'
? 'clang-18 --version'
: 'clang --version'
),
'altBuildCommand' => (PHP_OS_FAMILY != 'Windows'
? 'clang-18 -std=c17 -o %b%p_%l.exe %s -lm'
: 'clang -std=c17 -o %b%p_%l.exe %s'
),
'altRunCommand' => '%b%p_%l.exe',
'cleanPatterns' => ['%b%p_%l.exe'],
],
'c#' => [
'sourcePath' => 'c#/',
'sourceExtension' => '.cs',
'codinGameVersion' => '.NET 8.0.401',
'versionCommand' => 'dotnet --version',
'buildCommand' => 'dotnet publish %b%p' . $csprojExtension
. ' -o %b --nologo --use-current-runtime --sc -v:q',
'runCommand' => '%b%p' . (PHP_OS_FAMILY == 'Windows' ? '.exe' : ''),
'note' => '.NET SDK',
'cleanPatterns' => [
'%b%p' . (PHP_OS_FAMILY == 'Windows' ? '.exe' : ''),
'%b%p.pdb',
],
],
'c++' => [
'sourcePath' => 'c++/',
'sourceExtension' => '.cpp',
'codinGameVersion' => 'g++ 11.2.0-20',
'versionCommand' => 'g++ --version',
// note: omitting -ldl -lcrypt on Windows from CG settings
'buildCommand' => (PHP_OS_FAMILY != 'Windows'
? 'g++ -m64 -std=c++20 -x c++ -o %b%p_%l.exe %s -lm -lpthread -ldl -lcrypt'
: 'g++ -static-libgcc -static-libstdc++ -m64 -std=c++20 -x c++ -o %b%p_%l.exe %s -lm -lpthread'
),
'runCommand' => '%b%p_%l.exe',
'altVersionCommand' => (PHP_OS_FAMILY != 'Windows'
? 'clang++-18 --version'
: 'clang++ --version'
),
'altBuildCommand' => (PHP_OS_FAMILY != 'Windows'
? 'clang++-18 -m64 -std=c++20 -x c++ -o %b%p_%l.exe %s -lm'
: 'clang++ -m64 -std=c++20 -x c++ -o %b%p_%l.exe %s'
),
'altRunCommand' => '%b%p_%l.exe',
'cleanPatterns' => ['%b%p_%l.exe'],
],
'clojure' => [
'sourcePath' => 'clojure/',
'sourceExtension' => '.clj',
'codinGameVersion' => 'Clojure 1.11.1',
'versionCommand' => 'bb --version',
'buildCommand' => '',
'runCommand' => 'bb --classpath %b -m Solution -f %bSolution.clj',
'altVersionCommand' => 'clojure --version',
'altBuildCommand' => '',
'altRunCommand' => 'clojure -X Solution/main %bSolution.clj',
'cleanPatterns' => ['%bSolution.clj'],
],
'd' => [
'sourcePath' => 'd/',
'sourceExtension' => '.d',
'codinGameVersion' => 'DMD64 D Compiler v2.099.1',
'versionCommand' => 'dmd --version',
'buildCommand' => 'dmd -od=%b -of=%b%p_%l.exe %s',
'runCommand' => '%b%p_%l.exe',
'cleanPatterns' => [
'%b%p_%l.exe',
'%b%p_%l.obj',
'%b%p_%l.o',
],
],
'dart' => [
'sourcePath' => 'dart/',
'sourceExtension' => '.dart',
'codinGameVersion' => 'Dart SDK version: 2.16.2',
'versionCommand' => 'dart --version',
'buildCommand' => 'dart compile exe -o %b%p_%l.exe %s',
'runCommand' => '%b%p_%l.exe',
'cleanPatterns' => ['%b%p_%l.exe'],
],
'f#' => [
'sourcePath' => 'f#/',
'sourceExtension' => '.fsx',
'codinGameVersion' => '.NET 8.0.401',
'versionCommand' => 'dotnet --version',
'buildCommand' => '',
'runCommand' => 'dotnet fsi %s',
'note' => '.NET SDK',
'cleanPatterns' => [],
],
'go' => [
'sourcePath' => 'go/',
'sourceExtension' => '.go',
'codinGameVersion' => 'go version go1.18.1',
'versionCommand' => 'go version',
'buildCommand' => 'go build -o %b%p_%l.exe %s',
'runCommand' => '%b%p_%l.exe',
'cleanPatterns' => ['%b%p_%l.exe'],
],
'groovy' => [
'sourcePath' => 'groovy/',
'sourceExtension' => '.groovy',
'codinGameVersion' => 'Groovy Version: 3.0.8 JVM: 17.0.8',
'versionCommand' => 'groovy --version',
'buildCommand' => '',
'runCommand' => 'groovy %s',
'cleanPatterns' => [],
],
'haskell' => [
'sourcePath' => 'haskell/',
'sourceExtension' => '.hs',
'codinGameVersion' => 'The Glorious Glasgow Haskell Compilation System, version 8.4.3',
'versionCommand' => 'ghc --version',
'buildCommand' => 'ghc -outputdir %b -o %b%p_%l.exe %s',
'runCommand' => '%b%p_%l.exe',
'cleanPatterns' => [
'%b%p_%l.exe',
'%bMain.o',
'%bMain.hi',
],
],
'java' => [
'sourcePath' => 'java/',
'sourceExtension' => '.java',
'codinGameVersion' => 'openjdk 21.0.4',
'versionCommand' => 'java --version',
'buildCommand' => '',
'runCommand' => 'java %s',
'cleanPatterns' => [],
],
'javascript' => [
'sourcePath' => 'javascript/',
'sourceExtension' => '.js',
'codinGameVersion' => 'node.js v20.17.0',
'versionCommand' => 'node --version',
'buildCommand' => '',
'runCommand' => 'node -r polyfill.js %s',
'note' => 'Node.js',
'cleanPatterns' => [],
],
'kotlin' => [
'sourcePath' => 'kotlin/',
'sourceExtension' => '.kt',
'codinGameVersion' => 'kotlinc-jvm 1.7.10 (JRE 17.0.8+9)',
'versionCommand' => 'kotlinc -version',
'buildCommand' => 'kotlinc -include-runtime -d %b%p_%l.jar %s',
'runCommand' => 'java -jar %b%p_%l.jar',
'cleanPatterns' => ['%b%p_%l.jar'],
],
'lua' => [
'sourcePath' => 'lua/',
'sourceExtension' => '.lua',
'codinGameVersion' => 'Lua 5.4.4',
'versionCommand' => 'lua -v',
'buildCommand' => '',
'runCommand' => 'lua %s',
'cleanPatterns' => [],
],
// TODO: fix buildCommand, runCommand, cleanPatterns
'objective-c' => [
'sourcePath' => 'objective-c/',
'sourceExtension' => '.m',
'codinGameVersion' => 'clang version 13.0.1-3+b2',
'versionCommand' => 'gcc --version',
'buildCommand' => 'gcc -o %b%p_%l.exe -lobjc -lgnustep-base -F /usr/lib/GNUstep -I /usr/include/GNUstep'
. ' -fconstant-string-class=NSConstantString %s',
'runCommand' => '%b%p_%l.exe',
'cleanPatterns' => ['%b%p_%l.exe'],
],
// TODO: try out also in Windows:
'ocaml' => [
'sourcePath' => 'ocaml/',
'sourceExtension' => '.ml',
'codinGameVersion' => 'The OCaml native-code compiler, version 4.12.0',
'versionCommand' => 'ocamlopt -v',
'buildCommand' => 'ocamlopt %s -o %b%p_%l.exe',
'runCommand' => '%b%p_%l.exe',
// TODO: fix that ocamlopt creates interim files in source directory, --clean does not delete them
'cleanPatterns' => [
'%b%p_%l.cmi',
'%b%p_%l.cmx',
'%b%p_%l.o',
'%b%p_%l.exe',
],
],
'pascal' => [
'sourcePath' => 'pascal/',
'sourceExtension' => '.pas',
'codinGameVersion' => 'Free Pascal Compiler 3.2.2',
'versionCommand' => 'fpc -iW',
'buildCommand' => 'fpc -v0 -FE%b -o%p_%l.exe %s',
'runCommand' => '%b%p_%l.exe',
'note' => 'Free Pascal Compiler',
'cleanPatterns' => [
'%b%p_%l.exe',
'%b%p.o',
],
],
'perl' => [
'sourcePath' => 'perl/',
'sourceExtension' => '.pl',
'codinGameVersion' => 'perl 5, version 34, subversion 0 (v5.34.0)',
'versionCommand' => 'perl --version',
'buildCommand' => '',
'runCommand' => 'perl %s',
'cleanPatterns' => [],
],
'php' => [
'sourcePath' => 'php/',
'sourceExtension' => '.php',
'codinGameVersion' => 'PHP 7.3.9',
'versionCommand' => 'php --version',
'buildCommand' => '',
'runCommand' => 'php %s',
'altVersionCommand' => 'php --version',
'altBuildCommand' => '',
'altRunCommand' => 'php -d opcache.enable_cli=0 -d xdebug.mode=off %s',
'altNote' => 'JIT off',
'cleanPatterns' => [],
],
'python' => [
'sourcePath' => 'python/',
'sourceExtension' => '.py',
'codinGameVersion' => 'Python 3.11.5',
'versionCommand' => 'python --version',
'buildCommand' => '',
'runCommand' => 'python %s',
'altVersionCommand' => 'python3.12 --version',
'altBuildCommand' => '',
'altRunCommand' => 'python3.12 %s',
'cleanPatterns' => [],
],
'ruby' => [
'sourcePath' => 'ruby/',
'sourceExtension' => '.rb',
'codinGameVersion' => 'ruby 3.1.2p20',
'versionCommand' => 'ruby --version',
'buildCommand' => '',
'runCommand' => 'ruby %s',
'cleanPatterns' => [],
],
'rust' => [
'sourcePath' => 'rust/',
'sourceExtension' => '.rs',
'codinGameVersion' => 'rustc 1.70.0',
'versionCommand' => 'rustc --version',
'buildCommand' => 'rustc -C opt-level=3 --edition 2021 %s -o%b%p_%l.exe',
'runCommand' => '%b%p_%l.exe',
'cleanPatterns' => [
'%b%p_%l.exe',
'%b%p_%l.pdb',
],
],
'scala' => [
'sourcePath' => 'scala/',
'sourceExtension' => '.scala',
'codinGameVersion' => 'Scala code runner version 2.13.5',
'versionCommand' => 'scala --version',
'buildCommand' => '',
'runCommand' => 'scala -cp %b %s',
'cleanPatterns' => [],
],
// TODO: fix buildCommand, runCommand, cleanPatterns
'swift' => [
'sourcePath' => 'swift/',
'sourceExtension' => '.swift',
'codinGameVersion' => 'Swift version 5.3.3',
'versionCommand' => 'swift --version',
'buildCommand' => '',
'runCommand' => 'swift %s',
'cleanPatterns' => [],
],
'typescript' => [
'sourcePath' => 'typescript/',
'sourceExtension' => '.ts',
'codinGameVersion' => 'node.js v20.17.0; Typescript Compiler Version 5.6.2',
'versionCommand' => 'node --version',
// 'versionCommand' => 'tsc --version',
'buildCommand' => '',
'runCommand' => 'node -r polyfill.js %s',
'note' => 'Node.js',
'cleanPatterns' => [],
],
'vb.net' => [
'sourcePath' => 'vb.net/',
'sourceExtension' => '.vb',
'codinGameVersion' => '.NET 8.0.401',
'versionCommand' => 'dotnet --version',
'buildCommand' => 'dotnet publish %b' . $vbProjectName . $vbprojExtension
. ' -o %b --nologo --use-current-runtime --sc -v:q', // -v:q
'runCommand' => '%b' . $vbProjectName . (PHP_OS_FAMILY == 'Windows' ? '.exe' : ''),
'note' => '.NET SDK',
'cleanPatterns' => [
'%b' . $vbProjectName . (PHP_OS_FAMILY == 'Windows' ? '.exe' : ''),
'%b' . $vbProjectName . '.pdb',
],
],
// unsupported on CodinGame
// TODO: check
'cobol' => [
'sourcePath' => 'cobol/',
'sourceExtension' => '.cob',
'codinGameVersion' => 'cobc (GnuCOBOL) 3.1.2.0',
'versionCommand' => 'cobc --version',
'buildCommand' => 'cobc -x -o%b%p_%l.exe %s',
'runCommand' => '%b%p_%l.exe',
'cleanPatterns' => ['%b%p_%l.exe'],
],
'fortran' => [
'sourcePath' => 'fortran/',
'sourceExtension' => '.f90',
'codinGameVersion' => 'GNU Fortran 11.2.0-20',
'versionCommand' => 'gfortran --version',
'buildCommand' => 'gfortran -o%b%p_%l.exe %s',
'runCommand' => '%b%p_%l.exe',
'altVersionCommand' => 'gfortran-13 --version',
'altBuildCommand' => 'gfortran-13 -o%b%p_%l.exe %s',
'altRunCommand' => '%b%p_%l.exe',
'cleanPatterns' => ['%b%p_%l.exe'],
],
// TODO: check
'r' => [
'sourcePath' => 'r/',
'sourceExtension' => '.R',
'codinGameVersion' => 'R version 3.6.3',
'versionCommand' => 'Rscript --version',
'buildCommand' => '',
'runCommand' => 'Rscript %s',
'cleanPatterns' => [],
],
];
foreach ($defaultConfig['languages'] as $language) {
$defaultConfig[$language]['excludePuzzles'] = [];
$defaultConfig[$language]['includePuzzles'] = [];
$defaultConfig[$language]['runOnlyPuzzles'] = [];
foreach (['note', 'altVersionCommand', 'altBuildCommand', 'altRunCommand', 'altNote'] as $cfgToAdd) {
if (!isset($defaultConfig[$language][$cfgToAdd])) {
$defaultConfig[$language][$cfgToAdd] = '';
}
}
}
$booleanConfigKeys = ['dry-run', 'run-only', 'ansi', 'verbose', 'stats', 'lang-versions', 'clean', 'alt',
'show-defaults'];
$nonEmptyStringConfigKeys = ['inputPattern', 'expectedPattern', 'outputPattern'];
$optionalStringConfigKeys = ['inputPath', 'expectedPath', 'outputPath', 'buildPath', 'test-case', 'create'];
$arrayConfigKeys = ['languages', 'puzzles', 'runOnlyPuzzles'];
$languageStatsSpecKeys = ['totals', 'unique'];
$reservedConfigKeys = array_merge(
$booleanConfigKeys,
$nonEmptyStringConfigKeys,
$optionalStringConfigKeys,
$arrayConfigKeys,
$languageStatsSpecKeys,
);
$languageNonEmptyStringConfigKeys = ['sourceExtension', 'runCommand'];
$languageOptionalStringConfigKeys = ['sourcePath', 'codinGameVersion', 'versionCommand', 'buildCommand',
'note', 'altVersionCommand', 'altBuildCommand', 'altRunCommand', 'altNote'];
$languageArrayConfigKeys = ['excludePuzzles', 'includePuzzles', 'runOnlyPuzzles'];
$csprojTemplate =
"<Project Sdk=\"Microsoft.NET.Sdk\">
<ItemGroup>
<Compile Include = \"../../%s\"/>
</ItemGroup>
<PropertyGroup>
<OutputPath>bin/</OutputPath>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<PublishTrimmed>true</PublishTrimmed>
<PublishReadyToRun>true</PublishReadyToRun>
<PublishSingleFile>true</PublishSingleFile>
</PropertyGroup>
</Project>
";
$csDirectoryBuildPropsFilename = "Directory.Build.props";
$csDirectoryBuildPropsTemplate =
"<Project>
<PropertyGroup>
<BaseIntermediateOutputPath>obj/</BaseIntermediateOutputPath>
</PropertyGroup>
</Project>
";
$testIdxWidth = 2;
$noPathKey = '@';
// --------------------------------------------------------------------
// command-line arguments
$argumentConfig = [];
$argConfigFileName = '';
$errorMsg = '';
for ($i = 1; $i < $argc; ++$i) {
$arg = strtolower($argv[$i]);
if ($arg == '--version') {
$argumentConfig['version'] = true;
continue;
}
if ($arg == '--help') {
$argumentConfig['help'] = true;
continue;
}
if ($arg == '--show-defaults') {
$argumentConfig['show-defaults'] = true;
continue;
}
if ((substr($arg, 0, 9) == '--config=') and (strlen($arg) > 9)) {
if ($argConfigFileName != '') {
$errorMsg = $errorTag . 'Invalid arguments: only a single config file can be given.' . PHP_EOL . PHP_EOL;
continue;
}
$argConfigFileName = substr($arg, 9);
continue;
}
if ((substr($arg, 0, 7) == '--lang=') and (strlen($arg) > 7)) {
$langs = explode(',', substr($arg, 7));
if (!isset($argumentConfig['languages'])) {
$argumentConfig['languages'] = [];
}
foreach ($langs as $lang) {
if (array_search($lang, $reservedConfigKeys, true) !== false) {
$errorMsg = $errorTag . 'Invalid language name: ' . $ansiWarn . $lang . $ansiReset . PHP_EOL . PHP_EOL;
continue;
}
if (array_search($lang, $argumentConfig['languages'], true) === false) {
$argumentConfig['languages'][] = $lang;
}
}
continue;
}
if ((substr($arg, 0, 12) == '--test-case=') and (strlen($arg) > 12)) {
if (isset($argumentConfig['test-case'])) {
$errorMsg = $errorTag . 'Invalid arguments: ' . $ansiWarn . 'test-case' . $ansiReset
. ' can be given only once.' . PHP_EOL . PHP_EOL;
continue;
}
$argumentConfig['test-case'] = substr($arg, 12);
continue;
}
if ((substr($arg, 0, 9) == '--create=') and (strlen($arg) > 9)) {
if (isset($argumentConfig['create'])) {
$errorMsg = $errorTag . 'Invalid arguments: ' . $ansiWarn . 'create' . $ansiReset
. ' can be given only once.' . PHP_EOL . PHP_EOL;
continue;
}
$argumentConfig['create'] = substr($arg, 9);
continue;
}
if ($arg == '--no-ansi') {
if (isset($argumentConfig['ansi'])) {
$errorMsg = $errorTag . 'Invalid arguments: ' . $ansiWarn . '--ansi' . $ansiReset . ' or '
. $ansiWarn . '--no-ansi' . $ansiReset . ' can be given only once.' . PHP_EOL . PHP_EOL;
continue;
}
$argumentConfig['ansi'] = false;
continue;
}
if ($arg == '--quiet') {
if (isset($argumentConfig['verbose'])) {
$errorMsg = $errorTag . 'Invalid arguments: ' . $ansiWarn . '--verbose' . $ansiReset . ' or '
. $ansiWarn . '--quiet' . $ansiReset . ' can be given only once.' . PHP_EOL . PHP_EOL;
continue;
}
$argumentConfig['verbose'] = false;
continue;
}
if ((substr($arg, 0, 2) == '--') and in_array(substr($arg, 2), $booleanConfigKeys, true)) {
$argumentConfig[substr($arg, 2)] = true;
continue;
}
if ($arg[0] == '-') {
$errorMsg = $errorTag . 'Invalid argument: ' . $ansiWarn . $arg . $ansiReset . PHP_EOL . PHP_EOL;
continue;
}
if (!isset($argumentConfig['puzzles'])) {
$argumentConfig['puzzles'] = [];
}
$j = strlen($arg) - 1;
while (($j >= 0) and ($arg[$j] != '/') and ($arg[$j] != '\\')) {
--$j;
}
$path = substr($argv[$i], 0, $j + 1);
if ($path == '') {
$path = $noPathKey;
}
$puzzle = substr($argv[$i], $j + 1);
if ($puzzle == '') {
$errorMsg = $errorTag . 'Invalid puzzle name: ' . $ansiWarn . $argv[$i] . $ansiReset . PHP_EOL . PHP_EOL;
continue;
}
if (!isset($argumentConfig['puzzles'][$path])) {
$argumentConfig['puzzles'][$path] = [];
}
$argumentConfig['puzzles'][$path][] = $puzzle;
}
if ($argumentConfig['help'] ?? false) {
$errorMsg = 'Usage: ' . $ansiGreen . 'php cgtest.php' . $ansiInfo . ' [options] [puzzles]' . $ansiReset
. PHP_EOL . PHP_EOL
. 'Options:' . PHP_EOL
. $ansiInfo . ' --version ' . $ansiReset
. 'Display CGTest application version' . PHP_EOL
. $ansiInfo . ' --help ' . $ansiReset
. 'Display this help message' . PHP_EOL
. $ansiInfo . ' --dry-run ' . $ansiReset
. 'Do not run the tests; only show what test cases would run' . PHP_EOL
. $ansiInfo . ' --run-only ' . $ansiReset
. 'Run the tests, but do not evaluate results' . PHP_EOL
. $ansiInfo . ' --alt ' . $ansiReset
. 'Use alternative compiler, if such is defined in the config [e.g. for '
. $ansiInfo . 'c, c++, php' . $ansiReset . ']' . PHP_EOL
. $ansiInfo . ' --ansi ' . $ansiReset
. 'Use color output [' . $ansiInfo . 'default' . $ansiReset . ']' . PHP_EOL
. $ansiInfo . ' --no-ansi ' . $ansiReset
. 'Disable color output' . PHP_EOL
. $ansiInfo . ' --verbose ' . $ansiReset
. 'Increase the verbosity of messages: also show each passed tests [' . $ansiInfo . 'default' . $ansiReset
. ']' . PHP_EOL
. $ansiInfo . ' --quiet ' . $ansiReset
. 'Decrease the verbosity of messages: only show errors and warnings' . PHP_EOL
. $ansiInfo . ' --stats ' . $ansiReset
. 'Show per-language test stats' . PHP_EOL
. $ansiInfo . ' --lang-versions ' . $ansiReset
. 'Show versions for all configured programming languages' . PHP_EOL
. $ansiInfo . ' --show-defaults ' . $ansiReset
. 'Show default configuration settings (as json)' . PHP_EOL
. $ansiInfo . ' --clean ' . $ansiReset
. 'Delete temporary and output files of previous test run' . PHP_EOL
. $ansiInfo . ' --create=' . $ansiGreen . 'COUNT ' . $ansiReset
. 'Create COUNT number of empty test cases for the given puzzle' . PHP_EOL
. $ansiInfo . ' --config=' . $ansiGreen . 'FILENAME ' . $ansiReset
. 'Use configfile [default: ' . $ansiInfo . $defaultConfigFileName . $ansiReset . ']' . PHP_EOL
. $ansiInfo . ' --test-case=' . $ansiGreen . 'ID ' . $ansiReset
. 'Run only a specific test case [default: ' . $ansiInfo . 'all' . $ansiReset . ']' . PHP_EOL
. $ansiInfo . ' --lang=' . $ansiGreen . 'LANGUAGES ' . $ansiReset
. 'Run tests in these languages (comma separated list)' . PHP_EOL
. ' - default: ' . $ansiInfo . implode(',', $defaultConfig['languages'])
. $ansiReset . '; or the languages section in the config file' . PHP_EOL . PHP_EOL
. 'Puzzles: Space separated list of source filenames (without extension)' . PHP_EOL
. ' - if given, it overrides the list in the config file' . PHP_EOL
. ' - path can be given, but no wildcards allowed' . PHP_EOL . PHP_EOL;
} elseif ($argumentConfig['show-defaults'] ?? false) {
if ($errorMsg == '') {
$errorMsg = $infoTag . 'Default configuration settings (before applying any config file):' . PHP_EOL;
$errorMsg .= json_encode($defaultConfig, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . PHP_EOL . PHP_EOL;
} else {
$argumentConfig['show-defaults'] = false;
}
}
// --------------------------------------------------------------------
// setup color mode after cli arguments
if (isset($argumentConfig['ansi'])) {
if (!$argumentConfig['ansi'] and $useAnsi and ($errorMsg != '')) {
$errorMsg = str_replace($ansiRedInv, '', $errorMsg);
$errorMsg = str_replace($ansiGreenInv, '', $errorMsg);
$errorMsg = str_replace($ansiYellowInv, '', $errorMsg);
$errorMsg = str_replace($ansiGreen, '', $errorMsg);
$errorMsg = str_replace($ansiVersion, '', $errorMsg);
$errorMsg = str_replace($ansiInfo, '', $errorMsg);
$errorMsg = str_replace($ansiWarn, '', $errorMsg);
$errorMsg = str_replace($ansiReset, '', $errorMsg);
}
$useAnsi = $argumentConfig['ansi'];
$ansiRedInv = $useAnsi ? ANSI_RED_INV : '';
$ansiGreenInv = $useAnsi ? ANSI_GREEN_INV : '';
$ansiYellowInv = $useAnsi ? ANSI_YELLOW_INV : '';
$ansiGreen = $useAnsi ? ANSI_GREEN : '';
$ansiYellow = $useAnsi ? ANSI_YELLOW : '';
$ansiLightCyan = $useAnsi ? ANSI_LIGHT_CYAN : '';
$ansiReset = $useAnsi ? ANSI_RESET : '';
$ansiVersion = $ansiGreen;
$ansiInfo = $ansiLightCyan;
$ansiWarn = $ansiYellow;
$errorTag = $ansiRedInv . '[ERROR]' . $ansiReset . ' ';
$warnTag = $ansiYellowInv . '[WARN]' . $ansiReset . ' ';
$passTag = $ansiGreenInv . '[PASS]' . $ansiReset . ' ';
$failTag = $ansiRedInv . '[FAIL]' . $ansiReset . ' ';
}
if ($useAnsi) {
echo $titleAnsi . $titleDesc . PHP_EOL;
} else {
echo $title . $titleDesc . PHP_EOL;
}
if (($argumentConfig['version'] ?? false) and !($argumentConfig['help'] ?? false)) {
exit(0);
}
if ($errorMsg != '') {
echo $errorMsg;
if (($argumentConfig['help'] ?? false) or ($argumentConfig['show-defaults'] ?? false)) {
$exitCode = 0;
} else {
$exitCode = 2;
}
exit($exitCode);
}
// --------------------------------------------------------------------
// read config file
$configFromFile = [];
if ($argConfigFileName != '') {
if (!file_exists($argConfigFileName)) {
echo $errorTag . 'Cannot open config file: ' . $ansiWarn . $argConfigFileName . $ansiReset . PHP_EOL . PHP_EOL;
exit(2);
}
echo $infoTag . 'Using configuration file: ' . $ansiInfo . $argConfigFileName . $ansiReset . PHP_EOL;
$configFromFile = include_once $argConfigFileName;
} elseif (file_exists($defaultConfigFileName)) {
echo $infoTag . 'Using configuration file: ' . $ansiInfo . $defaultConfigFileName . $ansiReset . PHP_EOL;
$configFromFile = include_once $defaultConfigFileName;
}
// --------------------------------------------------------------------
// merge default config, config from config file and command-line arguments
$config = $defaultConfig;
foreach ($configFromFile as $configKey => $configValue) {
if (
!is_array($defaultConfig[$configKey])
or (in_array($configKey, $arrayConfigKeys, true) !== false)
) {
$config[$configKey] = $configValue;
continue;
}
if (!is_array($configValue)) {
continue;
}
foreach ($configValue as $languageConfigKey => $languageConfigValue) {
$config[$configKey][$languageConfigKey] = $languageConfigValue;
}
}
$config = array_merge($config, $argumentConfig);
if (isset($argumentConfig['puzzles']) and (count($argumentConfig['puzzles']) != 0)) {
$overrideSourcePath = false;
foreach ($config['puzzles'] as $path => $puzzleArray) {
if ($path != $noPathKey) {
$overrideSourcePath = true;
break;
}
}
if ($overrideSourcePath) {
foreach ($config['languages'] as $language) {
$config[$language]['sourcePath'] = '';
}
}
}
// --------------------------------------------------------------------
// setup color mode after config file
if (!isset($config['ansi']) or !is_bool($config['ansi'])) {
$config['ansi'] = false;
}
$useAnsi = $config['ansi'];
$ansiRedInv = $useAnsi ? ANSI_RED_INV : '';
$ansiGreenInv = $useAnsi ? ANSI_GREEN_INV : '';
$ansiYellowInv = $useAnsi ? ANSI_YELLOW_INV : '';
$ansiGreen = $useAnsi ? ANSI_GREEN : '';
$ansiYellow = $useAnsi ? ANSI_YELLOW : '';
$ansiLightCyan = $useAnsi ? ANSI_LIGHT_CYAN : '';
$ansiReset = $useAnsi ? ANSI_RESET : '';
$ansiVersion = $ansiGreen;
$ansiInfo = $ansiLightCyan;
$ansiWarn = $ansiYellow;
$errorTag = $ansiRedInv . '[ERROR]' . $ansiReset . ' ';
$warnTag = $ansiYellowInv . '[WARN]' . $ansiReset . ' ';
$passTag = $ansiGreenInv . '[PASS]' . $ansiReset . ' ';
$failTag = $ansiRedInv . '[FAIL]' . $ansiReset . ' ';
// --------------------------------------------------------------------
// check for configuration errors in global settings
foreach ($booleanConfigKeys as $configKey) {
if (!isset($config[$configKey])) {
$config[$configKey] = false;
continue;
}
if (!is_bool($config[$configKey])) {
echo $errorTag . 'Invalid configuration: setting must be a boolean value: '
. $ansiWarn . $configKey . $ansiReset . PHP_EOL . PHP_EOL;
exit(2);
}
}
foreach ($nonEmptyStringConfigKeys as $configKey) {
if (!isset($config[$configKey]) or !is_string($config[$configKey]) or ($config[$configKey] == '')) {
echo $errorTag . 'Invalid configuration: required setting must be a non-empty string value: '
. $ansiWarn . $configKey . $ansiReset . PHP_EOL . PHP_EOL;
exit(2);
}
}
foreach ($optionalStringConfigKeys as $configKey) {
if (!isset($config[$configKey])) {
$config[$configKey] = '';
continue;
}
if (!is_string($config[$configKey])) {
echo $errorTag . 'Invalid configuration: setting must be a string value: '
. $ansiWarn . $configKey . $ansiReset . PHP_EOL . PHP_EOL;
exit(2);
}
}
foreach ($arrayConfigKeys as $configKey) {
if (!isset($config[$configKey])) {
$config[$configKey] = [];
continue;
}
if (!is_array($config[$configKey])) {
echo $errorTag . 'Invalid configuration: setting must be an array: '
. $ansiWarn . $configKey . $ansiReset . PHP_EOL . PHP_EOL;
exit(2);
}
}
if ($config['test-case'] != 'all') {
$value = intval($config['test-case']);
if (($value <= 0) or ($value > 99)) {
echo $errorTag . 'Invalid arguments: ' . $ansiWarn . '--test-case' . $ansiReset
. " must be 'all' or between 01 and 99" . PHP_EOL . PHP_EOL;
exit(2);
}
}
if ($config['lang-versions']) {
if (
$config['dry-run']
or $config['run-only']
or $config['clean']
or ($config['create'] != '')
or ($config['test-case'] != 'all')
) {
echo $errorTag . 'Invalid arguments: if using ' . $ansiWarn . '--lang-versions' . $ansiReset
. ', cannot use --dry-run, --run-only, --clean, --create, --test-case' . PHP_EOL . PHP_EOL;
exit(2);
}
}
if ($config['clean']) {
if (
$config['dry-run']
or $config['run-only']
or $config['lang-versions']
or ($config['create'] != '')
) {
echo $errorTag . 'Invalid arguments: if using ' . $ansiWarn . '--clean' . $ansiReset
. ', cannot use --dry-run, --run-only, --lang-versions, --create' . PHP_EOL . PHP_EOL;
exit(2);
}
}
if ($config['dry-run'] and $config['run-only']) {
echo $errorTag . 'Invalid arguments: cannot use both ' . $ansiWarn . '--dry-run' . $ansiReset . ' and '
. $ansiWarn . '--run-only' . $ansiReset . PHP_EOL . PHP_EOL;
exit(2);
}
// --------------------------------------------------------------------
// --create
if ($config['create'] != '') {
$maxTests = intval($config['create']);
if (($maxTests <= 0) or ($maxTests > 99)) {
echo $errorTag . 'Invalid arguments: ' . $ansiWarn . '--create' . $ansiReset
. ' must be between 1 and 99' . PHP_EOL . PHP_EOL;
exit(2);
}
if (
$config['dry-run']
or $config['alt']
or $config['lang-versions']
or $config['clean']
or ($config['test-case'] != 'all')
) {
echo $errorTag . 'Invalid arguments: if using ' . $ansiWarn . '--create' . $ansiReset
. ', cannot use --dry-run, --alt, --lang-versions, --clean, --test-case' . PHP_EOL . PHP_EOL;
exit(2);
}
if (count($argumentConfig['puzzles'] ?? []) != 1) {
echo $errorTag . 'Invalid arguments: if using ' . $ansiWarn . '--create' . $ansiReset
. ', a single puzzle must be also given' . PHP_EOL . PHP_EOL;
exit(2);
}
$sourcePathKey = array_key_first($argumentConfig['puzzles']);
if (count($argumentConfig['puzzles'][$sourcePathKey]) != 1) {
echo $errorTag . 'Invalid arguments: if using ' . $ansiWarn . '--create' . $ansiReset
. ', a single puzzle must be also given' . PHP_EOL . PHP_EOL;
exit(2);
}
$puzzleName = $argumentConfig['puzzles'][$sourcePathKey][0];
$totalCreated = 0;
$totalSkipped = 0;
// run separately for input and expected test case files
for ($i = 0; $i < 2; ++$i) {
if ($config['run-only'] and ($i == 1)) {
continue;
}
$fullPattern = (
$i == 0
? $config['inputPath'] . $config['inputPattern']
: $config['expectedPath'] . $config['expectedPattern']
);
for ($idxTest = 1; $idxTest <= $maxTests; ++$idxTest) {
$stringIdxTest = str_pad(strval($idxTest), $testIdxWidth, '0', STR_PAD_LEFT);
$inputFullFileName = str_replace(
['%p', '%t'],
[$puzzleName, $stringIdxTest],
$fullPattern
);
if (file_exists($inputFullFileName)) {
echo $warnTag . 'Skipping existing file: ' . $ansiInfo . $inputFullFileName . $ansiReset . PHP_EOL;
++$totalSkipped;
continue;
}
$inputFile = @fopen($inputFullFileName, 'w');
if ($inputFile === false) {
echo $errorTag . 'Cannot create file: '
. $ansiWarn . $inputFullFileName . $ansiReset . PHP_EOL . PHP_EOL;
exit(2);
}
fclose($inputFile);
++$totalCreated;
if ($config['verbose']) {
echo $infoTag . 'Created file: ' . $ansiInfo . $inputFullFileName . $ansiReset . PHP_EOL;
}
}
}
echo PHP_EOL;
if ($totalCreated > 0) {
echo $infoTag . 'Created ' . $ansiInfo . $totalCreated . $ansiReset . ' empty input '
. (!$config['run-only'] ? 'and expected output ' : '')
. 'test case file' . ($totalCreated > 1 ? 's' : '') . '.' . PHP_EOL;
} else {
echo $infoTag . 'There was nothing to create.' . PHP_EOL;
}
echo PHP_EOL;
exit(0);
}
// --------------------------------------------------------------------
// delete / init log files
$noConfig = (($argumentConfig['puzzles'] ?? []) == []) && ($configFromFile == []);
$totalUnsuccessfulDeleteFiles = 0;
if (!$config['dry-run'] and !$noConfig and file_exists((string) $config['debugLog'])) {
$unlinkResult = unlink((string) $config['debugLog']);
if ($config['clean']) {
if (!$unlinkResult) {
++$totalUnsuccessfulDeleteFiles;
echo $warnTag . 'Could not delete file: ' . $ansiWarn . $config['debugLog'] . $ansiReset . PHP_EOL;
} else {
++$languageStats['totals']['countDeletedFiles'];
if ($config['verbose']) {
echo $infoTag . 'Deleted file: ' . $config['debugLog'] . PHP_EOL;
}
}
}
}
if (!$config['dry-run'] and !$noConfig and file_exists((string) $config['buildLog'])) {
$unlinkResult = unlink((string) $config['buildLog']);
if ($config['clean']) {
if (!$unlinkResult) {
++$totalUnsuccessfulDeleteFiles;
echo $warnTag . 'Could not delete file: ' . $ansiWarn . $config['buildLog'] . $ansiReset . PHP_EOL;
} else {
++$languageStats['totals']['countDeletedFiles'];
if ($config['verbose']) {