forked from ArchipelagoMW/Archipelago
- Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathsettings.py
More file actions
Latest commit
903 lines (770 loc) · 34.7 KB
/
Copy pathsettings.py
File metadata and controls
903 lines (770 loc) · 34.7 KB
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
"""
Application settings / host.yaml interface using type hints.
This is different from player options.
"""
importos
importos.path
importshutil
importsys
importtypes
importtyping
importwarnings
fromcollections.abcimportIterator, Sequence
fromenumimportIntEnum
fromthreadingimportLock
fromtypingimportcast, Any, BinaryIO, ClassVar, TextIO, TypeVar, Union
__all__= [
"get_settings", "fmt_doc", "no_gui",
"Group", "Bool", "Path", "UserFilePath", "UserFolderPath", "LocalFilePath", "LocalFolderPath",
"OptionalUserFilePath", "OptionalUserFolderPath", "OptionalLocalFilePath", "OptionalLocalFolderPath",
"GeneralOptions", "ServerOptions", "GeneratorOptions", "SNIOptions", "Settings"
]
no_gui=False
skip_autosave=False
_world_settings_name_cache: dict[str, str] = {} # TODO: cache on disk and update when worlds change
_world_settings_name_cache_updated=False
_lock=Lock()
def_update_cache() ->None:
"""Load all worlds and update world_settings_name_cache"""
global_world_settings_name_cache_updated
if_world_settings_name_cache_updated:
return
try:
fromworlds.AutoWorldimportAutoWorldRegister
forworldinAutoWorldRegister.world_types.values():
annotation=world.__annotations__.get("settings", None)
ifannotationisNoneorannotation=="ClassVar[Optional['Group']]":
continue
_world_settings_name_cache[world.settings_key] =f"{world.__module__}.{world.__name__}"
finally:
_world_settings_name_cache_updated=True
deffmt_doc(cls: type, level: int) ->str:
comment=cls.__doc__
assertcomment, f"{cls} has no __doc__"
indent=level*2*" "
return"\n".join(map(lambdas: f"{indent}# {s}", filter(None, map(lambdas: s.strip(), comment.split("\n")))))
classGroup:
_type_cache: ClassVar[dict[str, Any] |None] =None
_dumping: bool=False
_has_attr: bool=False
_changed: bool=False
_dumper: ClassVar[type]
def__getitem__(self, key: str) ->Any:
try:
returngetattr(self, key)
exceptNameError:
raiseKeyError(key)
def__iter__(self) ->Iterator[str]:
cls_members=dir(self.__class__)
members=filter(lambdak: notk.startswith("_") and (knotincls_membersorkinself.__annotations__),
list(self.__annotations__) +
[namefornameindir(self) ifnamenotinself.__annotations__])
returnmembers.__iter__()
def__contains__(self, key: str) ->bool:
try:
self._has_attr=True
returnhasattr(self, key)
finally:
self._has_attr=False
def__setitem__(self, key: str, value: Any) ->None:
setattr(self, key, value)
def__getattribute__(self, item: str) ->Any:
attr=super().__getattribute__(item)
ifisinstance(attr, Path) andnotsuper().__getattribute__("_dumping"):
ifattr.requiredandnotattr.exists() andnotsuper().__getattribute__("_has_attr"):
# if a file is required, and the one from settings does not exist, ask the user to provide it
# unless we are dumping the settings, because that would ask for each entry
with_lock: # lock to avoid opening multiple
new=Noneifno_guielseattr.browse()
ifnewisNone:
raiseFileNotFoundError(f"{attr} does not exist, but "
f"{self.__class__.__name__}.{item} is required")
setattr(self, item, new)
self._changed=True
attr=new
# resolve the path immediately when accessing it
returnattr.__class__(attr.resolve())
returnattr
@property
defchanged(self) ->bool:
returnself._changedorany(map(lambdav: isinstance(v, Group) andv.changed,
self.__dict__.values()))
@classmethod
defget_type_hints(cls) ->dict[str, Any]:
"""Returns resolved type hints for the class"""
ifcls._type_cacheisNone:
ifnotcls.__annotations__ornotisinstance(next(iter(cls.__annotations__.values())), str):
# non-str: assume already resolved
cls._type_cache=cls.__annotations__
else:
# str: build dicts and resolve with eval
mod=sys.modules[cls.__module__] # assume the module wasn't deleted
mod_dict= {k: getattr(mod, k) forkindir(mod)}
cls._type_cache=typing.get_type_hints(cls, globalns=mod_dict, localns=cls.__dict__)
returncls._type_cache
defget(self, key: str, default: Any=None) ->Any:
ifkeyinself:
returnself[key]
returndefault
defitems(self) ->list[tuple[str, Any]]:
return [(key, getattr(self, key)) forkeyinself]
defupdate(self, dct: dict[str, Any]) ->None:
assertisinstance(dct, dict), f"{self.__class__.__name__}.update called with " \
f"{dct.__class__.__name__} instead of dict."
forkinself.__annotations__:
ifnotk.startswith("_") andknotindct:
self._changed=True# key missing from host.yaml
fork, vindct.items():
# don't do getattr to stay lazy with world group init/loading
# instead we assign unknown groups as dicts and a later getattr will upcast them
attr=self.__dict__[k] ifkinself.__dict__else \
self.__class__.__dict__[k] ifkinself.__class__.__dict__elseNone
ifisinstance(attr, Group):
# update group
ifknotinself.__dict__:
attr=attr.__class__() # make a copy of default
setattr(self, k, attr)
ifisinstance(v, dict):
attr.update(v)
else:
warnings.warn(f"{self.__class__.__name__}.{k} "
f"tried to update Group from {type(v)}")
elifisinstance(attr, dict):
# update dict
ifknotinself.__dict__:
attr=attr.copy() # make a copy of default
setattr(self, k, attr)
ifisinstance(v, dict):
attr.update(v)
else:
warnings.warn(f"{self.__class__.__name__}.{k} "
f"tried to update dict from {type(v)}")
else:
# assign value, try to upcast to type hint
annotation=self.get_type_hints().get(k, None)
candidates= (
[] ifannotationisNoneelse (
typing.get_args(annotation)
iftyping.get_origin(annotation) in (Union, types.UnionType)
else [annotation]
)
)
none_type=type(None)
forclsincandidates:
assertisinstance(cls, type), f"{self.__class__.__name__}.{k}: type {cls} not supported in settings"
ifvisNoneandclsisnone_type:
# assign None, i.e. from Optional
setattr(self, k, v)
break
ifclsisboolandisinstance(v, bool):
# assign bool - special handling because issubclass(int, bool) is True
setattr(self, k, v)
break
ifclsisnotboolandissubclass(cls, type(v)):
# upcast, i.e. int -> IntEnum, str -> Path
setattr(self, k, cls.__call__(v))
break
ifissubclass(cls, (tuple, set)) andisinstance(v, list):
# convert or upcast from list
setattr(self, k, cls.__call__(v))
break
else:
# assign scalar and hope for the best
setattr(self, k, v)
ifannotation:
warnings.warn(f"{self.__class__.__name__}.{k} "
f"assigned from incompatible type {type(v).__name__}")
defas_dict(self, *args: str, downcast: bool=True) ->dict[str, Any]:
return {
name: _to_builtin(cast(object, getattr(self, name))) ifdowncastelsegetattr(self, name)
fornameinselfifnotargsornameinargs
}
@classmethod
def_dump_value(cls, value: Any, f: TextIO, indent: str) ->None:
"""Write a single yaml line to f"""
fromUtilsimportdump, DumperasBaseDumper
yaml_line: str=dump(value, Dumper=cast(BaseDumper, cls._dumper), width=2**31-1)
assertyaml_line.count("\n") ==1, f"Unexpected input for yaml dumper: {value}"
f.write(f"{indent}{yaml_line}")
@classmethod
def_dump_item(cls, name: str|None, attr: object, f: TextIO, level: int) ->None:
"""Write a group, dict or sequence item to f, where attr can be a scalar or a collection"""
# lazy construction of yaml Dumper to avoid loading Utils early
fromUtilsimportDumperasBaseDumper
fromyamlimportScalarNode, MappingNode
ifnothasattr(cls, "_dumper"):
ifclsisGroupornothasattr(Group, "_dumper"):
classDumper(BaseDumper):
defrepresent_mapping(self, tag: str, mapping: Any, flow_style: Any=None) ->MappingNode:
fromyamlimportScalarNode
res: MappingNode=super().represent_mapping(tag, mapping, flow_style)
pairs=cast(list[tuple[ScalarNode, Any]], res.value)
fork, vinpairs:
k.style=None# remove quotes from keys
returnres
defrepresent_str(self, data: str) ->ScalarNode:
# default double quote all strings
returnself.represent_scalar("tag:yaml.org,2002:str", data, style='"')
Dumper.add_representer(str, Dumper.represent_str)
Group._dumper=Dumper
ifclsisnotGroup:
cls._dumper=Group._dumper
indent=" "*level
start=f"{indent}-\n"ifnameisNoneelsef"{indent}{name}:\n"
ifisinstance(attr, Group):
# handle group
f.write(start)
attr.dump(f, level=level+1)
elifisinstance(attr, (list, tuple, set)) andattr:
# handle non-empty sequence; empty use one-line [] syntax
f.write(start)
forvalueinattr:
cls._dump_item(None, value, f, level=level+1)
elifisinstance(attr, dict) andattr:
# handle non-empty dict; empty use one-line {} syntax
f.write(start)
fordict_key, valueinattr.items():
# not dumping doc string here, since there is no way to upcast it after dumping
assertdict_keyisnotNone, "Key None is reserved for sequences"
cls._dump_item(dict_key, value, f, level=level+1)
else:
# dump scalar or empty sequence or mapping item
line= [_to_builtin(attr)] ifnameisNoneelse {name: _to_builtin(attr)}
cls._dump_value(line, f, indent=indent)
defdump(self, f: TextIO, level: int=0) ->None:
"""Dump Group to stream f at given indentation level"""
# There is no easy way to generate extra lines into default yaml output,
# so we format part of it by hand using an odd recursion here and in _dump_*.
self._dumping=True
try:
# fetch class to avoid going through getattr
cls=self.__class__
type_hints=cls.get_type_hints()
entries= [eforeinself]
ifnotentries:
# write empty dict for empty Group with no instance values
cls._dump_value({}, f, indent=" "*level)
# validate group
fornameincls.__annotations__.keys():
asserthasattr(cls, name), f"{cls}.{name} is missing a default value"
# dump ordered members
fornameinentries:
attr=cast(object, getattr(self, name))
attr_cls=type_hints[name] ifnameintype_hintselseattr.__class__
attr_cls_origin=typing.get_origin(attr_cls)
# resolve to first type for doc string
whileattr_cls_originisUnionorattr_cls_originistypes.UnionType:
attr_cls=typing.get_args(attr_cls)[0]
attr_cls_origin=typing.get_origin(attr_cls)
ifattr_cls.__doc__andattr_cls.__module__!="builtins":
f.write(fmt_doc(attr_cls, level=level) +"\n")
self._dump_item(name, attr, f, level=level)
self._changed=False
finally:
self._dumping=False
classBool:
# can't subclass bool, so we use this and Union or type: ignore
def__bool__(self) ->bool:
raiseNotImplementedError()
# Types for generic settings
T=TypeVar("T", bound="Path")
def_resolve_exe(s: str) ->str:
"""Append exe file extension if the file is an executable"""
ifisinstance(s, Path):
fromUtilsimportis_windows
ifs.is_exeandis_windowsandnots.lower().endswith(".exe"):
returnstr(s+".exe")
returnstr(s)
def_to_builtin(o: object) ->Any:
"""Downcast object to a builtin type for output"""
ifoisNone:
returnNone
c=o.__class__
whilec.__module__!="builtins":
c=c.__base__
returnc.__call__(o)
classPath(str):
# paths in host.yaml are str
required: bool=True
"""Marks the file as required and opens a file browser when missing"""
is_exe: bool=False
"""Special cross-platform handling for executables"""
description: str|None=None
"""Title to display when browsing for the file"""
copy_to: str|None=None
"""If not None, copy to AP folder instead of linking it"""
@classmethod
defvalidate(cls, path: str) ->None:
"""Overload and raise to validate input files from browse"""
pass
defbrowse(self: T, **kwargs: Any) ->T|None:
"""Opens a file browser to search for the file"""
raiseNotImplementedError(f"Please use a subclass of Path for {self.__class__.__name__}")
defresolve(self) ->str:
return_resolve_exe(self)
defexists(self) ->bool:
returnos.path.exists(self.resolve())
class_UserPath(str):
defresolve(self) ->str:
ifos.path.isabs(self):
returnstr(self)
fromUtilsimportuser_path
returnuser_path(_resolve_exe(self))
class_LocalPath(str):
defresolve(self) ->str:
ifos.path.isabs(self):
returnstr(self)
fromUtilsimportlocal_path
returnlocal_path(_resolve_exe(self))
classFilePath(Path):
# path to a file
md5s: ClassVar[list[str|bytes]] = []
"""MD5 hashes for default validator."""
defbrowse(self: T,
filetypes: Sequence[tuple[str, Sequence[str]]] |None=None, **kwargs: Any)\
->T|None:
fromUtilsimportopen_filename, is_windows
ifnotfiletypes:
ifself.is_exe:
name, ext="Program", ".exe"ifis_windowselse""
else:
ext=os.path.splitext(self)[1]
name=ext[1:] ifextelse"File"
filetypes= [(name, [ext])]
res=open_filename(f"Select {self.descriptionorself.__class__.__name__}", filetypes, self)
ifres:
self.validate(res)
ifself.copy_to:
# instead of linking the file, copy it
dst=self.__class__(self.copy_to).resolve()
shutil.copy(res, dst, follow_symlinks=True)
res=dst
try:
rel=os.path.relpath(res, self.__class__("").resolve())
ifnotrel.startswith(".."):
res=rel
exceptValueError:
pass
returnself.__class__(res)
returnNone
@classmethod
def_validate_stream_hashes(cls, f: BinaryIO) ->None:
"""Helper to efficiently validate stream against hashes"""
ifnotcls.md5s:
return# no hashes to validate against
pos=f.tell()
try:
fromhashlibimportmd5
file_md5=md5()
block=bytearray(64*1024)
view=memoryview(block)
whilen:=f.readinto(view): # type: ignore
file_md5.update(view[:n])
file_md5_hex=file_md5.hexdigest()
forvalid_md5incls.md5s:
ifisinstance(valid_md5, str):
ifvalid_md5.lower() ==file_md5_hex:
break
elifvalid_md5==file_md5.digest():
break
else:
raiseValueError(f"Hashes do not match for {cls.__name__}")
finally:
f.seek(pos)
@classmethod
defvalidate(cls, path: str) ->None:
"""Try to open and validate file against hashes"""
withopen(path, "rb", buffering=0) asf:
try:
cls._validate_stream_hashes(f)
exceptValueError:
raiseValueError(f"File hash does not match for {path}")
classFolderPath(Path):
# path to a folder
defbrowse(self: T, **kwargs: Any) ->T|None:
fromUtilsimportopen_directory
res=open_directory(f"Select {self.descriptionorself.__class__.__name__}", self)
ifres:
try:
rel=os.path.relpath(res, self.__class__("").resolve())
ifnotrel.startswith(".."):
res=rel
exceptValueError:
pass
returnself.__class__(res)
returnNone
classUserFilePath(_UserPath, FilePath):
pass
classUserFolderPath(_UserPath, FolderPath):
pass
classOptionalUserFilePath(UserFilePath):
required=False
classOptionalUserFolderPath(UserFolderPath):
required=False
classLocalFilePath(_LocalPath, FilePath):
pass
classLocalFolderPath(_LocalPath, FolderPath):
pass
classOptionalLocalFilePath(LocalFilePath):
required=False
classOptionalLocalFolderPath(LocalFolderPath):
required=False
classSNESRomPath(UserFilePath):
# Special UserFilePath that ignores an optional header when validating
@classmethod
defvalidate(cls, path: str) ->None:
"""Try to open and validate file against hashes"""
withopen(path, "rb", buffering=0) asf:
f.seek(0, os.SEEK_END)
size=f.tell()
ifsize%1024==512:
f.seek(512) # skip header
elifsize%1024==0:
f.seek(0) # header-less
else:
raiseValueError(f"Unexpected file size for {path}")
try:
cls._validate_stream_hashes(f)
exceptValueError:
raiseValueError(f"File hash does not match for {path}")
# World-independent setting groups
classGeneralOptions(Group):
classOutputPath(OptionalUserFolderPath):
"""
Where to place output files
"""
# created on demand, so marked as optional
output_path: OutputPath=OutputPath("output")
classServerOptions(Group):
"""
Options for MultiServer
Null means nothing, for the server this means to default the value
These overwrite command line arguments!
"""
classServerPassword(str):
"""
Allows for clients to log on and manage the server. If this is null, no remote administration is possible.
"""
classDisableItemCheat(Bool):
"""Disallow !getitem"""
classLocationCheckPoints(int):
"""
Client hint system
Points given to a player for each acquired item in their world
"""
classHintCost(int):
"""
Relative point cost to receive a hint via !hint for players
so for example hint_cost: 20 would mean that for every 20% of available checks, you get the ability to hint,
for a total of 5
"""
classReleaseMode(str):
"""
Release modes
A Release sends out the remaining items *from* a world that releases
"disabled" -> clients can't release,
"enabled" -> clients can always release
"auto" -> automatic release on goal completion
"auto-enabled" -> automatic release on goal completion and manual release is also enabled
"goal" -> release is allowed after goal completion
"""
classCollectMode(str):
"""
Collect modes
A Collect sends the remaining items *to* a world that collects
"disabled" -> clients can't collect,
"enabled" -> clients can always collect
"auto" -> automatic collect on goal completion
"auto-enabled" -> automatic collect on goal completion and manual collect is also enabled
"goal" -> collect is allowed after goal completion
"""
classRemainingMode(str):
"""
Remaining modes
!remaining handling, that tells a client which items remain in their pool
"enabled" -> Client can always ask for remaining items
"disabled" -> Client can never ask for remaining items
"goal" -> Client can ask for remaining items after goal completion
"""
classCountdownMode(str):
"""
Countdown modes
Determines whether or not a player can initiate a countdown with !countdown
Note that /countdown is always available to the host.
"enabled" -> Client can always initiate a countdown with !countdown.
"disabled" -> Client can never initiate a countdown with !countdown.
"auto" -> !countdown will be available for any room with less than 30 slots.
"""
classAutoShutdown(int):
"""Automatically shut down the server after this many seconds without new location checks, 0 to keep running"""
classCompatibility(IntEnum):
"""
Compatibility handling
2 -> Recommended for casual/cooperative play, attempt to be compatible with everything across all versions
1 -> No longer in use, kept reserved in case of future use
0 -> Recommended for tournaments to force a level playing field, only allow an exact version match
"""
OFF=0
ON=1
FULL=2
classLogNetwork(IntEnum):
"""log all server traffic, mostly for dev use"""
OFF=0
ON=1
host: str|None=None
port: int=38281
password: str|None=None
multidata: str|None=None
savefile: str|None=None
disable_save: bool=False
loglevel: str="info"
logtime: bool=False
server_password: ServerPassword|None=None
disable_item_cheat: DisableItemCheat|bool=False
location_check_points: LocationCheckPoints=LocationCheckPoints(1)
hint_cost: HintCost=HintCost(10)
release_mode: ReleaseMode=ReleaseMode("auto")
collect_mode: CollectMode=CollectMode("auto")
remaining_mode: RemainingMode=RemainingMode("goal")
countdown_mode: CountdownMode=CountdownMode("auto")
auto_shutdown: AutoShutdown=AutoShutdown(0)
compatibility: Compatibility=Compatibility(2)
log_network: LogNetwork=LogNetwork(0)
classGeneratorOptions(Group):
"""Options for Generation"""
classEnemizerPath(LocalFilePath):
"""Location of your Enemizer CLI, available here: https://github.com/Ijwu/Enemizer/releases"""
is_exe=True
classPlayerFilesPath(OptionalUserFolderPath):
"""Folder from which the player yaml files are pulled from"""
# created on demand, so marked as optional
classPlayers(int):
"""amount of players, 0 to infer from player files"""
classWeightsFilePath(str):
"""
general weights file, within the stated player_files_path location
gets used if players is higher than the amount of per-player files found to fill remaining slots
"""
# this is special because the path is relative to player_files_path
classMetaFilePath(str):
"""Meta file name, within the stated player_files_path location"""
# this is special because the path is relative to player_files_path
classSpoiler(IntEnum):
"""
Create a spoiler file
0 -> None
1 -> Spoiler without playthrough or paths to playthrough required items
2 -> Spoiler with playthrough (viable solution to goals)
3 -> Spoiler with playthrough and traversal paths towards items
"""
NONE=0
BASIC=1
PLAYTHROUGH=2
FULL=3
classPlandoOptions(str):
"""
List of options that can be plando'd. Can be combined, for example "bosses, items"
Available options: bosses, items, texts, connections
"""
classRace(IntEnum):
"""Create encrypted race roms and flag games as race mode"""
OFF=0
ON=1
classPanicMethod(str):
"""
What to do if the current item placements appear unsolvable.
raise -> Raise an exception and abort.
swap -> Attempt to fix it by swapping prior placements around. (Default)
start_inventory -> Move remaining items to start_inventory, generate additional filler items to fill locations.
"""
enemizer_path: EnemizerPath=EnemizerPath("EnemizerCLI/EnemizerCLI.Core") # + ".exe" is implied on Windows
player_files_path: PlayerFilesPath=PlayerFilesPath("Players")
players: Players=Players(0)
weights_file_path: WeightsFilePath=WeightsFilePath("weights.yaml")
meta_file_path: MetaFilePath=MetaFilePath("meta.yaml")
spoiler: Spoiler=Spoiler(3)
race: Race=Race(0)
plando_options: PlandoOptions=PlandoOptions("bosses, connections, texts")
panic_method: PanicMethod=PanicMethod("swap")
loglevel: str="info"
logtime: bool=False
classSNIOptions(Group):
classSNIPath(LocalFolderPath):
"""
Set this to your SNI folder location if you want the MultiClient to attempt an auto start, \
does nothing if not found
"""
classSnesRomStart(str):
"""
Set this to false to never autostart a rom (such as after patching)
True for operating system default program
Alternatively, a path to a program to open the .sfc file with
"""
sni_path: SNIPath=SNIPath("SNI")
snes_rom_start: SnesRomStart|bool=True
classBizHawkClientOptions(Group):
classEmuHawkPath(UserFilePath):
"""
The location of the EmuHawk you want to auto launch patched ROMs with
"""
is_exe=True
description="EmuHawk Executable"
classRomStart(str):
"""
Set this to true to autostart a patched ROM in BizHawk with the connector script,
to false to never open the patched rom automatically,
or to a path to an external program to open the ROM file with that instead.
"""
emuhawk_path: EmuHawkPath=EmuHawkPath(None)
rom_start: RomStart|bool=True
# Top-level group with lazy loading of worlds
classSettings(Group):
general_options: GeneralOptions=GeneralOptions()
server_options: ServerOptions=ServerOptions()
generator: GeneratorOptions=GeneratorOptions()
sni_options: SNIOptions=SNIOptions()
bizhawkclient_options: BizHawkClientOptions=BizHawkClientOptions()
_filename: str|None=None
def__getattribute__(self, key: str) ->Any:
ifkey.startswith("_") orkeyinself.__class__.__dict__:
# not a group or a hard-coded group
pass
elifkeynotindir(self) orisinstance(super().__getattribute__(key), dict):
# settings class not loaded yet
ifkeynotin_world_settings_name_cache:
# find world that provides the settings class
_update_cache()
# check for missing keys to update _changed
forworld_settings_namein_world_settings_name_cache:
ifworld_settings_namenotindir(self):
self._changed=True
ifkeynotin_world_settings_name_cache:
# not a world group
returnsuper().__getattribute__(key)
# directly import world and grab settings class
world_mod, world_cls_name=_world_settings_name_cache[key].rsplit(".", 1)
try:
world=cast(type, getattr(__import__(world_mod, fromlist=[world_cls_name]), world_cls_name))
exceptAttributeError:
importwarnings
warnings.warn(f"World {world_cls_name} failed to initialize properly.")
returnsuper().__getattribute__(key)
assertgetattr(world, "settings_key") ==key
try:
cls_or_name=world.__annotations__["settings"]
exceptKeyError:
importwarnings
warnings.warn(f"World {world_cls_name} does not define settings. Please consider upgrading the world.")
returnsuper().__getattribute__(key)
ifisinstance(cls_or_name, str):
# Try to resolve type. Sadly we can't use get_type_hints, see https://bugs.python.org/issue43463
cls_name=cls_or_name
if"["incls_name: # resolve ClassVar[]
cls_name=cls_name.split("[", 1)[1].rsplit("]", 1)[0]
cls=cast(type, getattr(__import__(world_mod, fromlist=[cls_name]), cls_name))
else:
type_args=typing.get_args(cls_or_name) # resolve ClassVar[]
cls=type_args[0] iftype_argselsecast(type, cls_or_name)
impl: Group=cast(Group, cls())
assertisinstance(impl, Group), f"{world_cls_name}.settings has to inherit from settings.Group. " \
"If that's already the case, please avoid recursive partial imports."
# above assert fails for recursive partial imports
# upcast loaded data to settings class
try:
dct=super().__getattribute__(key)
ifisinstance(dct, dict):
impl.update(dct)
else:
self._changed=True# key is a class var -> new section
exceptAttributeError:
self._changed=True# key is unknown -> new section
setattr(self, key, impl)
returnsuper().__getattribute__(key)
def__init__(self, location: str|None): # change to PathLike[str] once we drop 3.8?
super().__init__()
iflocation:
fromUtilsimportparse_yaml
withopen(location, encoding="utf-8-sig") asf:
fromyaml.errorimportMarkedYAMLError
try:
options=parse_yaml(f.read())
exceptMarkedYAMLErrorasex:
ifex.problem_mark:
f.seek(0)
lines=f.readlines()
problem_line=lines[ex.problem_mark.line]
error_line=" "*ex.problem_mark.column+"^"
raiseException(f"{ex.context}{ex.problem}\n{problem_line}{error_line}")
raiseex
# TODO: detect if upgrade is required
# TODO: once we have a cache for _world_settings_name_cache, detect if any game section is missing
self.update(optionsor {})
self._filename=location
defautosave() ->None:
if__debug__:
import__main__
main_file=getattr(__main__, "__file__", "")
assert"pytest"notinmain_fileand"unittest"notinmain_file, \
f"Auto-saving {self._filename} during unittests"
ifself._filenameandself.changedandnotskip_autosave:
self.save()
ifnotskip_autosave:
importatexit
atexit.register(autosave)
defsave(self, location: str|None=None) ->None: # as above
fromUtilsimportparse_yaml
location=locationorself._filename
assertlocation, "No file specified"
temp_location=location+".tmp"# not using tempfile to test expected file access
# remove old temps
ifos.path.exists(temp_location):
os.unlink(temp_location)
# can't use utf-8-sig because it breaks backward compat: pyyaml on Windows with bytes does not strip the BOM
withopen(temp_location, "w", encoding="utf-8") asf:
self.dump(f)
f.flush()
ifhasattr(os, "fsync"):
os.fsync(f.fileno())
# validate new file is valid yaml
withopen(temp_location, encoding="utf-8") asf:
parse_yaml(f.read())
# replace old with new, try atomic operation first
try:
os.rename(temp_location, location)
except (OSError, FileExistsError):
os.unlink(location)
os.rename(temp_location, location)
self._filename=location
defdump(self, f: TextIO, level: int=0) ->None:
# load all world setting classes
_update_cache()
forkeyin_world_settings_name_cache:
self.__getattribute__(key) # load all worlds
super().dump(f, level)
@property
deffilename(self) ->str|None:
returnself._filename
# host.yaml loader
defget_settings() ->Settings:
"""Returns settings from the default host.yaml"""
with_lock: # make sure we only have one instance
res=getattr(get_settings, "_cache", None)
ifnotres:
fromUtilsimportuser_path, local_path
filenames= ("options.yaml", "host.yaml")
locations: list[str] = []
ifos.path.join(os.getcwd()) !=local_path():
locations+=filenames# use files from cwd only if it's not the local_path
locations+= [user_path(filename) forfilenameinfilenames]
forlocationinlocations:
try:
res=Settings(location)
break
exceptFileNotFoundError:
continue
else:
warnings.warn(f"Could not find {filenames[1]} to load options. Creating a new one.")
res=Settings(None)
res.save(user_path(filenames[1]))
setattr(get_settings, "_cache", res)
returnres