pz-scripts-data 1.3.1__tar.gz → 1.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. {pz_scripts_data-1.3.1/src/pz_scripts_data.egg-info → pz_scripts_data-1.4.0}/PKG-INFO +3 -1
  2. {pz_scripts_data-1.3.1 → pz_scripts_data-1.4.0}/pyproject.toml +10 -2
  3. pz_scripts_data-1.4.0/src/pz_scripts_data/__init__.py +187 -0
  4. {pz_scripts_data-1.3.1 → pz_scripts_data-1.4.0}/src/pz_scripts_data/formatBlocks.py +92 -50
  5. pz_scripts_data-1.4.0/src/pz_scripts_data/patches/item_split.py +116 -0
  6. pz_scripts_data-1.4.0/src/pz_scripts_data/release.py +235 -0
  7. pz_scripts_data-1.4.0/src/pz_scripts_data/schema.py +736 -0
  8. pz_scripts_data-1.4.0/src/pz_scripts_data/tests/test_data.py +205 -0
  9. pz_scripts_data-1.4.0/src/pz_scripts_data/tests/test_release.py +226 -0
  10. pz_scripts_data-1.4.0/src/pz_scripts_data/tests/test_version.py +140 -0
  11. {pz_scripts_data-1.3.1 → pz_scripts_data-1.4.0/src/pz_scripts_data.egg-info}/PKG-INFO +3 -1
  12. {pz_scripts_data-1.3.1 → pz_scripts_data-1.4.0}/src/pz_scripts_data.egg-info/SOURCES.txt +6 -2
  13. pz_scripts_data-1.4.0/src/pz_scripts_data.egg-info/entry_points.txt +2 -0
  14. pz_scripts_data-1.4.0/src/pz_scripts_data.egg-info/requires.txt +5 -0
  15. pz_scripts_data-1.3.1/src/pz_scripts_data/release.py +0 -150
  16. pz_scripts_data-1.3.1/src/pz_scripts_data/schema.py +0 -556
  17. pz_scripts_data-1.3.1/src/pz_scripts_data/validateBlocks.py +0 -139
  18. pz_scripts_data-1.3.1/src/pz_scripts_data.egg-info/entry_points.txt +0 -2
  19. pz_scripts_data-1.3.1/src/pz_scripts_data.egg-info/requires.txt +0 -3
  20. {pz_scripts_data-1.3.1 → pz_scripts_data-1.4.0}/LICENSE +0 -0
  21. {pz_scripts_data-1.3.1 → pz_scripts_data-1.4.0}/README.md +0 -0
  22. {pz_scripts_data-1.3.1 → pz_scripts_data-1.4.0}/setup.cfg +0 -0
  23. {pz_scripts_data-1.3.1 → pz_scripts_data-1.4.0}/src/pz_scripts_data/blocks.py +0 -0
  24. {pz_scripts_data-1.3.1 → pz_scripts_data-1.4.0}/src/pz_scripts_data/py.typed +0 -0
  25. {pz_scripts_data-1.3.1 → pz_scripts_data-1.4.0}/src/pz_scripts_data/sortItemParameters.py +0 -0
  26. {pz_scripts_data-1.3.1 → pz_scripts_data-1.4.0}/src/pz_scripts_data.egg-info/dependency_links.txt +0 -0
  27. {pz_scripts_data-1.3.1 → pz_scripts_data-1.4.0}/src/pz_scripts_data.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pz-scripts-data
3
- Version: 1.3.1
3
+ Version: 1.4.0
4
4
  Summary: Dataset for the Scripts of Project Zomboid.
5
5
  Author: SimKDT
6
6
  License-Expression: MIT
@@ -16,6 +16,8 @@ License-File: LICENSE
16
16
  Requires-Dist: pyyaml
17
17
  Requires-Dist: jsonschema
18
18
  Requires-Dist: pydantic>=2.11
19
+ Requires-Dist: typed-argparse>=0.3.1
20
+ Requires-Dist: deprecated>=3.0.1
19
21
  Dynamic: license-file
20
22
 
21
23
  # PZ Scripts Data
@@ -3,7 +3,7 @@ name = "pz-scripts-data"
3
3
  description = "Dataset for the Scripts of Project Zomboid."
4
4
  readme = { file = "README.md", content-type = "text/markdown" }
5
5
  requires-python = ">=3.12.3"
6
- version = "1.3.1"
6
+ version = "1.4.0"
7
7
  license = "MIT"
8
8
  authors = [
9
9
  { name = "SimKDT" },
@@ -12,6 +12,8 @@ dependencies = [
12
12
  "pyyaml",
13
13
  "jsonschema",
14
14
  "pydantic>=2.11",
15
+ "typed-argparse>=0.3.1",
16
+ "deprecated>=3.0.1",
15
17
  ]
16
18
  classifiers = [
17
19
  "Programming Language :: Python :: 3.12",
@@ -23,7 +25,7 @@ classifiers = [
23
25
  ]
24
26
 
25
27
  [project.scripts]
26
- release = "pz_scripts_data.release:main"
28
+ pz_scripts_data = "pz_scripts_data.release:main"
27
29
 
28
30
  [tool.uv]
29
31
  package = true
@@ -32,3 +34,9 @@ package = true
32
34
  pz_scripts_data = [
33
35
  "py.typed"
34
36
  ]
37
+
38
+ [dependency-groups]
39
+ dev = [
40
+ "pytest>=9.2.0",
41
+ "ruamel-yaml>=0.19.1",
42
+ ]
@@ -0,0 +1,187 @@
1
+ import json
2
+ import datetime
3
+ from typing import Any, TypeVar, Generic
4
+ from pathlib import Path
5
+ from pydantic import BaseModel, GetCoreSchemaHandler, GetJsonSchemaHandler
6
+ from pydantic_core import core_schema
7
+ from pydantic.json_schema import JsonSchemaValue
8
+
9
+ WORKSPACE = Path(__file__).parent.parent.parent
10
+ MANIFEST_FILE = WORKSPACE / "manifest.json"
11
+
12
+
13
+ P = TypeVar("P", bound=tuple[int, ...])
14
+
15
+ class BaseVersion(Generic[P]):
16
+ pattern: str
17
+ def __init__(self, *args: int):
18
+ self._parts: P = args # type: ignore - due to generic tuple type not being passable to __init__ directly
19
+
20
+ def __str__(self) -> str:
21
+ return ".".join(map(str, self._key()))
22
+
23
+ def _key(self) -> P:
24
+ return self._parts
25
+
26
+ def __repr__(self) -> str:
27
+ return f"{type(self).__name__}({str(self)})"
28
+
29
+ def __eq__(self, other: object) -> bool:
30
+ if not isinstance(other, BaseVersion): return NotImplemented
31
+ return self._key() == other._key()
32
+
33
+ def __lt__(self, other: object) -> bool:
34
+ if not isinstance(other, BaseVersion): return NotImplemented
35
+ return self._key() < other._key()
36
+
37
+ def __le__(self, other: object) -> bool:
38
+ if not isinstance(other, BaseVersion): return NotImplemented
39
+ return self._key() <= other._key()
40
+
41
+ def __gt__(self, other: object) -> bool:
42
+ if not isinstance(other, BaseVersion): return NotImplemented
43
+ return self._key() > other._key()
44
+
45
+ def __ge__(self, other: object) -> bool:
46
+ if not isinstance(other, BaseVersion): return NotImplemented
47
+ return self._key() >= other._key()
48
+
49
+ def __hash__(self) -> int:
50
+ return hash((type(self), str(self)))
51
+
52
+ @classmethod
53
+ def from_string(cls, version: str) -> 'BaseVersion':
54
+ raise NotImplemented
55
+
56
+ @classmethod
57
+ def __get_pydantic_core_schema__(cls, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
58
+ return core_schema.no_info_plain_validator_function(
59
+ lambda v: v if isinstance(v, cls) else cls.from_string(str(v)),
60
+ serialization=core_schema.plain_serializer_function_ser_schema(str),
61
+ )
62
+
63
+ @classmethod
64
+ def __get_pydantic_json_schema__(cls, schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler) -> JsonSchemaValue:
65
+ return {"type": "string", "pattern": cls.pattern}
66
+
67
+
68
+
69
+ class BuildVersion(BaseVersion[tuple[int, int, int]]):
70
+ pattern: str = r"^\d+\.\d+\.\d+$"
71
+ def __init__(self, major: int, minor: int, patch: int):
72
+ super().__init__(major, minor, patch)
73
+ self.major = major
74
+ self.minor = minor
75
+ self.patch = patch
76
+
77
+ @staticmethod
78
+ def assert_release_number(version: 'str | BuildVersion') -> tuple[int, int, int]:
79
+ splitted = str(version).split('.')
80
+ if len(splitted) != 3:
81
+ raise ValueError("Invalid build version format. Expected format: 'major.minor.patch'")
82
+ try:
83
+ major, minor, patch = [int(x) for x in splitted]
84
+ except ValueError:
85
+ raise ValueError("Invalid build version format. Expected format: 'major.minor.patch' with integers")
86
+ except Exception as e:
87
+ raise ValueError(f"Error parsing build version: {e}")
88
+ return major, minor, patch
89
+
90
+ @classmethod
91
+ def from_string(cls, version: str) -> 'BuildVersion':
92
+ major, minor, patch = cls.assert_release_number(version)
93
+ return cls(major, minor, patch)
94
+
95
+ def to_release_version(self, release_version: int) -> 'ReleaseVersion':
96
+ """Convert the current build version to a release version
97
+ with the specified release version number."""
98
+ return ReleaseVersion(self.major, self.minor, self.patch, release_version)
99
+
100
+ class ReleaseVersion(BaseVersion[tuple[int, int, int, int]]):
101
+ pattern: str = r"^\d+\.\d+\.\d+\.\d+$"
102
+ def __init__(self, major: int, minor: int, patch: int, release_version: int):
103
+ super().__init__(major, minor, patch, release_version)
104
+ self.major: int = major
105
+ self.minor: int = minor
106
+ self.patch: int = patch
107
+ self.release_version: int = release_version
108
+
109
+ def _key(self) -> tuple[int, int, int, int]:
110
+ return super()._key()
111
+
112
+ @staticmethod
113
+ def assert_release_with_version(version: 'str | ReleaseVersion') -> tuple[int, int, int, int]:
114
+ splitted = str(version).split('.')
115
+ if len(splitted) != 4:
116
+ raise ValueError("Invalid release version format. Expected format: 'major.minor.patch.version'")
117
+ try:
118
+ major, minor, patch, release_version = [int(x) for x in splitted]
119
+ except ValueError:
120
+ raise ValueError("Invalid release version format. Expected format: 'major.minor.patch.version' with integers")
121
+ except Exception as e:
122
+ raise ValueError(f"Error parsing release version: {e}")
123
+ return major, minor, patch, release_version
124
+
125
+ @classmethod
126
+ def from_string(cls, version: str) -> 'ReleaseVersion':
127
+ major, minor, patch, release_version = cls.assert_release_with_version(version)
128
+ return cls(major, minor, patch, release_version)
129
+
130
+ def to_build_version(self) -> 'BuildVersion':
131
+ """Convert the current release version to a build version
132
+ by discarding the release version number."""
133
+ return BuildVersion(self.major, self.minor, self.patch)
134
+
135
+
136
+
137
+
138
+ class Release(BaseModel):
139
+ version: int
140
+ date: datetime.datetime
141
+
142
+ class Manifest(BaseModel):
143
+ latest_build: BuildVersion
144
+ stable: ReleaseVersion
145
+ releases: dict[BuildVersion, Release]
146
+
147
+ @classmethod
148
+ def load_manifest(cls) -> "Manifest":
149
+ assert MANIFEST_FILE.exists(), f"Manifest file not found at {MANIFEST_FILE}"
150
+ return Manifest.model_validate(json.loads(MANIFEST_FILE.read_text()))
151
+
152
+ def make_releases_list(self) -> list[str]:
153
+ """Retrieve a sorted list of all release versions as strings."""
154
+ releases_list: list[str] = []
155
+ for build, release in self.releases.items():
156
+ for v in range(release.version+1):
157
+ releases_list.append(str(build.to_release_version(v)))
158
+ return sorted(releases_list)
159
+
160
+ def get_latest_release(self) -> ReleaseVersion:
161
+ releases_list = self.make_releases_list()
162
+ if len(releases_list) == 0:
163
+ raise ValueError("No releases found in the manifest")
164
+ latest_release_str = releases_list[-1]
165
+ return ReleaseVersion.from_string(latest_release_str)
166
+
167
+ def get_latest_build(self) -> BuildVersion:
168
+ return self.latest_build
169
+
170
+ def get_releases(self) -> dict[BuildVersion, Release]:
171
+ return self.releases
172
+
173
+ def assert_release_exists(self, release_version: 'str | ReleaseVersion') -> None:
174
+ release_version_str = str(release_version)
175
+ releases_list = self.make_releases_list()
176
+ if release_version_str not in releases_list:
177
+ raise ValueError(f"Release version {release_version_str} not found in the manifest")
178
+
179
+ def write(self, path: Path | str) -> None:
180
+ path = Path(path)
181
+ path.write_text(self.model_dump_json(indent=4))
182
+
183
+ if __name__ == "__main__":
184
+ build1 = BuildVersion.from_string("42.22.2")
185
+ build2 = BuildVersion.from_string("42.22.2")
186
+
187
+ assert build1 == build2, "Build versions should be equal"
@@ -1,37 +1,13 @@
1
1
  import json
2
+ import copy
2
3
  from pathlib import Path
3
4
  from typing import Any, Literal, Optional, TypedDict
4
5
 
5
6
  import yaml
6
- from pydantic import BaseModel, Field, ValidationError, model_validator
7
+ from pydantic import BaseModel, ValidationError
7
8
 
8
9
  from pz_scripts_data.blocks import PropertyData
9
- from pz_scripts_data.schema import BlockDefinition, ParameterDefinition
10
-
11
-
12
- class ScriptsBlock(BlockDefinition):
13
- """Block used by the pipeline: parameters are keyed by lowercase name and relations are filled in during preparation."""
14
-
15
- parameters: dict[str, ParameterDefinition] = Field(default_factory=dict) # type: ignore
16
- children: list[str] | None = None
17
- variants: list[str] | None = None
18
-
19
- @model_validator(mode="before")
20
- @classmethod
21
- def _key_parameters_by_name(cls, data: Any) -> Any:
22
- if not isinstance(data, dict):
23
- return data
24
- parameters = data.get("parameters", [])
25
- if not isinstance(parameters, list):
26
- return data
27
-
28
- keyed: dict[str, Any] = {}
29
- for param in parameters:
30
- name = param.get("name") if isinstance(param, dict) else None
31
- if not isinstance(name, str):
32
- raise ValueError("every parameter must have a 'name' to be referenced")
33
- keyed[name.lower()] = param
34
- return {**data, "parameters": keyed}
10
+ from pz_scripts_data.schema import ScriptsBlocksFile, ScriptsBlock, ParameterDefinition
35
11
 
36
12
 
37
13
  class Item(TypedDict):
@@ -59,19 +35,21 @@ items: list[Item] = [
59
35
 
60
36
  ## PROCESS ITEM
61
37
 
62
- def fetchBlocks(item: Item):
38
+ def fetchBlocks(input: Path) -> dict[str, ScriptsBlock]:
63
39
  # combine all block yaml files into one, validating each against the schema
64
40
  blocks: dict[str, ScriptsBlock] = {}
65
- for file_path in sorted(item['input'].glob("*.yaml")):
41
+ for file_path in sorted(input.glob("*.yaml")):
66
42
  with open(file_path, 'r', encoding='utf-8') as f:
67
43
  data = yaml.safe_load(f)
44
+ def_id = file_path.stem.lower()
45
+ data['def_id'] = def_id
68
46
  try:
69
47
  block = ScriptsBlock.model_validate(data)
70
48
  except ValidationError as exc:
71
49
  raise ValueError(f"Invalid block definition in '{file_path}':\n{exc}") from exc
72
- if block.name.lower() in blocks:
73
- raise ValueError(f"Duplicate block name '{block.name}' found in '{file_path}'.")
74
- blocks[block.name.lower()] = block
50
+ if def_id in blocks and block.variant is None:
51
+ raise ValueError(f"Duplicate block name '{def_id}' found in '{file_path}'. Only variant duplicates are allowed.")
52
+ blocks[def_id] = block
75
53
  return blocks
76
54
 
77
55
  def process_properties(block: ScriptsBlock) -> ScriptsBlock:
@@ -85,8 +63,8 @@ def process_properties(block: ScriptsBlock) -> ScriptsBlock:
85
63
 
86
64
  # main
87
65
 
88
- def process(item: Item):
89
- blocks = fetchBlocks(item)
66
+ def process(item: Item) -> dict[str, ScriptsBlock]:
67
+ blocks = fetchBlocks(item['input'])
90
68
  for block in blocks.values():
91
69
  process_properties(block)
92
70
 
@@ -102,7 +80,7 @@ def add_source_ref_to_targets(
102
80
  source_name: str,
103
81
  targets_names: list[str],
104
82
  items: list[Item],
105
- array_type: Literal["children", "variants"]):
83
+ array_type: Literal["children", "variants"]) -> None:
106
84
  """
107
85
  This is used to add source_name to the targets's array_type.
108
86
 
@@ -113,10 +91,12 @@ def add_source_ref_to_targets(
113
91
  will add source_name in the array stored at key array_type of the targets of targets_names.
114
92
  (child_name --append--> array (key: children) of each parents)
115
93
  """
94
+ # print(source_name, targets_names, array_type)
116
95
  _processed: list[str] = []
117
96
  for item in items:
118
97
  blocks = item['data']
119
98
  assert blocks is not None, "Something went wrong."
99
+ # print(blocks.keys())
120
100
 
121
101
  # add children_name ref to every parents
122
102
  for parent_name in targets_names:
@@ -130,17 +110,31 @@ def add_source_ref_to_targets(
130
110
 
131
111
  # add name
132
112
  children: list[str] = getattr(parent_block, array_type)
113
+ # print("\t", parent_name, children)
133
114
  if source_name not in children:
134
- children.append(source_name)
115
+ children.append(source_name.lower())
135
116
  _processed.append(parent_name)
136
117
 
137
118
  # we make sure they were all properly processed
138
- for parent_name in targets_names:
139
- if parent_name not in _processed:
140
- raise ValueError(f"Parent block '{parent_name}' not found for block '{source_name}'.")
119
+ # print("\t"*2, _processed)
120
+ if len(targets_names) != len(_processed):
121
+ missing = set(targets_names) - set(_processed)
122
+ raise ValueError(f"Some {array_type} blocks not found for block '{source_name}': {', '.join(missing)}")
141
123
 
124
+ def verify_parents(block: ScriptsBlock, items: list[Item]) -> None:
125
+ """
126
+ Verifies that all parents of the block exist in the items.
127
+ Raises a ValueError if any parent is missing.
128
+ """
129
+ if not block.parents:
130
+ return
142
131
 
143
- def prepare_relationship(block: ScriptsBlock, items: list[Item]):
132
+ for parent_name in block.parents:
133
+ parent_block = find_block_in_items(parent_name, items)
134
+ if parent_block is None:
135
+ raise ValueError(f"Parent block '{parent_name}' not found for block '{block.name}'.")
136
+
137
+ def prepare_relationship(block: ScriptsBlock, items: list[Item]) -> None:
144
138
  """
145
139
  This will retrieve the parents of this block and add a reference to itself inside the data,
146
140
  of this parent block
@@ -151,7 +145,7 @@ def prepare_relationship(block: ScriptsBlock, items: list[Item]):
151
145
  add_source_ref_to_targets(block.name, parents, items, "children")
152
146
 
153
147
  # handle variants
154
- variant = block.variant_of
148
+ variant = block.variant_of_deprecated
155
149
  if variant:
156
150
  add_source_ref_to_targets(block.name, [variant], items, "variants")
157
151
 
@@ -220,11 +214,11 @@ def get_source_parameter(ref_key: str, items: list[Item]) -> ParameterDefinition
220
214
  if origin_block_data is None:
221
215
  raise ValueError(f"Source block '{origin_block}' not found for parameter '{origin_param}'.")
222
216
  if origin_param not in origin_block_data.parameters:
223
- raise ValueError(f"Source block '{origin_block}' has no parameter '{origin_param}'.")
217
+ raise ValueError(f"Source block '{origin_block}' has no parameter '{origin_param}' ({ref_key}).")
224
218
 
225
219
  return origin_block_data.parameters[origin_param]
226
220
 
227
- def copy_parameters_ref(parameters: dict[str, ParameterDefinition], items: list[Item]):
221
+ def copy_parameters_ref(parameters: dict[str, ParameterDefinition], items: list[Item]) -> None:
228
222
  for param_key, param in parameters.items():
229
223
  if param.ref is not None:
230
224
  source_param = get_source_parameter(param.ref, items)
@@ -243,10 +237,47 @@ def copy_parameters_ref(parameters: dict[str, ParameterDefinition], items: list[
243
237
  # only copy the description
244
238
  param.description = source_param.description
245
239
 
240
+ def find_variants(blocks: dict[str, ScriptsBlock]) -> None:
241
+ # gather variants hierarchy
242
+ # key is source block id
243
+ # value is the block that's a variant
244
+ variants_hierarchy = {}
245
+ for block in blocks.values():
246
+ variant = block.variant
247
+ def_id = block.def_id
248
+ if variant is None:
249
+ continue
250
+ variants_hierarchy.setdefault(variant.source, []).append(def_id)
251
+
252
+ # copy parameters if needed
253
+ if variant.copy_source_parameters:
254
+ source_block = blocks.get(variant.source)
255
+ if source_block is None:
256
+ raise ValueError(f"Source block '{variant.source}' not found for variant '{def_id}'.")
257
+ # deep copy source params
258
+ source_params = copy.deepcopy(source_block.parameters)
259
+ for param in source_params.values():
260
+ param.is_from_variant = True
261
+
262
+ # update source parameters with the block's parameters
263
+ # to override any existing parameters with the block's parameters
264
+ block_params = block.parameters
265
+ for key, value in block_params.items():
266
+ source_params[key] = value
267
+ block.parameters = source_params
268
+
269
+ # assign variants to their source blocks
270
+ for source_id, variant_ids in variants_hierarchy.items():
271
+ source_block = blocks.get(source_id)
272
+ if source_block is None:
273
+ raise ValueError(f"Source block '{source_id}' not found for variants.")
274
+ if source_block.variants is None:
275
+ source_block.variants = []
276
+ source_block.variants.extend(variant_ids)
246
277
 
247
278
  # main
248
279
 
249
- def prepare(item: Item, items: list[Item]):
280
+ def prepare(item: Item, items: list[Item]) -> dict[str, ScriptsBlock]:
250
281
  blocks = item['data']
251
282
  assert blocks is not None, "Something went wrong."
252
283
 
@@ -255,6 +286,9 @@ def prepare(item: Item, items: list[Item]):
255
286
  copy_block_ref(block, items)
256
287
  copy_parameters_ref(block.parameters, items)
257
288
 
289
+ # find and assign variants to their source blocks
290
+ find_variants(blocks)
291
+
258
292
  # children and variants are appended in processing order, so sort them for stable output
259
293
  for block in blocks.values():
260
294
  if block.children:
@@ -270,10 +304,15 @@ def prepare(item: Item, items: list[Item]):
270
304
  def serialize(blocks: dict[str, ScriptsBlock]) -> dict[str, dict[str, Any]]:
271
305
  # only write the fields that were set, using their schema (alias) names
272
306
  # the version is only used for validation, so it is not written
273
- return {
274
- name: block.model_dump(by_alias=True, exclude_unset=True, exclude={"version"})
275
- for name, block in blocks.items()
276
- }
307
+ for block in blocks.values():
308
+ # Mark in-place list mutations as set after all relationship and ref processing.
309
+ if block.children:
310
+ block.children = block.children
311
+ if block.variants:
312
+ block.variants = block.variants
313
+ return ScriptsBlocksFile.model_validate(blocks).model_dump(
314
+ by_alias=True, exclude_unset=True, exclude={"__all__": {"version"}}
315
+ )
277
316
 
278
317
 
279
318
  def main():
@@ -286,8 +325,11 @@ def main():
286
325
  output_file.parent.mkdir(parents=True, exist_ok=True)
287
326
  with open(output_file, 'w', encoding='utf-8') as f:
288
327
  assert item['data'] is not None
289
- json.dump(serialize(item['data']), f, indent=2,
290
- ensure_ascii=False, sort_keys=True)
328
+ json.dump(
329
+ serialize(item['data']),
330
+ f, indent=2,
331
+ ensure_ascii=False, sort_keys=True
332
+ )
291
333
 
292
334
  if __name__ == "__main__":
293
335
  main()
@@ -0,0 +1,116 @@
1
+ import yaml
2
+ from pathlib import Path
3
+
4
+ from pz_scripts_data.schema import BlockDefinition, ParameterDefinition, VariantDefinition
5
+ from pz_scripts_data.formatBlocks import fetchBlocks, Item
6
+
7
+
8
+ class LiteralStr(str):
9
+ pass
10
+
11
+
12
+ # Custom representer to write multiline description strings in literal block style
13
+ def literal_str_representer(dumper, data):
14
+ return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')
15
+
16
+ yaml.add_representer(LiteralStr, literal_str_representer, Dumper=yaml.SafeDumper)
17
+
18
+
19
+ def mark_literal_descriptions(node, key=None):
20
+ # Representers only see values, so tag multiline "description" strings by their key
21
+ if isinstance(node, dict):
22
+ return {k: mark_literal_descriptions(v, k) for k, v in node.items()}
23
+ if isinstance(node, list):
24
+ return [mark_literal_descriptions(v, key) for v in node]
25
+ if key == "description" and isinstance(node, str):
26
+ return LiteralStr(node)
27
+ return node
28
+
29
+
30
+
31
+ def main() -> None:
32
+ BLOCKS_FOLDER = Path("data/blocks")
33
+ OUTPUT_FOLDER = Path("data/blocks_split")
34
+
35
+ blocks = fetchBlocks(BLOCKS_FOLDER)
36
+ OUTPUT_FOLDER.mkdir(parents=True, exist_ok=True)
37
+
38
+ item_types: dict[str, list[str]] = {}
39
+
40
+ item_block = blocks['item']
41
+ for param in item_block.parameters.values():
42
+ needs = param.needs
43
+ if needs is None:
44
+ continue
45
+ item_type_needs = None
46
+ for need in needs:
47
+ if need.parameter == "ItemType":
48
+ item_type_needs = need
49
+ break
50
+ if item_type_needs is None:
51
+ continue
52
+ print(param.name)
53
+ needs_values = item_type_needs.values
54
+ assert needs_values is not None
55
+ for value in needs_values:
56
+ assert type(value) is str
57
+ item_types.setdefault(value, []).append(param.name)
58
+
59
+ from pprint import pprint
60
+ pprint(item_types)
61
+
62
+ for key, value in item_types.items():
63
+ itemtype = key.split(":")[1]
64
+ export_path = OUTPUT_FOLDER / f"item_{itemtype}.yaml"
65
+
66
+ parameters: list[ParameterDefinition] = []
67
+ parameter_need = None
68
+ for param_name in value:
69
+ source_param = item_block.parameters[param_name.lower()].model_copy()
70
+ needs = source_param.needs
71
+ assert needs is not None
72
+
73
+ if parameter_need is None:
74
+ for need_source in needs:
75
+ need = need_source.model_copy()
76
+ if need.parameter != "ItemType":
77
+ continue
78
+ values = need.values
79
+ assert values is not None
80
+ print(key, need)
81
+
82
+ ok = False
83
+ for val in values:
84
+ if val == key:
85
+ ok = True
86
+ break
87
+ if not ok:
88
+ continue
89
+
90
+ need.values = [v for v in values if v == key]
91
+ parameter_need = need.model_copy()
92
+ break
93
+
94
+ parameters.append(source_param)
95
+
96
+ assert parameter_need is not None
97
+ block_def = BlockDefinition(
98
+ name=f'item',
99
+ parameters=parameters,
100
+ variant=VariantDefinition(
101
+ source="item",
102
+ needs=[parameter_need],
103
+ )
104
+ ) # pyright: ignore[reportCallIssue]
105
+
106
+ # write only the set fields, using their schema (alias) names, like formatBlocks.serialize
107
+ with open(export_path, "w", encoding="utf-8") as f:
108
+ yaml.safe_dump(
109
+ mark_literal_descriptions(block_def.model_dump(by_alias=True, exclude_unset=True)),
110
+ f,
111
+ sort_keys=False,
112
+ allow_unicode=True,
113
+ )
114
+
115
+ if __name__ == "__main__":
116
+ main()