scjson 0.1.0__py3-none-any.whl

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.

Potentially problematic release.


This version of scjson might be problematic. Click here for more details.

@@ -0,0 +1,142 @@
1
+ from typing import Optional, Type, Union, Any, get_args, get_origin
2
+ from enum import Enum
3
+ from decimal import Decimal
4
+ import xmlschema
5
+ import json
6
+ from dataclasses import asdict, fields, is_dataclass
7
+ from xsdata.formats.dataclass.serializers.config import SerializerConfig
8
+ from xsdata.formats.dataclass.parsers import XmlParser
9
+ from xsdata.formats.dataclass.serializers import XmlSerializer
10
+ from .dataclasses import Scxml as Scxml
11
+
12
+ class SCXMLDocumentHandler:
13
+ def __init__(
14
+ self,
15
+ model_class: Type = Scxml,
16
+ schema_path: Optional[str] = None,
17
+ pretty: bool = True,
18
+ omit_empty: bool = True,
19
+ ) -> None:
20
+ self.model_class = model_class
21
+ self.schema_path = schema_path
22
+ self.parser = XmlParser()
23
+ self.serializer = XmlSerializer(
24
+ config=SerializerConfig(
25
+ pretty_print=pretty, encoding="utf-8", xml_declaration=True
26
+ )
27
+ )
28
+ self.schema = xmlschema.XMLSchema(schema_path) if schema_path else None
29
+ self.omit_empty = omit_empty
30
+
31
+ def validate(self, xml_path: str) -> bool:
32
+ if not self.schema:
33
+ raise ValueError("No schema path provided for validation.")
34
+ return self.schema.is_valid(xml_path)
35
+
36
+ def load(self, xml_path: str):
37
+ with open(xml_path, "rb") as f:
38
+ return self.parser.from_bytes(f.read(), self.model_class)
39
+
40
+ def dump(self, instance, output_path: str):
41
+ xml_string = self.serializer.render(instance)
42
+ with open(output_path, "w", encoding="utf-8") as f:
43
+ f.write(xml_string)
44
+
45
+ def to_string(self, instance) -> str:
46
+ return self.serializer.render(instance)
47
+
48
+ def _fix_decimal(obj):
49
+ if isinstance(obj, Enum):
50
+ return obj.value
51
+ if isinstance(obj, Decimal):
52
+ return float(obj)
53
+ if isinstance(obj, dict):
54
+ return {k: SCXMLDocumentHandler._fix_decimal(v) for k, v in obj.items()}
55
+ if isinstance(obj, list):
56
+ return [SCXMLDocumentHandler._fix_decimal(v) for v in obj]
57
+ return obj
58
+
59
+ @staticmethod
60
+ def _remove_empty(obj: Any):
61
+ """Recursively remove keys with None or empty containers."""
62
+ if isinstance(obj, dict):
63
+ return {
64
+ k: SCXMLDocumentHandler._remove_empty(v)
65
+ for k, v in obj.items()
66
+ if v is not None
67
+ and not (isinstance(v, (list, dict)) and len(v) == 0)
68
+ }
69
+ if isinstance(obj, list):
70
+ return [
71
+ SCXMLDocumentHandler._remove_empty(v)
72
+ for v in obj
73
+ if v is not None
74
+ and not (isinstance(v, (list, dict)) and len(v) == 0)
75
+ ]
76
+ return obj
77
+
78
+ def xml_to_json(self, xml_str: str) -> str:
79
+ """Convert SCXML string to canonical JSON."""
80
+ model = self.parser.from_string(xml_str, self.model_class)
81
+ if hasattr(model, "model_dump"):
82
+ data = model.model_dump()
83
+ else:
84
+ data = asdict(model)
85
+ data = SCXMLDocumentHandler._fix_decimal(data)
86
+ if self.omit_empty:
87
+ data = SCXMLDocumentHandler._remove_empty(data)
88
+ return json.dumps(data, indent=2)
89
+
90
+ def _to_dataclass(self, cls: type, data: Any):
91
+ """Recursively build dataclass instance from dict."""
92
+ origin = get_origin(cls)
93
+ if origin is list:
94
+ item_type = get_args(cls)[0]
95
+ return [self._to_dataclass(item_type, x) for x in data]
96
+ if origin is Union:
97
+ for arg in get_args(cls):
98
+ if arg is type(None):
99
+ continue
100
+ try:
101
+ return self._to_dataclass(arg, data)
102
+ except Exception:
103
+ pass
104
+ return data
105
+ if is_dataclass(cls):
106
+ kwargs = {}
107
+ post = {}
108
+ for f in fields(cls):
109
+ if f.name not in data:
110
+ continue
111
+ value = self._to_dataclass(f.type, data[f.name])
112
+ if f.type is Decimal or f.name == "version":
113
+ try:
114
+ value = Decimal(str(value))
115
+ except Exception:
116
+ pass
117
+ if f.init:
118
+ # xsdata dataclasses mark some attributes with init=False.
119
+ # Handle them after instantiation to avoid TypeError.
120
+ kwargs[f.name] = value
121
+ else:
122
+ post[f.name] = value
123
+ obj = cls(**kwargs)
124
+ for name, value in post.items():
125
+ setattr(obj, name, value)
126
+ return obj
127
+ if isinstance(cls, type) and issubclass(cls, Enum):
128
+ try:
129
+ return cls(data)
130
+ except Exception:
131
+ return data
132
+ return data
133
+
134
+ def json_to_xml(self, json_str: str) -> str:
135
+ """Convert stored JSON string to SCXML."""
136
+ data = json.loads(json_str)
137
+ if hasattr(self.model_class, "model_validate"):
138
+ model = self.model_class.model_validate(data)
139
+ else:
140
+ model = self._to_dataclass(self.model_class, data)
141
+ return self.to_string(model)
142
+
scjson/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """scjson conversion tools."""
2
+
3
+ __progname__ = "scjson"
4
+ __description__ = "Convert between scjson and SCXML"
5
+ __version__ = "0.1.0"
6
+
7
+ __all__ = ["__progname__", "__description__", "__version__"]
scjson/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
scjson/cli.py ADDED
@@ -0,0 +1,171 @@
1
+ import click
2
+ from pathlib import Path
3
+ from .SCXMLDocumentHandler import SCXMLDocumentHandler
4
+ from . import __version__, __description__, __progname__
5
+
6
+
7
+ def _splash() -> None:
8
+ """Display program header."""
9
+ click.echo(f"{__progname__} {__version__} - {__description__}")
10
+
11
+
12
+ @click.group(help=__description__, invoke_without_command=True)
13
+ @click.pass_context
14
+ def main(ctx):
15
+ """Command line interface for scjson conversions."""
16
+ _splash()
17
+ if ctx.invoked_subcommand is None:
18
+ click.echo(ctx.get_help())
19
+
20
+
21
+ @main.command(help="Convert scjson file to SCXML.")
22
+ @click.argument("path", type=click.Path(exists=True, path_type=Path))
23
+ @click.option("--output", "-o", type=click.Path(path_type=Path), help="Output file or directory")
24
+ @click.option("--recursive", "-r", is_flag=True, default=False, help="Recurse into subdirectories when PATH is a directory")
25
+ @click.option("--verify", "-v", is_flag=True, default=False, help="Verify conversion without writing output")
26
+ @click.option("--keep-empty", is_flag=True, default=False, help="Keep null or empty items when producing JSON")
27
+ def xml(path: Path, output: Path | None, recursive: bool, verify: bool, keep_empty: bool):
28
+ """Convert a single scjson file or all scjson files in a directory."""
29
+ handler = SCXMLDocumentHandler(omit_empty=not keep_empty)
30
+
31
+ def convert_file(src: Path, dest: Path | None):
32
+ try:
33
+ with open(src, "r", encoding="utf-8") as f:
34
+ json_str = f.read()
35
+ xml_str = handler.json_to_xml(json_str)
36
+ if verify:
37
+ handler.xml_to_json(xml_str)
38
+ click.echo(f"Verified {src}")
39
+ return True
40
+ except Exception as e:
41
+ click.echo(f"Failed to convert {src}: {e}", err=True)
42
+ return False
43
+ if dest is None:
44
+ return True
45
+ dest.parent.mkdir(parents=True, exist_ok=True)
46
+ with open(dest, "w", encoding="utf-8") as f:
47
+ f.write(xml_str)
48
+ click.echo(f"Wrote {dest}")
49
+ return True
50
+
51
+ if path.is_dir():
52
+ out_dir = output if output else path
53
+ pattern = "**/*.scjson" if recursive else "*.scjson"
54
+ for src in path.glob(pattern):
55
+ if src.is_file():
56
+ rel = src.relative_to(path)
57
+ dest = out_dir / rel.with_suffix(".scxml") if not verify else None
58
+ convert_file(src, dest)
59
+ else:
60
+ if output and (output.is_dir() or not output.suffix):
61
+ base = output
62
+ else:
63
+ base = output.parent if output else path.parent
64
+ if base:
65
+ base.mkdir(parents=True, exist_ok=True)
66
+ out_file = (
67
+ output
68
+ if output and output.suffix
69
+ else (base / path.with_suffix(".scxml").name)
70
+ ) if output else path.with_suffix(".scxml")
71
+ dest = None if verify else out_file
72
+ convert_file(path, dest)
73
+
74
+
75
+ @main.command(help="Convert SCXML file to scjson.")
76
+ @click.argument("path", type=click.Path(exists=True, path_type=Path))
77
+ @click.option("--output", "-o", type=click.Path(path_type=Path), help="Output file or directory")
78
+ @click.option("--recursive", "-r", is_flag=True, default=False, help="Recurse into subdirectories when PATH is a directory")
79
+ @click.option("--verify", "-v", is_flag=True, default=False, help="Verify conversion without writing output")
80
+ @click.option("--keep-empty", is_flag=True, default=False, help="Keep null or empty items when producing JSON")
81
+ def json(path: Path, output: Path | None, recursive: bool, verify: bool, keep_empty: bool):
82
+ """Convert a single SCXML file or all SCXML files in a directory."""
83
+ handler = SCXMLDocumentHandler(omit_empty=not keep_empty)
84
+
85
+ def convert_file(src: Path, dest: Path | None):
86
+ try:
87
+ with open(src, "r", encoding="utf-8") as f:
88
+ xml_str = f.read()
89
+ json_str = handler.xml_to_json(xml_str)
90
+ if verify:
91
+ handler.json_to_xml(json_str)
92
+ click.echo(f"Verified {src}")
93
+ return True
94
+ except Exception as e:
95
+ click.echo(f"Failed to convert {src}: {e}", err=True)
96
+ return False
97
+ if dest is None:
98
+ return True
99
+ dest.parent.mkdir(parents=True, exist_ok=True)
100
+ with open(dest, "w", encoding="utf-8") as f:
101
+ f.write(json_str)
102
+ click.echo(f"Wrote {dest}")
103
+ return True
104
+
105
+ if path.is_dir():
106
+ out_dir = output if output else path
107
+ pattern = "**/*.scxml" if recursive else "*.scxml"
108
+ for src in path.glob(pattern):
109
+ if src.is_file():
110
+ rel = src.relative_to(path)
111
+ dest = out_dir / rel.with_suffix(".scjson") if not verify else None
112
+ convert_file(src, dest)
113
+ else:
114
+ if output and (output.is_dir() or not output.suffix):
115
+ base = output
116
+ else:
117
+ base = output.parent if output else path.parent
118
+ if base:
119
+ base.mkdir(parents=True, exist_ok=True)
120
+ out_file = (
121
+ output
122
+ if output and output.suffix
123
+ else (base / path.with_suffix(".scjson").name)
124
+ ) if output else path.with_suffix(".scjson")
125
+ dest = None if verify else out_file
126
+ convert_file(path, dest)
127
+
128
+
129
+ @main.command(help="Validate scjson or SCXML files by round-tripping them in memory.")
130
+ @click.argument("path", type=click.Path(exists=True, path_type=Path))
131
+ @click.option("--recursive", "-r", is_flag=True, default=False, help="Recurse into subdirectories when PATH is a directory")
132
+ def validate(path: Path, recursive: bool):
133
+ """Check that files can be converted to the opposite format and back."""
134
+ handler = SCXMLDocumentHandler()
135
+
136
+ def validate_file(src: Path) -> bool:
137
+ try:
138
+ data = src.read_text(encoding="utf-8")
139
+ if src.suffix == ".scxml":
140
+ json_str = handler.xml_to_json(data)
141
+ handler.json_to_xml(json_str)
142
+ elif src.suffix == ".scjson":
143
+ xml_str = handler.json_to_xml(data)
144
+ handler.xml_to_json(xml_str)
145
+ else:
146
+ return True
147
+ except Exception as e:
148
+ click.echo(f"Validation failed for {src}: {e}", err=True)
149
+ return False
150
+ return True
151
+
152
+ success = True
153
+ if path.is_dir():
154
+ pattern = "**/*" if recursive else "*"
155
+ for src in path.glob(pattern):
156
+ if src.is_file() and src.suffix in {".scxml", ".scjson"}:
157
+ if not validate_file(src):
158
+ success = False
159
+ else:
160
+ if path.suffix in {".scxml", ".scjson"}:
161
+ success = validate_file(path)
162
+ else:
163
+ click.echo("Unsupported file type", err=True)
164
+ success = False
165
+
166
+ if not success:
167
+ raise SystemExit(1)
168
+
169
+
170
+ if __name__ == "__main__":
171
+ main()
@@ -0,0 +1,121 @@
1
+ from .generated import (
2
+ Assign,
3
+ AssignTypeDatatype,
4
+ BindingDatatype,
5
+ BooleanDatatype,
6
+ Cancel,
7
+ Content,
8
+ Data,
9
+ Datamodel,
10
+ Donedata,
11
+ Else,
12
+ Elseif,
13
+ ExmodeDatatype,
14
+ Final,
15
+ Finalize,
16
+ Foreach,
17
+ History,
18
+ HistoryTypeDatatype,
19
+ If,
20
+ Initial,
21
+ Invoke,
22
+ Log,
23
+ Onentry,
24
+ Onexit,
25
+ Parallel,
26
+ Param,
27
+ Raise,
28
+ Script,
29
+ Scxml,
30
+ ScxmlAssignType,
31
+ ScxmlCancelType,
32
+ ScxmlContentType,
33
+ ScxmlDatamodelType,
34
+ ScxmlDataType,
35
+ ScxmlDonedataType,
36
+ ScxmlElseifType,
37
+ ScxmlElseType,
38
+ ScxmlFinalizeType,
39
+ ScxmlFinalType,
40
+ ScxmlForeachType,
41
+ ScxmlHistoryType,
42
+ ScxmlIfType,
43
+ ScxmlInitialType,
44
+ ScxmlInvokeType,
45
+ ScxmlLogType,
46
+ ScxmlOnentryType,
47
+ ScxmlOnexitType,
48
+ ScxmlParallelType,
49
+ ScxmlParamType,
50
+ ScxmlRaiseType,
51
+ ScxmlScriptType,
52
+ ScxmlScxmlType,
53
+ ScxmlSendType,
54
+ ScxmlStateType,
55
+ ScxmlTransitionType,
56
+ Send,
57
+ State,
58
+ Transition,
59
+ TransitionTypeDatatype,
60
+ )
61
+
62
+ __all__ = [
63
+ "AssignTypeDatatype",
64
+ "BindingDatatype",
65
+ "BooleanDatatype",
66
+ "ExmodeDatatype",
67
+ "HistoryTypeDatatype",
68
+ "TransitionTypeDatatype",
69
+ "Assign",
70
+ "Cancel",
71
+ "Content",
72
+ "Data",
73
+ "Datamodel",
74
+ "Donedata",
75
+ "Else",
76
+ "Elseif",
77
+ "Final",
78
+ "Finalize",
79
+ "Foreach",
80
+ "History",
81
+ "If",
82
+ "Initial",
83
+ "Invoke",
84
+ "Log",
85
+ "Onentry",
86
+ "Onexit",
87
+ "Parallel",
88
+ "Param",
89
+ "Raise",
90
+ "Script",
91
+ "Scxml",
92
+ "ScxmlAssignType",
93
+ "ScxmlCancelType",
94
+ "ScxmlContentType",
95
+ "ScxmlDataType",
96
+ "ScxmlDatamodelType",
97
+ "ScxmlDonedataType",
98
+ "ScxmlElseType",
99
+ "ScxmlElseifType",
100
+ "ScxmlFinalType",
101
+ "ScxmlFinalizeType",
102
+ "ScxmlForeachType",
103
+ "ScxmlHistoryType",
104
+ "ScxmlIfType",
105
+ "ScxmlInitialType",
106
+ "ScxmlInvokeType",
107
+ "ScxmlLogType",
108
+ "ScxmlOnentryType",
109
+ "ScxmlOnexitType",
110
+ "ScxmlParallelType",
111
+ "ScxmlParamType",
112
+ "ScxmlRaiseType",
113
+ "ScxmlScriptType",
114
+ "ScxmlScxmlType",
115
+ "ScxmlSendType",
116
+ "ScxmlStateType",
117
+ "ScxmlTransitionType",
118
+ "Send",
119
+ "State",
120
+ "Transition",
121
+ ]