openapi-spec-tools 0.22.0__tar.gz → 0.24.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/PKG-INFO +1 -1
  2. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/api_gen/api_generator.py +4 -1
  3. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/api_gen/flat_generator.py +1 -0
  4. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/api_gen/opaque_generator.py +1 -0
  5. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/api_gen/property_generator.py +1 -0
  6. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/base_gen/__init__.py +2 -0
  7. openapi_spec_tools-0.24.0/openapi_spec_tools/base_gen/_constants.py +3 -0
  8. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/base_gen/_requests.py +21 -8
  9. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/base_gen/base_generator.py +66 -9
  10. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/base_gen/config.py +10 -0
  11. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/base_gen/constants.py +0 -5
  12. openapi_spec_tools-0.24.0/openapi_spec_tools/base_gen/exceptions.py +5 -0
  13. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli/analyze.py +2 -0
  14. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli/api_gen.py +2 -0
  15. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli/cli_gen.py +6 -6
  16. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli/oas.py +4 -2
  17. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli/paths.py +1 -2
  18. openapi_spec_tools-0.24.0/openapi_spec_tools/cli/properties.py +159 -0
  19. openapi_spec_tools-0.24.0/openapi_spec_tools/cli/references.py +244 -0
  20. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli/utils.py +11 -0
  21. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli_gen/_display.py +7 -0
  22. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli_gen/cli_generator.py +8 -5
  23. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/constants.py +7 -0
  24. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/layout/config.py +4 -0
  25. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/layout/layout_generator.py +78 -10
  26. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/layout/types.py +1 -1
  27. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/layout/utils.py +1 -2
  28. openapi_spec_tools-0.24.0/openapi_spec_tools/properties.py +147 -0
  29. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/types.py +1 -0
  30. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/utils.py +47 -2
  31. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/pyproject.toml +3 -1
  32. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/tests/cli_gen/test_cli_generator.py +11 -3
  33. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/tests/cli_gen/test_display.py +6 -0
  34. openapi_spec_tools-0.24.0/tests/cli_gen/test_main.py +51 -0
  35. openapi_spec_tools-0.22.0/tests/cli_gen/test_main.py +0 -34
  36. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/.gitignore +0 -0
  37. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/LICENSE +0 -0
  38. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/README.md +0 -0
  39. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/__init__.py +0 -0
  40. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/api_gen/__init__.py +0 -0
  41. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/api_gen/_environment.py +0 -0
  42. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/base_gen/_logging.py +0 -0
  43. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/base_gen/files.py +0 -0
  44. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/base_gen/utils.py +0 -0
  45. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli/__init__.py +0 -0
  46. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli/arguments.py +0 -0
  47. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli/constants.py +0 -0
  48. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli/content.py +0 -0
  49. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli/history.py +0 -0
  50. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli/layout.py +0 -0
  51. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli/models.py +0 -0
  52. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli/operations.py +0 -0
  53. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli/tags.py +0 -0
  54. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli_gen/__init__.py +0 -0
  55. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli_gen/_arguments.py +0 -0
  56. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli_gen/_exceptions.py +0 -0
  57. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli_gen/_tree.py +0 -0
  58. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli_gen/files.py +0 -0
  59. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/expand.py +0 -0
  60. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/flatten.py +0 -0
  61. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/layout/__init__.py +0 -0
  62. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/layout/merge.py +0 -0
  63. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/tests/cli_gen/__init__.py +0 -0
  64. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/tests/cli_gen/test_exceptions.py +0 -0
  65. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/tests/cli_gen/test_files.py +0 -0
  66. {openapi_spec_tools-0.22.0 → openapi_spec_tools-0.24.0}/tests/cli_gen/test_tree.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: openapi-spec-tools
3
- Version: 0.22.0
3
+ Version: 0.24.0
4
4
  Summary: OpenAPI specification tools for analyzing, updating, and generating a CLI.
5
5
  Project-URL: Homepage, https://github.com/rickwporter/openapi-spec-tools
6
6
  Project-URL: Repository, https://github.com/rickwporter/openapi-spec-tools
@@ -49,6 +49,7 @@ class ApiGenerator(BaseGenerator, ABC):
49
49
  api_gen = Path(__file__).parent
50
50
  base_gen = Path(__file__).parent.parent / "base_gen"
51
51
  return {
52
+ **super().default_infra_files(),
52
53
  base_gen / "_logging.py": "_logging.py",
53
54
  base_gen / "_requests.py": "_requests.py",
54
55
  api_gen / "_environment.py": "_environment.py",
@@ -57,6 +58,7 @@ class ApiGenerator(BaseGenerator, ABC):
57
58
  def default_infra_replacements(self) -> dict[str, str]:
58
59
  """Default infrastructure line replacements."""
59
60
  return {
61
+ **super().default_infra_replacements(),
60
62
  "openapi_spec_tools.api_gen": self.package_name,
61
63
  "openapi_spec_tools.base_gen": self.package_name,
62
64
  __package__: self.package_name,
@@ -104,6 +106,7 @@ from datetime import datetime # noqa: F401
104
106
  from enum import Enum # noqa: F401
105
107
  from typing import Any
106
108
 
109
+ from {self.package_name} import _constants as _c
107
110
  from {self.package_name} import _environment as _e
108
111
  from {self.package_name} import _logging as _l
109
112
  from {self.package_name} import _requests as _r
@@ -113,7 +116,7 @@ from {self.package_name} import _requests as _r
113
116
  """Provide initialization of standard arguments inside body."""
114
117
  host_default = (
115
118
  f'_e.env_string({maybe_quoted(self.env_host)}, '
116
- f'default={quoted(self.default_host)}, except_missing=True)'
119
+ f'default=_c.DEFAULT_HOST, except_missing=True)'
117
120
  )
118
121
  key_default = f'_e.env_string({maybe_quoted(self.env_key)}, except_missing=True)'
119
122
  timeout_default = f'_e.env_int({maybe_quoted(self.env_timeout)}, default={self.default_timeout})'
@@ -63,6 +63,7 @@ class FlatApiGenerator(ApiGenerator):
63
63
  args_str = SEP1 + SEP1.join(func_args) + NL
64
64
 
65
65
  logger.debug(f"{func_name}({len(path_params)} path, {len(query_params)} query, {len(body_params)} body)")
66
+ self.check_duplicates(node.identifier, func_args)
66
67
 
67
68
  user_header_init = ""
68
69
  user_header_arg = ""
@@ -81,6 +81,7 @@ class OpaqueApiGenerator(ApiGenerator):
81
81
  args_str = SEP1 + SEP1.join(func_args) + NL
82
82
 
83
83
  logger.debug(f"{func_name}({len(path_params)} path, {len(query_params)} query")
84
+ self.check_duplicates(node.identifier, func_args)
84
85
 
85
86
  user_header_init = ""
86
87
  user_header_arg = ""
@@ -117,6 +117,7 @@ class PropertyApiGenerator(ApiGenerator):
117
117
  args_str = SEP1 + SEP1.join(func_args) + NL
118
118
 
119
119
  logger.debug(f"{func_name}({len(path_params)} path, {len(query_params)} query")
120
+ self.check_duplicates(node.identifier, func_args)
120
121
 
121
122
  user_header_init = ""
122
123
  user_header_arg = ""
@@ -1,10 +1,12 @@
1
1
  """Base generator which is the base class for API and CLI generoators."""
2
2
  from .base_generator import BaseGenerator
3
+ from .config import ErrorHandling
3
4
  from .config import GeneratorConfig
4
5
  from .constants import COLLECTIONS
5
6
  from .constants import NL
6
7
  from .constants import SEP1
7
8
  from .constants import SEP2
9
+ from .exceptions import CodeGeneration
8
10
  from .utils import is_case_sensitive
9
11
  from .utils import maybe_quoted
10
12
  from .utils import prepend
@@ -0,0 +1,3 @@
1
+ """Shared constants for generated packages."""
2
+
3
+ DEFAULT_HOST = ""
@@ -82,7 +82,7 @@ class PageParams(BaseModel):
82
82
  # items property specifies the property name to pull out the data from
83
83
  items_property_name: str | None = None
84
84
 
85
- # locations for next url
85
+ # locations for the next URL. next_property_name may be a dotted path such as "links.next"
86
86
  next_header_name: str | None = None
87
87
  next_property_name: str | None = None
88
88
 
@@ -148,6 +148,17 @@ def raise_for_error(response: requests.Response) -> None:
148
148
  raise requests.HTTPError(message, response=response)
149
149
 
150
150
 
151
+ def _value_at(data: Any, keys: list[str]) -> Any:
152
+ """Return the value at a property path identified by keys."""
153
+ _data = data
154
+ for k in keys:
155
+ if not isinstance(_data, dict):
156
+ return None
157
+ _data = _data.get(k)
158
+
159
+ return _data
160
+
161
+
151
162
  def _pretty_params(params: dict[str, Any] | None) -> str:
152
163
  if not params:
153
164
  return ""
@@ -180,15 +191,15 @@ def request(
180
191
  return None
181
192
 
182
193
  encoding = response.encoding or "utf-8"
183
- content_type = response.headers.get("Content-type", "application/json")
184
- if content_type == "application/json":
194
+ content_type = response.headers.get("Content-type", "application/json").lower()
195
+ if any(content_type.startswith(x) for x in ("application/json", "application/vnd.api+json")):
185
196
  try:
186
197
  return response.json()
187
198
  except json.JSONDecodeError:
188
199
  logger.error(f"Failed to decode {method} {pretty_url} response")
189
200
  return None
190
201
 
191
- if content_type == "application/yaml":
202
+ if content_type.startswith("application/yaml"):
192
203
  try:
193
204
  content = response.content.decode(encoding=encoding, errors="ignore")
194
205
  return yaml.safe_load(content)
@@ -196,7 +207,7 @@ def request(
196
207
  logger.error(f"Failed to decode {method} {pretty_url} response: {ex}")
197
208
  return None
198
209
 
199
- if content_type == "text/plain":
210
+ if content_type.startswith("text/plain"):
200
211
  return response.content.decode(encoding=encoding, errors="ignore")
201
212
 
202
213
  extension = EXTENSION_MAP.get(content_type)
@@ -244,6 +255,7 @@ def depaginate(
244
255
  page_params.next_header_name,
245
256
  page_params.next_property_name,
246
257
  ])
258
+ next_prop_keys = page_params.next_property_name.split(".") if page_params.next_property_name else None
247
259
 
248
260
  while _url:
249
261
  if next_url:
@@ -264,7 +276,8 @@ def depaginate(
264
276
  raise_for_error(response)
265
277
 
266
278
  # update list with current items from the response
267
- current = response.json()
279
+ body = response.json()
280
+ current = body
268
281
  if page_params.items_property_name:
269
282
  current = current.get(page_params.items_property_name)
270
283
  items.extend(current)
@@ -273,8 +286,8 @@ def depaginate(
273
286
  if page_params.next_header_name:
274
287
  _url = response.headers.get(page_params.next_header_name)
275
288
  next_url = _url
276
- elif page_params.next_property_name:
277
- _url = response.json().get(page_params.next_property_name)
289
+ elif next_prop_keys:
290
+ _url = _value_at(body, next_prop_keys)
278
291
  next_url = _url
279
292
 
280
293
  # some book-keeping
@@ -4,13 +4,13 @@ from copy import deepcopy
4
4
  from pathlib import Path
5
5
  from typing import Any
6
6
 
7
+ from openapi_spec_tools.base_gen.config import ErrorHandling
7
8
  from openapi_spec_tools.base_gen.config import GeneratorConfig
8
9
  from openapi_spec_tools.base_gen.constants import COLLECTIONS
9
10
  from openapi_spec_tools.base_gen.constants import DEFAULT_CONFLICT_SUFFIX
10
11
  from openapi_spec_tools.base_gen.constants import DEFAULT_COPYRIGHT
11
12
  from openapi_spec_tools.base_gen.constants import DEFAULT_MAX_HELP_LENGTH
12
13
  from openapi_spec_tools.base_gen.constants import DEFAULT_RESERVED
13
- from openapi_spec_tools.base_gen.constants import DEFAULT_SUPPORTED_CONTENT
14
14
  from openapi_spec_tools.base_gen.constants import DEFAULT_VALUE_LOG_LEVEL
15
15
  from openapi_spec_tools.base_gen.constants import DEFAULT_VALUE_TIMEOUT
16
16
  from openapi_spec_tools.base_gen.constants import DEFAULT_VAR_HOST
@@ -20,6 +20,7 @@ from openapi_spec_tools.base_gen.constants import DEFAULT_VAR_TIMEOUT
20
20
  from openapi_spec_tools.base_gen.constants import NL
21
21
  from openapi_spec_tools.base_gen.constants import SEP1
22
22
  from openapi_spec_tools.base_gen.constants import SEP2
23
+ from openapi_spec_tools.base_gen.exceptions import CodeGeneration
23
24
  from openapi_spec_tools.base_gen.files import copy_and_update
24
25
  from openapi_spec_tools.base_gen.utils import maybe_quoted
25
26
  from openapi_spec_tools.base_gen.utils import quoted
@@ -27,6 +28,7 @@ from openapi_spec_tools.base_gen.utils import replace_special
27
28
  from openapi_spec_tools.base_gen.utils import simple_escape
28
29
  from openapi_spec_tools.base_gen.utils import to_camel_case
29
30
  from openapi_spec_tools.base_gen.utils import to_snake_case
31
+ from openapi_spec_tools.constants import DEFAULT_SUPPORTED_CONTENT
30
32
  from openapi_spec_tools.constants import NULL_TYPES
31
33
  from openapi_spec_tools.expand import expand_schema
32
34
  from openapi_spec_tools.flatten import flatten_schema
@@ -70,6 +72,7 @@ class BaseGenerator:
70
72
  default_host: str | None = None,
71
73
  default_log_level: str | None = None,
72
74
  default_timeout: int | None = None,
75
+ error_handling: ErrorHandling | None = None,
73
76
  ):
74
77
  """Initialize with the OpenAPI spec and other data for generating multiple modules.
75
78
 
@@ -81,7 +84,7 @@ class BaseGenerator:
81
84
 
82
85
  Default values are as follows (see openapi_spec_tools.base_gen.constants for values):
83
86
  * package_name - no default, required
84
- * supported_content - DEFAULT_SUPPORTED_CONTENT
87
+ * supported_content - DEFAULT_SUPPORTED_CONTENT in openapi_spec_tools.constants
85
88
  * max_help_length - DEFAULT_MAX_HELP_LENGTH
86
89
  * reserved - DEFAULT_RESERVED
87
90
  * conflict_suffix - DEFAULT_CONFLICT_SUFFIX
@@ -95,6 +98,7 @@ class BaseGenerator:
95
98
  * default_host - empty string
96
99
  * default_log_level - DEFAULT_VALUE_LOG_LEVEL
97
100
  * default_timeout - DEFAULT_VALUE_TIMEOUT
101
+ * error_handling - ErrorHandling.DEFER
98
102
  """
99
103
  config = config or GeneratorConfig() # reduce logic by creating a default (if no config provided)
100
104
  self.operations = map_operations(oas.get(OasField.PATHS, {}))
@@ -117,6 +121,8 @@ class BaseGenerator:
117
121
  self.env_log_level = _or(env_log_level, config.env_log_level, DEFAULT_VAR_LOG_LEVEL)
118
122
  self.default_log = _or(default_log_level, config.default_log_level, DEFAULT_VALUE_LOG_LEVEL)
119
123
  self.default_timeout = _or(default_timeout, config.default_timeout, DEFAULT_VALUE_TIMEOUT)
124
+ self.error_handling = _or(error_handling, config.error_handling, ErrorHandling.DEFER)
125
+ self.errors: list[str] = []
120
126
 
121
127
  if not self.default_host:
122
128
  servers = oas.get(OasField.SERVERS)
@@ -142,11 +148,20 @@ class BaseGenerator:
142
148
 
143
149
  def default_infra_files(self) -> dict[Path, str]:
144
150
  """Default map of infrastructure files to copy."""
145
- return {}
151
+ base_gen = Path(__file__).parent
152
+ return {
153
+ base_gen / "_constants.py": "_constants.py",
154
+ }
146
155
 
147
156
  def default_infra_replacements(self) -> dict[str, str]:
148
157
  """Default map of infrastructure file line replacements."""
149
- return {}
158
+ return self._constants_replacements()
159
+
160
+ def _constants_replacements(self) -> dict[str, str]:
161
+ """Assign default_host when copying _constants.py."""
162
+ return {
163
+ 'DEFAULT_HOST = ""': f'DEFAULT_HOST = {quoted(self.default_host or "")}',
164
+ }
150
165
 
151
166
  def default_test_files(self) -> dict[Path, str]:
152
167
  """Default map of test files to copy."""
@@ -220,7 +235,9 @@ class BaseGenerator:
220
235
  if not line:
221
236
  result += NL
222
237
  else:
223
- _line = line.replace("'''", "\\'''") # avoid breaking docstring
238
+ # NOTE: SIMPLE_TRANSLATIONS would escape all the quotes, and we don't want that
239
+ translations = str.maketrans({"\\": r"\\"})
240
+ _line = line.translate(translations).replace("'''", r"\'''") # avoid closing docstring
224
241
  inner = textwrap.wrap(_line, width=self.max_help_length, replace_whitespace=False)
225
242
  result += SEP1 + SEP1.join(inner)
226
243
  result += f"{SEP1}'''{SEP1}"
@@ -536,6 +553,8 @@ class BaseGenerator:
536
553
  lines = ["body = {}"]
537
554
  found = set()
538
555
  forced_single = set()
556
+ # The body schema itself is a list of one complex item.
557
+ body_forced_single = False
539
558
  lineage = []
540
559
  for prop_data in body_params.values():
541
560
  parents = prop_data.get(OasField.X_PARENTS, [])
@@ -543,7 +562,10 @@ class BaseGenerator:
543
562
  lineage.append(parents)
544
563
 
545
564
  if prop_data.get(OasField.X_SINGLE):
546
- forced_single.add(parents[-1])
565
+ if parents:
566
+ forced_single.add(parents[-1])
567
+ else:
568
+ body_forced_single = True
547
569
 
548
570
  for parent in parents:
549
571
  if parent not in found:
@@ -580,10 +602,9 @@ class BaseGenerator:
580
602
  for parents in lineage:
581
603
  prev = "body"
582
604
  for curr in parents:
583
- items = depends.get(prev, [])
605
+ items = depends.setdefault(prev, [])
584
606
  if curr not in items:
585
607
  items.append(curr)
586
- depends[prev] = items
587
608
  prev = curr
588
609
 
589
610
  while depends:
@@ -605,6 +626,10 @@ class BaseGenerator:
605
626
  for r in removal:
606
627
  depends.pop(r)
607
628
 
629
+ if body_forced_single:
630
+ lines.append("if body:")
631
+ lines.append(" body = [body] # convert to list")
632
+
608
633
  return SEP1 + SEP1.join(lines)
609
634
 
610
635
  def clean_enum_name(self, value: str) -> bool:
@@ -749,7 +774,10 @@ class BaseGenerator:
749
774
  )
750
775
  for src, dst in files.items():
751
776
  dfile = dpath / dst
752
- copy_and_update(src.as_posix(), dfile.as_posix(), replacements, self.copyright)
777
+ file_replacements = replacements
778
+ if Path(dst).name == "_constants.py":
779
+ file_replacements = {**replacements, **self._constants_replacements()}
780
+ copy_and_update(src.as_posix(), dfile.as_posix(), file_replacements, self.copyright)
753
781
 
754
782
  def copy_test_files(self, dst_dir: str) -> None:
755
783
  """Iterate over the test_files and copy from local to dst."""
@@ -775,3 +803,32 @@ class BaseGenerator:
775
803
  return
776
804
 
777
805
  dfile.write_text(content, encoding="utf-8", newline="\n")
806
+
807
+ def add_error(self, message: str) -> None:
808
+ """Log a generation error and apply the configured error handling."""
809
+ logger.error(message)
810
+
811
+ if self.error_handling == ErrorHandling.IGNORE:
812
+ return
813
+
814
+ if self.error_handling == ErrorHandling.IMMEDIATE:
815
+ raise CodeGeneration(message)
816
+
817
+ self.errors.append(message)
818
+
819
+ def check_duplicates(self, op_id: str, arguments: list[str]) -> None:
820
+ """Record duplicate argument names for one generated function.
821
+
822
+ Every mode logs the error. Ignore then continues. Immediate raises
823
+ CodeGeneration. Defer stores the message for the caller to report.
824
+ """
825
+ names = [
826
+ line.split(":", 1)[0].strip()
827
+ for line in arguments
828
+ ]
829
+ duplicates = sorted({name for name in names if names.count(name) > 1})
830
+ if not duplicates:
831
+ return
832
+
833
+ message = f"Duplicate arguments for {op_id}: {', '.join(duplicates)}"
834
+ self.add_error(message)
@@ -1,6 +1,7 @@
1
1
  """Configuration data used to construct a base generator."""
2
2
  from __future__ import annotations
3
3
 
4
+ from enum import Enum
4
5
  from pathlib import Path
5
6
 
6
7
  import yaml
@@ -9,6 +10,14 @@ from pydantic import BaseModel
9
10
  from openapi_spec_tools.types import ContentType
10
11
 
11
12
 
13
+ class ErrorHandling(str, Enum):
14
+ """How generation treats errors such as duplicate arguments."""
15
+
16
+ IGNORE = "ignore"
17
+ DEFER = "defer"
18
+ IMMEDIATE = "immediate"
19
+
20
+
12
21
  class GeneratorConfig(BaseModel):
13
22
  """Data elements accepted by the BaseGenerator initializer.
14
23
 
@@ -33,6 +42,7 @@ class GeneratorConfig(BaseModel):
33
42
  default_host: str | None = None
34
43
  default_log_level: str | None = None
35
44
  default_timeout: int | None = None
45
+ error_handling: ErrorHandling | None = None
36
46
 
37
47
  @classmethod
38
48
  def from_yaml(cls, filename: str | Path) -> GeneratorConfig:
@@ -1,8 +1,6 @@
1
1
  """Common definitions for code generation."""
2
2
  from datetime import datetime
3
3
 
4
- from openapi_spec_tools.types import ContentType
5
-
6
4
  NL = "\n"
7
5
  SEP1 = "\n "
8
6
  SEP2 = "\n "
@@ -18,9 +16,6 @@ DEFAULT_COPYRIGHT = f"""\
18
16
  # This code was generated by the openapi-spec-tools CLI generator, DO NOT EDIT
19
17
  #
20
18
  """
21
- DEFAULT_SUPPORTED_CONTENT = [
22
- ContentType.APP_JSON,
23
- ]
24
19
  DEFAULT_MAX_HELP_LENGTH = 120
25
20
  DEFAULT_CONFLICT_SUFFIX = "_"
26
21
  DEFAULT_VAR_HOST = "API_HOST"
@@ -0,0 +1,5 @@
1
+ """Exceptions raised while generating code."""
2
+
3
+
4
+ class CodeGeneration(Exception): # noqa: N818
5
+ """Raised when code generation stops because of errors."""
@@ -6,6 +6,7 @@ from openapi_spec_tools.cli.content import app as content_app
6
6
  from openapi_spec_tools.cli.models import app as models_app
7
7
  from openapi_spec_tools.cli.operations import app as op_app
8
8
  from openapi_spec_tools.cli.paths import app as path_app
9
+ from openapi_spec_tools.cli.properties import app as props_app
9
10
  from openapi_spec_tools.cli.tags import app as tag_app
10
11
 
11
12
  app = typer.Typer(no_args_is_help=True, short_help="Tools for analyzing an OAS file")
@@ -14,3 +15,4 @@ app.add_typer(path_app, name="paths")
14
15
  app.add_typer(models_app, name="models")
15
16
  app.add_typer(tag_app, name="tags")
16
17
  app.add_typer(content_app, name="content")
18
+ app.add_typer(props_app, name="properties")
@@ -17,6 +17,7 @@ from openapi_spec_tools.cli.arguments import OpenApiFilenameArgument
17
17
  from openapi_spec_tools.cli.arguments import PackageNameOption
18
18
  from openapi_spec_tools.cli.arguments import PathPrefixOption
19
19
  from openapi_spec_tools.cli.arguments import StartPointOption
20
+ from openapi_spec_tools.cli.utils import check_errors
20
21
  from openapi_spec_tools.cli.utils import gen_config_from_file
21
22
  from openapi_spec_tools.cli.utils import init_logging
22
23
  from openapi_spec_tools.cli.utils import layout_tree_with_error_handling
@@ -90,6 +91,7 @@ def generate_api(
90
91
  generator.add_init_file(code_dir)
91
92
  generator.copy_infrastructure_files(code_dir)
92
93
  generator.generate_files(commands, code_dir)
94
+ check_errors(generator)
93
95
 
94
96
  typer.echo("Generated API files")
95
97
 
@@ -6,7 +6,6 @@ from typing import Annotated
6
6
  from typing import Any
7
7
 
8
8
  import typer
9
- import yaml
10
9
  from rich_objects import console_factory
11
10
 
12
11
  from openapi_spec_tools.cli.arguments import CodeDirectoryOption
@@ -22,6 +21,7 @@ from openapi_spec_tools.cli.arguments import StartPointOption
22
21
  from openapi_spec_tools.cli.arguments import UpdatedOpenApiFilenameOption
23
22
  from openapi_spec_tools.cli.constants import DIRECTORY
24
23
  from openapi_spec_tools.cli.constants import SEP
24
+ from openapi_spec_tools.cli.utils import check_errors
25
25
  from openapi_spec_tools.cli.utils import gen_config_from_file
26
26
  from openapi_spec_tools.cli.utils import init_logging
27
27
  from openapi_spec_tools.cli.utils import layout_tree_with_error_handling
@@ -43,6 +43,7 @@ from openapi_spec_tools.utils import remove_property
43
43
  from openapi_spec_tools.utils import remove_schema_tags
44
44
  from openapi_spec_tools.utils import schema_operations_filter
45
45
  from openapi_spec_tools.utils import set_nullable_not_required
46
+ from openapi_spec_tools.utils import write_oas
46
47
 
47
48
  #################################################
48
49
  # Utilities
@@ -135,6 +136,7 @@ def generate_cli(
135
136
  generator.add_init_file(code_dir)
136
137
  generator.copy_infrastructure_files(code_dir)
137
138
  generator.generate_files(commands, code_dir)
139
+ check_errors(generator)
138
140
 
139
141
  if include_tests:
140
142
  os.makedirs(test_dir, exist_ok=True)
@@ -189,9 +191,7 @@ def generate_unreferenced(
189
191
  parts = path.split("/")
190
192
  path = "/".join([p for p in parts if p and '{' not in p])
191
193
 
192
- operations = paths.get(path, [])
193
- operations.append(op)
194
- paths[path] = operations
194
+ paths.setdefault(path, []).append(op)
195
195
 
196
196
  # display each operations below the path
197
197
  for path, ops in paths.items():
@@ -295,6 +295,7 @@ def show_cli_tree(
295
295
  generator = CliGenerator(package_name="", oas=oas)
296
296
 
297
297
  tree = generate_tree_node(generator, layout)
298
+ check_errors(generator)
298
299
  if not tree.children:
299
300
  typer.echo("No operations or sub-commands found")
300
301
  return
@@ -358,8 +359,7 @@ def trim_oas(
358
359
  updated = set_nullable_not_required(updated)
359
360
 
360
361
  out_file = updated_file or openapi_file
361
- with open(out_file, "w", encoding="utf-8", newline="\n") as fp:
362
- yaml.dump(updated, fp, indent=indent, sort_keys=True)
362
+ write_oas(out_file, updated, indent=indent)
363
363
 
364
364
  typer.echo(f"Wrote to {out_file}")
365
365
  return
@@ -14,6 +14,7 @@ from openapi_spec_tools.cli.arguments import OpenApiFilenameArgument
14
14
  from openapi_spec_tools.cli.arguments import UpdatedOpenApiFilenameOption
15
15
  from openapi_spec_tools.cli.constants import INDENT
16
16
  from openapi_spec_tools.cli.history import app as history_app
17
+ from openapi_spec_tools.cli.references import app as references_app
17
18
  from openapi_spec_tools.cli.utils import error_out
18
19
  from openapi_spec_tools.cli.utils import init_logging
19
20
  from openapi_spec_tools.cli.utils import open_oas_with_error_handling
@@ -26,6 +27,7 @@ from openapi_spec_tools.utils import remove_property
26
27
  from openapi_spec_tools.utils import remove_schema_tags
27
28
  from openapi_spec_tools.utils import schema_operations_filter
28
29
  from openapi_spec_tools.utils import set_nullable_not_required
30
+ from openapi_spec_tools.utils import write_oas
29
31
 
30
32
  #################################################
31
33
  # Top-level stuff
@@ -37,6 +39,7 @@ app = typer.Typer(
37
39
  )
38
40
  app.add_typer(history_app, name="history")
39
41
  app.add_typer(analyze_app, name="analyze")
42
+ app.add_typer(references_app, name="references")
40
43
 
41
44
 
42
45
  @app.command("info", short_help="Display the 'info' from the OpenAPI specification")
@@ -185,8 +188,7 @@ def update(
185
188
  updated = schema_operations_filter(updated, allow=set(allowed_operations))
186
189
 
187
190
  if updated_filename:
188
- with open(updated_filename, "w", encoding="utf-8", newline="\n") as fp:
189
- yaml.dump(updated, fp, indent=indent)
191
+ write_oas(updated_filename, updated, indent=indent)
190
192
 
191
193
  console = console_factory()
192
194
  diffs = find_diffs(old_spec, updated)
@@ -107,8 +107,7 @@ def paths_operations(
107
107
  if method == OasField.PARAMS:
108
108
  continue
109
109
  op_id = operation_id(op_data, method, path)
110
- items = result.get(path, []) + [op_id]
111
- result[path] = items
110
+ result.setdefault(path, []).append(op_id)
112
111
 
113
112
  if not result:
114
113
  error_out(f"failed to find {path_name}")