././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1722320324.4395576 voluptuous_openapi-0.0.5/0000755000175100001770000000000014652102704015102 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722320312.0 voluptuous_openapi-0.0.5/LICENSE0000644000175100001770000002612214652102670016114 0ustar00runnerdocker Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2018 Paulus Schoutsen Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722320312.0 voluptuous_openapi-0.0.5/MANIFEST.in0000644000175100001770000000004314652102670016637 0ustar00runnerdockerinclude tests/*.py include LICENSE ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1722320324.4395576 voluptuous_openapi-0.0.5/PKG-INFO0000644000175100001770000000050414652102704016176 0ustar00runnerdockerMetadata-Version: 2.1 Name: voluptuous-openapi Version: 0.0.5 Summary: Convert voluptuous schemas to OpenAPI Schema object Home-page: https://github.com/home-assistant-libs/voluptuous-openapi Author: Denis Shulyaka Author-email: Shulyaka@gmail.com License: Apache License 2.0 License-File: LICENSE Requires-Dist: voluptuous ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722320312.0 voluptuous_openapi-0.0.5/README.md0000644000175100001770000000245014652102670016364 0ustar00runnerdocker# Voluptuous OpenAPI Convert Voluptuous schemas to [OpenAPI Schema object](https://spec.openapis.org/oas/v3.0.3#schema-object). ```python schema = {} schema[vol.Required('name')] = vol.All(str, vol.Length(min=5)) schema[vol.Required('age', description='Age in full years')] = vol.All(vol.Coerce(int), vol.Range(min=18)) schema[vol.Optional('hobby', default='not specified')] = str schema = vol.Schema(schema) ``` becomes ```json { "type": "object", "properties": { "name": { "type": "string", "minLength": 5, }, "age": { "type": "integer", "minimum": 18, "description": "Age in full years", }, "hobby": { "type": "string", "default": "not specified", }, }, "required": ["name", "age"], } ``` See the tests for more examples. ## Custom serializer You can pass a custom serializer to be able to process custom validators. If the serializer returns `UNSUPPORTED`, it will return to normal processing. Example: ```python from voluptuous_openai import UNSUPPORTED, convert def custom_convert(value): if value is my_custom_validator: return {'pattern': '^[a-zA-Z0-9]$'} return UNSUPPORTED convert(value, custom_serializer=custom_convert) ``` ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1722320324.4395576 voluptuous_openapi-0.0.5/setup.cfg0000644000175100001770000000022214652102704016717 0ustar00runnerdocker[tool:pytest] testpaths = tests norecursedirs = .git [flake8] ignore = E501, W503, E203, D202, W504 [egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722320312.0 voluptuous_openapi-0.0.5/setup.py0000644000175100001770000000065214652102670016621 0ustar00runnerdockerfrom setuptools import setup setup( name="voluptuous-openapi", version="0.0.5", description="Convert voluptuous schemas to OpenAPI Schema object", url="https://github.com/home-assistant-libs/voluptuous-openapi", author="Denis Shulyaka", author_email="Shulyaka@gmail.com", license="Apache License 2.0", install_requires=["voluptuous"], packages=["voluptuous_openapi"], zip_safe=True, ) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1722320324.4355576 voluptuous_openapi-0.0.5/tests/0000755000175100001770000000000014652102704016244 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722320312.0 voluptuous_openapi-0.0.5/tests/test_lib.py0000644000175100001770000003145114652102670020431 0ustar00runnerdockerfrom enum import Enum import voluptuous as vol from typing import Any, TypeVar from voluptuous_openapi import UNSUPPORTED, convert def test_int_schema(): for value in int, vol.Coerce(int): assert {"type": "integer"} == convert(vol.Schema(value)) def test_str_schema(): for value in str, vol.Coerce(str): assert {"type": "string"} == convert(vol.Schema(value)) def test_float_schema(): for value in float, vol.Coerce(float): assert {"type": "number"} == convert(vol.Schema(value)) def test_bool_schema(): for value in bool, vol.Coerce(bool): assert {"type": "boolean"} == convert(vol.Schema(value)) def test_integer_clamp(): assert { "type": "integer", "minimum": 100, "maximum": 1000, } == convert(vol.Schema(vol.All(vol.Coerce(int), vol.Clamp(min=100, max=1000)))) def test_length(): assert { "type": "string", "minLength": 100, "maxLength": 1000, } == convert(vol.Schema(vol.All(vol.Coerce(str), vol.Length(min=100, max=1000)))) def test_datetime(): assert { "type": "string", "format": "date-time", } == convert(vol.Schema(vol.Datetime())) def test_in(): assert {"type": "string", "enum": ["beer", "wine"]} == convert( vol.Schema(vol.In(["beer", "wine"])) ) def test_in_integer(): assert {"type": "integer", "enum": [1, 2]} == convert(vol.Schema(vol.In([1, 2]))) def test_in_dict(): assert { "type": "string", "enum": ["en_US", "zh_CN"], } == convert( vol.Schema( vol.In({"en_US": "American English", "zh_CN": "Chinese (Simplified)"}) ) ) def test_dict(): assert { "type": "object", "properties": { "name": { "type": "string", "minLength": 5, }, "age": { "type": "integer", "minimum": 18, }, "hobby": { "type": "string", "default": "not specified", }, }, "required": ["name", "age"], } == convert( vol.Schema( { vol.Required("name"): vol.All(str, vol.Length(min=5)), vol.Required("age"): vol.All(vol.Coerce(int), vol.Range(min=18)), vol.Optional("hobby", default="not specified"): str, } ) ) assert {"type": "object", "additionalProperties": True} == convert(vol.Schema(dict)) assert {"type": "object", "additionalProperties": True} == convert( vol.Schema(dict[str, Any]) ) assert {"type": "object", "additionalProperties": {"type": "integer"}} == convert( vol.Schema({str: int}) ) assert { "type": "object", "properties": {"x": {"type": "integer"}}, "required": [], "additionalProperties": {"type": "string"}, } == convert(vol.Schema({"x": int, str: str})) assert {"type": "object", "properties": {}, "required": []} == convert( vol.Schema({}) ) def string(x: str) -> str: return x assert {"type": "object", "additionalProperties": {"type": "string"}} == convert( vol.Schema({string: string}) ) assert {"type": "object", "additionalProperties": True} == convert( vol.Schema(object) ) assert {"type": "object", "additionalProperties": True} == convert( vol.Schema({string: object}) ) def test_tuple(): assert {"type": "array", "items": {"type": "string"}} == convert(vol.Schema(tuple)) assert {"type": "array", "items": {"type": "string"}} == convert( vol.Schema(tuple[Any]) ) assert {"type": "array", "items": {"type": "integer"}} == convert( vol.Schema(tuple[int]) ) def test_marker_description(): assert { "type": "object", "properties": { "name": { "type": "string", "description": "Description of name", }, }, "required": ["name"], } == convert( vol.Schema( { vol.Required("name", description="Description of name"): str, } ) ) def test_lower(): assert { "type": "string", "format": "lower", } == convert(vol.Schema(vol.All(vol.Lower, str))) def test_upper(): assert { "type": "string", "format": "upper", } == convert(vol.Schema(vol.All(vol.Upper, str))) def test_capitalize(): assert { "type": "string", "format": "capitalize", } == convert(vol.Schema(vol.All(vol.Capitalize, str))) def test_title(): assert { "type": "string", "format": "title", } == convert(vol.Schema(vol.All(vol.Title, str))) def test_strip(): assert { "type": "string", "format": "strip", } == convert(vol.Schema(vol.All(vol.Strip, str))) def test_email(): assert { "type": "string", "format": "email", } == convert(vol.Schema(vol.All(vol.Email, str))) def test_url(): assert { "type": "string", "format": "url", } == convert(vol.Schema(vol.All(vol.Url, str))) def test_fqdnurl(): assert { "type": "string", "format": "fqdnurl", } == convert(vol.Schema(vol.All(vol.FqdnUrl, str))) def test_maybe(): assert { "type": "string", "nullable": True, } == convert(vol.Schema(vol.Maybe(str))) def test_custom_serializer(): def custem_serializer(schema): if schema is str: return {"pattern": "[A-Z]{1,8}\\.[A-Z]{3,3}", "type": "string"} return UNSUPPORTED assert { "type": "string", "pattern": "[A-Z]{1,8}\\.[A-Z]{3,3}", "format": "upper", } == convert( vol.Schema(vol.All(vol.Upper, str)), custom_serializer=custem_serializer ) def test_constant(): assert {"type": "boolean", "enum": [True]} == convert(vol.Schema(True)) assert {"type": "boolean", "enum": [False]} == convert(vol.Schema(False)) assert {"type": "string", "enum": ["Hello"]} == convert(vol.Schema("Hello")) assert {"type": "integer", "enum": [1]} == convert(vol.Schema(1)) assert {"type": "number", "enum": [1.5]} == convert(vol.Schema(1.5)) assert { "type": "object", "nullable": True, "description": "Must be null", } == convert(vol.Schema(None)) assert { "type": "object", "nullable": True, "description": "Must be null", } == convert(vol.Schema(type(None))) def test_enum(): class StringEnum(Enum): ONE = "one" TWO = "two" assert {"type": "string", "enum": ["one", "two"]} == convert( vol.Schema(vol.Coerce(StringEnum)) ) class IntEnum(Enum): ONE = 1 TWO = 2 assert {"type": "integer", "enum": [1, 2]} == convert( vol.Schema(vol.Coerce(IntEnum)) ) def test_list(): assert { "type": "array", "items": {"type": "string"}, } == convert(vol.Schema([str])) assert {"type": "array", "items": {"type": "string"}} == convert(vol.Schema(list)) assert {"type": "array", "items": {"type": "string"}} == convert( vol.Schema(list[Any]) ) assert {"type": "array", "items": {"type": "integer"}} == convert( vol.Schema(list[int]) ) def test_any_of(): assert {"anyOf": [{"type": "number"}, {"type": "integer"}]} == convert( vol.Any(float, int) ) assert {"anyOf": [{"type": "number"}, {"type": "integer"}]} == convert( vol.Any(float, int, float, int, int) ) assert {"type": "object", "additionalProperties": True} == convert( vol.Any(float, int, object) ) assert {"type": "integer", "nullable": True, "enum": [1, 2]} == convert( vol.Schema(vol.In([1, 2, None])) ) assert {"type": "integer", "enum": [1, 2, 3]} == convert( vol.Schema(vol.Any(1, 2, 3)) ) assert { "anyOf": [{"type": "number"}, {"type": "integer"}, {"type": "string"}] } == convert( vol.Any( vol.Any(float, int), vol.Any(int, float), vol.Any(float, vol.Any(int, str)) ) ) assert { "anyOf": [{"type": "number"}, {"type": "integer"}], "nullable": True, } == convert(vol.Any(vol.Maybe(float), vol.Maybe(int))) def test_all_of(): assert {"allOf": [{"minimum": 5}, {"minimum": 10}]} == convert( vol.All(vol.Range(min=5), vol.Range(min=10)) ) assert {"type": "string"} == convert(vol.All(object, str)) assert {"type": "object", "additionalProperties": {"type": "string"}} == convert( vol.All(object, {str: str}) ) assert {"maximum": 10, "minimum": 5, "type": "number"} == convert( vol.All(vol.Range(min=5), vol.Range(max=10)) ) assert {"maximum": 10, "minimum": 5, "type": "number"} == convert( vol.All( vol.All(vol.Range(min=5), float), vol.All(vol.All(vol.Range(max=10), float), float), ) ) def test_key_any(): assert { "type": "object", "properties": { "name": { "type": "string", }, "area": { "type": "string", "description": "The ID or the area", }, }, "required": [], } == convert( vol.Schema( { vol.Any( "name", vol.Optional("area", description="The ID or the area") ): str } ) ) assert { "properties": { "conversation_command": {"type": "string"}, "hours": {"type": "integer"}, "minutes": {"type": "integer"}, "name": {"type": "string"}, "seconds": {"type": "integer"}, }, "required": [], "type": "object", } == convert( { vol.Required(vol.Any("hours", "minutes", "seconds")): int, vol.Optional("name"): str, vol.Optional("conversation_command"): str, } ) def test_function(): def validator(data): return data assert { "type": "object", "properties": {"test_data": {"type": "string"}}, "required": [], } == convert(vol.Schema({"test_data": validator})) def validator_str(data: str): return data assert {"type": "string"} == convert(vol.Schema(validator_str)) def validator_any(data: Any): return data assert {} == convert(validator_any) assert {"type": "integer"} == convert(vol.All(vol.Coerce(int), lambda x: x / 100)) def validator_nullable(data: float | None): return data assert {"type": "number", "nullable": True} == convert( vol.Schema(validator_nullable) ) def validator_union(data: float | int): return data assert {"anyOf": [{"type": "number"}, {"type": "integer"}]} == convert( vol.Schema(validator_union) ) _T = TypeVar("_T") def validator_nullable_2(value: _T | None): return value assert { "type": "object", "properties": {"var": {"type": "array", "items": {"type": "string"}}}, "required": [], } == convert(vol.Schema({"var": vol.All(validator_nullable_2, [validator_any])})) def validator_list_int(value: list[int]): return value assert {"type": "array", "items": {"type": "integer"}} == convert( validator_list_int ) def validator_list_any(value: list[Any]): return value assert {"type": "array", "items": {"type": "string"}} == convert(validator_list_any) def validator_list(value: list): return value assert {"type": "array", "items": {"type": "string"}} == convert(validator_list) def validator_set_int(value: set[int]): return value assert {"type": "array", "items": {"type": "integer"}} == convert(validator_set_int) def validator_set_any(value: set[Any]): return value assert {"type": "array", "items": {"type": "string"}} == convert(validator_set_any) def validator_set(value: set): return value assert {"type": "array", "items": {"type": "string"}} == convert(validator_set) def validator_dict(value: dict): return value assert {"type": "object", "additionalProperties": True} == convert(validator_dict) def validator_dict_int(value: dict[str, int]): return value assert {"type": "object", "additionalProperties": {"type": "integer"}} == convert( validator_dict_int ) def test_nested_in_list(): assert { "properties": { "drink": { "type": "array", "items": {"type": "string", "enum": ["beer", "wine"]}, }, }, "required": [], "type": "object", } == convert(vol.Schema({vol.Optional("drink"): [vol.In(["beer", "wine"])]})) assert {"type": "integer", "enum": [1, 2, 3]} == convert( vol.Schema(vol.In([1, 2, 3])) ) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1722320324.4355576 voluptuous_openapi-0.0.5/voluptuous_openapi/0000755000175100001770000000000014652102704021062 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722320312.0 voluptuous_openapi-0.0.5/voluptuous_openapi/__init__.py0000644000175100001770000003152114652102670023177 0ustar00runnerdocker"""Module to convert voluptuous schemas to dictionaries.""" from collections.abc import Callable, Mapping, Sequence from enum import Enum from typing import Any, TypeVar, Union, get_args, get_origin, get_type_hints from types import NoneType, UnionType from inspect import signature import voluptuous as vol TYPES_MAP = { int: "integer", str: "string", float: "number", bool: "boolean", } UNSUPPORTED = object() def convert(schema: Any, *, custom_serializer: Callable | None = None) -> dict: """Convert a voluptuous schema to a OpenAPI Schema object.""" # pylint: disable=too-many-return-statements,too-many-branches def ensure_default(value: dict[str:Any]): """Make sure that type is set.""" if all(x not in value for x in ("type", "anyOf", "oneOf", "allOf", "not")): if any( x in value for x in ("minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum") ): value["type"] = "number" else: value["type"] = "string" return value additional_properties = None if isinstance(schema, vol.Schema): if schema.extra == vol.ALLOW_EXTRA: additional_properties = True schema = schema.schema if custom_serializer: val = custom_serializer(schema) if val is not UNSUPPORTED: return val if isinstance(schema, vol.Object): schema = schema.schema if custom_serializer: val = custom_serializer(schema) if val is not UNSUPPORTED: return val if isinstance(schema, Mapping): properties = {} required = [] for key, value in schema.items(): description = None if isinstance(key, vol.Marker): pkey = key.schema description = key.description else: pkey = key pval = convert(value, custom_serializer=custom_serializer) if description: pval["description"] = key.description if isinstance(key, (vol.Required, vol.Optional)): if key.default is not vol.UNDEFINED: pval["default"] = key.default() pval = ensure_default(pval) if isinstance(pkey, vol.Any): for val in pkey.validators: if isinstance(val, vol.Marker): if val.description: properties[str(val.schema)] = pval.copy() properties[str(val.schema)]["description"] = val.description else: properties[str(val)] = pval else: properties[str(val)] = pval elif isinstance(pkey, str): properties[pkey] = pval else: if pval == {"type": "object", "additionalProperties": True}: pval = True additional_properties = None if additional_properties is None: additional_properties = pval if isinstance(key, vol.Required) and not isinstance(pkey, vol.Any): required.append(str(pkey)) val = {"type": "object"} if properties or not additional_properties: val["properties"] = properties val["required"] = required if additional_properties: val["additionalProperties"] = additional_properties return val if isinstance(schema, vol.All): val = {} fallback = False allOf = [] for validator in schema.validators: v = convert(validator, custom_serializer=custom_serializer) if ( not v or v in allOf or v == {"type": "object", "additionalProperties": True} ): continue if any(v[key] != val[key] for key in v.keys() & val.keys()): # Some of the keys are intersecting - fallback to allOf fallback = True allOf.append(v) if not fallback: val.update(v) if fallback: return {"allOf": allOf} return ensure_default(val) if isinstance(schema, (vol.Clamp, vol.Range)): val = {} if schema.min is not None: if isinstance(schema, vol.Clamp) or schema.min_included: val["minimum"] = schema.min else: val["exclusiveMinimum"] = schema.min if schema.max is not None: if isinstance(schema, vol.Clamp) or schema.max_included: val["maximum"] = schema.max else: val["exclusiveMaximum"] = schema.max return val if isinstance(schema, vol.Length): val = {} if schema.min is not None: val["minLength"] = schema.min if schema.max is not None: val["maxLength"] = schema.max return val if isinstance(schema, vol.Datetime): return { "type": "string", "format": "date-time", } if isinstance(schema, vol.Match): return {"pattern": schema.pattern.pattern} if isinstance(schema, vol.In): if isinstance(schema.container, Mapping): enum_values = list(schema.container.keys()) else: enum_values = schema.container # Infer the enum type based on the type of the first value, but default # to a string as a fallback. nullable = False while None in enum_values: enum_values.remove(None) nullable = True while NoneType in enum_values: enum_values.remove(NoneType) nullable = True if enum_values: enum_type = TYPES_MAP.get(type(enum_values[0]), "string") else: enum_type = "string" if nullable: return {"type": enum_type, "enum": enum_values, "nullable": True} return {"type": enum_type, "enum": enum_values} if schema in ( vol.Lower, vol.Upper, vol.Capitalize, vol.Title, vol.Strip, vol.Email, vol.Url, vol.FqdnUrl, ): return { "format": schema.__name__.lower(), } if isinstance(schema, vol.Any): schema = schema.validators if None in schema or NoneType in schema: schema = [val for val in schema if val is not None and val is not NoneType] nullable = True else: nullable = False if len(schema) == 1: result = convert(schema[0], custom_serializer=custom_serializer) else: anyOf = [ convert(val, custom_serializer=custom_serializer) for val in schema ] # Merge nested anyOf tmpAnyOf = [] for item in anyOf: if item.get("anyOf"): tmpAnyOf.extend(item["anyOf"]) if item.get("nullable"): nullable = True else: tmpAnyOf.append(item) anyOf = tmpAnyOf if {"type": "object", "additionalProperties": True} in anyOf: result = {"type": "object", "additionalProperties": True} else: tmpAnyOf = [] for item in anyOf: if item in tmpAnyOf: # Remove duplicated items continue tmpItem = item.copy() if item.get( "nullable" ): # Merge "nullable" property into an existing item tmpItem.pop("nullable") if tmpItem in tmpAnyOf: tmpAnyOf[tmpAnyOf.index(tmpItem)]["nullable"] = True continue tmpItem["nullable"] = True if tmpItem in tmpAnyOf: # Ignore duplicated items that are nullable continue if item.get("enum"): merged = False for item2 in tmpAnyOf: if item2.get("enum") and item.get("type") == item2.get( "type" ): # Merge nested enums of the same type if item.get("nullable"): item2["nullable"] = True item2["enum"] = list(set(item2["enum"] + item["enum"])) merged = True break if merged: continue tmpAnyOf.append(item) anyOf = tmpAnyOf # Remove excessive nullables null_count = 0 if not nullable: for item in anyOf: if item.get("nullable") is True: null_count = null_count + 1 if null_count > 1: break if nullable or null_count > 1: nullable = True tmpAnyOf = [] for item in anyOf: if "nullable" not in item: tmpAnyOf.append(item) continue tmpItem = item.copy() tmpItem.pop("nullable") tmpAnyOf.append(tmpItem) anyOf = tmpAnyOf if len(anyOf) == 1: result = anyOf[0] else: result = {"anyOf": anyOf} if nullable: result["nullable"] = True return result if isinstance(schema, vol.Coerce): schema = schema.type if isinstance(schema, (str, int, float, bool)): return {"type": TYPES_MAP[type(schema)], "enum": [schema]} if schema is None: return {"type": "object", "nullable": True, "description": "Must be null"} if ( get_origin(schema) is list or get_origin(schema) is set or get_origin(schema) is tuple ): schema = [get_args(schema)[0]] if isinstance(schema, Sequence): if len(schema) == 1: return { "type": "array", "items": ensure_default( convert(schema[0], custom_serializer=custom_serializer) ), } return { "type": "array", "items": [ ensure_default(convert(s, custom_serializer=custom_serializer)) for s in schema.items() ], } if schema in TYPES_MAP: return {"type": TYPES_MAP[schema]} if get_origin(schema) is dict: if get_args(schema)[1] is Any or isinstance(get_args(schema)[1], TypeVar): schema = dict else: return convert({get_args(schema)[0]: get_args(schema)[1]}) if isinstance(schema, type): if schema is dict: return {"type": "object", "additionalProperties": True} if schema is list or schema is set or schema is tuple: return {"type": "array", "items": ensure_default({})} if issubclass(schema, Enum): enum_values = list(item.value for item in schema) nullable = False while None in enum_values: enum_values.remove(None) nullable = True while NoneType in enum_values: enum_values.remove(NoneType) nullable = True if enum_values: enum_type = TYPES_MAP.get(type(enum_values[0]), "string") else: enum_type = "string" if nullable: return {"type": enum_type, "enum": enum_values, "nullable": True} return {"type": enum_type, "enum": enum_values} elif schema is NoneType: return {"type": "object", "nullable": True, "description": "Must be null"} if schema is object: return {"type": "object", "additionalProperties": True} if callable(schema): schema = get_type_hints(schema).get( list(signature(schema).parameters.keys())[0], Any ) if schema is Any or isinstance(schema, TypeVar): return {} if isinstance(schema, UnionType) or get_origin(schema) is Union: schema = [t for t in get_args(schema) if not isinstance(t, TypeVar)] if len(schema) > 1: schema = vol.Any(*schema) elif len(schema) == 1 and schema[0] is not NoneType: schema = schema[0] else: return {} return ensure_default(convert(schema, custom_serializer=custom_serializer)) raise ValueError("Unable to convert schema: {}".format(schema)) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1722320324.4395576 voluptuous_openapi-0.0.5/voluptuous_openapi.egg-info/0000755000175100001770000000000014652102704022554 5ustar00runnerdocker././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722320324.0 voluptuous_openapi-0.0.5/voluptuous_openapi.egg-info/PKG-INFO0000644000175100001770000000050414652102704023650 0ustar00runnerdockerMetadata-Version: 2.1 Name: voluptuous-openapi Version: 0.0.5 Summary: Convert voluptuous schemas to OpenAPI Schema object Home-page: https://github.com/home-assistant-libs/voluptuous-openapi Author: Denis Shulyaka Author-email: Shulyaka@gmail.com License: Apache License 2.0 License-File: LICENSE Requires-Dist: voluptuous ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722320324.0 voluptuous_openapi-0.0.5/voluptuous_openapi.egg-info/SOURCES.txt0000644000175100001770000000052714652102704024444 0ustar00runnerdockerLICENSE MANIFEST.in README.md setup.cfg setup.py tests/test_lib.py voluptuous_openapi/__init__.py voluptuous_openapi.egg-info/PKG-INFO voluptuous_openapi.egg-info/SOURCES.txt voluptuous_openapi.egg-info/dependency_links.txt voluptuous_openapi.egg-info/requires.txt voluptuous_openapi.egg-info/top_level.txt voluptuous_openapi.egg-info/zip-safe././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722320324.0 voluptuous_openapi-0.0.5/voluptuous_openapi.egg-info/dependency_links.txt0000644000175100001770000000000114652102704026622 0ustar00runnerdocker ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722320324.0 voluptuous_openapi-0.0.5/voluptuous_openapi.egg-info/requires.txt0000644000175100001770000000001314652102704025146 0ustar00runnerdockervoluptuous ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722320324.0 voluptuous_openapi-0.0.5/voluptuous_openapi.egg-info/top_level.txt0000644000175100001770000000002314652102704025301 0ustar00runnerdockervoluptuous_openapi ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722320324.0 voluptuous_openapi-0.0.5/voluptuous_openapi.egg-info/zip-safe0000644000175100001770000000000114652102704024204 0ustar00runnerdocker