-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathme3mmcli.py
More file actions
1679 lines (1498 loc) · 64 KB
/
Copy pathme3mmcli.py
File metadata and controls
1679 lines (1498 loc) · 64 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
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
"""convert ME3 Tweaks moddesc.ini file into json and back"""
from abc import ABC, abstractmethod
from collections.abc import Iterable, MutableSequence
from dataclasses import dataclass, field, fields
from difflib import unified_diff
from pathlib import Path
from rich.console import Console
from rich.pretty import Pretty
from rich.syntax import Syntax
from rich.tree import Tree
from typing import Any, Generic, Self, TypeAlias, TypeVar, cast, overload, override
import click
import codecs
import json
import re
import sys
_JSON_INDENT: int = 4
JsonValue: TypeAlias = str | dict[str, "JsonValue"] | list["JsonValue"] | None
class IdKeyStore():
_id_none: int = -1
_id: dict[int, str] = {}
_key_none: str = 'None'
_key: dict[str, int] = {}
def __repr__(self) -> str:
return f'{self.__class__.__name__}(_id={self._id}, _key={self._key})'
def set_id(self, id: int, key: str) -> None:
if id <= self._id_none:
raise ValueError(f"Id for key '{key}' cannot be lower or equal than ({self._id_none}).")
if key == self._key_none:
raise ValueError(f"Cannot set key '{self._key_none}' for id ({id}).")
self._id[id] = key
self._key[key] = id
def set_key(self, key: str, id: int) -> None:
self.set_id(id, key)
def get_id(self, key: str) -> int:
if key in self._key.keys():
return self._key[key]
return self._id_none
def get_key(self, id: int) -> str:
if id in self._id.keys():
return self._id[id]
return self._key_none
multilist_key_map: IdKeyStore = IdKeyStore()
@dataclass
class IFormatting(ABC):
uses_key: bool = field(default=True)
key: str = field(default="")
def __post_init__(self) -> None:
# set default keys
for name, attr in self.serializable_fields().items():
if attr.key:
continue
attr.key = name
def get_id(self) -> str:
"""Returns main key name that this object can be represented as."""
return f"{self.__class__.__name__}[{id(self)}]"
@classmethod
def get_type(cls) -> type["IFormatting"]:
"""Get reference to class type"""
return cls
def serializable_field_names(self) -> set[str]:
"""List of names available for serialization to supported formats."""
names: set[str] = set()
ignored: list[str] = [
'uses_key',
'ini_separator',
'wrapper_left',
'wrapper_right',
'quote_wrap'
]
for f in fields(self):
if f.name in ignored:
continue
names.add(f.name)
return names
def serializable_fields(self) -> dict[str, IFormatting]:
"""List of fields available for serialization to supported formats.\n
Uses serializable_field_names() to determine which files to return."""
attrs: dict[str, IFormatting] = {}
# do not iterate over serializable_field_names()
# its a set and the loop gets wonky and unordered
for f in fields(self):
if f.name not in self.serializable_field_names():
continue
attr: IFormatting | None = getattr(self, f.name, None)
if isinstance(attr, IFormatting):
attrs[f.name] = attr
return attrs
def get_field(self, name: str) -> IFormatting | None:
"""Get classs field, must exist in serializable names."""
if name in self.serializable_field_names() and hasattr(self, name):
return cast(IFormatting, getattr(self, name))
return None
def set_field(self, name: str, value: IFormatting) -> None:
"""Set value of a class field, must exist in serializable names."""
if name in self.serializable_field_names() and hasattr(self, name):
setattr(self, name, value)
@abstractmethod
def is_empty(self) -> bool:
"""Return true if this Value holds no data."""
raise NotImplementedError()
@abstractmethod
def reset_value(self) -> None:
"""Reset value to it's defaults."""
raise NotImplementedError()
@abstractmethod
def as_ini(self, formatted: bool = True, pretty: bool = False) -> str:
"""Return value representation as INI moddesc format."""
raise NotImplementedError()
@abstractmethod
def set_from_ini(self, ini: str | list[str]) -> Self:
"""Parse value from INI moddesc format."""
raise NotImplementedError()
@abstractmethod
def jsonable(self) -> JsonValue:
"""Return Value representation as combination of python dicts and lists."""
raise NotImplementedError()
def as_json(self) -> str:
"""Return Value representation as JSON moddesc format."""
return json.dumps(obj=self.jsonable(), indent=_JSON_INDENT)
@abstractmethod
def set_from_json(self, json_data: JsonValue) -> Self:
"""Parse value from JSON moddesc format."""
raise NotImplementedError()
TFormatting = TypeVar(name="TFormatting", bound=IFormatting)
class IJsonableDict(IFormatting, ABC):
@override
@abstractmethod
def jsonable(self) -> dict[str, JsonValue]:
raise NotImplementedError()
# =============================================================================
#
# VALUE TYPES
# - RawValue
# - BoolValue (RawValue)
# - IntValue (RawValue)
# - EnumValue (RawValue)
# - PathValue (RawValue)
# - UrlValue (RawValue)
# - IWrappedValue
# - OptionsValue (IWrappedValue)
# - DlcOptionKey (OptionsValue)
# - DlcOptions (OptionsValue)
# - DlcValue (RawValue)
# - ListValue
# - ArrayValue(ListValue)
# - DictValue(ListValue)
# - MultiListValue(DictValue)
#
# =============================================================================
@dataclass
class RawValue(IFormatting):
"""Holds one specific value that will be represented as raw value."""
value: str = field(default="")
@override
def is_empty(self) -> bool:
return self.value == ''
@override
def reset_value(self) -> None:
self.value = ''
@override
def as_ini(self, formatted: bool = True, pretty: bool = False) -> str:
if self.is_empty():
return ""
# return valid ini pattern as key = value
# formatted bool controls if to include "pretty" formatting or not
keyed: str = (f'{self.key} = ' if formatted else f'{self.key}=') if self.uses_key else ''
return f'{keyed}{self.value}'
@override
def set_from_ini(self, ini: str | list[str]) -> Self:
if isinstance(ini, list):
raise TypeError(f'{self.__class__.__name__} cannot accept INI input from list variable.')
# ini pattern is simple, key = value
self.reset_value()
ini = ini.strip()
if not self.uses_key:
self.key = ini
self.value = ini
return self
kvp: list[str] = re.split(pattern=r'\s*=\s*', string=ini, maxsplit=1)
key: str = ''
value: str = ''
if len(kvp) == 2:
key = kvp[0].strip()
value = kvp[1].strip()
if not key or not value:
raise ValueError(f"Could not parse key value pair from provided ini line.\n\nini: {ini}\nkey: {key}\nvalue: {value}")
self.key: str = key
self.value = value
return self
@override
def jsonable(self) -> JsonValue:
return self.value if not self.is_empty() else ""
@override
def set_from_json(self, json_data: JsonValue) -> Self:
self.reset_value()
if not self.uses_key and isinstance(json_data, str):
self.key = json_data
self.value = json_data
return self
if not isinstance(json_data, dict):
return self # not a dict, cant tell whats key and whats value
if len(json_data) != 1:
return self # theres more than just key => value
key, value = next(iter(json_data.items()))
value = cast(str, value)
if not key or not value:
raise ValueError(f"Could not parse key value pair from provided json data.\n\njson: {json_data}\nkey: {key}\nvalue: {value}")
self.key = key
self.value = value
return self
TValue = TypeVar(name="TValue", bound=RawValue)
@dataclass
class BoolValue(RawValue):
"""Holds one specific value that will be represented as a boolean value."""
@override
def set_from_ini(self, ini: str | list[str]) -> Self:
if isinstance(ini, list):
raise TypeError(f'{self.__class__.__name__} cannot accept INI input from list variable.')
_ = super().set_from_ini(ini)
if self.value.lower() not in ['true','false']:
raise ValueError(f"BoolValue can only accept 'true' or 'false' values.\n\nref: {self.value}")
#self.reset_value()
return self
@dataclass
class IntValue(RawValue):
"""Holds one specific value holding close encounters of the numeric kind"""
@override
def set_from_ini(self, ini: str | list[str]) -> Self:
if isinstance(ini, list):
raise TypeError(f'{self.__class__.__name__} cannot accept INI input from list variable.')
_ = super().set_from_ini(ini)
try:
_ = int(self.value)
except ValueError:
raise ValueError(f"IntValue can accept only numbers as its value.\n\nref: {self.value}")
_ = super().set_from_ini(ini)
return self
@dataclass
class EnumValue(RawValue):
"""Holds one specific value from list of possible values."""
items: set[str] = field(default_factory=set[str])
@override
def set_from_ini(self, ini: str | list[str]) -> Self:
if isinstance(ini, list):
raise TypeError(f'{self.__class__.__name__} cannot accept INI input from list variable.')
_ = super().set_from_ini(ini)
if self.value not in self.items:
raise ValueError(f"EnumValue can accept only one of its pre-defined values [{",".join(self.items)}].\n\nref: {self.value}")
#self.reset_value()
return self
@dataclass
class PathValue(RawValue):
"""Holds one specific value that will be represented as a path, eg. \\Directory\\File.jpeg."""
pass
@dataclass
class UrlValue(RawValue):
"""Holds one specific value that will be represented as an url, eg. https://masseffect.com."""
pass
@dataclass
class IWrappedValue(RawValue, ABC):
"""Interface for value thats wrapped in characters, for example as key = (value)"""
wrapper_left: str = field(default="", repr=False)
wrapper_right: str = field(default="", repr=False)
@override
def as_ini(self, formatted: bool = True, pretty: bool = False) -> str:
if self.is_empty():
return ''
keyed: str = (f'{self.key} = ' if formatted else f'{self.key}=') if self.uses_key else ''
return f'{keyed}{self.wrapper_left}{self.value}{self.wrapper_right}'
@override
def set_from_ini(self, ini: str | list[str]) -> Self:
_ = super().set_from_ini(ini)
if self.is_empty():
return self
# confirm that the value was wrapped in correct wrapper
value: str = self.value
if value.startswith(self.wrapper_left) and value.endswith(self.wrapper_right):
value = value[1:-1]
self.value: str = value
return self
@dataclass
class StringValue(IWrappedValue, RawValue):
"""Holds one specific value that will be represented as a string value with single quotes."""
wrapper_left: str = field(default="'", repr=False)
wrapper_right: str = field(default="'", repr=False)
@dataclass
class TextValue(IWrappedValue, RawValue):
"""Holds one specific value that will be represented as a string value with double quotes."""
wrapper_left: str = field(default='"', repr=False)
wrapper_right: str = field(default='"', repr=False)
@dataclass
class TagValue(IWrappedValue, RawValue):
"""Special value type thats used only for tagging the main dictionaries in moddesc format."""
uses_key: bool = field(default=False)
wrapper_left: str = field(default="[", repr=False)
wrapper_right: str = field(default="]", repr=False)
@dataclass
class OptionsValue(IJsonableDict, IWrappedValue, RawValue):
"""Holds arbitrary amount of values, each with their own type."""
ini_separator: str = field(default=",", repr=False)
wrapper_left: str = field(default="[", repr=False)
wrapper_right: str = field(default="]", repr=False)
# INI option values are separated by a comma and wrapped in [] brackets
@override
def as_ini(self, formatted: bool = True, pretty: bool = False) -> str:
if self.is_empty():
return ''
parts: list[str] = []
for attr in self.serializable_fields().values():
if not attr.is_empty():
parts.append(attr.as_ini(formatted))
return f'{self.key}={self.wrapper_left}{self.ini_separator.join(parts)}{self.wrapper_right}'
# INI option values are separated by a comma and wrapped in [] brackets
@override
def set_from_ini(self, ini: str | list[str]) -> Self:
_ = super().set_from_ini(ini)
# match only separators outside of [] for recursion
recursive_options: list[str] = re.split(rf'{self.ini_separator}(?=(?:[^\[\]]*\[[^\[\]]*\])*[^\[\]]*$)', self.value)
for option in recursive_options:
# parse option as RawValue
kvp: RawValue = RawValue().set_from_ini(option)
if not kvp.is_empty():
# get attr by key
attr = self.get_field(kvp.key)
if isinstance(attr, IFormatting):
_ = attr.set_from_ini(option)
return self
@override
def jsonable(self) -> dict[str, JsonValue]:
result: dict[str, JsonValue] = {}
for name, attr in self.serializable_fields().items():
if attr.is_empty():
continue
result[name] = attr.jsonable()
return result
@override
def set_from_json(self, json_data: JsonValue) -> Self:
if not isinstance(json_data, dict):
return self
# similar to dicts, the self.key value should equal the key of received data:
if not json_data[self.key]:
return self
json_data = cast(dict[str, JsonValue], json_data[self.key])
if self.is_empty():
self.value: str = str(json_data)
for key, value in json_data.items():
attr = self.get_field(key)
if isinstance(attr, IFormatting):
_ = attr.set_from_json({key: value})
return self
@dataclass
class DlcOptionKey(OptionsValue):
"""OptionKey options for DLC values."""
option: RawValue = field(default_factory=RawValue)
uistring: StringValue = field(default_factory=StringValue)
@dataclass
class DlcOptions(OptionsValue):
"""DLC options for DLC values."""
minversion: RawValue = field(default_factory=RawValue)
optionkey: DlcOptionKey = field(default_factory=DlcOptionKey)
@dataclass
class DlcValue(IJsonableDict, RawValue):
"""Option values reside in [] bloc attached to RawValue,
its content is accessible in the .options property as parsed formatting object."""
quote_wrap: bool = field(default=False)
options: DlcOptions = field(default_factory=DlcOptions)
# NOTE: I'm setting options= into the ini value and then removing it on as_ini
# this is because both RawValue and OptionsValue expect key=value input
# and initial options [tag] dont have equalsign so its attached there to correctly
# recognize options as options, the key of the object also becomes 'options'
# DLC values are just RawValues with extra DLC options.
@override
def as_ini(self, formatted: bool = True, pretty: bool = False) -> str:
# return with quotes if uistring is not empty
# this is only for CUSTOMDLC fields
result: str = self.key + self.options.as_ini(False)
result = result.replace('options=', '', 1)
if self.quote_wrap and not self.options.optionkey.uistring.is_empty():
result = f'"{result}"'
return result
@override
def set_from_ini(self, ini: str | list[str]) -> Self:
if isinstance(ini, list):
raise TypeError(f'{self.__class__.__name__} cannot accept INI input from list variable.')
_ = self.reset_value()
# DLC format example:
# NOTE: can be wrapped in quotes if uistring option exists
# +DLC_MOD_EGM[minversion=1.0.6,optionkey=[option=+D0DB2884,uistring='Squadmate Pack (Full)']]
ini = ini.strip()
# wrapped in quotes?
if ini.startswith('"') and ini.endswith('"'):
ini = ini[1:-1]
# is there options?
if self.options.wrapper_left in ini and ini.endswith(self.options.wrapper_right):
value, options = ini.split(self.options.wrapper_left, 1)
# put the separator back after it got splitted away
options: str = f'{self.options.wrapper_left}{options}'
_ = super().set_from_ini(f'{value}{options}')
self.key: str = value
_ = self.options.set_from_ini(f'options={options}')
# no options exist
# treat this as plain RawValue and just call the ini parsing on super()
else:
_ = super().set_from_ini(ini)
return self
@override
def jsonable(self) -> dict[str, JsonValue]:
result: dict[str, JsonValue] = {}
result[self.key] = self.options.jsonable()
return result
@override
def set_from_json(self, json_data: JsonValue) -> Self:
self.reset_value()
if not isinstance(json_data, dict):
return self
for key, value in json_data.items():
self.key = key
self.value: str = str(value)
_ = self.options.set_from_json({'options': value})
return self
@dataclass
class MultilistIDValue(RawValue):
"""Holds either ID or friendly_key value"""
@override
def as_ini(self, formatted: bool = True, pretty: bool = False) -> str:
new_value: RawValue = RawValue()
new_value.uses_key = self.uses_key
new_value.key = self.key if new_value.uses_key else self.value_as_id()
new_value.value = self.value_as_id()
return new_value.as_ini(formatted)
@override
def jsonable(self) -> JsonValue:
new_value: RawValue = RawValue()
new_value.uses_key = self.uses_key
new_value.key = self.key if new_value.uses_key else self.value_as_key()
new_value.value = self.value_as_key()
return new_value.jsonable()
def value_as_key(self) -> str:
if self.value.isdigit():
friendly_key: str = multilist_key_map.get_key(int(self.value))
if friendly_key != multilist_key_map._key_none: # pyright: ignore[reportPrivateUsage]
return friendly_key
return self.value
def value_as_id(self) -> str:
if not self.value.isdigit():
id: int = multilist_key_map.get_id(self.value)
if id != multilist_key_map._id_none: # pyright: ignore[reportPrivateUsage]
return str(id)
return self.value
@dataclass
class ListValue(RawValue, MutableSequence[TFormatting], Generic[TFormatting]):
ini_separator: str = field(default=";", repr=False)
item_type: type[TFormatting] | type[None] = type(None)
items: list[TFormatting] = field(default_factory=list[TFormatting])
@override
def __init__(self, item_type: type[TFormatting]) -> None:
super().__init__()
self.item_type = item_type
self.items = []
return
# MutableSequence[IFormatting]
@override
def __len__(self) -> int:
return len(self.items)
@overload
def __getitem__(self, index: int) -> TFormatting: ...
@overload
def __getitem__(self, index: slice) -> list[TFormatting]: ...
@override
def __getitem__(self, index: int | slice) -> IFormatting | list[TFormatting]:
return self.items[index]
@overload
def __setitem__(self, index: int, value: TFormatting) -> None: ...
@overload
def __setitem__(self, index: slice, value: Iterable[TFormatting]) -> None: ...
@override
def __setitem__(self, index: int | slice, value: TFormatting | Iterable[TFormatting]) -> None:
if isinstance(index, slice):
if isinstance(value, Iterable) and not isinstance(value, (str, bytes)):
self.items[index] = list[TFormatting](value)
return
raise TypeError(f"Slice assignment requires an iterable of IFormatting items.\n\nref: {value}")
if isinstance(value, IFormatting):
self.items[index] = value
return
raise TypeError("IFormattingList only accepts IFormatting items.")
@overload
def __delitem__(self, index: int) -> None: ...
@overload
def __delitem__(self, index: slice) -> None: ...
@override
def __delitem__(self, index: int | slice) -> None:
del self.items[index]
@override
def insert(self, index: int, value: TFormatting) -> None:
self.items.insert(index, value)
@override
def is_empty(self) -> bool:
return len(self.items) <= 0
def reset_items(self) -> Self:
self.items = []
return self
def get_index_by_key(self, key: str) -> int:
"""returns -1 if not found"""
return next((i for i, item in enumerate(self.items) if item.key == key), -1)
def get_item_by_key(self, key: str) -> TFormatting | None:
if self.get_index_by_key(key) < 0:
return None
return self.items[self.get_index_by_key(key)]
@override
def as_ini(self, formatted: bool = True, pretty: bool = False) -> str:
# pretty multilists
if self.key.startswith('multilist') and pretty:
keyed: str = f'{self.key} = '
spaced: str = ' ' * len(keyed)
items: list[str] = []
for item in self.items:
items.append(spaced + item.as_ini(pretty=pretty))
return f'{keyed}{f'{self.ini_separator}\n'.join(items).strip()}'
# ugly
if self.is_empty():
return ""
# save ini into the value param
self.value: str = self.ini_separator.join(item.as_ini(formatted) for item in self.items).strip()
# return RawValue as usual
return super().as_ini(formatted)
@override
def set_from_ini(self, ini: str | list[str]) -> Self:
# cannot map raw value into items
if self.item_type == type(None):
return self
_ = self.reset_items()
items: list[str] = []
if isinstance(ini, list):
# setting from list does not allow me to know a key
self.key: str = f'list[{len(ini)}]'
items = ini
else:
# first parse the key and raw value into key and value fields
_ = super().set_from_ini(ini)
items = self.value.split(self.ini_separator)
for item in items:
# item_type() cannot be None here
# create new item from item_type
# turn off key=value parsing
new_item: TFormatting = cast(TFormatting, self.item_type())
new_item.uses_key = False
self.items.append(new_item.set_from_ini(item))
return self
@override
def jsonable(self) -> JsonValue:
# collapse key value dict jsonable content
if issubclass(self.item_type, IJsonableDict):
result_dict: dict[str, JsonValue] = {}
for item in self.items:
item = cast(IJsonableDict, item)
if not item or item.is_empty():
continue
result_dict.update(item.jsonable())
return result_dict
# return as list of values
result: list[JsonValue] = []
for item in self.items:
if item.is_empty():
continue
result.append(item.jsonable())
return result
@override
def set_from_json(self, json_data: JsonValue) -> Self:
_ = self.reset_items()
# convert string to data if needed
json_obj: JsonValue = cast(JsonValue, json.loads(json_data)) if isinstance(json_data, str) else json_data
if not json_obj:
return self
# flatten json keys for those that are the same name of this attr:
if isinstance(json_obj, dict) and self.key in json_obj.keys():
json_obj = cast(dict[str, JsonValue], json_obj[self.key])
# dictionaries?
if isinstance(json_obj, dict):
for key, item in json_obj.items():
new_item = cast(TFormatting, self.item_type())
_ = new_item.set_from_json({key: item})
if not new_item.is_empty():
self.items.append(new_item)
# lists?
elif isinstance(json_obj, list):
for item in json_obj:
new_item = cast(TFormatting, self.item_type())
new_item.uses_key = False
_ = new_item.set_from_json(item)
if not new_item.is_empty():
self.items.append(new_item)
return self
@dataclass
class ArrayValue(ListValue[TFormatting]):
ini_separator: str = field(default=',', repr=False)
item_type: type[TFormatting] | type[None] = type(None)
items: list[TFormatting] = field(default_factory=list[TFormatting])
@override
def __init__(self, item_type: type[TFormatting]) -> None:
super().__init__(item_type)
self.item_type = item_type
self.items = []
return
@override
def as_ini(self, formatted: bool = True, pretty: bool = False) -> str:
# return wrapped in brackets as ((item),(item),(item))
if not pretty:
keyed: str = f'{self.key} = ' if formatted else f'{self.key}='
items: list[str] = []
for item in self.items:
items.append(f'({item.as_ini(formatted)})')
return f"{keyed}({self.ini_separator.join(items)})"
# pretty output of array so its not all dumped on single line
# useless as mod manager doesnt like reading this, but good for console echos
lines: list[str] = []
lines.append(f'{self.key} = (')
for item in self.items:
inner: list[str] = []
inner.append(' (')
inner.append(item.as_ini(pretty=pretty))
inner.append(f' ){self.ini_separator if not item == self.items[-1] else ''}')
lines.append(f'\n'.join(inner))
lines.append(')')
return '\n'.join(lines)
@override
def set_from_ini(self, ini: str | list[str]) -> Self:
if isinstance(ini, list):
raise TypeError(f'{self.__class__.__name__} cannot accept INI input from list variable.')
# cannot map raw value into items
if self.item_type == type(None):
return self
_ = self.reset_items()
# try parse
# this will separate key=value
raw = RawValue().set_from_ini(ini)
if raw.is_empty():
return self
self.key: str = raw.key
ini = raw.value
# format: ((item),(item),(item))
# get rid of wrapping brackets
if not ini.startswith('(') or not ini.endswith(')'):
raise ValueError(f"Invalid format, INI line containing array of items must begin with ( and end with ).\n\nref: {ini}")
ini = ini[1:-1].strip()
# format: (item),(item),(item)
# getting rid of the brackets again from start and end
if not ini.startswith('(') or not ini.endswith(')'):
raise ValueError(f"Invalid format, INI array item(s) not wrapped inside ( ) brackets correctly.\n\nref: {ini}")
ini = ini[1:-1].strip()
# format: item),(item),(item
# now I can just split by bracketed comma and get the separate items
# matching ),( with possible spaces between, idk if there could be but rather make sure
items: list[str] = re.split(rf'\)\s*?{self.ini_separator}\s*?\(', ini)
# since arrays are packed to single line, lets unpack em
# create pattern out of accepted fields and split the string by them:
# r',\s*?(?=Description\s*?=|OptionKey\s*?=|DependsOnKeys\s*?=)'
keywords: set[str] = cast(TFormatting, self.item_type()).serializable_field_names()
pattern: str = rf'{self.ini_separator}\s*?(?=' + r'|'.join(re.escape(keyword) + r'\s*?=' for keyword in keywords) + r')'
for i, item in enumerate[str](items):
# then pull the separated into a list
new_item = cast(TFormatting, self.item_type()).set_from_ini(re.split(pattern, item))
if new_item.is_empty():
continue
self.items.append(new_item)
return self
@dataclass
class DictValue(ListValue[TValue]):
ini_separator: str = field(default='\n', repr=False)
item_type: type[TValue] | type[None] = type(None)
items: list[TValue] = field(default_factory=list[TValue])
@override
def __init__(self, item_type: type[TValue]) -> None:
super().__init__(item_type)
self.item_type = item_type
self.items = []
return
@override
def as_ini(self, formatted: bool = True, pretty: bool = False) -> str:
# return as key = value
items: list[str] = []
for item in self.items:
items.append(item.as_ini(formatted))
return self.ini_separator.join(items)
@override
def set_from_ini(self, ini: str | list[str]) -> Self:
# cannot map raw value into items
if self.item_type == type(None):
return self
_ = self.reset_items()
# parse ini input and append to items
lines: list[str] = ini if isinstance(ini, list) else ini.split(self.ini_separator)
for line in lines:
if not is_valid_ini_line(line):
continue
new_item = self.item_type()
if isinstance(new_item, IFormatting):
new_item = new_item.set_from_ini(line)
if new_item.is_empty():
continue
self.items.append(new_item)
return self
@override
def jsonable(self) -> dict[str, JsonValue]:
result: dict[str, JsonValue] = {}
for item in self.items:
if item.is_empty():
continue
if isinstance(item, ListValue):
result[item.key] = item.jsonable()
else:
result[item.key] = item.value
return result
@dataclass
class MultiListValue(ListValue[PathValue]):
friendly_key: str = field(default='')
comment: str = field(default='')
item_type: type[PathValue] | type[None] = PathValue
items: list[PathValue] = field(default_factory=list)
@override
def __init__(self) -> None:
super().__init__(PathValue)
self.items = []
@override
def as_ini(self, formatted: bool = True, pretty: bool = False) -> str:
# return as key = value
items: list[str] = []
for item in self.items:
# kinda hacky but the RawValue list format returns the items as 1 = files, 2 = files, etc
result = item.as_ini(formatted)
items.append(result)
line_key = f'{self.key} = ' if formatted else f'{self.key}='
line_items: str = line_key + self.ini_separator.join(items)
line_data: str = ''
if self.friendly_key:
line_key = '; ' + line_key if formatted else ';' + line_key
line_friendly: str = f'{self.friendly_key}'
line_comment: str = ''
if self.comment:
line_comment = f' ; {self.comment}' if formatted else f';{self.comment}'
line_data = f'{line_key}{line_friendly}{line_comment}'
if line_data:
return f'{line_items}\n{line_data}'
return line_items
@override
def set_from_ini(self, ini: str | list[str]) -> Self:
# parse incoming list as normal list
_ = super().set_from_ini(ini)
return self
def set_data_from_ini(self, ini_line: str) -> Self:
ini_line = ini_line.strip()
# the first portion of data line is a friendly key value and second, if present, is a comment string
# ensure that last item is either comment or empty:
# split(';', 1) max 2 parts, add empty string to the end, take first 2 elements back
friendly_key, comment = (ini_line.split(';', 1) + [''])[:2]
friendly_key = friendly_key.strip()
comment = comment.strip()
# set comment
self.comment = comment if comment else ''
# parse ID:
ms_id: int = -1
match = re.search(r'multilist([0-9]+)', self.key)
if match:
ms_id = int(match.group(1))
# set friendly_key
if friendly_key:
self.friendly_key = friendly_key
multilist_key_map.set_id(ms_id, self.friendly_key)
else:
self.friendly_key = ''
return self
@override
def jsonable(self) -> dict[str, JsonValue]:
items: list[JsonValue] = []
for item in self.items:
if item.is_empty():
continue
jsonable: JsonValue = item.jsonable()
items.append(jsonable)
result: dict[str, JsonValue] = {
'friendly_key': self.friendly_key,
'comment': self.comment,
'items': items
}
return result
@override
def set_from_json(self, json_data: JsonValue) -> Self:
# can only handle dicts
if not isinstance(json_data, dict):
return self
if len(json_data) != 1:
raise ValueError('Cannot create MultilistValue from JSON data containing more items than one.')
# key must begin with "multilist"
key: str = next(iter(json_data.keys()), '')
if not key.startswith('multilist'):
raise ValueError(f"Cannot create MultilistValue from JSON data that are not marked with multilist key, expected: 'multilistID', received: {key}")
# parse ID:
ms_id: int = -1
match = re.search(r'multilist([0-9]+)', key)
if match:
ms_id = int(match.group(1))
if isinstance(json_data[key], dict):
self.key: str = key
data = json_data[key]
if isinstance(data, dict):
# data must have 'items' present
if not 'items' in data.keys():
return self
if not isinstance(data['items'], list):
return self
# all is ok, use ListValue parser to process items:
self.value: str = codecs.decode(str(data['items']), 'unicode_escape')
_ = super().set_from_json(data['items'])
# set extra data:
if 'friendly_key' in data.keys():
self.friendly_key = str(data['friendly_key'])
multilist_key_map.set_id(ms_id, self.friendly_key)
if 'comment' in data.keys():
self.comment = str(data['comment'])
return self
# =============================================================================
#
# DATA STRUCTURES
# - IFormattingDict
# - ITaggedDict (IFormattingDict)
# - ModManager (ITaggedDict)
# - ModInfo (ITaggedDict)
# - Updates (ITaggedDict)
# - AltDLC (IFormattingDict)
# - CustomDlc (ITaggedDict)
#
# =============================================================================
@dataclass
class IFormattingDict(IFormatting, ABC):
ini_separator: str = field(default='\n', repr=False)
@override
def is_empty(self) -> bool:
for attr in self.serializable_fields().values():
if not attr.is_empty():
return False
return True
@override
def reset_value(self) -> None:
for attr in self.serializable_fields().values():
attr.reset_value()
@override
def as_ini(self, formatted: bool = True, pretty: bool = False) -> str:
if self.is_empty():
return ""
result: list[str] = []
for attr in self.serializable_fields().values():
if attr.is_empty():
continue
result.append(attr.as_ini(formatted))
return self.ini_separator.join(result)
@override
def set_from_ini(self, ini: str | list[str]) -> Self:
# dict ini values are separated by newlines
# the resulting RawValue key needs to represent a field on the dict
# or it will not be accessible and falls thru
self.reset_value()
lines: list[str] = []
if isinstance(ini, str):
ini = ini.strip()
lines = ini.split(self.ini_separator)
else:
lines = ini
for line in lines:
if not is_valid_ini_line(line):
continue
temp: RawValue = RawValue().set_from_ini(line)
# parse successful
if not temp.is_empty():
field: IFormatting | None = self.get_field(temp.key)
if isinstance(field, IFormatting):
# dict keys are set during init so it just needs new data
_ = field.set_from_ini(line)
return self
@override
def jsonable(self) -> dict[str, JsonValue]:
result: dict[str, JsonValue] = {}
for name, field in self.serializable_fields().items():
if field.is_empty():
continue
result[name] = field.jsonable()
return result
@override
def set_from_json(self, json_data: JsonValue) -> Self:
if not json_data:
return self
if not isinstance(json_data, dict):
return self
for key, value in json_data.items():
attr: IFormatting | None = self.get_field(key)
if isinstance(attr, IFormatting):
_ = attr.set_from_json({key: value})
return self
@dataclass
class ITaggedDict(IFormattingDict, ABC):