@autorest/python 5.16.0 → 5.17.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 (92) hide show
  1. package/ChangeLog.md +43 -3
  2. package/README.md +30 -4
  3. package/autorest/__init__.py +1 -1
  4. package/autorest/codegen/__init__.py +48 -209
  5. package/autorest/codegen/models/__init__.py +116 -83
  6. package/autorest/codegen/models/base_builder.py +49 -88
  7. package/autorest/codegen/models/base_model.py +1 -1
  8. package/autorest/codegen/models/{base_schema.py → base_type.py} +56 -40
  9. package/autorest/codegen/models/client.py +157 -48
  10. package/autorest/codegen/models/code_model.py +108 -254
  11. package/autorest/codegen/models/combined_type.py +107 -0
  12. package/autorest/codegen/models/{constant_schema.py → constant_type.py} +49 -40
  13. package/autorest/codegen/models/credential_types.py +224 -0
  14. package/autorest/codegen/models/{dictionary_schema.py → dictionary_type.py} +41 -31
  15. package/autorest/codegen/models/enum_type.py +195 -0
  16. package/autorest/codegen/models/imports.py +23 -0
  17. package/autorest/codegen/models/list_type.py +134 -0
  18. package/autorest/codegen/models/lro_operation.py +77 -156
  19. package/autorest/codegen/models/lro_paging_operation.py +28 -11
  20. package/autorest/codegen/models/model_type.py +239 -0
  21. package/autorest/codegen/models/operation.py +303 -269
  22. package/autorest/codegen/models/operation_group.py +48 -89
  23. package/autorest/codegen/models/paging_operation.py +80 -123
  24. package/autorest/codegen/models/parameter.py +289 -396
  25. package/autorest/codegen/models/parameter_list.py +348 -360
  26. package/autorest/codegen/models/primitive_types.py +544 -0
  27. package/autorest/codegen/models/property.py +109 -139
  28. package/autorest/codegen/models/request_builder.py +105 -88
  29. package/autorest/codegen/models/request_builder_parameter.py +112 -100
  30. package/autorest/codegen/models/response.py +325 -0
  31. package/autorest/codegen/models/utils.py +12 -19
  32. package/autorest/codegen/serializers/__init__.py +46 -37
  33. package/autorest/codegen/serializers/builder_serializer.py +604 -1146
  34. package/autorest/codegen/serializers/client_serializer.py +83 -88
  35. package/autorest/codegen/serializers/general_serializer.py +5 -64
  36. package/autorest/codegen/serializers/import_serializer.py +7 -4
  37. package/autorest/codegen/serializers/metadata_serializer.py +15 -104
  38. package/autorest/codegen/serializers/model_base_serializer.py +40 -32
  39. package/autorest/codegen/serializers/model_generic_serializer.py +8 -6
  40. package/autorest/codegen/serializers/model_init_serializer.py +2 -4
  41. package/autorest/codegen/serializers/model_python3_serializer.py +22 -16
  42. package/autorest/codegen/serializers/operation_groups_serializer.py +4 -13
  43. package/autorest/codegen/serializers/parameter_serializer.py +174 -0
  44. package/autorest/codegen/serializers/request_builders_serializer.py +12 -29
  45. package/autorest/codegen/serializers/utils.py +0 -142
  46. package/autorest/codegen/templates/MANIFEST.in.jinja2 +1 -0
  47. package/autorest/codegen/templates/{service_client.py.jinja2 → client.py.jinja2} +7 -7
  48. package/autorest/codegen/templates/config.py.jinja2 +13 -13
  49. package/autorest/codegen/templates/enum.py.jinja2 +4 -4
  50. package/autorest/codegen/templates/enum_container.py.jinja2 +1 -1
  51. package/autorest/codegen/templates/init.py.jinja2 +2 -2
  52. package/autorest/codegen/templates/lro_operation.py.jinja2 +4 -1
  53. package/autorest/codegen/templates/lro_paging_operation.py.jinja2 +4 -1
  54. package/autorest/codegen/templates/metadata.json.jinja2 +33 -33
  55. package/autorest/codegen/templates/model.py.jinja2 +23 -24
  56. package/autorest/codegen/templates/model_container.py.jinja2 +2 -1
  57. package/autorest/codegen/templates/model_init.py.jinja2 +3 -5
  58. package/autorest/codegen/templates/operation.py.jinja2 +6 -8
  59. package/autorest/codegen/templates/operation_group.py.jinja2 +7 -7
  60. package/autorest/codegen/templates/operation_groups_container.py.jinja2 +1 -1
  61. package/autorest/codegen/templates/operation_tools.jinja2 +8 -2
  62. package/autorest/codegen/templates/paging_operation.py.jinja2 +2 -2
  63. package/autorest/codegen/templates/request_builder.py.jinja2 +13 -11
  64. package/autorest/codegen/templates/setup.py.jinja2 +9 -3
  65. package/autorest/codegen/templates/vendor.py.jinja2 +1 -1
  66. package/autorest/jsonrpc/server.py +15 -3
  67. package/autorest/m4reformatter/__init__.py +1108 -0
  68. package/autorest/multiapi/models/code_model.py +1 -1
  69. package/autorest/multiapi/serializers/__init__.py +4 -4
  70. package/autorest/multiapi/templates/multiapi_config.py.jinja2 +3 -3
  71. package/autorest/multiapi/templates/multiapi_init.py.jinja2 +2 -2
  72. package/autorest/multiapi/templates/multiapi_operations_mixin.py.jinja2 +3 -3
  73. package/autorest/multiapi/templates/multiapi_service_client.py.jinja2 +9 -9
  74. package/autorest/postprocess/__init__.py +202 -0
  75. package/autorest/postprocess/get_all.py +19 -0
  76. package/autorest/postprocess/venvtools.py +73 -0
  77. package/autorest/preprocess/__init__.py +209 -0
  78. package/autorest/preprocess/helpers.py +54 -0
  79. package/autorest/{namer → preprocess}/python_mappings.py +21 -16
  80. package/package.json +2 -2
  81. package/autorest/codegen/models/credential_model.py +0 -55
  82. package/autorest/codegen/models/credential_schema.py +0 -95
  83. package/autorest/codegen/models/credential_schema_policy.py +0 -73
  84. package/autorest/codegen/models/enum_schema.py +0 -225
  85. package/autorest/codegen/models/list_schema.py +0 -135
  86. package/autorest/codegen/models/object_schema.py +0 -303
  87. package/autorest/codegen/models/primitive_schemas.py +0 -495
  88. package/autorest/codegen/models/request_builder_parameter_list.py +0 -249
  89. package/autorest/codegen/models/schema_request.py +0 -55
  90. package/autorest/codegen/models/schema_response.py +0 -141
  91. package/autorest/namer/__init__.py +0 -23
  92. package/autorest/namer/name_converter.py +0 -509
@@ -0,0 +1,54 @@
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
7
+ import re
8
+ from .python_mappings import PadType, RESERVED_WORDS, REDEFINED_BUILTINS
9
+
10
+
11
+ def to_snake_case(name: str) -> str:
12
+ def replace_upper_characters(m) -> str:
13
+ match_str = m.group().lower()
14
+ if m.start() > 0 and name[m.start() - 1] == "_":
15
+ # we are good if a '_' already exists
16
+ return match_str
17
+ # the first letter should not have _
18
+ prefix = "_" if m.start() > 0 else ""
19
+
20
+ # we will add an extra _ if there are multiple upper case chars together
21
+ next_non_upper_case_char_location = m.start() + len(match_str)
22
+ if (
23
+ len(match_str) > 2
24
+ and len(name) - next_non_upper_case_char_location > 1
25
+ and name[next_non_upper_case_char_location].isalpha()
26
+ ):
27
+
28
+ return (
29
+ prefix
30
+ + match_str[: len(match_str) - 1]
31
+ + "_"
32
+ + match_str[len(match_str) - 1]
33
+ )
34
+
35
+ return prefix + match_str
36
+
37
+ return re.sub("[A-Z]+", replace_upper_characters, name)
38
+
39
+
40
+ def pad_reserved_words(name: str, pad_type: PadType):
41
+ # we want to pad hidden variables as well
42
+ if not name:
43
+ # we'll pass in empty operation groups sometime etc.
44
+ return name
45
+ name_prefix = "_" if name[0] == "_" else ""
46
+ name = name[1:] if name[0] == "_" else name
47
+ if name.lower() in RESERVED_WORDS[pad_type]:
48
+ return name_prefix + name + pad_type
49
+ return name_prefix + name
50
+
51
+
52
+ def add_redefined_builtin_info(name: str, yaml_data: Dict[str, Any]) -> None:
53
+ if name in REDEFINED_BUILTINS:
54
+ yaml_data["pylintDisable"] = "redefined-builtin"
@@ -51,14 +51,13 @@ basic_latin_chars = {
51
51
  }
52
52
 
53
53
 
54
- class PadType(Enum):
55
- Model = "Model"
56
- Method = "Method"
57
- Parameter = "Parameter"
58
- Enum = "Enum"
59
- Property = "Property"
60
- OperationGroup = "Operations"
61
- BuilderGroup = "Builders"
54
+ class PadType(str, Enum):
55
+ MODEL = "Model"
56
+ METHOD = "_method"
57
+ PARAMETER = "_parameter"
58
+ ENUM = "_enum"
59
+ PROPERTY = "_property"
60
+ OPERATION_GROUP = "Operations"
62
61
 
63
62
 
64
63
  _always_reserved = [
@@ -96,9 +95,9 @@ _always_reserved = [
96
95
  "await",
97
96
  ]
98
97
 
99
- reserved_words = {
100
- PadType.Method: [*_always_reserved],
101
- PadType.Parameter: [
98
+ RESERVED_WORDS = {
99
+ PadType.METHOD: [*_always_reserved],
100
+ PadType.PARAMETER: [
102
101
  "self",
103
102
  # these are kwargs we've reserved for our autorest generated operations
104
103
  "content_type",
@@ -163,9 +162,15 @@ reserved_words = {
163
162
  "retry_on_status_codes",
164
163
  *_always_reserved,
165
164
  ],
166
- PadType.Model: [*_always_reserved],
167
- PadType.Property: ["self", *_always_reserved],
168
- PadType.Enum: ["mro", *_always_reserved],
169
- PadType.OperationGroup: [*_always_reserved],
170
- PadType.BuilderGroup: [*_always_reserved],
165
+ PadType.MODEL: [*_always_reserved],
166
+ PadType.PROPERTY: ["self", *_always_reserved],
167
+ PadType.ENUM: ["mro", *_always_reserved],
168
+ PadType.OPERATION_GROUP: [*_always_reserved],
171
169
  }
170
+
171
+ REDEFINED_BUILTINS = [ # we don't pad, but we need to do lint ignores
172
+ "id",
173
+ "min",
174
+ "max",
175
+ "filter",
176
+ ]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autorest/python",
3
- "version": "5.16.0",
3
+ "version": "5.17.0",
4
4
  "description": "The Python extension for generators in AutoRest.",
5
5
  "scripts": {
6
6
  "prepare": "node run-python3.js prepare.py",
@@ -27,7 +27,7 @@
27
27
  "@autorest/system-requirements": "~1.0.0"
28
28
  },
29
29
  "devDependencies": {
30
- "@microsoft.azure/autorest.testserver": "3.3.23"
30
+ "@microsoft.azure/autorest.testserver": "^3.3.26"
31
31
  },
32
32
  "files": [
33
33
  "autorest/**/*.py",
@@ -1,55 +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 Set, Optional, Type
7
- from .credential_schema_policy import (
8
- CredentialSchemaPolicy,
9
- BearerTokenCredentialPolicy,
10
- )
11
- from .credential_schema_policy import ARMChallengeAuthenticationPolicy
12
- from .credential_schema import TokenCredentialSchema, AzureKeyCredentialSchema
13
-
14
-
15
- class CredentialModel:
16
- """Store info about credential."""
17
-
18
- def __init__(self, azure_arm: bool) -> None:
19
- self.azure_arm: bool = azure_arm
20
- self.credential_scopes: Set[str] = set()
21
- self.key_header_name: str = ""
22
- self.policy_type: Optional[Type[CredentialSchemaPolicy]] = None
23
- self._credential_schema_policy: Optional[CredentialSchemaPolicy] = None
24
-
25
- @property
26
- def default_authentication_policy(self) -> Type[CredentialSchemaPolicy]:
27
- return (
28
- ARMChallengeAuthenticationPolicy
29
- if self.azure_arm
30
- else BearerTokenCredentialPolicy
31
- )
32
-
33
- @property
34
- def credential_schema_policy(self) -> CredentialSchemaPolicy:
35
- if not self._credential_schema_policy:
36
- raise ValueError(
37
- "You want to find the Credential Schema Policy, but have not given a value"
38
- )
39
- return self._credential_schema_policy
40
-
41
- def build_authentication_policy(self):
42
- if hasattr(self.policy_type, "credential_scopes"):
43
- self._credential_schema_policy = (
44
- self.policy_type( # pylint: disable=not-callable
45
- credential=TokenCredentialSchema(async_mode=False),
46
- credential_scopes=list(self.credential_scopes),
47
- )
48
- )
49
- elif hasattr(self.policy_type, "credential_key_header_name"):
50
- self._credential_schema_policy = (
51
- self.policy_type( # pylint: disable=not-callable
52
- credential=AzureKeyCredentialSchema(),
53
- credential_key_header_name=self.key_header_name,
54
- )
55
- )
@@ -1,95 +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
-
11
- class CredentialSchema(BaseSchema):
12
- def __init__(self) -> None: # pylint: disable=super-init-not-called
13
- self.default_value = None
14
-
15
- def type_annotation(self, *, is_operation_file: bool = False) -> str:
16
- raise ValueError("Children classes should set their own type annotation")
17
-
18
- @property
19
- def docstring_type(self) -> str:
20
- return self.serialization_type
21
-
22
- @property
23
- def docstring_text(self) -> str:
24
- return "credential"
25
-
26
- @property
27
- def serialization_type(self) -> str:
28
- # this property is added, because otherwise pylint says that
29
- # abstract serialization_type in BaseSchema is not overridden
30
- pass
31
-
32
- def get_json_template_representation(self, **kwargs: Any) -> Any:
33
- raise TypeError(
34
- "You should not try to get a JSON template representation of a CredentialSchema"
35
- )
36
-
37
-
38
- class AzureKeyCredentialSchema(CredentialSchema):
39
- @property
40
- def serialization_type(self) -> str:
41
- return "~azure.core.credentials.AzureKeyCredential"
42
-
43
- def type_annotation(
44
- self, *, is_operation_file: bool = False # pylint: disable=unused-argument
45
- ) -> str:
46
- return "AzureKeyCredential"
47
-
48
- def imports(self) -> FileImport:
49
- file_import = FileImport()
50
- file_import.add_submodule_import(
51
- "azure.core.credentials",
52
- "AzureKeyCredential",
53
- ImportType.AZURECORE,
54
- typing_section=TypingSection.CONDITIONAL,
55
- )
56
- return file_import
57
-
58
-
59
- class TokenCredentialSchema(CredentialSchema):
60
- def __init__(self, async_mode) -> None:
61
- super().__init__()
62
- self.async_mode = async_mode
63
- self.async_type = "~azure.core.credentials_async.AsyncTokenCredential"
64
- self.sync_type = "~azure.core.credentials.TokenCredential"
65
-
66
- @property
67
- def serialization_type(self) -> str:
68
- if self.async_mode:
69
- return self.async_type
70
- return self.sync_type
71
-
72
- def type_annotation(
73
- self, *, is_operation_file: bool = False # pylint: disable=unused-argument
74
- ) -> str:
75
- if self.async_mode:
76
- return '"AsyncTokenCredential"'
77
- return '"TokenCredential"'
78
-
79
- def imports(self) -> FileImport:
80
- file_import = FileImport()
81
- if self.async_mode:
82
- file_import.add_submodule_import(
83
- "azure.core.credentials_async",
84
- "AsyncTokenCredential",
85
- ImportType.AZURECORE,
86
- typing_section=TypingSection.TYPING,
87
- )
88
- else:
89
- file_import.add_submodule_import(
90
- "azure.core.credentials",
91
- "TokenCredential",
92
- ImportType.AZURECORE,
93
- typing_section=TypingSection.TYPING,
94
- )
95
- return file_import
@@ -1,73 +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
-
11
- class CredentialSchemaPolicy:
12
- def __init__(self, credential: CredentialSchema) -> None:
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
- def __init__(
26
- self, credential: CredentialSchema, credential_scopes: List[str]
27
- ) -> None:
28
- super().__init__(credential)
29
- self._credential_scopes = credential_scopes
30
-
31
- @property
32
- def credential_scopes(self):
33
- return self._credential_scopes
34
-
35
- def call(self, async_mode: bool) -> str:
36
- policy_name = f"Async{self.name()}" if async_mode else self.name()
37
- return f"policies.{policy_name}(self.credential, *self.credential_scopes, **kwargs)"
38
-
39
-
40
- class ARMChallengeAuthenticationPolicy(BearerTokenCredentialPolicy):
41
- def call(self, async_mode: bool) -> str:
42
- policy_name = f"Async{self.name()}" if async_mode else self.name()
43
- return f"{policy_name}(self.credential, *self.credential_scopes, **kwargs)"
44
-
45
-
46
- class AzureKeyCredentialPolicy(CredentialSchemaPolicy):
47
- def __init__(
48
- self, credential: CredentialSchema, credential_key_header_name: str
49
- ) -> None:
50
- super().__init__(credential)
51
- self._credential_key_header_name = credential_key_header_name
52
-
53
- @property
54
- def credential_key_header_name(self):
55
- return self._credential_key_header_name
56
-
57
- def call(self, async_mode: bool) -> str:
58
- return f'policies.AzureKeyCredentialPolicy(self.credential, "{self.credential_key_header_name}", **kwargs)'
59
-
60
-
61
- def get_credential_schema_policy_type(name):
62
- policies = [
63
- ARMChallengeAuthenticationPolicy,
64
- BearerTokenCredentialPolicy,
65
- AzureKeyCredentialPolicy,
66
- ]
67
- try:
68
- return next(p for p in policies if p.name().lower() == name.lower())
69
- except StopIteration:
70
- raise ValueError(
71
- "The credential policy you pass in with --credential-default-policy-type must be either "
72
- "{}".format(" or ".join([p.name() for p in policies]))
73
- )
@@ -1,225 +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, TYPE_CHECKING
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
- if TYPE_CHECKING:
12
- from .code_model import CodeModel
13
-
14
-
15
- class EnumValue:
16
- """Model containing necessary information for a single value of an enum.
17
-
18
- :param str name: The name of this enum value
19
- :param str value: The value of this enum value
20
- :param str description: Optional. The description for this enum value
21
- """
22
-
23
- def __init__(
24
- self, name: str, value: str, description: Optional[str] = None
25
- ) -> None:
26
- self.name = name
27
- self.value = value
28
- self.description = description
29
-
30
- @classmethod
31
- def from_yaml(cls, yaml_data: Dict[str, Any]) -> "EnumValue":
32
- """Constructs an EnumValue from yaml data.
33
-
34
- :param yaml_data: the yaml data from which we will construct this object
35
- :type yaml_data: dict[str, Any]
36
-
37
- :return: A created EnumValue
38
- :rtype: ~autorest.models.EnumValue
39
- """
40
- return cls(
41
- name=yaml_data["language"]["python"]["name"],
42
- value=yaml_data["value"],
43
- description=yaml_data["language"]["python"].get("description"),
44
- )
45
-
46
-
47
- class EnumSchema(BaseSchema):
48
- """Schema for enums that will be serialized.
49
-
50
- :param yaml_data: the yaml data for this schema
51
- :type yaml_data: dict[str, Any]
52
- :param str description: The description of this enum
53
- :param str name: The name of the enum.
54
- :type element_type: ~autorest.models.PrimitiveSchema
55
- :param values: List of the values for this enum
56
- :type values: list[~autorest.models.EnumValue]
57
- """
58
-
59
- def __init__(
60
- self,
61
- yaml_data: Dict[str, Any],
62
- code_model: "CodeModel",
63
- description: str,
64
- name: str,
65
- values: List["EnumValue"],
66
- enum_type: PrimitiveSchema,
67
- ) -> None:
68
- super().__init__(yaml_data=yaml_data, code_model=code_model)
69
- self.description = description
70
- self.name = name
71
- self.values = values
72
- self.enum_type = enum_type
73
-
74
- def __lt__(self, other):
75
- return self.name.lower() < other.name.lower()
76
-
77
- @property
78
- def serialization_type(self) -> str:
79
- """Returns the serialization value for msrest.
80
-
81
- :return: The serialization value for msrest
82
- :rtype: str
83
- """
84
- return self.enum_type.serialization_type
85
-
86
- def type_annotation(self, *, is_operation_file: bool = False) -> str:
87
- """The python type used for type annotation
88
-
89
- :return: The type annotation for this schema
90
- :rtype: str
91
- """
92
- return f'Union[{self.enum_type.type_annotation(is_operation_file=is_operation_file)}, "_models.{self.name}"]'
93
-
94
- def get_declaration(self, value: Any) -> str:
95
- return self.enum_type.get_declaration(value)
96
-
97
- @property
98
- def docstring_text(self) -> str:
99
- return self.name
100
-
101
- @property
102
- def docstring_type(self) -> str:
103
- """The python type used for RST syntax input and type annotation."""
104
- return f"{self.enum_type.type_annotation()} or ~{self.code_model.namespace}.models.{self.name}"
105
-
106
- @staticmethod
107
- def _get_enum_values(yaml_data: List[Dict[str, Any]]) -> List["EnumValue"]:
108
- """Creates the list of values for this enum.
109
-
110
- :param yaml_data: yaml data about the enum's values
111
- :type yaml_data: dict[str, Any]
112
- :return: The list of values for this enum
113
- :rtype: list[~autorest.models.EnumValue]
114
- """
115
- values = []
116
- seen_enums: Set[str] = set()
117
-
118
- for enum in yaml_data:
119
- enum_name = enum["language"]["python"]["name"]
120
- if enum_name in seen_enums:
121
- continue
122
- values.append(EnumValue.from_yaml(enum))
123
- seen_enums.add(enum_name)
124
- return values
125
-
126
- def _template_kwargs(self, **kwargs: Any) -> Any:
127
- if len(self.values) == 1 and not kwargs.get("default_value_declaration"):
128
- kwargs["default_value_declaration"] = self.enum_type.get_declaration(
129
- self.values[0].value
130
- )
131
- description = kwargs.pop("description", "")
132
- kwargs["description"] = description
133
- return kwargs
134
-
135
- def get_json_template_representation(self, **kwargs: Any) -> Any:
136
- # for better display effect, use the only value instead of var type
137
- return self.enum_type.get_json_template_representation(
138
- **self._template_kwargs(**kwargs)
139
- )
140
-
141
- @classmethod
142
- def from_yaml(
143
- cls, yaml_data: Dict[str, Any], code_model: "CodeModel"
144
- ) -> "EnumSchema":
145
- """Constructs an EnumSchema from yaml data.
146
-
147
- :param yaml_data: the yaml data from which we will construct this schema
148
- :type yaml_data: dict[str, Any]
149
-
150
- :return: A created EnumSchema
151
- :rtype: ~autorest.models.EnumSchema
152
- """
153
- name = yaml_data["language"]["python"]["name"]
154
-
155
- # choice type doesn't always exist. if there is no choiceType, we default to string
156
- if yaml_data.get("choiceType"):
157
- enum_type = get_primitive_schema(yaml_data["choiceType"], code_model)
158
- else:
159
- enum_type = StringSchema({"type": "str"}, code_model)
160
- values = EnumSchema._get_enum_values(yaml_data["choices"])
161
- return cls(
162
- yaml_data=yaml_data,
163
- code_model=code_model,
164
- description=yaml_data["language"]["python"]["description"],
165
- name=name,
166
- values=values,
167
- enum_type=enum_type,
168
- )
169
-
170
- def imports(self) -> FileImport:
171
- file_import = FileImport()
172
- file_import.add_submodule_import(
173
- "typing", "Union", ImportType.STDLIB, TypingSection.CONDITIONAL
174
- )
175
- file_import.merge(self.enum_type.imports())
176
- return file_import
177
-
178
-
179
- class HiddenModelEnumSchema(EnumSchema):
180
- def imports(self) -> FileImport:
181
- file_import = FileImport()
182
- file_import.merge(self.enum_type.imports())
183
- return file_import
184
-
185
- def type_annotation(self, *, is_operation_file: bool = False) -> str:
186
- """The python type used for type annotation
187
-
188
- :return: The type annotation for this schema
189
- :rtype: str
190
- """
191
- return self.enum_type.type_annotation(is_operation_file=is_operation_file)
192
-
193
- @property
194
- def docstring_text(self) -> str:
195
- return (
196
- f"{self.enum_type.type_annotation()}. {self.extra_description_information}"
197
- )
198
-
199
- @property
200
- def extra_description_information(self):
201
- possible_values = [self.get_declaration(v.value) for v in self.values]
202
- if not possible_values:
203
- return ""
204
- if len(possible_values) == 1:
205
- return possible_values[0]
206
- if len(possible_values) == 2:
207
- possible_values_str = " or ".join(possible_values)
208
- else:
209
- possible_values_str = (
210
- ", ".join(possible_values[: len(possible_values) - 1])
211
- + f", and {possible_values[-1]}"
212
- )
213
-
214
- return "Known values are: {}.".format(possible_values_str)
215
-
216
- @property
217
- def docstring_type(self) -> str:
218
- """The python type used for RST syntax input and type annotation."""
219
- return self.enum_type.type_annotation()
220
-
221
-
222
- def get_enum_schema(code_model) -> Type[EnumSchema]:
223
- if code_model.options["models_mode"]:
224
- return EnumSchema
225
- return HiddenModelEnumSchema