@autorest/python 6.2.0 → 6.2.2

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 (73) hide show
  1. package/autorest/codegen/__init__.py +9 -74
  2. package/autorest/codegen/models/__init__.py +11 -12
  3. package/autorest/codegen/models/{base_type.py → base.py} +29 -10
  4. package/autorest/codegen/models/base_builder.py +8 -10
  5. package/autorest/codegen/models/client.py +111 -40
  6. package/autorest/codegen/models/code_model.py +131 -90
  7. package/autorest/codegen/models/combined_type.py +7 -7
  8. package/autorest/codegen/models/constant_type.py +44 -10
  9. package/autorest/codegen/models/credential_types.py +17 -19
  10. package/autorest/codegen/models/dictionary_type.py +7 -9
  11. package/autorest/codegen/models/enum_type.py +19 -24
  12. package/autorest/codegen/models/imports.py +82 -33
  13. package/autorest/codegen/models/list_type.py +11 -15
  14. package/autorest/codegen/models/lro_operation.py +6 -10
  15. package/autorest/codegen/models/model_type.py +20 -21
  16. package/autorest/codegen/models/operation.py +49 -42
  17. package/autorest/codegen/models/operation_group.py +11 -11
  18. package/autorest/codegen/models/paging_operation.py +9 -11
  19. package/autorest/codegen/models/parameter.py +48 -32
  20. package/autorest/codegen/models/parameter_list.py +16 -22
  21. package/autorest/codegen/models/primitive_types.py +12 -23
  22. package/autorest/codegen/models/property.py +11 -11
  23. package/autorest/codegen/models/request_builder.py +19 -19
  24. package/autorest/codegen/models/request_builder_parameter.py +14 -16
  25. package/autorest/codegen/models/response.py +24 -28
  26. package/autorest/codegen/serializers/__init__.py +202 -187
  27. package/autorest/codegen/serializers/builder_serializer.py +49 -50
  28. package/autorest/codegen/serializers/client_serializer.py +9 -7
  29. package/autorest/codegen/serializers/enum_serializer.py +4 -4
  30. package/autorest/codegen/serializers/general_serializer.py +26 -36
  31. package/autorest/codegen/serializers/import_serializer.py +30 -36
  32. package/autorest/codegen/serializers/metadata_serializer.py +35 -17
  33. package/autorest/codegen/serializers/model_init_serializer.py +6 -10
  34. package/autorest/codegen/serializers/model_serializer.py +42 -27
  35. package/autorest/codegen/serializers/operation_groups_serializer.py +12 -8
  36. package/autorest/codegen/serializers/operations_init_serializer.py +13 -6
  37. package/autorest/codegen/serializers/patch_serializer.py +4 -4
  38. package/autorest/codegen/serializers/request_builders_serializer.py +6 -6
  39. package/autorest/codegen/serializers/sample_serializer.py +10 -12
  40. package/autorest/codegen/templates/client_container.py.jinja2 +2 -2
  41. package/autorest/codegen/templates/config.py.jinja2 +1 -1
  42. package/autorest/codegen/templates/config_container.py.jinja2 +3 -3
  43. package/autorest/codegen/templates/enum_container.py.jinja2 +2 -2
  44. package/autorest/codegen/templates/init.py.jinja2 +2 -2
  45. package/autorest/codegen/templates/lro_operation.py.jinja2 +1 -1
  46. package/autorest/codegen/templates/lro_paging_operation.py.jinja2 +1 -1
  47. package/autorest/codegen/templates/metadata.json.jinja2 +2 -2
  48. package/autorest/codegen/templates/model_container.py.jinja2 +3 -3
  49. package/autorest/codegen/templates/model_dpg.py.jinja2 +4 -4
  50. package/autorest/codegen/templates/model_init.py.jinja2 +3 -3
  51. package/autorest/codegen/templates/operation.py.jinja2 +1 -1
  52. package/autorest/codegen/templates/operation_group.py.jinja2 +2 -2
  53. package/autorest/codegen/templates/operation_groups_container.py.jinja2 +3 -3
  54. package/autorest/codegen/templates/operation_tools.jinja2 +3 -3
  55. package/autorest/codegen/templates/operations_folder_init.py.jinja2 +4 -4
  56. package/autorest/codegen/templates/packaging_templates/setup.py.jinja2 +4 -1
  57. package/autorest/codegen/templates/paging_operation.py.jinja2 +1 -1
  58. package/autorest/codegen/templates/request_builder.py.jinja2 +1 -1
  59. package/autorest/codegen/templates/request_builders.py.jinja2 +2 -2
  60. package/autorest/codegen/templates/rest_init.py.jinja2 +1 -1
  61. package/autorest/codegen/templates/sample.py.jinja2 +5 -5
  62. package/autorest/codegen/templates/validation.py.jinja2 +1 -1
  63. package/autorest/codegen/templates/vendor.py.jinja2 +6 -6
  64. package/autorest/codegen/templates/version.py.jinja2 +2 -2
  65. package/autorest/m4reformatter/__init__.py +57 -47
  66. package/autorest/multiapi/models/imports.py +89 -18
  67. package/autorest/multiapi/serializers/import_serializer.py +88 -7
  68. package/autorest/multiapi/utils.py +6 -0
  69. package/autorest/preprocess/__init__.py +23 -26
  70. package/package.json +1 -1
  71. package/run_cadl.py +0 -1
  72. package/autorest/cadlflags/__init__.py +0 -130
  73. package/autorest/codegen/models/base_model.py +0 -30
@@ -5,6 +5,7 @@
5
5
  # --------------------------------------------------------------------------
6
6
  from enum import Enum
7
7
  from typing import Dict, Optional, Set, Union, Tuple
8
+ from ..utils import convert_list_to_tuple
8
9
 
9
10
 
10
11
  class ImportType(str, Enum):
@@ -12,6 +13,7 @@ class ImportType(str, Enum):
12
13
  THIRDPARTY = "thirdparty"
13
14
  AZURECORE = "azurecore"
14
15
  LOCAL = "local"
16
+ BYVERSION = "by_version"
15
17
 
16
18
 
17
19
  class TypingSection(str, Enum):
@@ -25,7 +27,28 @@ class FileImport:
25
27
  self,
26
28
  imports: Dict[
27
29
  TypingSection,
28
- Dict[ImportType, Dict[str, Set[Optional[Union[str, Tuple[str, str]]]]]],
30
+ Dict[
31
+ ImportType,
32
+ Dict[
33
+ str,
34
+ Set[
35
+ Optional[
36
+ Union[
37
+ str,
38
+ Tuple[
39
+ str,
40
+ str,
41
+ ],
42
+ Tuple[
43
+ str,
44
+ str,
45
+ Tuple[Tuple[Tuple[int, int], str, Optional[str]]],
46
+ ],
47
+ ]
48
+ ]
49
+ ],
50
+ ],
51
+ ],
29
52
  ] = None,
30
53
  ) -> None:
31
54
  # Basic implementation
@@ -35,7 +58,28 @@ class FileImport:
35
58
  # Fourth level set: None if this import is a "import", the name to import if it's a "from"
36
59
  self._imports: Dict[
37
60
  TypingSection,
38
- Dict[ImportType, Dict[str, Set[Optional[Union[str, Tuple[str, str]]]]]],
61
+ Dict[
62
+ ImportType,
63
+ Dict[
64
+ str,
65
+ Set[
66
+ Optional[
67
+ Union[
68
+ str,
69
+ Tuple[
70
+ str,
71
+ str,
72
+ ],
73
+ Tuple[
74
+ str,
75
+ str,
76
+ Tuple[Tuple[Tuple[int, int], str, Optional[str]]],
77
+ ],
78
+ ]
79
+ ]
80
+ ],
81
+ ],
82
+ ],
39
83
  ] = (
40
84
  imports or dict()
41
85
  )
@@ -44,14 +88,29 @@ class FileImport:
44
88
  self,
45
89
  from_section: str,
46
90
  import_type: ImportType,
47
- name_import: Optional[Union[str, Tuple[str, str]]] = None,
91
+ name_import: Optional[
92
+ Union[
93
+ str,
94
+ Tuple[
95
+ str,
96
+ str,
97
+ ],
98
+ Tuple[str, str, Tuple[Tuple[Tuple[int, int], str, Optional[str]]]],
99
+ ]
100
+ ] = None,
48
101
  typing_section: TypingSection = TypingSection.REGULAR,
49
102
  ) -> None:
50
- name_input: Optional[Union[str, Tuple[str, str]]] = None
51
- if isinstance(name_import, list):
52
- name_input = tuple(name_import)
53
- else:
54
- name_input = name_import
103
+ name_input: Optional[
104
+ Union[
105
+ str,
106
+ Tuple[
107
+ str,
108
+ str,
109
+ ],
110
+ Tuple[str, str, Tuple[Tuple[Tuple[int, int], str, Optional[str]]]],
111
+ ]
112
+ ] = None
113
+ name_input = convert_list_to_tuple(name_import)
55
114
  self._imports.setdefault(typing_section, dict()).setdefault(
56
115
  import_type, dict()
57
116
  ).setdefault(from_section, set()).add(name_input)
@@ -66,21 +125,33 @@ class FileImport:
66
125
  """Add an import to this import block."""
67
126
  self._add_import(from_section, import_type, name_import, typing_section)
68
127
 
69
- def add_import(
70
- self,
71
- name_import: str,
72
- import_type: ImportType,
73
- typing_section: TypingSection = TypingSection.REGULAR,
74
- ) -> None:
75
- # Implementation detail: a regular import is just a "from" with no from
76
- self._add_import(name_import, import_type, None, typing_section)
77
-
78
128
  @property
79
129
  def imports(
80
130
  self,
81
131
  ) -> Dict[
82
132
  TypingSection,
83
- Dict[ImportType, Dict[str, Set[Optional[Union[str, Tuple[str, str]]]]]],
133
+ Dict[
134
+ ImportType,
135
+ Dict[
136
+ str,
137
+ Set[
138
+ Optional[
139
+ Union[
140
+ str,
141
+ Tuple[
142
+ str,
143
+ str,
144
+ ],
145
+ Tuple[
146
+ str,
147
+ str,
148
+ Tuple[Tuple[Tuple[int, int], str, Optional[str]]],
149
+ ],
150
+ ]
151
+ ]
152
+ ],
153
+ ],
154
+ ],
84
155
  ]:
85
156
  return self._imports
86
157
 
@@ -4,17 +4,43 @@
4
4
  # license information.
5
5
  # --------------------------------------------------------------------------
6
6
  from copy import deepcopy
7
- from typing import Dict, Set, Optional, List
7
+ from typing import Dict, Set, Optional, List, Tuple, Union
8
8
  from ..models import ImportType, FileImport, TypingSection
9
+ from ..utils import convert_list_to_tuple
9
10
 
10
11
 
11
12
  def _serialize_package(
12
- package_name: str, module_list: Set[Optional[str]], delimiter: str
13
+ package_name: str,
14
+ module_list: Set[
15
+ Optional[
16
+ Union[
17
+ str,
18
+ Tuple[
19
+ str,
20
+ str,
21
+ ],
22
+ Tuple[
23
+ str,
24
+ Optional[str],
25
+ Tuple[Tuple[Tuple[int, int], str, Optional[str]]],
26
+ ],
27
+ ]
28
+ ]
29
+ ],
30
+ delimiter: str,
13
31
  ) -> str:
14
32
  buffer = []
15
- if None in module_list:
33
+
34
+ versioned_modules = set()
35
+ normal_modules = set()
36
+ for m in module_list:
37
+ if m and isinstance(m, (tuple, list)) and len(m) > 2:
38
+ versioned_modules.add(convert_list_to_tuple(m))
39
+ else:
40
+ normal_modules.add(m)
41
+ if None in normal_modules:
16
42
  buffer.append(f"import {package_name}")
17
- if module_list != {None}:
43
+ if normal_modules != {None} and len(normal_modules) > 0:
18
44
  buffer.append(
19
45
  "from {} import {}".format(
20
46
  package_name,
@@ -22,18 +48,51 @@ def _serialize_package(
22
48
  sorted(
23
49
  [
24
50
  mod if isinstance(mod, str) else f"{mod[0]} as {mod[1]}"
25
- for mod in module_list
51
+ for mod in normal_modules
26
52
  if mod is not None
27
53
  ]
28
54
  )
29
55
  ),
30
56
  )
31
57
  )
58
+ for submodule_name, alias, version_modules in versioned_modules: # type: ignore
59
+ for n, (version, module_name, comment) in enumerate(version_modules):
60
+ buffer.append(
61
+ "{} sys.version_info >= {}:".format("if" if n == 0 else "elif", version)
62
+ )
63
+ buffer.append(
64
+ f" from {module_name} import {submodule_name}{f' as {alias}' if alias else ''}"
65
+ f"{f' # {comment}' if comment else ''}"
66
+ )
67
+ buffer.append("else:")
68
+ buffer.append(
69
+ f" from {package_name} import {submodule_name}{f' as {alias}' if alias else ''}"
70
+ " # type: ignore # pylint: disable=ungrouped-imports"
71
+ )
32
72
  return delimiter.join(buffer)
33
73
 
34
74
 
35
75
  def _serialize_type(
36
- import_type_dict: Dict[str, Set[Optional[str]]], delimiter: str
76
+ import_type_dict: Dict[
77
+ str,
78
+ Set[
79
+ Optional[
80
+ Union[
81
+ str,
82
+ Tuple[
83
+ str,
84
+ str,
85
+ ],
86
+ Tuple[
87
+ str,
88
+ Optional[str],
89
+ Tuple[Tuple[Tuple[int, int], str, Optional[str]]],
90
+ ],
91
+ ]
92
+ ]
93
+ ],
94
+ ],
95
+ delimiter: str,
37
96
  ) -> str:
38
97
  """Serialize a given import type."""
39
98
  import_list = []
@@ -44,7 +103,29 @@ def _serialize_type(
44
103
 
45
104
 
46
105
  def _get_import_clauses(
47
- imports: Dict[ImportType, Dict[str, Set[Optional[str]]]], delimiter: str
106
+ imports: Dict[
107
+ ImportType,
108
+ Dict[
109
+ str,
110
+ Set[
111
+ Optional[
112
+ Union[
113
+ str,
114
+ Tuple[
115
+ str,
116
+ str,
117
+ ],
118
+ Tuple[
119
+ str,
120
+ Optional[str],
121
+ Tuple[Tuple[Tuple[int, int], str, Optional[str]]],
122
+ ],
123
+ ]
124
+ ]
125
+ ],
126
+ ],
127
+ ],
128
+ delimiter: str,
48
129
  ) -> List[str]:
49
130
  import_clause = []
50
131
  for import_type in ImportType:
@@ -47,3 +47,9 @@ def _get_default_api_version_from_list(
47
47
 
48
48
  # If not preview mode, and there is preview, take the latest known stable
49
49
  return sorted(not_preview_versions)[-1]
50
+
51
+
52
+ def convert_list_to_tuple(l):
53
+ if not isinstance(l, list):
54
+ return l
55
+ return tuple(convert_list_to_tuple(x) for x in l) if isinstance(l, list) else l
@@ -16,9 +16,7 @@ from .. import YamlUpdatePlugin, YamlUpdatePluginAutorest
16
16
  from .._utils import parse_args, get_body_type_for_description, JSON_REGEXP, KNOWN_TYPES
17
17
 
18
18
 
19
- def add_body_param_type(
20
- namespace_model: Dict[str, Any], body_parameter: Dict[str, Any]
21
- ):
19
+ def add_body_param_type(code_model: Dict[str, Any], body_parameter: Dict[str, Any]):
22
20
  if (
23
21
  body_parameter
24
22
  and body_parameter["type"]["type"] in ("model", "dict", "list")
@@ -32,7 +30,7 @@ def add_body_param_type(
32
30
  "type": "combined",
33
31
  "types": [body_parameter["type"], KNOWN_TYPES["binary"]],
34
32
  }
35
- namespace_model["types"].append(body_parameter["type"])
33
+ code_model["types"].append(body_parameter["type"])
36
34
 
37
35
 
38
36
  def update_overload_section(
@@ -214,7 +212,7 @@ class PreProcessPlugin(YamlUpdatePlugin): # pylint: disable=abstract-method
214
212
 
215
213
  def update_operation(
216
214
  self,
217
- namespace_model: Dict[str, Any],
215
+ code_model: Dict[str, Any],
218
216
  yaml_data: Dict[str, Any],
219
217
  *,
220
218
  is_overload: bool = False,
@@ -237,12 +235,12 @@ class PreProcessPlugin(YamlUpdatePlugin): # pylint: disable=abstract-method
237
235
  for entry in yaml_data["bodyParameter"].get("entries", []):
238
236
  update_parameter(entry)
239
237
  for overload in yaml_data.get("overloads", []):
240
- self.update_operation(namespace_model, overload, is_overload=True)
238
+ self.update_operation(code_model, overload, is_overload=True)
241
239
  for response in yaml_data.get("responses", []):
242
240
  response["discriminator"] = "operation"
243
241
  if body_parameter and not is_overload:
244
242
  # if we have a JSON body, we add a binary overload
245
- add_body_param_type(namespace_model, body_parameter)
243
+ add_body_param_type(code_model, body_parameter)
246
244
  add_overloads_for_body_param(yaml_data)
247
245
 
248
246
  def _update_lro_operation_helper(self, yaml_data: Dict[str, Any]) -> None:
@@ -270,40 +268,36 @@ class PreProcessPlugin(YamlUpdatePlugin): # pylint: disable=abstract-method
270
268
 
271
269
  def update_lro_paging_operation(
272
270
  self,
273
- namespace_model: Dict[str, Any],
271
+ code_model: Dict[str, Any],
274
272
  yaml_data: Dict[str, Any],
275
273
  is_overload: bool = False,
276
274
  ) -> None:
277
- self.update_lro_operation(namespace_model, yaml_data, is_overload=is_overload)
278
- self.update_paging_operation(
279
- namespace_model, yaml_data, is_overload=is_overload
280
- )
275
+ self.update_lro_operation(code_model, yaml_data, is_overload=is_overload)
276
+ self.update_paging_operation(code_model, yaml_data, is_overload=is_overload)
281
277
  yaml_data["discriminator"] = "lropaging"
282
278
  for response in yaml_data.get("responses", []):
283
279
  response["discriminator"] = "lropaging"
284
280
  for overload in yaml_data.get("overloads", []):
285
- self.update_lro_paging_operation(
286
- namespace_model, overload, is_overload=True
287
- )
281
+ self.update_lro_paging_operation(code_model, overload, is_overload=True)
288
282
 
289
283
  def update_lro_operation(
290
284
  self,
291
- namespace_model: Dict[str, Any],
285
+ code_model: Dict[str, Any],
292
286
  yaml_data: Dict[str, Any],
293
287
  is_overload: bool = False,
294
288
  ) -> None:
295
- self.update_operation(namespace_model, yaml_data, is_overload=is_overload)
289
+ self.update_operation(code_model, yaml_data, is_overload=is_overload)
296
290
  self._update_lro_operation_helper(yaml_data)
297
291
  for overload in yaml_data.get("overloads", []):
298
292
  self._update_lro_operation_helper(overload)
299
293
 
300
294
  def update_paging_operation(
301
295
  self,
302
- namespace_model: Dict[str, Any],
296
+ code_model: Dict[str, Any],
303
297
  yaml_data: Dict[str, Any],
304
298
  is_overload: bool = False,
305
299
  ) -> None:
306
- self.update_operation(namespace_model, yaml_data, is_overload=is_overload)
300
+ self.update_operation(code_model, yaml_data, is_overload=is_overload)
307
301
  if not yaml_data.get("pagerSync"):
308
302
  yaml_data["pagerSync"] = "azure.core.paging.ItemPaged"
309
303
  if not yaml_data.get("pagerAsync"):
@@ -338,10 +332,10 @@ class PreProcessPlugin(YamlUpdatePlugin): # pylint: disable=abstract-method
338
332
  update_paging_response(response)
339
333
  response["itemType"] = item_type
340
334
  for overload in yaml_data.get("overloads", []):
341
- self.update_paging_operation(namespace_model, overload, is_overload=True)
335
+ self.update_paging_operation(code_model, overload, is_overload=True)
342
336
 
343
337
  def update_operation_groups(
344
- self, namespace: Dict[str, Any], client: Dict[str, Any]
338
+ self, code_model: Dict[str, Any], client: Dict[str, Any]
345
339
  ) -> None:
346
340
  operation_groups_yaml_data = client["operationGroups"]
347
341
  for operation_group in operation_groups_yaml_data:
@@ -356,15 +350,18 @@ class PreProcessPlugin(YamlUpdatePlugin): # pylint: disable=abstract-method
356
350
  client, operation_group["className"]
357
351
  )
358
352
  for operation in operation_group["operations"]:
359
- self.get_operation_updater(operation)(namespace, operation)
353
+ self.get_operation_updater(operation)(code_model, operation)
360
354
 
361
355
  def update_yaml(self, yaml_data: Dict[str, Any]) -> None:
362
356
  """Convert in place the YAML str."""
363
- for namespace in yaml_data.values():
364
- update_types(namespace["types"])
365
- for client in namespace["clients"]:
357
+ update_types(yaml_data["types"])
358
+ for client in yaml_data["clients"]:
359
+ update_client(client)
360
+ self.update_operation_groups(yaml_data, client)
361
+ for clients in yaml_data["subnamespaceToClients"].values():
362
+ for client in clients:
366
363
  update_client(client)
367
- self.update_operation_groups(namespace, client)
364
+ self.update_operation_groups(yaml_data, client)
368
365
 
369
366
 
370
367
  class PreProcessPluginAutorest(YamlUpdatePluginAutorest, PreProcessPlugin):
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autorest/python",
3
- "version": "6.2.0",
3
+ "version": "6.2.2",
4
4
  "description": "The Python extension for generators in AutoRest.",
5
5
  "repository": {
6
6
  "type": "git",
package/run_cadl.py CHANGED
@@ -38,6 +38,5 @@ if __name__ == "__main__":
38
38
  # run m2r
39
39
  python_run(venv_context, "autorest.m2r.__init__", command=sys.argv[1:])
40
40
  python_run(venv_context, "autorest.preprocess.__init__", command=sys.argv[1:])
41
- python_run(venv_context, "autorest.cadlflags.__init__", command=sys.argv[1:])
42
41
  python_run(venv_context, "autorest.codegen.__init__", command=sys.argv[1:])
43
42
  python_run(venv_context, "autorest.black.__init__", command=sys.argv[1:])
@@ -1,130 +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
- import logging
7
- from typing import Any, Dict, List
8
- from .. import YamlUpdatePlugin
9
- from .._utils import parse_args
10
-
11
- _LOGGER = logging.getLogger(__name__)
12
-
13
- OAUTH_TYPE = "OAuth2"
14
- KEY_TYPE = "Key"
15
-
16
-
17
- def get_azure_key_credential(key: str) -> Dict[str, Any]:
18
- return {
19
- "type": KEY_TYPE,
20
- "policy": {"type": "AzureKeyCredentialPolicy", "key": key},
21
- }
22
-
23
-
24
- class CadlFlags(YamlUpdatePlugin): # pylint: disable=abstract-method
25
- """A plugin to apply flags from backdoor python.json into cadl yaml file"""
26
-
27
- def update_yaml(self, yaml_data: Dict[str, Any]) -> None:
28
- """Convert in place the YAML str."""
29
- if self.options.get("add-credential"):
30
- self.update_credential(yaml_data)
31
- if self.options.get("namespace"):
32
- yaml_data["client"]["namespace"] = self.options["namespace"]
33
- if self.options.get("title"):
34
- yaml_data["client"]["name"] = self.options["title"]
35
-
36
- def get_credential_scopes_from_flags(self, auth_policy: str) -> List[str]:
37
- if self.options.get("azure-arm"):
38
- return ["https://management.azure.com/.default"]
39
- credential_scopes_temp = self.options.get("credential-scopes")
40
- credential_scopes = (
41
- credential_scopes_temp.split(",") if credential_scopes_temp else None
42
- )
43
- if self.options.get("credential-scopes", False) and not credential_scopes:
44
- raise ValueError(
45
- "--credential-scopes takes a list of scopes in comma separated format. "
46
- "For example: --credential-scopes=https://cognitiveservices.azure.com/.default"
47
- )
48
- if not credential_scopes:
49
- _LOGGER.warning(
50
- "You have default credential policy %s "
51
- "but not the --credential-scopes flag set while generating non-management plane code. "
52
- "This is not recommend because it forces the customer to pass credential scopes "
53
- "through kwargs if they want to authenticate.",
54
- auth_policy,
55
- )
56
- credential_scopes = []
57
- return credential_scopes
58
-
59
- def get_token_credential(self, credential_scopes: List[str]) -> Dict[str, Any]:
60
- return {
61
- "type": OAUTH_TYPE,
62
- "policy": {
63
- "type": "ARMChallengeAuthenticationPolicy"
64
- if self.options.get("azure-arm")
65
- else "BearerTokenCredentialPolicy",
66
- "credentialScopes": credential_scopes,
67
- },
68
- }
69
-
70
- def update_credential_from_flags(self) -> Dict[str, Any]:
71
- default_auth_policy = (
72
- "ARMChallengeAuthenticationPolicy"
73
- if self.options.get("azure-arm")
74
- else "BearerTokenCredentialPolicy"
75
- )
76
- auth_policy = (
77
- self.options.get("credential-default-policy-type") or default_auth_policy
78
- )
79
- credential_scopes = self.get_credential_scopes_from_flags(auth_policy)
80
- key = self.options.get("credential-key-header-name")
81
- if auth_policy.lower() in (
82
- "armchallengeauthenticationpolicy",
83
- "bearertokencredentialpolicy",
84
- ):
85
- if key:
86
- raise ValueError(
87
- "You have passed in a credential key header name with default credential policy type "
88
- f"{auth_policy}. This is not allowed, since credential key header "
89
- "name is tied with AzureKeyCredentialPolicy. Instead, with this policy it is recommend you "
90
- "pass in --credential-scopes."
91
- )
92
- return self.get_token_credential(credential_scopes)
93
- # Otherwise you have AzureKeyCredentialPolicy
94
- if self.options.get("credential-scopes"):
95
- raise ValueError(
96
- "You have passed in credential scopes with default credential policy type "
97
- "AzureKeyCredentialPolicy. This is not allowed, since credential scopes is tied with "
98
- f"{default_auth_policy}. Instead, with this policy "
99
- "you must pass in --credential-key-header-name."
100
- )
101
- if not key:
102
- key = "api-key"
103
- _LOGGER.info(
104
- "Defaulting the AzureKeyCredentialPolicy header's name to 'api-key'"
105
- )
106
- return get_azure_key_credential(key)
107
-
108
- def update_credential(self, yaml_data: Dict[str, Any]) -> None:
109
- credential_type = self.update_credential_from_flags()
110
- yaml_data["types"].append(credential_type)
111
- credential = {
112
- "type": credential_type,
113
- "optional": False,
114
- "description": "Credential needed for the client to connect to Azure.",
115
- "clientName": "credential",
116
- "location": "other",
117
- "restApiName": "credential",
118
- "implementation": "Client",
119
- "skipUrlEncoding": True,
120
- "inOverload": False,
121
- }
122
- yaml_data["client"]["parameters"].append(credential)
123
-
124
-
125
- if __name__ == "__main__":
126
- # CADL pipeline will call this
127
- args, unknown_args = parse_args()
128
- CadlFlags(
129
- output_folder=args.output_folder, cadl_file=args.cadl_file, **unknown_args
130
- ).process()
@@ -1,30 +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, TYPE_CHECKING
7
-
8
- if TYPE_CHECKING:
9
- from .code_model import NamespaceModel
10
-
11
-
12
- class BaseModel:
13
- """This is the base class for model representations that are based on some YAML data.
14
-
15
- :param yaml_data: the yaml data for this schema
16
- :type yaml_data: dict[str, Any]
17
- """
18
-
19
- def __init__(
20
- self, yaml_data: Dict[str, Any], namespace_model: "NamespaceModel"
21
- ) -> None:
22
- self.yaml_data = yaml_data
23
- self.namespace_model = namespace_model
24
-
25
- @property
26
- def id(self) -> int:
27
- return id(self.yaml_data)
28
-
29
- def __repr__(self):
30
- return f"<{self.__class__.__name__}>"