Skip to content

Commit 1964e78

Browse files
committed
Remove InvokeOnJsonNbt and other mecha rules
1 parent 6f46a1a commit 1964e78

File tree

3 files changed

+6
-143
lines changed

3 files changed

+6
-143
lines changed

gm4/plugins/player_heads.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,6 @@
2424
from nbtlib import String # type: ignore
2525
from PIL.Image import Image
2626

27-
from gm4.utils import InvokeOnJsonNbt
28-
2927
parent_logger = logging.getLogger("gm4.player_heads")
3028

3129
USER_AGENT = "Gamemode4Dev/GM4_Datapacks/player_head_management (gamemode4official@gmail.com)"
@@ -50,7 +48,7 @@ class Skin(PngFile):
5048
image: ClassVar[FileDeserialize[Image]] = FileDeserialize() # purely here to solve type-warnings on PIL images
5149

5250

53-
class SkinNbtTransformer(MutatingReducer, InvokeOnJsonNbt):
51+
class SkinNbtTransformer(MutatingReducer):
5452
"""Reducer class defining custom mecha parsing rules for skin texture data, and storing needed data for those operations"""
5553
def __init__(self, ctx: Context):
5654
self.ctx: Context = ctx

gm4/plugins/resource_pack.py

Lines changed: 1 addition & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -25,24 +25,10 @@
2525
from beet.contrib.vanilla import Vanilla, ClientJar
2626
from beet.core.utils import format_validation_error
2727
from mecha import (
28-
AstCommand,
29-
AstItemComponent,
30-
AstItemPredicateTestComponent,
31-
AstJson,
3228
AstJsonObject,
33-
AstJsonObjectEntry,
34-
AstJsonObjectKey,
3529
AstNbtCompound,
36-
AstNbtCompoundEntry,
37-
AstNbtCompoundKey,
38-
AstNbtPath,
39-
AstNbtPathKey,
40-
AstNbtValue,
4130
Diagnostic,
42-
DiagnosticCollection,
43-
DiagnosticError,
4431
Mecha,
45-
MutatingReducer,
4632
Reducer,
4733
rule,
4834
)
@@ -51,10 +37,8 @@
5137
from tokenstream import set_location
5238

5339
from gm4.utils import (
54-
InvokeOnJsonNbt,
5540
MapOption,
5641
add_namespace,
57-
propagate_location,
5842
)
5943

6044
JsonType = dict[str,Any]
@@ -295,7 +279,6 @@ def beet_default(ctx: Context):
295279
tl = ctx.inject(TranslationLinter)
296280
ctx.require("mecha.contrib.json_files")
297281
# mecha register
298-
ctx.inject(Mecha).transform.extend(rp)
299282
ctx.inject(Mecha).lint.extend(tl)
300283

301284
logging.getLogger("beet.contrib.babelbox").addFilter(block_incomplete_translation)
@@ -358,7 +341,7 @@ def link_resource_pack(ctx: Context):
358341

359342
lm.data_pack = dp_dir # restore the DP link
360343

361-
class GM4ResourcePack(MutatingReducer, InvokeOnJsonNbt):
344+
class GM4ResourcePack:
362345
"""Service Object handling custom_model_data and generated item models"""
363346

364347
def __init__(self, ctx: Context):
@@ -420,42 +403,6 @@ def generate_item_definitions(self):
420403

421404
self.ctx.assets.item_models[f"minecraft:{item_id}"] = ItemModel(new_itemdef)
422405

423-
424-
#== Mecha Transformer Rules ==#
425-
@rule(AstJsonObjectEntry, key=AstJsonObjectKey(value="minecraft:custom_model_data"))
426-
def json_substitutions(self, node: AstJsonObjectEntry, **kwargs: Any):
427-
# TODO: validate custom model data strings
428-
return node
429-
430-
@rule(AstJsonObject)
431-
def json_substitutions_item_modifier(self, node: AstJsonObject, **kwargs: Any):
432-
# TODO: validate custom model data strings
433-
return node
434-
435-
@rule(AstNbtCompoundEntry, key=AstNbtCompoundKey(value="minecraft:custom_model_data"))
436-
def cmd_substitutions_nbt(self, node: AstNbtCompoundEntry, **kwargs: Any):
437-
# TODO: validate custom model data strings
438-
return node
439-
440-
@rule(AstItemComponent)
441-
@rule(AstItemPredicateTestComponent)
442-
def cmd_substitutions_component(self, node: AstItemComponent | AstItemPredicateTestComponent, **kwargs: Any):
443-
# TODO: validate custom model data strings
444-
return node
445-
446-
@rule(AstCommand, identifier="data:modify:storage:target:targetPath:set:value:value")
447-
@rule(AstCommand, identifier="data:modify:block:targetPos:targetPath:set:value:value")
448-
@rule(AstCommand, identifier="data:modify:entity:target:targetPath:set:value:value")
449-
def cmd_substitutions_datamodify(self, node: AstCommand):
450-
_ast_target, ast_target_path, ast_nbt = node.arguments
451-
match ast_target_path, ast_nbt:
452-
case AstNbtPath(components=[*_, AstNbtPathKey(value="minecraft:custom_model_data")]), AstNbtValue(value=String(_reference)):
453-
pass # TODO: validate custom model data strings
454-
case _:
455-
pass
456-
return node
457-
458-
459406
#== Model file generation ==#
460407
def generate_model_files(self):
461408
"""Create individual models for each item/block according to its config"""
@@ -521,19 +468,6 @@ def __init__(self, ctx: Context):
521468
self.ignored_keys: set[str] = set(ctx.validate("gm4", TranslationLinterOptions).translation_linter_ignores)
522469
super().__init__()
523470

524-
@rule(AstNbtValue)
525-
def check_nbt_json(self, node: AstNbtValue):
526-
mc = self.ctx.inject(Mecha)
527-
if isinstance(node.value, (String, str)):
528-
try:
529-
json_ast = mc.parse(node.value, type=AstJson)
530-
with self.use_diagnostics(collec:=DiagnosticCollection()):
531-
self.invoke(json_ast) # process new node with reducer rules
532-
for exc in collec.exceptions:
533-
yield propagate_location(exc, node)
534-
except DiagnosticError:
535-
pass # string is not json
536-
537471
@rule(AstNbtCompound)
538472
@rule(AstJsonObject)
539473
def missing_en_us_translations(self, node: Union[AstNbtCompound, AstJsonObject]):

gm4/utils.py

Lines changed: 4 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,11 @@
11
import subprocess
22
import warnings
3-
from contextlib import contextmanager
4-
from dataclasses import asdict, dataclass, replace
3+
from dataclasses import asdict, dataclass
54
from functools import total_ordering
6-
from typing import Any, Generic, Iterator, List, TypeVar
7-
8-
from beet import Advancement, Context, ItemModifier, ListOption, LootTable, Predicate
9-
from mecha import (
10-
AbstractNode,
11-
AstJsonObjectEntry,
12-
AstJsonObjectKey,
13-
AstJsonValue,
14-
AstNbtCompound,
15-
DiagnosticCollection,
16-
DiagnosticError,
17-
Mecha,
18-
rule,
19-
)
5+
from typing import Any, Generic, List, TypeVar
6+
7+
from beet import ListOption
208
from pydantic import RootModel, field_validator
21-
from tokenstream import SourceLocation, set_location
229

2310
T = TypeVar('T')
2411
import csv
@@ -142,62 +129,6 @@ def validate_root(cls, value: list[T]|dict[str,T]|T) -> list[T]|dict[str,T]:
142129
value = [value]
143130
return value # type: ignore
144131

145-
# TODO 1.20.5: might not need this anymore
146-
class InvokeOnJsonNbt:
147-
"""Extendable mixin to run MutatingReducer's rules on nbt within advancements, loot_tables ect..."""
148-
def __init__(self, ctx: Context):
149-
self.ctx = ctx
150-
raise RuntimeError("InvokeOnJsonNbt should not be directly instantiated. It is a mixin for MutatingReducers and should be interited instead")
151-
152-
@contextmanager
153-
def use_diagnostics(self, diagnostics: DiagnosticCollection) -> Iterator[None]:
154-
"""Class is mixed into MutatingReducer, who does have this method. Passed here for type completion"""
155-
raise NotImplementedError()
156-
157-
def invoke(self, node: AbstractNode, *args: Any, **kwargs: Any) -> Any:
158-
"""Class is mixed into MutatingReducer, who does have this method. Passed here for type completion"""
159-
raise NotImplementedError()
160-
161-
162-
@rule(AstJsonObjectEntry, key=AstJsonObjectKey(value='nbt'))
163-
@rule(AstJsonObjectEntry, key=AstJsonObjectKey(value='tag'))
164-
def process_nbt_in_json(self, node: AstJsonObjectEntry):
165-
mc = self.ctx.inject(Mecha)
166-
if isinstance(mc.database.current, (Advancement, LootTable, ItemModifier, Predicate)):
167-
if isinstance(node.value, AstJsonValue) and isinstance(node.value.value, str) \
168-
and node.value.value.startswith("{") and node.value.value.endswith("}"): # excludes location check block/fluid tags - easier than making rule that checks for 'set_nbt' functions on the same json level
169-
try:
170-
nbt = mc.parse(node.value.value.replace("\n", "\\\\n"), type=AstNbtCompound)
171-
except DiagnosticError as exc:
172-
# if parsing failed, give pretty traceback
173-
for d in exc.diagnostics.exceptions:
174-
yield set_location(replace(d, file=mc.database.current), node.value)
175-
return replace(node, value="{}")
176-
177-
## TEMP - trial on yielding children rather than using invoke
178-
# with self.use_diagnostics(captured_diagnostics:=DiagnosticCollection()):
179-
# nbt = yield nbt # run all rules on child-node
180-
# print(captured_diagnostics.exceptions)
181-
# print(nbt)
182-
# new_node = replace(node, value=AstJsonValue(value=mc.serialize(nbt, type=AstNbtCompound)))
183-
184-
with self.use_diagnostics(captured_diagnostics:=DiagnosticCollection()):
185-
processed_nbt = mc.serialize(self.invoke(nbt, type=AstNbtCompound))
186-
for exc in captured_diagnostics.exceptions:
187-
yield propagate_location(exc, node.value) # set error location to nbt key-value that caused the problem and pass diagnostic back to mecha
188-
189-
new_node = replace(node, value=AstJsonValue(value=processed_nbt))
190-
if new_node != node:
191-
return new_node
192-
193-
return node
194-
195-
def propagate_location(obj: T, parent_location_obj: Any) -> T:
196-
"""a set_location like function propagating diagnostic information for manually invoked rules"""
197-
return set_location(obj,
198-
SourceLocation(pos=parent_location_obj.location.pos+obj.location.pos, lineno=parent_location_obj.location.lineno, colno=parent_location_obj.location.colno+obj.location.colno), # type: ignore
199-
SourceLocation(pos=parent_location_obj.location.pos+obj.end_location.pos, lineno=parent_location_obj.location.lineno, colno=parent_location_obj.location.colno+obj.end_location.colno) # type: ignore
200-
)
201132

202133
# CSV READING UTILS
203134
class CSVCell(str):

0 commit comments

Comments
 (0)