bonsai-sgen 0.10.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.
- bonsai_sgen-0.10.0/LICENSE +19 -0
- bonsai_sgen-0.10.0/PKG-INFO +83 -0
- bonsai_sgen-0.10.0/pyproject.toml +51 -0
- bonsai_sgen-0.10.0/setup.cfg +4 -0
- bonsai_sgen-0.10.0/src/bonsai/sgen/README.md +69 -0
- bonsai_sgen-0.10.0/src/bonsai/sgen/__init__.py +37 -0
- bonsai_sgen-0.10.0/src/bonsai/sgen/__main__.py +7 -0
- bonsai_sgen-0.10.0/src/bonsai/sgen/cli.py +253 -0
- bonsai_sgen-0.10.0/src/bonsai/sgen/export.py +334 -0
- bonsai_sgen-0.10.0/src/bonsai/sgen/py.typed +0 -0
- bonsai_sgen-0.10.0/src/bonsai/sgen/schema.py +577 -0
- bonsai_sgen-0.10.0/src/bonsai_sgen.egg-info/SOURCES.txt +21 -0
- bonsai_sgen-0.10.0/tests/conftest.py +100 -0
- bonsai_sgen-0.10.0/tests/models/base.py +15 -0
- bonsai_sgen-0.10.0/tests/models/derived.py +228 -0
- bonsai_sgen-0.10.0/tests/models/late.py +28 -0
- bonsai_sgen-0.10.0/tests/models/local.py +40 -0
- bonsai_sgen-0.10.0/tests/models/owners.py +29 -0
- bonsai_sgen-0.10.0/tests/models/plain.py +75 -0
- bonsai_sgen-0.10.0/tests/models/unnamed.py +48 -0
- bonsai_sgen-0.10.0/tests/test_cli.py +223 -0
- bonsai_sgen-0.10.0/tests/test_roundtrip.py +186 -0
- bonsai_sgen-0.10.0/tests/test_schema.py +1626 -0
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
Copyright (c) Bonsai Foundation CIC and Contributors
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
4
|
+
this software and associated documentation files (the "Software"), to deal in
|
|
5
|
+
the Software without restriction, including without limitation the rights to
|
|
6
|
+
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
|
7
|
+
of the Software, and to permit persons to whom the Software is furnished to do
|
|
8
|
+
so, subject to the following conditions:
|
|
9
|
+
|
|
10
|
+
The above copyright notice and this permission notice shall be included in all
|
|
11
|
+
copies or substantial portions of the Software.
|
|
12
|
+
|
|
13
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
14
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
15
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
16
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
17
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
19
|
+
SOFTWARE.
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: bonsai-sgen
|
|
3
|
+
Version: 0.10.0
|
|
4
|
+
Summary: Pydantic base classes for types generated by Bonsai.Sgen.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Documentation, https://bonsai-rx.org/sgen
|
|
7
|
+
Project-URL: Repository, https://github.com/bonsai-rx/sgen
|
|
8
|
+
Requires-Python: >=3.11
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Requires-Dist: pydantic>=2.11.2
|
|
12
|
+
Requires-Dist: typing-extensions>=4.6.1
|
|
13
|
+
Dynamic: license-file
|
|
14
|
+
|
|
15
|
+
# bonsai-sgen
|
|
16
|
+
|
|
17
|
+
`bonsai-sgen` provides pydantic base classes for data types shared with the [Bonsai visual reactive programming language](https://bonsai-rx.org). Models derived from these classes export JSON schemas from which [`Bonsai.Sgen`](https://www.nuget.org/packages/Bonsai.Sgen) generates matching C# types and serialization operators.
|
|
18
|
+
|
|
19
|
+
Each release of `bonsai-sgen` matches the release of `Bonsai.Sgen` with the same version number, and exports schemas following the conventions of that release.
|
|
20
|
+
|
|
21
|
+
## How to Use
|
|
22
|
+
|
|
23
|
+
1. Install the package:
|
|
24
|
+
|
|
25
|
+
```cmd
|
|
26
|
+
pip install bonsai-sgen
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
2. Define the models in a module, `person_and_discriminated_pets.py`, that declares the namespace of the generated types:
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from abc import ABC
|
|
33
|
+
from typing import Annotated, Literal
|
|
34
|
+
|
|
35
|
+
from pydantic import Field
|
|
36
|
+
from typing_extensions import TypeAliasType
|
|
37
|
+
|
|
38
|
+
from bonsai.sgen import SchemaModel
|
|
39
|
+
|
|
40
|
+
SGEN_NAMESPACE = "PersonAndDiscriminatedPets"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class PetBase(SchemaModel, ABC):
|
|
44
|
+
age: int | None = None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class Cat(PetBase):
|
|
48
|
+
pet_type: Literal["cat"] = "cat"
|
|
49
|
+
can_meow: bool = True
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class Dog(PetBase):
|
|
53
|
+
pet_type: Literal["dog"] = "dog"
|
|
54
|
+
can_bark: bool | None = True
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
Pet = TypeAliasType("Pet", Annotated[Cat | Dog, Field(discriminator="pet_type")])
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class PersonAndPet(SchemaModel):
|
|
61
|
+
owner: str
|
|
62
|
+
pet: Pet | None = None
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
3. Write the schema of the models to a file named after the namespace:
|
|
66
|
+
|
|
67
|
+
```cmd
|
|
68
|
+
bonsai-sgen export person_and_discriminated_pets -o schemas
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
4. Generate the C# types with the release of `Bonsai.Sgen` matching the installed version of `bonsai-sgen`:
|
|
72
|
+
|
|
73
|
+
```cmd
|
|
74
|
+
dotnet bonsai.sgen schemas/PersonAndDiscriminatedPets.json -o Extensions --serializer json yaml
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## Additional Documentation
|
|
78
|
+
|
|
79
|
+
For additional documentation and examples, refer to the [official Bonsai.Sgen documentation](https://bonsai-rx.org/sgen).
|
|
80
|
+
|
|
81
|
+
## Feedback & Contributing
|
|
82
|
+
|
|
83
|
+
`bonsai-sgen` is released as open source under the [MIT license](https://github.com/bonsai-rx/sgen/blob/main/LICENSE). Bug reports and contributions are welcome at [the GitHub repository](https://github.com/bonsai-rx/sgen).
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "bonsai-sgen"
|
|
3
|
+
dynamic = ["version"]
|
|
4
|
+
description = "Pydantic base classes for types generated by Bonsai.Sgen."
|
|
5
|
+
license = "MIT"
|
|
6
|
+
license-files = ["LICENSE"]
|
|
7
|
+
readme = "src/bonsai/sgen/README.md"
|
|
8
|
+
requires-python = ">=3.11"
|
|
9
|
+
dependencies = ["pydantic>=2.11.2", "typing-extensions>=4.6.1"]
|
|
10
|
+
|
|
11
|
+
[project.scripts]
|
|
12
|
+
bonsai-sgen = "bonsai.sgen.cli:main"
|
|
13
|
+
|
|
14
|
+
[project.urls]
|
|
15
|
+
Documentation = "https://bonsai-rx.org/sgen"
|
|
16
|
+
Repository = "https://github.com/bonsai-rx/sgen"
|
|
17
|
+
|
|
18
|
+
[build-system]
|
|
19
|
+
requires = ["setuptools>=77", "setuptools-scm>=8"]
|
|
20
|
+
build-backend = "setuptools.build_meta"
|
|
21
|
+
|
|
22
|
+
[tool.setuptools_scm]
|
|
23
|
+
|
|
24
|
+
[tool.setuptools.packages.find]
|
|
25
|
+
where = ["src"]
|
|
26
|
+
include = ["bonsai*"]
|
|
27
|
+
|
|
28
|
+
[tool.setuptools.exclude-package-data]
|
|
29
|
+
"bonsai.sgen" = ["README.md"]
|
|
30
|
+
|
|
31
|
+
[dependency-groups]
|
|
32
|
+
dev = ["pyright>=1.1.400", "pytest>=8", "pyyaml>=6", "ruff>=0.11"]
|
|
33
|
+
|
|
34
|
+
[tool.ruff]
|
|
35
|
+
line-length = 100
|
|
36
|
+
include = ["src/bonsai/**/*.py", "tests/**/*.py"]
|
|
37
|
+
|
|
38
|
+
[tool.ruff.lint]
|
|
39
|
+
select = ["E", "F", "I", "D", "UP", "B"]
|
|
40
|
+
|
|
41
|
+
[tool.ruff.lint.pydocstyle]
|
|
42
|
+
convention = "google"
|
|
43
|
+
|
|
44
|
+
[tool.pyright]
|
|
45
|
+
include = ["src/bonsai", "tests"]
|
|
46
|
+
|
|
47
|
+
[tool.pytest.ini_options]
|
|
48
|
+
testpaths = ["tests"]
|
|
49
|
+
|
|
50
|
+
[tool.docfx-tools]
|
|
51
|
+
inventories = ["https://docs.pydantic.dev/latest/objects.inv"]
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# bonsai-sgen
|
|
2
|
+
|
|
3
|
+
`bonsai-sgen` provides pydantic base classes for data types shared with the [Bonsai visual reactive programming language](https://bonsai-rx.org). Models derived from these classes export JSON schemas from which [`Bonsai.Sgen`](https://www.nuget.org/packages/Bonsai.Sgen) generates matching C# types and serialization operators.
|
|
4
|
+
|
|
5
|
+
Each release of `bonsai-sgen` matches the release of `Bonsai.Sgen` with the same version number, and exports schemas following the conventions of that release.
|
|
6
|
+
|
|
7
|
+
## How to Use
|
|
8
|
+
|
|
9
|
+
1. Install the package:
|
|
10
|
+
|
|
11
|
+
```cmd
|
|
12
|
+
pip install bonsai-sgen
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
2. Define the models in a module, `person_and_discriminated_pets.py`, that declares the namespace of the generated types:
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
from abc import ABC
|
|
19
|
+
from typing import Annotated, Literal
|
|
20
|
+
|
|
21
|
+
from pydantic import Field
|
|
22
|
+
from typing_extensions import TypeAliasType
|
|
23
|
+
|
|
24
|
+
from bonsai.sgen import SchemaModel
|
|
25
|
+
|
|
26
|
+
SGEN_NAMESPACE = "PersonAndDiscriminatedPets"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class PetBase(SchemaModel, ABC):
|
|
30
|
+
age: int | None = None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Cat(PetBase):
|
|
34
|
+
pet_type: Literal["cat"] = "cat"
|
|
35
|
+
can_meow: bool = True
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Dog(PetBase):
|
|
39
|
+
pet_type: Literal["dog"] = "dog"
|
|
40
|
+
can_bark: bool | None = True
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
Pet = TypeAliasType("Pet", Annotated[Cat | Dog, Field(discriminator="pet_type")])
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class PersonAndPet(SchemaModel):
|
|
47
|
+
owner: str
|
|
48
|
+
pet: Pet | None = None
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
3. Write the schema of the models to a file named after the namespace:
|
|
52
|
+
|
|
53
|
+
```cmd
|
|
54
|
+
bonsai-sgen export person_and_discriminated_pets -o schemas
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
4. Generate the C# types with the release of `Bonsai.Sgen` matching the installed version of `bonsai-sgen`:
|
|
58
|
+
|
|
59
|
+
```cmd
|
|
60
|
+
dotnet bonsai.sgen schemas/PersonAndDiscriminatedPets.json -o Extensions --serializer json yaml
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Additional Documentation
|
|
64
|
+
|
|
65
|
+
For additional documentation and examples, refer to the [official Bonsai.Sgen documentation](https://bonsai-rx.org/sgen).
|
|
66
|
+
|
|
67
|
+
## Feedback & Contributing
|
|
68
|
+
|
|
69
|
+
`bonsai-sgen` is released as open source under the [MIT license](https://github.com/bonsai-rx/sgen/blob/main/LICENSE). Bug reports and contributions are welcome at [the GitHub repository](https://github.com/bonsai-rx/sgen).
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Pydantic base classes for types generated by Bonsai.Sgen."""
|
|
2
|
+
|
|
3
|
+
from .export import export_schema, schema_types, write_schema
|
|
4
|
+
from .schema import (
|
|
5
|
+
ABSTRACT_KEY,
|
|
6
|
+
CAMEL_CASE_CONFIG,
|
|
7
|
+
ENUM_NAMES_KEY,
|
|
8
|
+
NAMESPACE_ATTRIBUTE,
|
|
9
|
+
TYPENAME_KEY,
|
|
10
|
+
DiscriminatedUnion,
|
|
11
|
+
SchemaAlias,
|
|
12
|
+
SchemaEnum,
|
|
13
|
+
SchemaModel,
|
|
14
|
+
SchemaType,
|
|
15
|
+
SchemaUnion,
|
|
16
|
+
SgenWarning,
|
|
17
|
+
get_typename,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"ABSTRACT_KEY",
|
|
22
|
+
"CAMEL_CASE_CONFIG",
|
|
23
|
+
"ENUM_NAMES_KEY",
|
|
24
|
+
"NAMESPACE_ATTRIBUTE",
|
|
25
|
+
"TYPENAME_KEY",
|
|
26
|
+
"DiscriminatedUnion",
|
|
27
|
+
"SchemaAlias",
|
|
28
|
+
"SchemaEnum",
|
|
29
|
+
"SchemaModel",
|
|
30
|
+
"SchemaType",
|
|
31
|
+
"SchemaUnion",
|
|
32
|
+
"SgenWarning",
|
|
33
|
+
"export_schema",
|
|
34
|
+
"get_typename",
|
|
35
|
+
"schema_types",
|
|
36
|
+
"write_schema",
|
|
37
|
+
]
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
"""Exports schemas of Python models, or generates their C# types with Bonsai.Sgen.
|
|
2
|
+
|
|
3
|
+
Each module or package is specified by its fully qualified name and imported
|
|
4
|
+
from the current environment. Each module declares the namespace of its types
|
|
5
|
+
in its SGEN_NAMESPACE attribute. Modules that declare the same namespace are
|
|
6
|
+
exported together.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import importlib
|
|
11
|
+
import importlib.metadata
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
import shlex
|
|
16
|
+
import subprocess
|
|
17
|
+
import sys
|
|
18
|
+
import warnings
|
|
19
|
+
from collections.abc import Sequence
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from types import ModuleType
|
|
22
|
+
|
|
23
|
+
from pydantic.json_schema import JsonSchemaValue
|
|
24
|
+
|
|
25
|
+
from .export import _write_schema_file, export_schema, schema_types
|
|
26
|
+
from .schema import NAMESPACE_ATTRIBUTE, SchemaType, _namespace, get_typename
|
|
27
|
+
|
|
28
|
+
_COMMAND_VARIABLE = "BONSAI_SGEN"
|
|
29
|
+
"""Environment variable overriding the command line running Bonsai.Sgen."""
|
|
30
|
+
|
|
31
|
+
_DEFAULT_COMMAND: tuple[str, ...] = ("dotnet", "bonsai.sgen")
|
|
32
|
+
"""Command line running Bonsai.Sgen from the local tool manifest of a repository."""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class _CommandError(Exception):
|
|
36
|
+
"""Reports a failure that the command describes without a traceback."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _import_module(module_name: str) -> ModuleType:
|
|
40
|
+
try:
|
|
41
|
+
return importlib.import_module(module_name)
|
|
42
|
+
except ModuleNotFoundError as error:
|
|
43
|
+
raise _CommandError(f"Cannot import {module_name}: {error}.") from error
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _submodule_names(package: ModuleType) -> list[str]:
|
|
47
|
+
names: set[str] = set()
|
|
48
|
+
for directory in package.__path__:
|
|
49
|
+
root = Path(directory)
|
|
50
|
+
for path in root.rglob("*.py"):
|
|
51
|
+
parts = path.relative_to(root).with_suffix("").parts
|
|
52
|
+
if parts[-1] == "__init__":
|
|
53
|
+
parts = parts[:-1]
|
|
54
|
+
if parts and parts[-1] != "__main__" and all(part.isidentifier() for part in parts):
|
|
55
|
+
names.add(".".join([package.__name__, *parts]))
|
|
56
|
+
return sorted(names)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _module_types(module: ModuleType) -> tuple[str | None, list[SchemaType]]:
|
|
60
|
+
namespace = getattr(module, NAMESPACE_ATTRIBUTE, None)
|
|
61
|
+
if namespace is None:
|
|
62
|
+
return None, []
|
|
63
|
+
types = [
|
|
64
|
+
schema_type
|
|
65
|
+
for schema_type in schema_types(module)
|
|
66
|
+
if _namespace(get_typename(schema_type)) == namespace
|
|
67
|
+
]
|
|
68
|
+
return namespace, types
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _namespace_types(module_names: Sequence[str]) -> dict[str, list[SchemaType]]:
|
|
72
|
+
namespaces: dict[str, list[SchemaType]] = {}
|
|
73
|
+
exported: set[str] = set()
|
|
74
|
+
for module_name in module_names:
|
|
75
|
+
module = _import_module(module_name)
|
|
76
|
+
if hasattr(module, "__path__"):
|
|
77
|
+
modules = [module, *map(_import_module, _submodule_names(module))]
|
|
78
|
+
found = [_module_types(submodule) for submodule in modules]
|
|
79
|
+
if not any(types for _, types in found):
|
|
80
|
+
raise _CommandError(f"Package {module_name} defines no schema types.")
|
|
81
|
+
else:
|
|
82
|
+
modules = [module]
|
|
83
|
+
namespace, types = _module_types(module)
|
|
84
|
+
if namespace is None:
|
|
85
|
+
raise _CommandError(f"Module {module_name} does not declare {NAMESPACE_ATTRIBUTE}.")
|
|
86
|
+
if not types:
|
|
87
|
+
raise _CommandError(f"Module {module_name} defines no schema types.")
|
|
88
|
+
found = [(namespace, types)]
|
|
89
|
+
for submodule, (namespace, types) in zip(modules, found, strict=True):
|
|
90
|
+
if namespace is not None and types and submodule.__name__ not in exported:
|
|
91
|
+
exported.add(submodule.__name__)
|
|
92
|
+
namespaces.setdefault(namespace, []).extend(types)
|
|
93
|
+
return namespaces
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _export_schemas(
|
|
97
|
+
module_names: Sequence[str], allow_local_types: bool
|
|
98
|
+
) -> dict[str, JsonSchemaValue]:
|
|
99
|
+
try:
|
|
100
|
+
return {
|
|
101
|
+
namespace: export_schema(*types, allow_local_types=allow_local_types)
|
|
102
|
+
for namespace, types in _namespace_types(module_names).items()
|
|
103
|
+
}
|
|
104
|
+
except (TypeError, ValueError) as error:
|
|
105
|
+
raise _CommandError(str(error)) from error
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _split_command(command: str) -> list[str]:
|
|
109
|
+
if os.name != "nt":
|
|
110
|
+
return shlex.split(command)
|
|
111
|
+
return [
|
|
112
|
+
token[1:-1] if len(token) > 1 and token[0] == token[-1] == '"' else token
|
|
113
|
+
for token in shlex.split(command, posix=False)
|
|
114
|
+
]
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _minor_release(version: str) -> tuple[str, str] | None:
|
|
118
|
+
match = re.match(r"(\d+)\.(\d+)", version)
|
|
119
|
+
return (match[1], match[2]) if match else None
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _sgen_command() -> list[str]:
|
|
123
|
+
override = os.environ.get(_COMMAND_VARIABLE)
|
|
124
|
+
if override:
|
|
125
|
+
return _split_command(override)
|
|
126
|
+
command = list(_DEFAULT_COMMAND)
|
|
127
|
+
try:
|
|
128
|
+
result = subprocess.run([*command, "--version"], capture_output=True, text=True)
|
|
129
|
+
except FileNotFoundError as error:
|
|
130
|
+
raise _CommandError("The .NET SDK is not installed, so Bonsai.Sgen cannot run.") from error
|
|
131
|
+
if result.returncode != 0:
|
|
132
|
+
raise _CommandError(
|
|
133
|
+
"Bonsai.Sgen is not installed. Install it as a local tool with "
|
|
134
|
+
"'dotnet tool install Bonsai.Sgen', or restore the local tools with "
|
|
135
|
+
"'dotnet tool restore'."
|
|
136
|
+
)
|
|
137
|
+
sgen_version = result.stdout.strip()
|
|
138
|
+
package_version = importlib.metadata.version("bonsai-sgen")
|
|
139
|
+
if _minor_release(sgen_version) is None or (
|
|
140
|
+
_minor_release(sgen_version) != _minor_release(package_version)
|
|
141
|
+
):
|
|
142
|
+
raise _CommandError(
|
|
143
|
+
f"Bonsai.Sgen {sgen_version} does not match bonsai-sgen {package_version}. "
|
|
144
|
+
"Install the same minor release of both."
|
|
145
|
+
)
|
|
146
|
+
return command
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _export(arguments: argparse.Namespace) -> int:
|
|
150
|
+
schemas = _export_schemas(arguments.modules, arguments.allow_local_types)
|
|
151
|
+
output = Path(arguments.output)
|
|
152
|
+
output.mkdir(parents=True, exist_ok=True)
|
|
153
|
+
for namespace, schema in schemas.items():
|
|
154
|
+
path = _write_schema_file(output, namespace, schema)
|
|
155
|
+
print(f"Writing schema to {path}...")
|
|
156
|
+
return 0
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _generate(arguments: argparse.Namespace) -> int:
|
|
160
|
+
command = _sgen_command()
|
|
161
|
+
schemas = _export_schemas(arguments.modules, arguments.allow_local_types)
|
|
162
|
+
for namespace, schema in schemas.items():
|
|
163
|
+
options = ["--namespace", namespace, "--output", arguments.output]
|
|
164
|
+
if arguments.serializer:
|
|
165
|
+
options += ["--serializer", *arguments.serializer]
|
|
166
|
+
result = subprocess.run([*command, *options], input=json.dumps(schema).encode())
|
|
167
|
+
if result.returncode != 0:
|
|
168
|
+
return result.returncode
|
|
169
|
+
return 0
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _parser() -> argparse.ArgumentParser:
|
|
173
|
+
shared = argparse.ArgumentParser(add_help=False)
|
|
174
|
+
shared.add_argument(
|
|
175
|
+
"modules",
|
|
176
|
+
nargs="+",
|
|
177
|
+
metavar="module",
|
|
178
|
+
help="The name of a module or package to export, such as pkg.schema.",
|
|
179
|
+
)
|
|
180
|
+
shared.add_argument(
|
|
181
|
+
"-o",
|
|
182
|
+
"--output",
|
|
183
|
+
default=".",
|
|
184
|
+
help="Location to place the generated output. The default is the current directory.",
|
|
185
|
+
)
|
|
186
|
+
shared.add_argument(
|
|
187
|
+
"--allow-local-types",
|
|
188
|
+
action="store_true",
|
|
189
|
+
help="Allows types with no type name as local types, generated in each namespace that "
|
|
190
|
+
"refers to them.",
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
parser = argparse.ArgumentParser(
|
|
194
|
+
prog="bonsai-sgen",
|
|
195
|
+
description=__doc__,
|
|
196
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
197
|
+
)
|
|
198
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
199
|
+
commands.add_parser(
|
|
200
|
+
"export",
|
|
201
|
+
parents=[shared],
|
|
202
|
+
help="Writes the schema of each namespace to a file.",
|
|
203
|
+
description="Writes the schema of each namespace to a file.",
|
|
204
|
+
)
|
|
205
|
+
generate = commands.add_parser(
|
|
206
|
+
"generate",
|
|
207
|
+
parents=[shared],
|
|
208
|
+
help="Generates the C# types of each namespace with Bonsai.Sgen.",
|
|
209
|
+
description=(
|
|
210
|
+
"Generates the C# types of each namespace with Bonsai.Sgen. The "
|
|
211
|
+
f"{_COMMAND_VARIABLE} environment variable overrides the command line."
|
|
212
|
+
),
|
|
213
|
+
)
|
|
214
|
+
generate.add_argument(
|
|
215
|
+
"--serializer",
|
|
216
|
+
nargs="+",
|
|
217
|
+
choices=["json", "yaml"],
|
|
218
|
+
help="Specifies the serializer data annotations to include in the generated classes.",
|
|
219
|
+
)
|
|
220
|
+
return parser
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
224
|
+
"""Runs the command line of the package and returns its exit code.
|
|
225
|
+
|
|
226
|
+
Args:
|
|
227
|
+
argv: The command-line arguments, or None to read them from `sys.argv`.
|
|
228
|
+
|
|
229
|
+
Returns:
|
|
230
|
+
Zero if the command succeeded; otherwise a nonzero exit code.
|
|
231
|
+
"""
|
|
232
|
+
parser = _parser()
|
|
233
|
+
arguments = parser.parse_args(argv)
|
|
234
|
+
current_folder = os.getcwd()
|
|
235
|
+
add_current_folder = "" not in sys.path and current_folder not in sys.path
|
|
236
|
+
if add_current_folder:
|
|
237
|
+
sys.path.insert(0, current_folder)
|
|
238
|
+
|
|
239
|
+
def show_warning(message: Warning | str, *_: object, **__: object) -> None:
|
|
240
|
+
print(f"{parser.prog}: warning: {message}", file=sys.stderr)
|
|
241
|
+
|
|
242
|
+
try:
|
|
243
|
+
with warnings.catch_warnings():
|
|
244
|
+
warnings.showwarning = show_warning
|
|
245
|
+
if arguments.command == "export":
|
|
246
|
+
return _export(arguments)
|
|
247
|
+
return _generate(arguments)
|
|
248
|
+
except _CommandError as error:
|
|
249
|
+
print(f"{parser.prog}: error: {error}", file=sys.stderr)
|
|
250
|
+
return 1
|
|
251
|
+
finally:
|
|
252
|
+
if add_current_folder and current_folder in sys.path:
|
|
253
|
+
sys.path.remove(current_folder)
|