@autorest/python 5.15.0 → 5.18.0

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 (118) hide show
  1. package/ChangeLog.md +98 -4
  2. package/README.md +30 -4
  3. package/autorest/__init__.py +2 -3
  4. package/autorest/black/__init__.py +12 -5
  5. package/autorest/codegen/__init__.py +122 -211
  6. package/autorest/codegen/models/__init__.py +122 -78
  7. package/autorest/codegen/models/base_builder.py +70 -72
  8. package/autorest/codegen/models/base_model.py +7 -5
  9. package/autorest/codegen/models/{base_schema.py → base_type.py} +68 -45
  10. package/autorest/codegen/models/client.py +193 -40
  11. package/autorest/codegen/models/code_model.py +145 -245
  12. package/autorest/codegen/models/combined_type.py +107 -0
  13. package/autorest/codegen/models/constant_type.py +122 -0
  14. package/autorest/codegen/models/credential_types.py +224 -0
  15. package/autorest/codegen/models/dictionary_type.py +131 -0
  16. package/autorest/codegen/models/enum_type.py +195 -0
  17. package/autorest/codegen/models/imports.py +93 -41
  18. package/autorest/codegen/models/list_type.py +149 -0
  19. package/autorest/codegen/models/lro_operation.py +90 -133
  20. package/autorest/codegen/models/lro_paging_operation.py +28 -12
  21. package/autorest/codegen/models/model_type.py +262 -0
  22. package/autorest/codegen/models/operation.py +412 -259
  23. package/autorest/codegen/models/operation_group.py +80 -91
  24. package/autorest/codegen/models/paging_operation.py +101 -117
  25. package/autorest/codegen/models/parameter.py +302 -341
  26. package/autorest/codegen/models/parameter_list.py +373 -357
  27. package/autorest/codegen/models/primitive_types.py +544 -0
  28. package/autorest/codegen/models/property.py +136 -134
  29. package/autorest/codegen/models/request_builder.py +138 -86
  30. package/autorest/codegen/models/request_builder_parameter.py +122 -86
  31. package/autorest/codegen/models/response.py +325 -0
  32. package/autorest/codegen/models/utils.py +13 -17
  33. package/autorest/codegen/serializers/__init__.py +212 -112
  34. package/autorest/codegen/serializers/builder_serializer.py +931 -1040
  35. package/autorest/codegen/serializers/client_serializer.py +140 -84
  36. package/autorest/codegen/serializers/general_serializer.py +26 -50
  37. package/autorest/codegen/serializers/import_serializer.py +96 -31
  38. package/autorest/codegen/serializers/metadata_serializer.py +39 -79
  39. package/autorest/codegen/serializers/model_base_serializer.py +62 -34
  40. package/autorest/codegen/serializers/model_generic_serializer.py +9 -10
  41. package/autorest/codegen/serializers/model_init_serializer.py +4 -2
  42. package/autorest/codegen/serializers/model_python3_serializer.py +29 -22
  43. package/autorest/codegen/serializers/operation_groups_serializer.py +21 -19
  44. package/autorest/codegen/serializers/operations_init_serializer.py +23 -11
  45. package/autorest/codegen/serializers/parameter_serializer.py +174 -0
  46. package/autorest/codegen/serializers/patch_serializer.py +4 -1
  47. package/autorest/codegen/serializers/request_builders_serializer.py +57 -0
  48. package/autorest/codegen/serializers/utils.py +0 -126
  49. package/autorest/codegen/templates/MANIFEST.in.jinja2 +1 -0
  50. package/autorest/codegen/templates/{service_client.py.jinja2 → client.py.jinja2} +7 -7
  51. package/autorest/codegen/templates/config.py.jinja2 +13 -13
  52. package/autorest/codegen/templates/enum.py.jinja2 +4 -4
  53. package/autorest/codegen/templates/enum_container.py.jinja2 +1 -1
  54. package/autorest/codegen/templates/init.py.jinja2 +3 -3
  55. package/autorest/codegen/templates/lro_operation.py.jinja2 +6 -5
  56. package/autorest/codegen/templates/lro_paging_operation.py.jinja2 +6 -5
  57. package/autorest/codegen/templates/metadata.json.jinja2 +36 -35
  58. package/autorest/codegen/templates/model.py.jinja2 +23 -24
  59. package/autorest/codegen/templates/model_container.py.jinja2 +2 -1
  60. package/autorest/codegen/templates/model_init.py.jinja2 +3 -5
  61. package/autorest/codegen/templates/operation.py.jinja2 +10 -14
  62. package/autorest/codegen/templates/operation_group.py.jinja2 +9 -15
  63. package/autorest/codegen/templates/operation_groups_container.py.jinja2 +1 -1
  64. package/autorest/codegen/templates/operation_tools.jinja2 +8 -2
  65. package/autorest/codegen/templates/paging_operation.py.jinja2 +7 -8
  66. package/autorest/codegen/templates/request_builder.py.jinja2 +19 -10
  67. package/autorest/codegen/templates/setup.py.jinja2 +9 -3
  68. package/autorest/codegen/templates/vendor.py.jinja2 +1 -1
  69. package/autorest/jsonrpc/__init__.py +7 -12
  70. package/autorest/jsonrpc/localapi.py +4 -3
  71. package/autorest/jsonrpc/server.py +28 -9
  72. package/autorest/jsonrpc/stdstream.py +13 -6
  73. package/autorest/m2r/__init__.py +5 -8
  74. package/autorest/m4reformatter/__init__.py +1126 -0
  75. package/autorest/multiapi/__init__.py +24 -14
  76. package/autorest/multiapi/models/client.py +21 -11
  77. package/autorest/multiapi/models/code_model.py +23 -10
  78. package/autorest/multiapi/models/config.py +4 -1
  79. package/autorest/multiapi/models/constant_global_parameter.py +1 -0
  80. package/autorest/multiapi/models/global_parameter.py +2 -1
  81. package/autorest/multiapi/models/global_parameters.py +14 -8
  82. package/autorest/multiapi/models/imports.py +24 -17
  83. package/autorest/multiapi/models/mixin_operation.py +5 -5
  84. package/autorest/multiapi/models/operation_group.py +2 -1
  85. package/autorest/multiapi/models/operation_mixin_group.py +21 -10
  86. package/autorest/multiapi/serializers/__init__.py +20 -25
  87. package/autorest/multiapi/serializers/import_serializer.py +47 -17
  88. package/autorest/multiapi/serializers/multiapi_serializer.py +17 -17
  89. package/autorest/multiapi/templates/multiapi_config.py.jinja2 +3 -3
  90. package/autorest/multiapi/templates/multiapi_init.py.jinja2 +2 -2
  91. package/autorest/multiapi/templates/multiapi_operations_mixin.py.jinja2 +4 -4
  92. package/autorest/multiapi/templates/multiapi_service_client.py.jinja2 +9 -9
  93. package/autorest/multiapi/utils.py +3 -3
  94. package/autorest/postprocess/__init__.py +202 -0
  95. package/autorest/postprocess/get_all.py +19 -0
  96. package/autorest/postprocess/venvtools.py +73 -0
  97. package/autorest/preprocess/__init__.py +210 -0
  98. package/autorest/preprocess/helpers.py +54 -0
  99. package/autorest/{namer → preprocess}/python_mappings.py +25 -32
  100. package/package.json +3 -3
  101. package/run-python3.js +2 -3
  102. package/venvtools.py +1 -1
  103. package/autorest/codegen/models/constant_schema.py +0 -101
  104. package/autorest/codegen/models/credential_model.py +0 -47
  105. package/autorest/codegen/models/credential_schema.py +0 -91
  106. package/autorest/codegen/models/credential_schema_policy.py +0 -77
  107. package/autorest/codegen/models/dictionary_schema.py +0 -103
  108. package/autorest/codegen/models/enum_schema.py +0 -215
  109. package/autorest/codegen/models/list_schema.py +0 -123
  110. package/autorest/codegen/models/object_schema.py +0 -253
  111. package/autorest/codegen/models/primitive_schemas.py +0 -466
  112. package/autorest/codegen/models/request_builder_parameter_list.py +0 -280
  113. package/autorest/codegen/models/rest.py +0 -42
  114. package/autorest/codegen/models/schema_request.py +0 -45
  115. package/autorest/codegen/models/schema_response.py +0 -136
  116. package/autorest/codegen/serializers/rest_serializer.py +0 -57
  117. package/autorest/namer/__init__.py +0 -25
  118. package/autorest/namer/name_converter.py +0 -412
@@ -1,91 +0,0 @@
1
- # -------------------------------------------------------------------------
2
- # Copyright (c) Microsoft Corporation. All rights reserved.
3
- # Licensed under the MIT License. See License.txt in the project root for
4
- # license information.
5
- # --------------------------------------------------------------------------
6
- from typing import Any
7
- from .base_schema import BaseSchema
8
- from .imports import FileImport, ImportType, TypingSection
9
-
10
- class CredentialSchema(BaseSchema):
11
- def __init__(self) -> None: # pylint: disable=super-init-not-called
12
- self.default_value = None
13
-
14
- def type_annotation(self, *, is_operation_file: bool = False) -> str:
15
- raise ValueError("Children classes should set their own type annotation")
16
-
17
- @property
18
- def docstring_type(self) -> str:
19
- return self.serialization_type
20
-
21
- @property
22
- def docstring_text(self) -> str:
23
- return "credential"
24
-
25
- @property
26
- def serialization_type(self) -> str:
27
- # this property is added, because otherwise pylint says that
28
- # abstract serialization_type in BaseSchema is not overridden
29
- pass
30
-
31
- def get_json_template_representation(self, **kwargs: Any) -> Any:
32
- raise TypeError("You should not try to get a JSON template representation of a CredentialSchema")
33
-
34
- def get_files_and_data_template_representation(self, **kwargs: Any) -> Any:
35
- raise TypeError("You should not try to get a files template representation of a CredentialSchema")
36
-
37
-
38
- class AzureKeyCredentialSchema(CredentialSchema):
39
-
40
- @property
41
- def serialization_type(self) -> str:
42
- return "~azure.core.credentials.AzureKeyCredential"
43
-
44
- def type_annotation(self, *, is_operation_file: bool = False) -> str: # pylint: disable=unused-argument
45
- return "AzureKeyCredential"
46
-
47
- def imports(self) -> FileImport:
48
- file_import = FileImport()
49
- file_import.add_submodule_import(
50
- "azure.core.credentials",
51
- "AzureKeyCredential",
52
- ImportType.AZURECORE,
53
- typing_section=TypingSection.CONDITIONAL
54
- )
55
- return file_import
56
-
57
-
58
- class TokenCredentialSchema(CredentialSchema):
59
- def __init__(self, async_mode) -> None:
60
- super(TokenCredentialSchema, self).__init__()
61
- self.async_mode = async_mode
62
- self.async_type = "~azure.core.credentials_async.AsyncTokenCredential"
63
- self.sync_type = "~azure.core.credentials.TokenCredential"
64
-
65
- @property
66
- def serialization_type(self) -> str:
67
- if self.async_mode:
68
- return self.async_type
69
- return self.sync_type
70
-
71
- def type_annotation(self, *, is_operation_file: bool = False) -> str: # pylint: disable=unused-argument
72
- if self.async_mode:
73
- return '"AsyncTokenCredential"'
74
- return '"TokenCredential"'
75
-
76
-
77
- def imports(self) -> FileImport:
78
- file_import = FileImport()
79
- if self.async_mode:
80
- file_import.add_submodule_import(
81
- "azure.core.credentials_async", "AsyncTokenCredential",
82
- ImportType.AZURECORE,
83
- typing_section=TypingSection.TYPING
84
- )
85
- else:
86
- file_import.add_submodule_import(
87
- "azure.core.credentials", "TokenCredential",
88
- ImportType.AZURECORE,
89
- typing_section=TypingSection.TYPING
90
- )
91
- return file_import
@@ -1,77 +0,0 @@
1
- # -------------------------------------------------------------------------
2
- # Copyright (c) Microsoft Corporation. All rights reserved.
3
- # Licensed under the MIT License. See License.txt in the project root for
4
- # license information.
5
- # --------------------------------------------------------------------------
6
- from abc import abstractmethod
7
- from typing import List
8
- from .credential_schema import CredentialSchema
9
-
10
- class CredentialSchemaPolicy:
11
-
12
- def __init__(self, credential: CredentialSchema, *args, **kwargs) -> None: # pylint: disable=unused-argument
13
- self.credential = credential
14
-
15
- @abstractmethod
16
- def call(self, async_mode: bool) -> str:
17
- ...
18
-
19
- @classmethod
20
- def name(cls):
21
- return cls.__name__
22
-
23
-
24
- class BearerTokenCredentialPolicy(CredentialSchemaPolicy):
25
-
26
- def __init__(
27
- self,
28
- credential: CredentialSchema,
29
- credential_scopes: List[str]
30
- ) -> None:
31
- super().__init__(credential)
32
- self._credential_scopes = credential_scopes
33
-
34
- @property
35
- def credential_scopes(self):
36
- return self._credential_scopes
37
-
38
- def call(self, async_mode: bool) -> str:
39
- policy_name = f"Async{self.name()}" if async_mode else self.name()
40
- return f"policies.{policy_name}(self.credential, *self.credential_scopes, **kwargs)"
41
-
42
-
43
- class ARMChallengeAuthenticationPolicy(BearerTokenCredentialPolicy):
44
-
45
- def call(self, async_mode: bool) -> str:
46
- policy_name = f"Async{self.name()}" if async_mode else self.name()
47
- return f"{policy_name}(self.credential, *self.credential_scopes, **kwargs)"
48
-
49
-
50
- class AzureKeyCredentialPolicy(CredentialSchemaPolicy):
51
-
52
- def __init__(
53
- self,
54
- credential: CredentialSchema,
55
- credential_key_header_name: str
56
- ) -> None:
57
- super().__init__(credential)
58
- self._credential_key_header_name = credential_key_header_name
59
-
60
- @property
61
- def credential_key_header_name(self):
62
- return self._credential_key_header_name
63
-
64
- def call(self, async_mode: bool) -> str:
65
- return f'policies.AzureKeyCredentialPolicy(self.credential, "{self.credential_key_header_name}", **kwargs)'
66
-
67
- def get_credential_schema_policy_type(name):
68
- policies = [ARMChallengeAuthenticationPolicy, BearerTokenCredentialPolicy, AzureKeyCredentialPolicy]
69
- try:
70
- return next(p for p in policies if p.name().lower() == name.lower())
71
- except StopIteration:
72
- raise ValueError(
73
- "The credential policy you pass in with --credential-default-policy-type must be either "
74
- "{}".format(
75
- " or ".join([p.name() for p in policies])
76
- )
77
- )
@@ -1,103 +0,0 @@
1
- # -------------------------------------------------------------------------
2
- # Copyright (c) Microsoft Corporation. All rights reserved.
3
- # Licensed under the MIT License. See License.txt in the project root for
4
- # license information.
5
- # --------------------------------------------------------------------------
6
- from typing import Any, Dict, Optional
7
- from .base_schema import BaseSchema
8
- from .imports import FileImport, ImportType, TypingSection
9
-
10
- class DictionarySchema(BaseSchema):
11
- """Schema for dictionaries that will be serialized.
12
-
13
- :param yaml_data: the yaml data for this schema
14
- :type yaml_data: dict[str, Any]
15
- :param element_type: The type of the value for the dictionary
16
- :type element_type: ~autorest.models.BaseSchema
17
- """
18
-
19
- def __init__(
20
- self,
21
- namespace: str,
22
- yaml_data: Dict[str, Any],
23
- element_type: "BaseSchema"
24
- ) -> None:
25
- super(DictionarySchema, self).__init__(namespace=namespace, yaml_data=yaml_data)
26
- self.element_type = element_type
27
-
28
- @property
29
- def serialization_type(self) -> str:
30
- """Returns the serialization value for msrest.
31
-
32
- :return: The serialization value for msrest
33
- :rtype: str
34
- """
35
- return f"{{{self.element_type.serialization_type}}}"
36
-
37
- def type_annotation(self, *, is_operation_file: bool = False) -> str:
38
- """The python type used for type annotation
39
-
40
- :return: The type annotation for this schema
41
- :rtype: str
42
- """
43
- return f"Dict[str, {self.element_type.type_annotation(is_operation_file=is_operation_file)}]"
44
-
45
- @property
46
- def docstring_text(self) -> str:
47
- return f"dict mapping str to {self.element_type.docstring_text}"
48
-
49
- @property
50
- def docstring_type(self) -> str:
51
- """The python type used for RST syntax input and type annotation.
52
-
53
- :param str namespace: Optional. The namespace for the models.
54
- """
55
- return f"dict[str, {self.element_type.docstring_type}]"
56
-
57
- def xml_serialization_ctxt(self) -> Optional[str]:
58
- raise NotImplementedError("Dictionary schema does not support XML serialization.")
59
-
60
- def get_json_template_representation(self, **kwargs: Any) -> Any:
61
- return {
62
- f'"{"str"}"' : self.element_type.get_json_template_representation(**kwargs)
63
- }
64
-
65
- def get_files_and_data_template_representation(self, **kwargs: Any) -> Any:
66
- return {
67
- f'"{"str"}"' : self.element_type.get_files_and_data_template_representation(**kwargs)
68
- }
69
-
70
- @classmethod
71
- def from_yaml(cls, namespace: str, yaml_data: Dict[str, Any], **kwargs: Any) -> "DictionarySchema":
72
- """Constructs a DictionarySchema from yaml data.
73
-
74
- :param yaml_data: the yaml data from which we will construct this schema
75
- :type yaml_data: dict[str, Any]
76
-
77
- :return: A created DictionarySchema
78
- :rtype: ~autorest.models.DictionarySchema
79
- """
80
- element_schema = yaml_data["elementType"]
81
-
82
- from . import build_schema # pylint: disable=import-outside-toplevel
83
-
84
- element_type = build_schema(
85
- yaml_data=element_schema, **kwargs
86
- )
87
-
88
- return cls(
89
- namespace=namespace,
90
- yaml_data=yaml_data,
91
- element_type=element_type,
92
- )
93
-
94
- def imports(self) -> FileImport:
95
- file_import = FileImport()
96
- file_import.add_submodule_import("typing", "Dict", ImportType.STDLIB, TypingSection.CONDITIONAL)
97
- file_import.merge(self.element_type.imports())
98
- return file_import
99
-
100
- def model_file_imports(self) -> FileImport:
101
- file_import = self.imports()
102
- file_import.merge(self.element_type.model_file_imports())
103
- return file_import
@@ -1,215 +0,0 @@
1
- # -------------------------------------------------------------------------
2
- # Copyright (c) Microsoft Corporation. All rights reserved.
3
- # Licensed under the MIT License. See License.txt in the project root for
4
- # license information.
5
- # --------------------------------------------------------------------------
6
- from typing import Any, Dict, List, Optional, Set, Type
7
- from .base_schema import BaseSchema
8
- from .primitive_schemas import PrimitiveSchema, get_primitive_schema, StringSchema
9
- from .imports import FileImport, ImportType, TypingSection
10
-
11
-
12
- class EnumValue:
13
- """Model containing necessary information for a single value of an enum.
14
-
15
- :param str name: The name of this enum value
16
- :param str value: The value of this enum value
17
- :param str description: Optional. The description for this enum value
18
- """
19
-
20
- def __init__(self, name: str, value: str, description: Optional[str] = None) -> None:
21
- self.name = name
22
- self.value = value
23
- self.description = description
24
-
25
- @classmethod
26
- def from_yaml(cls, yaml_data: Dict[str, Any]) -> "EnumValue":
27
- """Constructs an EnumValue from yaml data.
28
-
29
- :param yaml_data: the yaml data from which we will construct this object
30
- :type yaml_data: dict[str, Any]
31
-
32
- :return: A created EnumValue
33
- :rtype: ~autorest.models.EnumValue
34
- """
35
- return cls(
36
- name=yaml_data["language"]["python"]["name"],
37
- value=yaml_data["value"],
38
- description=yaml_data["language"]["python"].get("description"),
39
- )
40
-
41
-
42
- class EnumSchema(BaseSchema):
43
- """Schema for enums that will be serialized.
44
-
45
- :param yaml_data: the yaml data for this schema
46
- :type yaml_data: dict[str, Any]
47
- :param str description: The description of this enum
48
- :param str name: The name of the enum.
49
- :type element_type: ~autorest.models.PrimitiveSchema
50
- :param values: List of the values for this enum
51
- :type values: list[~autorest.models.EnumValue]
52
- """
53
-
54
- def __init__(
55
- self,
56
- namespace: str,
57
- yaml_data: Dict[str, Any],
58
- description: str,
59
- name: str,
60
- values: List["EnumValue"],
61
- enum_type: PrimitiveSchema,
62
- ) -> None:
63
- super(EnumSchema, self).__init__(namespace=namespace, yaml_data=yaml_data)
64
- self.description = description
65
- self.name = name
66
- self.values = values
67
- self.enum_type = enum_type
68
-
69
- def __lt__(self, other):
70
- return self.name.lower() < other.name.lower()
71
-
72
- @property
73
- def serialization_type(self) -> str:
74
- """Returns the serialization value for msrest.
75
-
76
- :return: The serialization value for msrest
77
- :rtype: str
78
- """
79
- return self.enum_type.serialization_type
80
-
81
- def type_annotation(self, *, is_operation_file: bool = False) -> str:
82
- """The python type used for type annotation
83
-
84
- :return: The type annotation for this schema
85
- :rtype: str
86
- """
87
- return f'Union[{self.enum_type.type_annotation(is_operation_file=is_operation_file)}, "_models.{self.name}"]'
88
-
89
- def get_declaration(self, value: Any) -> str:
90
- return self.enum_type.get_declaration(value)
91
-
92
- @property
93
- def docstring_text(self) -> str:
94
- return self.name
95
-
96
- @property
97
- def docstring_type(self) -> str:
98
- """The python type used for RST syntax input and type annotation.
99
- """
100
- return f"{self.enum_type.type_annotation()} or ~{self.namespace}.models.{self.name}"
101
-
102
- @staticmethod
103
- def _get_enum_values(yaml_data: List[Dict[str, Any]]) -> List["EnumValue"]:
104
- """Creates the list of values for this enum.
105
-
106
- :param yaml_data: yaml data about the enum's values
107
- :type yaml_data: dict[str, Any]
108
- :return: The list of values for this enum
109
- :rtype: list[~autorest.models.EnumValue]
110
- """
111
- values = []
112
- seen_enums: Set[str] = set()
113
-
114
- for enum in yaml_data:
115
- enum_name = enum["language"]["python"]["name"]
116
- if enum_name in seen_enums:
117
- continue
118
- values.append(EnumValue.from_yaml(enum))
119
- seen_enums.add(enum_name)
120
- return values
121
-
122
- def _template_kwargs(self, **kwargs: Any) -> Any:
123
- if len(self.values) == 1 and not kwargs.get("default_value_declaration"):
124
- kwargs['default_value_declaration'] = self.enum_type.get_declaration(self.values[0].value)
125
- description = kwargs.pop("description", "")
126
- kwargs["description"] = description
127
- return kwargs
128
-
129
-
130
- def get_json_template_representation(self, **kwargs: Any) -> Any:
131
- # for better display effect, use the only value instead of var type
132
- return self.enum_type.get_json_template_representation(**self._template_kwargs(**kwargs))
133
-
134
- def get_files_and_data_template_representation(self, **kwargs: Any) -> Any:
135
- return self.enum_type.get_files_and_data_template_representation(**self._template_kwargs(**kwargs))
136
-
137
- @classmethod
138
- def from_yaml(cls, namespace: str, yaml_data: Dict[str, Any], **kwargs: Any) -> "EnumSchema":
139
- """Constructs an EnumSchema from yaml data.
140
-
141
- :param yaml_data: the yaml data from which we will construct this schema
142
- :type yaml_data: dict[str, Any]
143
-
144
- :return: A created EnumSchema
145
- :rtype: ~autorest.models.EnumSchema
146
- """
147
- name = yaml_data["language"]["python"]["name"]
148
-
149
- # choice type doesn't always exist. if there is no choiceType, we default to string
150
- if yaml_data.get("choiceType"):
151
- enum_type = get_primitive_schema(namespace, yaml_data["choiceType"])
152
- else:
153
- enum_type = StringSchema(namespace, {"type": "str"})
154
- values = EnumSchema._get_enum_values(yaml_data["choices"])
155
- return cls(
156
- namespace=namespace,
157
- yaml_data=yaml_data,
158
- description=yaml_data["language"]["python"]["description"],
159
- name=name,
160
- values=values,
161
- enum_type=enum_type,
162
- )
163
-
164
- def imports(self) -> FileImport:
165
- file_import = FileImport()
166
- file_import.add_submodule_import("typing", "Union", ImportType.STDLIB, TypingSection.CONDITIONAL)
167
- file_import.merge(self.enum_type.imports())
168
- return file_import
169
-
170
-
171
- class HiddenModelEnumSchema(EnumSchema):
172
-
173
- def imports(self) -> FileImport:
174
- file_import = FileImport()
175
- file_import.merge(self.enum_type.imports())
176
- return file_import
177
-
178
- def type_annotation(self, *, is_operation_file: bool = False) -> str:
179
- """The python type used for type annotation
180
-
181
- :return: The type annotation for this schema
182
- :rtype: str
183
- """
184
- return self.enum_type.type_annotation(is_operation_file=is_operation_file)
185
-
186
- @property
187
- def docstring_text(self) -> str:
188
- return f"{self.enum_type.type_annotation()}. {self.extra_description_information}"
189
-
190
- @property
191
- def extra_description_information(self):
192
- possible_values = [self.get_declaration(v.value) for v in self.values]
193
- if not possible_values:
194
- return ""
195
- if len(possible_values) == 1:
196
- return possible_values[0]
197
- if len(possible_values) == 2:
198
- possible_values_str = " or ".join(possible_values)
199
- else:
200
- possible_values_str = ", ".join(
201
- possible_values[: len(possible_values) - 1]
202
- ) + f", and {possible_values[-1]}"
203
-
204
- return "Known values are: {}.".format(possible_values_str)
205
-
206
- @property
207
- def docstring_type(self) -> str:
208
- """The python type used for RST syntax input and type annotation.
209
- """
210
- return self.enum_type.type_annotation()
211
-
212
- def get_enum_schema(code_model) -> Type[EnumSchema]:
213
- if code_model.options["models_mode"]:
214
- return EnumSchema
215
- return HiddenModelEnumSchema
@@ -1,123 +0,0 @@
1
- # -------------------------------------------------------------------------
2
- # Copyright (c) Microsoft Corporation. All rights reserved.
3
- # Licensed under the MIT License. See License.txt in the project root for
4
- # license information.
5
- # --------------------------------------------------------------------------
6
- from typing import Any, Dict, Optional, Union
7
- from .base_schema import BaseSchema
8
- from .imports import FileImport, ImportType, TypingSection
9
-
10
-
11
- class ListSchema(BaseSchema):
12
- def __init__(
13
- self,
14
- namespace: str,
15
- yaml_data: Dict[str, Any],
16
- element_type: BaseSchema,
17
- *,
18
- max_items: Optional[int] = None,
19
- min_items: Optional[int] = None,
20
- unique_items: Optional[int] = None,
21
- ) -> None:
22
- super(ListSchema, self).__init__(namespace=namespace, yaml_data=yaml_data)
23
- self.element_type = element_type
24
- self.max_items = max_items
25
- self.min_items = min_items
26
- self.unique_items = unique_items
27
-
28
- @property
29
- def serialization_type(self) -> str:
30
- return f"[{self.element_type.serialization_type}]"
31
-
32
- def type_annotation(self, *, is_operation_file: bool = False) -> str:
33
- if self.element_type.type_annotation() == "ET.Element":
34
- # this means we're version tolerant XML, we just return the XML element
35
- return self.element_type.type_annotation(is_operation_file=is_operation_file)
36
- return f"List[{self.element_type.type_annotation(is_operation_file=is_operation_file)}]"
37
-
38
- @property
39
- def docstring_type(self) -> str:
40
- if self.element_type.docstring_type == "ET.Element":
41
- # this means we're version tolerant XML, we just return the XML element
42
- return self.element_type.docstring_type
43
- return f"list[{self.element_type.docstring_type}]"
44
-
45
- @property
46
- def docstring_text(self) -> str:
47
- if self.element_type.docstring_text == "XML Element":
48
- # this means we're version tolerant XML, we just return the XML element
49
- return self.element_type.docstring_text
50
- return f"list of {self.element_type.docstring_text}"
51
-
52
- @property
53
- def validation_map(self) -> Optional[Dict[str, Union[bool, int, str]]]:
54
- validation_map: Dict[str, Union[bool, int, str]] = {}
55
- if self.max_items:
56
- validation_map["max_items"] = self.max_items
57
- validation_map["min_items"] = self.min_items or 0
58
- if self.min_items:
59
- validation_map["min_items"] = self.min_items
60
- if self.unique_items:
61
- validation_map["unique"] = True
62
- return validation_map or None
63
-
64
- @property
65
- def has_xml_serialization_ctxt(self) -> bool:
66
- return super().has_xml_serialization_ctxt or self.element_type.has_xml_serialization_ctxt
67
-
68
- def get_json_template_representation(self, **kwargs: Any) -> Any:
69
- return [self.element_type.get_json_template_representation(**kwargs)]
70
-
71
- def get_files_and_data_template_representation(self, **kwargs: Any) -> Any:
72
- return [self.element_type.get_files_and_data_template_representation(**kwargs)]
73
-
74
- def xml_serialization_ctxt(self) -> Optional[str]:
75
- attrs_list = []
76
- base_xml_map = super().xml_serialization_ctxt()
77
- if base_xml_map:
78
- attrs_list.append(base_xml_map)
79
-
80
- # Attribute at the list level
81
- if self.xml_metadata.get("wrapped", False):
82
- attrs_list.append("'wrapped': True")
83
-
84
- # Attributes of the items
85
- item_xml_metadata = self.element_type.xml_metadata
86
- if item_xml_metadata.get("name"):
87
- attrs_list.append(f"'itemsName': '{item_xml_metadata['name']}'")
88
- if item_xml_metadata.get("prefix", False):
89
- attrs_list.append(f"'itemsPrefix': '{item_xml_metadata['prefix']}'")
90
- if item_xml_metadata.get("namespace", False):
91
- attrs_list.append(f"'itemsNs': '{item_xml_metadata['namespace']}'")
92
-
93
- return ", ".join(attrs_list)
94
-
95
- @classmethod
96
- def from_yaml(cls, namespace: str, yaml_data: Dict[str, Any], **kwargs) -> "ListSchema":
97
- # TODO: for items, if the type is a primitive is it listed in type instead of $ref?
98
- element_schema = yaml_data["elementType"]
99
-
100
- from . import build_schema # pylint: disable=import-outside-toplevel
101
-
102
- element_type = build_schema(yaml_data=element_schema, **kwargs)
103
-
104
- return cls(
105
- namespace=namespace,
106
- yaml_data=yaml_data,
107
- element_type=element_type,
108
- max_items=yaml_data.get("maxItems"),
109
- min_items=yaml_data.get("minItems"),
110
- unique_items=yaml_data.get("uniqueItems"),
111
- )
112
-
113
- def imports(self) -> FileImport:
114
- file_import = FileImport()
115
- if not self.element_type.type_annotation(is_operation_file=True) == "ET.Element":
116
- file_import.add_submodule_import("typing", "List", ImportType.STDLIB, TypingSection.CONDITIONAL)
117
- file_import.merge(self.element_type.imports())
118
- return file_import
119
-
120
- def model_file_imports(self) -> FileImport:
121
- file_import = self.imports()
122
- file_import.merge(self.element_type.model_file_imports())
123
- return file_import