-
Notifications
You must be signed in to change notification settings - Fork 21
/
generate.py
executable file
·1348 lines (1211 loc) · 47.9 KB
/
generate.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
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/python3
import getopt
import hashlib
import os.path
import re
import shutil
import sys
from io import BufferedIOBase
from pathlib import Path
from threading import current_thread
from typing import Optional, Match, List, Dict, Pattern, Callable, Union, \
TextIO, IO
from zipfile import ZipFile, ZipInfo, is_zipfile
from modules import datafile, header
from modules.classes import GameEntry, Score, RegionData, \
GameEntryKeyGenerator, FileData, MultiThreadedProgressBar, IndexedThread, \
CustomJsonEncoder
from modules.header import Rule
from modules.utils import get_index, check_in_pattern_list, to_int_list, \
add_padding, get_or_default, available_columns, trim_to, is_valid
__version__ = '1.9.12-SNAPSHOT'
PROGRESSBAR: Optional[MultiThreadedProgressBar] = None
FOUND_PREFIX = 'Found: '
THREADS: int = 4
CHUNK_SIZE = 33554432 # 32 MiB
MAX_FILE_SIZE = 268435456 # 256 MiB
FILE_PREFIX = 'file:'
UNSELECTED = 10000
NOT_PRERELEASE = "Z"
AVOIDED_ROM_BASE = 1000
RULES: List[Rule] = []
LOG_FILE: Optional[TextIO] = None
JSON_ENCODER = CustomJsonEncoder()
DEBUG = False
COUNTRY_REGION_CORRELATION = [
# Language needs checking
RegionData('ASI', re.compile(r'(Asia)', re.IGNORECASE), ['zh']),
RegionData('ARG', re.compile(r'(Argentina)', re.IGNORECASE), ['es']),
RegionData('AUS', re.compile(r'(Australia)', re.IGNORECASE), ['en']),
RegionData('BRA', re.compile(r'(Brazil)', re.IGNORECASE), ['pt']),
# Language needs checking
RegionData('CAN', re.compile(r'(Canada)', re.IGNORECASE), ['en', 'fr']),
RegionData('CHN', re.compile(r'(China)', re.IGNORECASE),['zh']),
RegionData('DAN', re.compile(r'(Denmark)', re.IGNORECASE), ['da']),
RegionData('EUR', re.compile(r'((Europe)|(World))', re.IGNORECASE), ['en']),
RegionData('FRA', re.compile(r'(France)', re.IGNORECASE), ['fr']),
RegionData('FYN', re.compile(r'(Finland)', re.IGNORECASE), ['fi']),
RegionData('GER', re.compile(r'(Germany)', re.IGNORECASE), ['de']),
RegionData('GRE', re.compile(r'(Greece)', re.IGNORECASE), ['el']),
RegionData('ITA', re.compile(r'(Italy)', re.IGNORECASE), ['it']),
RegionData('JPN', re.compile(r'((Japan)|(World))', re.IGNORECASE), ['ja']),
RegionData('HK', re.compile(r'(Hong Kong)', re.IGNORECASE), ['zh']),
RegionData('HOL', re.compile(r'(Netherlands)', re.IGNORECASE), ['nl']),
RegionData('KOR', re.compile(r'(Korea)', re.IGNORECASE), ['ko']),
RegionData('MEX', re.compile(r'(Mexico)', re.IGNORECASE), ['es']),
RegionData('NOR', re.compile(r'(Norway)', re.IGNORECASE), ['no']),
RegionData('NZ', re.compile(r'(New Zealand)', re.IGNORECASE), ['en']),
RegionData('POR', re.compile(r'(Portugal)', re.IGNORECASE), ['pt']),
RegionData('RUS', re.compile(r'(Russia)', re.IGNORECASE), ['ru']),
RegionData('SPA', re.compile(r'(Spain)', re.IGNORECASE), ['es']),
# Language needs checking
RegionData('TAI', re.compile(r'(Taiwan)', re.IGNORECASE), ['zh']),
RegionData('SWE', re.compile(r'(Sweden)', re.IGNORECASE), ['sv']),
RegionData('UK', re.compile(r'(United Kingdom)', re.IGNORECASE), ['en']),
RegionData('USA', re.compile(r'((USA)|(World))', re.IGNORECASE), ['en']),
RegionData('UNK', re.compile(r'(Unknown)', re.IGNORECASE), ['en'])
]
SECTIONS_REGEX = re.compile(r'\(([^()]+)\)')
BIOS_REGEX = re.compile(re.escape('[BIOS]'), re.IGNORECASE)
PROGRAM_REGEX = re.compile(r'\((?:Test\s*)?Program\)', re.IGNORECASE)
ENHANCEMENT_CHIP_REGEX = re.compile(r'\(Enhancement\s*Chip\)', re.IGNORECASE)
UNL_REGEX = re.compile(re.escape('(Unl)'), re.IGNORECASE)
PIRATE_REGEX = re.compile(re.escape('(Pirate)'), re.IGNORECASE)
AFTERMARKET_REGEX = re.compile(re.escape('(Aftermarket)'), re.IGNORECASE)
HOMEBREW_REGEX = re.compile(re.escape('(Homebrew)'), re.IGNORECASE)
PROMO_REGEX = re.compile(re.escape('(Promo)'), re.IGNORECASE)
BETA_REGEX = re.compile(r'\(Beta(?:\s*([a-z0-9.]+))?\)', re.IGNORECASE)
PROTO_REGEX = re.compile(r'\(Proto(?:\s*([a-z0-9.]+))?\)', re.IGNORECASE)
SAMPLE_REGEX = re.compile(r'\(Sample(?:\s*([a-z0-9.]+))?\)', re.IGNORECASE)
DEMO_REGEX = re.compile(r'\(Demo(?:\s*([a-z0-9.]+))?\)', re.IGNORECASE)
REV_REGEX = re.compile(r'\(Rev\s*([a-z0-9.]+)\)', re.IGNORECASE)
VERSION_REGEX = re.compile(r'\(v\s*([a-z0-9.]+)\)', re.IGNORECASE)
LANGUAGES_REGEX = re.compile(r'\(([a-z]{2}(?:[,+][a-z]{2})*)\)', re.IGNORECASE)
BAD_REGEX = re.compile(re.escape('[b]'), re.IGNORECASE)
ZIP_REGEX = re.compile(r'\.zip$', re.IGNORECASE)
ALPHABETICAL_REGEX = re.compile(r'^[a-z]', re.IGNORECASE)
def parse_revision(name: str) -> str:
return get_or_default(REV_REGEX.search(name), '0')
def parse_version(name: str) -> str:
return get_or_default(VERSION_REGEX.search(name), '0')
def parse_prerelease(match: Optional[Match]) -> str:
return get_or_default(match, NOT_PRERELEASE)
def parse_region_data(name: str) -> List[RegionData]:
parsed = []
for section in SECTIONS_REGEX.finditer(name):
elements = [element.strip() for element in section.group(1).split(',')]
for element in elements:
for region_data in COUNTRY_REGION_CORRELATION:
if region_data.pattern \
and region_data.pattern.fullmatch(element):
parsed.append(region_data)
return parsed
def parse_languages(name: str) -> List[str]:
lang_matcher = LANGUAGES_REGEX.search(name)
languages = []
if lang_matcher:
for entry in lang_matcher.group(1).split(','):
for lang in entry.split('+'):
languages.append(lang.lower())
return languages
def get_region_data(code: str) -> Optional[RegionData]:
code = code.upper() if code else code
region_data = None
for r in COUNTRY_REGION_CORRELATION:
if r.code == code:
region_data = r
break
if not region_data:
# We don't know which region this is, but we should filter/classify it
log('WARNING: unrecognized region (%s)' % code)
region_data = RegionData(code, None, [])
COUNTRY_REGION_CORRELATION.append(region_data)
return region_data
def get_languages(region_data_list: List[RegionData]) -> List[str]:
languages = []
for region_data in region_data_list:
for language in region_data.languages:
if language not in languages:
languages.append(language)
return languages
def is_present(code: str, region_data: List[RegionData]) -> bool:
for r in region_data:
if r.code == code:
return True
return False
def validate_dat(file: Path, use_hashes: bool) -> None:
root = datafile.parse(file, silence=True)
has_cloneof = False
lacks_sha1 = False
offending_entry = ''
for game in root.game:
if game.cloneof:
has_cloneof = True
break
for game in root.game:
for game_rom in game.rom:
if not game_rom.sha1:
lacks_sha1 = True
offending_entry = game.name
break
if use_hashes and lacks_sha1:
sys.exit(
'ERROR: Cannot use hash information because DAT lacks SHA1 digests '
'for [%s].' % offending_entry)
if not has_cloneof:
print('This DAT *seems* to be a Standard DAT', file=sys.stderr)
print(
'A Parent/Clone XML DAT is required to generate a 1G1R ROM set',
file=sys.stderr)
if use_hashes:
print(
'If you are using this to rename files based on their hashes, '
'a Standard DAT is enough',
file=sys.stderr)
print('Do you want to continue anyway? (y/n)', file=sys.stderr)
answer = input()
if answer.strip() not in ('y', 'Y'):
sys.exit()
def parse_games(
file: Path,
filter_bios: bool,
filter_program: bool,
filter_enhancement_chip: bool,
filter_pirate: bool,
filter_aftermarket: bool,
filter_homebrew: bool,
filter_promo: bool,
filter_unlicensed: bool,
filter_proto: bool,
filter_beta: bool,
filter_demo: bool,
filter_sample: bool,
exclude: List[Pattern]) -> Dict[str, List[GameEntry]]:
games = {}
root = datafile.parse(file, silence=True)
for input_index in range(0, len(root.game)):
game = root.game[input_index]
beta_match = BETA_REGEX.search(game.name)
demo_match = DEMO_REGEX.search(game.name)
sample_match = SAMPLE_REGEX.search(game.name)
proto_match = PROTO_REGEX.search(game.name)
if filter_bios and BIOS_REGEX.search(game.name):
continue
if filter_unlicensed and UNL_REGEX.search(game.name):
continue
if filter_pirate and PIRATE_REGEX.search(game.name):
continue
if filter_aftermarket and AFTERMARKET_REGEX.search(game.name):
continue
if filter_homebrew and HOMEBREW_REGEX.search(game.name):
continue
if filter_promo and PROMO_REGEX.search(game.name):
continue
if filter_program and PROGRAM_REGEX.search(game.name):
continue
if filter_enhancement_chip and ENHANCEMENT_CHIP_REGEX.search(game.name):
continue
if filter_beta and beta_match:
continue
if filter_demo and demo_match:
continue
if filter_sample and sample_match:
continue
if filter_proto and proto_match:
continue
if check_in_pattern_list(game.name, exclude):
continue
is_parent = not game.cloneof
is_bad = bool(BAD_REGEX.search(game.name))
beta = parse_prerelease(beta_match)
demo = parse_prerelease(demo_match)
sample = parse_prerelease(sample_match)
proto = parse_prerelease(proto_match)
is_prerelease = bool(
beta_match
or demo_match
or sample_match
or proto_match)
revision = parse_revision(game.name)
version = parse_version(game.name)
region_data = parse_region_data(game.name)
for release in game.release:
if release.region and not is_present(release.region, region_data):
region_data.append(get_region_data(release.region))
languages = parse_languages(game.name)
if not languages:
languages = get_languages(region_data)
parent_name = game.cloneof if game.cloneof else game.name
region_codes = [rd.code for rd in region_data]
game_entries: List[GameEntry] = []
for region in region_codes:
game_entries.append(
GameEntry(
is_bad,
is_prerelease,
region,
languages,
input_index,
revision,
version,
sample,
demo,
beta,
proto,
is_parent,
game.name,
game.rom if game.rom else []))
if game_entries:
if parent_name not in games:
games[parent_name] = game_entries
else:
games[parent_name].extend(game_entries)
else:
log('WARNING [%s]: no recognizable regions found' % game.name)
if not game.rom:
log('WARNING [%s]: no ROMs found in the DAT file' % game.name)
return games
def pad_values(
games: List[GameEntry],
get_function: Callable[[GameEntry], str],
set_function: Callable[[GameEntry, str], None]) -> None:
padded = add_padding([get_function(g) for g in games])
for i in range(0, len(padded)):
set_function(games[i], padded[i])
def language_value(
languages: List[str],
weight: int,
selected_languages: List[str]) -> int:
return sum([
(get_index(selected_languages, lang, -1) + 1) * weight * -1
for lang in languages])
def index_files(
input_dir: Path,
dat_file: Path) -> Dict[str, Optional[Path]]:
result: Dict[str, Optional[Path]] = {}
also_check_archive: bool = False
root = datafile.parse(dat_file, silence=True)
global RULES
if not RULES:
RULES = get_header_rules(root)
for game in root.game:
for rom_entry in game.rom:
result[rom_entry.sha1.lower()] = None
also_check_archive |= bool(ZIP_REGEX.search(rom_entry.name))
print('Scanning directory: %s\033[K' % input_dir, file=sys.stderr)
files_data = []
for full_path in input_dir.rglob('*'):
if not full_path.is_file():
continue
try:
print(
'%s%s\033[K' % (
FOUND_PREFIX,
trim_to(
full_path.relative_to(input_dir),
available_columns(FOUND_PREFIX) - 2)),
end='\r',
file=sys.stderr)
file_size = full_path.stat().st_size
files_data.append(FileData(file_size, full_path))
except OSError as e:
print(
'Error while reading file: %s\033[K' % e,
file=sys.stderr)
files_data.sort(key=FileData.get_size, reverse=True)
print('%s%i files\033[K' % (FOUND_PREFIX, len(files_data)), file=sys.stderr)
if files_data:
global PROGRESSBAR
PROGRESSBAR = MultiThreadedProgressBar(
len(files_data),
THREADS,
prefix='Calculating hashes')
PROGRESSBAR.init()
def process_thread_with_progress(
shared_files_data: List[FileData],
shared_result_data: List[Dict[str, Path]]) -> None:
curr_thread = current_thread()
if not isinstance(curr_thread, IndexedThread):
sys.exit('Bad thread type. Expected %s' % IndexedThread)
while True:
try:
next_file = shared_files_data.pop(0)
PROGRESSBAR.print_thread(
curr_thread.index,
next_file.path.relative_to(input_dir))
shared_result_data.append(process_file(
next_file,
also_check_archive))
PROGRESSBAR.print_bar()
except IndexError:
PROGRESSBAR.print_thread(curr_thread.index, "DONE")
break
threads = []
intermediate_results = []
for i in range(0, THREADS):
t = IndexedThread(
index=i,
target=process_thread_with_progress,
args=[files_data, intermediate_results],
daemon=True)
t.start()
threads.append(t)
for t in threads:
t.join()
print('\n', file=sys.stderr)
for intermediate_result in intermediate_results:
for key, value in intermediate_result.items():
if key in result and not \
(result[key] and is_zipfile(result[key])):
result[key] = value
return result
def get_header_rules(root: datafile) -> List[Rule]:
if root.header.clrmamepro:
if root.header.clrmamepro.header:
header_file = Path('headers', root.header.clrmamepro.header)
if header_file.is_file():
return header.parse_rules(header_file)
else:
log(
'WARNING: could not find header file %s. '
'This may cause hashes to be calculated wrong'
% header_file)
return []
# noinspection PyBroadException
def process_file(
file_data: FileData,
also_check_archive: bool) -> Dict[str, Path]:
full_path = file_data.path
result: Dict[str, Path] = {}
is_zip = is_zipfile(full_path)
if is_zip:
try:
with ZipFile(full_path) as compressed_file:
infos: List[ZipInfo] = compressed_file.infolist()
for file_info in infos:
if file_info.is_dir():
continue
file_size = file_info.file_size
with compressed_file.open(file_info) as internal_file:
digest = compute_hash(file_size, internal_file)
result[digest] = full_path
if DEBUG:
log("DEBUG: Scan result for file [%s]: %s"
% (
"%s:%s" % (full_path, file_info.filename),
digest))
except Exception as e:
print(
'Error while reading file [%s]: %s\033[K' % (full_path, e),
file=sys.stderr)
if not is_zip or also_check_archive:
try:
file_size: int = full_path.stat().st_size
with full_path.open('rb') as uncompressed_file:
digest = compute_hash(file_size, uncompressed_file)
if DEBUG:
log("DEBUG: Scan result for file [%s]: %s"
% (full_path, digest))
if digest not in result or \
(result[digest] and is_zipfile(result[digest])):
result[digest] = full_path
except Exception as e:
print(
'Error while reading file: %s\033[K' % e,
file=sys.stderr)
return result
def compute_hash(
file_size: int,
internal_file: Union[BufferedIOBase, IO[bytes]]) -> str:
hasher = hashlib.sha1()
if RULES and file_size <= MAX_FILE_SIZE:
file_bytes = internal_file.read()
for rule in RULES:
if rule.test(file_bytes):
file_bytes = rule.apply(file_bytes)
hasher.update(file_bytes)
else:
while True:
chunk = internal_file.read(CHUNK_SIZE)
if not chunk:
break
hasher.update(chunk)
return hasher.hexdigest().lower()
def main(argv: List[str]):
try:
opts, args = getopt.getopt(argv, 'hd:r:e:i:Vo:l:w:v', [
'help',
'dat=',
'regions=',
'no-bios',
'no-program',
'no-enhancement-chip',
'no-beta',
'no-demo',
'no-sample',
'no-proto',
'no-pirate',
'no-aftermarket',
'no-homebrew',
'no-promo',
'no-all',
'no-unlicensed',
'all-regions',
'early-revisions',
'early-versions',
'input-order',
'extension=',
'no-scan',
'input-dir=',
'prefer=',
'avoid=',
'exclude=',
'exclude-after=',
'separator=',
'ignore-case',
'regex',
'verbose',
'output-dir=',
'languages=',
'prioritize-languages',
'language-weight=',
'prefer-parents',
'prefer-prereleases',
'all-regions-with-lang',
'debug',
'move',
'symlink',
'relative',
'chunk-size=',
'threads=',
'header-file=',
'max-file-size=',
'version',
'only-selected-lang',
'group-by-first-letter'
])
except getopt.GetoptError as e:
sys.exit(help_msg(e))
dat_file: Optional[Path] = None
filter_bios = False
filter_program = False
filter_enhancement_chip = False
filter_unlicensed = False
filter_pirate = False
filter_aftermarket = False
filter_homebrew = False
filter_promo = False
filter_proto = False
filter_beta = False
filter_demo = False
filter_sample = False
all_regions = False
all_regions_with_lang = False
only_selected_lang = False
revision_asc = False
version_asc = False
verbose = False
no_scan = False
input_order = False
selected_regions: List[str] = []
file_extension = ""
input_dir: Optional[Path] = None
prefer_str = ""
exclude_str = ""
avoid_str = ""
exclude_after_str = ""
sep = ','
ignore_case = False
regex = False
output_dir: Optional[Path] = None
selected_languages: List[str] = []
prioritize_languages = False
prefer_parents = False
prefer_prereleases = False
group_by_first_letter = False
language_weight = 3
move = False
symlink = False
relative = False
global THREADS
global RULES
global MAX_FILE_SIZE
global CHUNK_SIZE
global DEBUG
for opt, arg in opts:
if opt in ('-h', '--help'):
print(help_msg())
sys.exit()
if opt in ('-v', '--version'):
print('1G1R ROM set generator v%s' % __version__)
sys.exit()
if opt in ('-r', '--regions'):
selected_regions = [x.strip().upper() for x in arg.split(',')
if is_valid(x)]
if opt in ('-l', '--languages'):
selected_languages = [x.strip().lower()
for x in reversed(arg.split(','))
if is_valid(x)]
if opt in ('-w', '--language-weight'):
try:
language_weight = int(arg.strip())
if language_weight <= 0:
sys.exit(help_msg(
'language-weight must be a positive integer'))
except ValueError:
sys.exit(help_msg('invalid value for language-weight'))
prioritize_languages |= opt == '--prioritize-languages'
filter_bios |= opt in ('--no-bios', '--no-all')
filter_program |= opt in ('--no-program', '--no-all')
filter_enhancement_chip |= opt in ('--no-enhancement-chip', '--no-all')
filter_proto |= opt in ('--no-proto', '--no-all')
filter_beta |= opt in ('--no-beta', '--no-all')
filter_demo |= opt in ('--no-demo', '--no-all')
filter_sample |= opt in ('--no-sample', '--no-all')
filter_pirate |= opt in ('--no-pirate', '--no-all')
filter_aftermarket |= opt in ('--no-aftermarket', '--no-all')
filter_homebrew |= opt in ('--no-homebrew', '--no-all')
filter_promo |= opt in ('--no-promo', '--no-all')
filter_unlicensed |= opt == '--no-unlicensed'
all_regions |= opt == '--all-regions'
all_regions_with_lang |= opt == '--all-regions-with-lang'
only_selected_lang |= opt == '--only-selected-lang'
revision_asc |= opt == '--early-revisions'
version_asc |= opt == '--early-versions'
DEBUG |= opt == '--debug'
verbose |= DEBUG or opt in ('-V', '--verbose')
ignore_case |= opt == '--ignore-case'
regex |= opt == '--regex'
if opt == '--separator':
sep = arg.strip()
input_order |= opt == '--input-order'
prefer_parents |= opt == '--prefer-parents'
prefer_prereleases |= opt == '--prefer-prereleases'
if opt in ('-d', '--dat'):
dat_file = Path(arg.strip()).expanduser()
if not dat_file.is_file():
sys.exit(help_msg('invalid DAT file: %s' % dat_file))
if opt in ('-e', '--extension'):
file_extension = arg.strip().lstrip('.')
no_scan |= opt == '--no-scan'
if opt == '--prefer':
prefer_str = arg
if opt == '--avoid':
avoid_str = arg
if opt == '--exclude':
exclude_str = arg
if opt == '--exclude-after':
exclude_after_str = arg
if opt in ('-i', '--input-dir'):
input_dir = Path(arg.strip()).expanduser()
if not input_dir.is_dir():
sys.exit(help_msg('invalid input directory: %s' % input_dir))
if opt in ('-o', '--output-dir'):
output_dir = Path(arg.strip()).expanduser()
if not output_dir.is_dir():
try:
output_dir.mkdir(parents=True, exist_ok=True)
except OSError:
sys.exit(help_msg('invalid output DIR: %s' % output_dir))
move |= opt == '--move'
symlink |= opt == '--symlink'
relative |= opt == '--relative'
if opt == '--chunk-size':
CHUNK_SIZE = int(arg)
if opt == '--threads':
THREADS = int(arg)
if opt == '--header-file':
header_file = Path(arg.strip()).expanduser()
if not header_file.is_file():
sys.exit(help_msg('invalid header file: %s' % header_file))
RULES = header.parse_rules(header_file)
if opt == '--max-file-size':
MAX_FILE_SIZE = int(arg)
group_by_first_letter |= opt == '--group-by-first-letter'
if not no_scan and not input_dir:
print(
'No input directory was provided. File scanning is disabled!',
file=sys.stderr)
print('Do you want to continue anyway? (y/n)', file=sys.stderr)
answer = input()
if answer.strip() not in ('y', 'Y'):
sys.exit()
use_hashes = bool(not no_scan and input_dir)
if file_extension and use_hashes:
sys.exit(help_msg('extensions cannot be used when scanning'))
if not dat_file:
sys.exit(help_msg('DAT file is required'))
if not selected_regions:
sys.exit(help_msg('invalid region selection'))
if (revision_asc or version_asc) and input_order:
sys.exit(help_msg(
'early-revisions and early-versions are mutually exclusive '
'with input-order'))
if (revision_asc or version_asc) and prefer_parents:
sys.exit(help_msg(
'early-revisions and early-versions are mutually exclusive '
'with prefer-parents'))
if prefer_parents and input_order:
sys.exit(help_msg(
'prefer-parents is mutually exclusive with input-order'))
if output_dir and not input_dir:
sys.exit(help_msg('output-dir requires an input-dir'))
if ignore_case and not prefer_str and not avoid_str and not exclude_str:
sys.exit(help_msg(
"ignore-case only works if there's a prefer, "
"avoid or exclude list too"))
if regex and not prefer_str and not avoid_str and not exclude_str:
sys.exit(help_msg(
"regex only works if there's a prefer, avoid or exclude list too"))
if all_regions and all_regions_with_lang:
sys.exit(help_msg(
'all-regions is mutually exclusive with all-regions-with-lang'))
if group_by_first_letter and not output_dir:
sys.exit(help_msg('group-by-first-letter requires an output directory'))
if THREADS <= 0:
sys.exit(help_msg('Number of threads should be > 0'))
if MAX_FILE_SIZE <= 0:
sys.exit(help_msg('Maximum file size should be > 0'))
try:
prefer = parse_list(prefer_str, ignore_case, regex, sep)
except (re.error, OSError) as e:
sys.exit(help_msg('invalid prefer list: %s' % e))
try:
avoid = parse_list(avoid_str, ignore_case, regex, sep)
except (re.error, OSError) as e:
sys.exit(help_msg('invalid avoid list: %s' % e))
try:
exclude = parse_list(exclude_str, ignore_case, regex, sep)
except (re.error, OSError) as e:
sys.exit(help_msg('invalid exclude list: %s' % e))
try:
exclude_after = parse_list(exclude_after_str, ignore_case, regex, sep)
except (re.error, OSError) as e:
sys.exit(help_msg('invalid exclude-after list: %s' % e))
validate_dat(dat_file, use_hashes)
hash_index: Dict[str, Optional[Path]] = {}
if use_hashes and input_dir:
hash_index = index_files(input_dir, dat_file)
if DEBUG:
log('DEBUG: Scanned files: %s' % JSON_ENCODER.encode(hash_index))
parsed_games = parse_games(
dat_file,
filter_bios,
filter_program,
filter_enhancement_chip,
filter_pirate,
filter_aftermarket,
filter_homebrew,
filter_promo,
filter_unlicensed,
filter_proto,
filter_beta,
filter_demo,
filter_sample,
exclude)
if verbose:
region_text = 'Best region match'
lang_text = 'Best language match'
parents_text = 'Parent ROMs'
index_text = 'Input order'
filters = [
(filter_bios, 'BIOSes'),
(filter_program, 'Programs'),
(filter_enhancement_chip, 'Enhancement Chips'),
(filter_proto, 'Prototypes'),
(filter_beta, 'Betas'),
(filter_demo, 'Demos'),
(filter_sample, 'Samples'),
(filter_unlicensed, 'Unlicensed ROMs'),
(filter_pirate, 'Pirate ROMs'),
(filter_aftermarket, 'Aftermarket ROMs'),
(filter_homebrew, 'Homebrew ROMs'),
(filter_promo, 'Promo ROMs'),
(only_selected_lang, 'ROMs not matching selected languages'),
(bool(exclude_str), 'Excluded ROMs by name'),
(bool(exclude_after_str), 'Excluded ROMs by name (after selection)')
]
active_filters = [f[1] for f in filters if f[0]]
if active_filters:
print(
'Filtering out:\n%s'
% "".join(
['\t%d. %s\n' % (i[0] + 1, i[1])
for i in enumerate(active_filters)]),
file=sys.stderr)
print(
'Sorting with the following criteria:\n'
'\t1. Good dumps\n'
'\t2. %s\n'
'\t3. Non-avoided items%s\n'
'\t4. %s\n'
'\t5. %s\n'
'\t6. %s\n'
'\t7. %s\n'
'\t8. Preferred items%s\n'
'\t9. %s revision\n'
'\t10. %s version\n'
'\t11. Latest sample\n'
'\t12. Latest demo\n'
'\t13. Latest beta\n'
'\t14. Latest prototype\n'
'\t15. Most languages supported\n'
'\t16. Parent ROMs\n' %
('Prelease ROMs' if prefer_prereleases else 'Released ROMs',
'' if avoid else ' (Ignored)',
lang_text if prioritize_languages else region_text,
region_text if prioritize_languages else lang_text,
parents_text if prefer_parents else parents_text + ' (Ignored)',
index_text if input_order else index_text + ' (Ignored)',
'' if prefer else ' (Ignored)',
'Earliest' if revision_asc else 'Latest',
'Earliest' if version_asc else 'Latest'),
file=sys.stderr)
key_generator = GameEntryKeyGenerator(
prioritize_languages,
prefer_prereleases,
prefer_parents,
input_order,
prefer,
avoid)
for key in parsed_games:
games = parsed_games[key]
pad_values(
games,
GameEntry.get_version,
GameEntry.set_version)
pad_values(
games,
GameEntry.get_revision,
GameEntry.set_revision)
pad_values(
games,
GameEntry.get_sample,
GameEntry.set_sample)
pad_values(
games,
GameEntry.get_demo,
GameEntry.set_demo)
pad_values(
games,
GameEntry.get_beta,
GameEntry.set_beta)
pad_values(
games,
GameEntry.get_proto,
GameEntry.set_proto)
set_scores(
games,
selected_regions,
selected_languages,
language_weight,
revision_asc,
version_asc)
games.sort(key=key_generator.generate)
if verbose:
log(
'INFO: Candidate order for [%s]: %s'
% (key, [g.name for g in games]))
printed_items: List[str] = []
def include_candidate(x: GameEntry) -> bool:
if only_selected_lang and x.score.languages >= 0:
return False
if all_regions_with_lang and x.score.languages < 0:
return True
if all_regions:
return True
return x.score.region != UNSELECTED
for game in sorted(parsed_games.keys()):
entries = parsed_games[game]
if DEBUG:
log(
'DEBUG: Candidates for game [%s] before filtering: %s'
% (game, JSON_ENCODER.encode(entries)))
if not all_regions:
entries = [x for x in entries if include_candidate(x)]
if DEBUG:
log(
'DEBUG: Candidates for game [%s] after filtering: %s'
% (game, JSON_ENCODER.encode(entries)))
size = len(entries)
curr_out_dir = output_dir
for i in range(0, size):
entry = entries[i]
if check_in_pattern_list(entry.name, exclude_after):
break
if output_dir and group_by_first_letter:
curr_out_dir = output_dir / \
(entry.name[0].lower()
if ALPHABETICAL_REGEX.search(entry.name)
else '#')
if use_hashes:
copied_files = set()
num_roms = len(entry.roms)
for entry_rom in entry.roms:
digest = entry_rom.sha1.lower()
rom_input_path = hash_index[digest]
if rom_input_path:
is_zip = is_zipfile(rom_input_path)
file = rom_input_path.relative_to(input_dir)
if not curr_out_dir:
if rom_input_path not in copied_files:
printed_items.append(str(file))
copied_files.add(rom_input_path)
elif rom_input_path not in copied_files:
if not is_zip and num_roms > 1:
rom_output_dir = curr_out_dir / entry.name
else:
rom_output_dir = curr_out_dir
rom_output_dir.mkdir(
parents=True,
exist_ok=True)
if is_zip:
zip_name = add_extension(entry.name, 'zip')
rom_output_path = rom_output_dir / zip_name
else:
rom_output_path = \
rom_output_dir / entry_rom.name
transfer_file(
rom_input_path,
rom_output_path,
move,
symlink,
relative)
copied_files.add(rom_input_path)
else:
log(
'WARNING: ROM file [%s] for candidate [%s] '
'not found' % (entry_rom.name, entry.name))
if copied_files:
break
else:
log(
'WARNING: candidate [%s] not found, trying next one'
% entry.name)
if i == size - 1:
log(
'WARNING: no eligible candidates for [%s] '
'have been found!' % game)
elif input_dir:
file_name = add_extension(entry.name, file_extension)
full_path = input_dir / file_name
if full_path.is_file():
if curr_out_dir:
curr_out_dir.mkdir(parents=True, exist_ok=True)
if symlink:
curr_out_dir = curr_out_dir / file_name
transfer_file(full_path, curr_out_dir, move, symlink, relative)
else:
printed_items.append(file_name)
break
elif full_path.is_dir():
for entry_rom in entry.roms:
rom_input_path = full_path / entry_rom.name
if rom_input_path.is_file():
if curr_out_dir:
rom_output_dir = curr_out_dir / file_name
rom_output_dir.mkdir(
parents=True,
exist_ok=True)
transfer_file(
rom_input_path,
rom_output_dir,
move,
symlink,
relative)
shutil.copystat(
str(full_path),
str(rom_output_dir))
else:
printed_items.append(
file_name + '/' + entry_rom.name)
else:
log(
'WARNING: ROM file [%s] for candidate [%s] '
'not found' % (entry_rom.name, file_name))
break
else:
log(
'WARNING: candidate [%s] not found, trying next one'
% file_name)
if i == size - 1:
log(
'WARNING: no eligible candidates for [%s] '