openapi-spec-tools 0.21.0__tar.gz → 0.23.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 (63) hide show
  1. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/PKG-INFO +7 -5
  2. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/README.md +2 -0
  3. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/api_gen/api_generator.py +9 -3
  4. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/api_gen/flat_generator.py +5 -1
  5. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/api_gen/opaque_generator.py +5 -1
  6. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/api_gen/property_generator.py +5 -1
  7. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/base_gen/__init__.py +2 -0
  8. openapi_spec_tools-0.23.0/openapi_spec_tools/base_gen/_constants.py +3 -0
  9. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/base_gen/_logging.py +6 -4
  10. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/base_gen/base_generator.py +72 -17
  11. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/base_gen/config.py +10 -0
  12. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/base_gen/constants.py +33 -0
  13. openapi_spec_tools-0.23.0/openapi_spec_tools/base_gen/exceptions.py +5 -0
  14. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/cli/api_gen.py +6 -5
  15. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/cli/cli_gen.py +25 -23
  16. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/cli/content.py +2 -3
  17. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/cli/layout.py +13 -14
  18. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/cli/models.py +13 -13
  19. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/cli/oas.py +9 -10
  20. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/cli/operations.py +12 -13
  21. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/cli/paths.py +8 -8
  22. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/cli/tags.py +10 -9
  23. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/cli/utils.py +21 -6
  24. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/cli_gen/cli_generator.py +15 -9
  25. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/expand.py +2 -3
  26. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/flatten.py +2 -3
  27. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/layout/layout_generator.py +9 -5
  28. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/utils.py +29 -3
  29. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/pyproject.toml +5 -5
  30. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/tests/cli_gen/test_cli_generator.py +12 -4
  31. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/tests/cli_gen/test_files.py +1 -1
  32. openapi_spec_tools-0.23.0/tests/cli_gen/test_main.py +51 -0
  33. openapi_spec_tools-0.21.0/tests/cli_gen/test_main.py +0 -34
  34. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/.gitignore +0 -0
  35. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/LICENSE +0 -0
  36. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/__init__.py +0 -0
  37. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/api_gen/__init__.py +0 -0
  38. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/api_gen/_environment.py +0 -0
  39. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/base_gen/_requests.py +0 -0
  40. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/base_gen/files.py +0 -0
  41. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/base_gen/utils.py +0 -0
  42. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/cli/__init__.py +0 -0
  43. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/cli/analyze.py +0 -0
  44. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/cli/arguments.py +0 -0
  45. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/cli/constants.py +0 -0
  46. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/cli/history.py +0 -0
  47. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/cli_gen/__init__.py +0 -0
  48. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/cli_gen/_arguments.py +0 -0
  49. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/cli_gen/_display.py +0 -0
  50. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/cli_gen/_exceptions.py +0 -0
  51. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/cli_gen/_tree.py +0 -0
  52. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/cli_gen/files.py +0 -0
  53. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/constants.py +0 -0
  54. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/layout/__init__.py +0 -0
  55. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/layout/config.py +0 -0
  56. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/layout/merge.py +0 -0
  57. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/layout/types.py +0 -0
  58. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/layout/utils.py +0 -0
  59. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/openapi_spec_tools/types.py +0 -0
  60. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/tests/cli_gen/__init__.py +0 -0
  61. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/tests/cli_gen/test_display.py +0 -0
  62. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.0}/tests/cli_gen/test_exceptions.py +0 -0
  63. {openapi_spec_tools-0.21.0 → openapi_spec_tools-0.23.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.21.0
3
+ Version: 0.23.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
@@ -25,15 +25,17 @@ Classifier: Topic :: Software Development :: Libraries :: Python Modules
25
25
  Classifier: Topic :: Utilities
26
26
  Classifier: Typing :: Typed
27
27
  Requires-Python: <4,>=3.10
28
- Requires-Dist: gitpython>=3.2.0
29
- Requires-Dist: pydantic<3,>=2.13.3
28
+ Requires-Dist: gitpython>=3.2.1
29
+ Requires-Dist: pydantic<3,>=2.14.3
30
30
  Requires-Dist: pyyaml>=6.0.3
31
31
  Requires-Dist: requests>=2.34.2
32
- Requires-Dist: rich-objects>=0.3.1
32
+ Requires-Dist: rich-objects>=0.4.0
33
33
  Requires-Dist: rich>=15.0.0
34
- Requires-Dist: typer>=0.27.2
34
+ Requires-Dist: typer>=0.29.1
35
35
  Description-Content-Type: text/markdown
36
36
 
37
+ [![codecov](https://codecov.io/gh/rickwporter/openapi-spec-tools/branch/main/graph/badge.svg)](https://codecov.io/gh/rickwporter/openapi-spec-tools)
38
+
37
39
  # openapi-spec-tools
38
40
 
39
41
  This is a collection of tools for using OpenAPI specifications. The OpenAPI community has a plethora of tools, and this is intended to supplement those. The tools here provide functionality that has not been readily available elsewhere.
@@ -1,3 +1,5 @@
1
+ [![codecov](https://codecov.io/gh/rickwporter/openapi-spec-tools/branch/main/graph/badge.svg)](https://codecov.io/gh/rickwporter/openapi-spec-tools)
2
+
1
3
  # openapi-spec-tools
2
4
 
3
5
  This is a collection of tools for using OpenAPI specifications. The OpenAPI community has a plethora of tools, and this is intended to supplement those. The tools here provide functionality that has not been readily available elsewhere.
@@ -18,10 +18,13 @@ from openapi_spec_tools.base_gen import simple_escape
18
18
  from openapi_spec_tools.base_gen import to_snake_case
19
19
  from openapi_spec_tools.layout import LayoutNode
20
20
  from openapi_spec_tools.types import OasField
21
+ from openapi_spec_tools.utils import get_logger
21
22
 
22
23
  DEFAULT_VAR_LOG_LEVEL = "API_LOG_LEVEL"
23
24
  DEFAULT_VALUE_LOG_LEVEL = "info"
24
25
 
26
+ logger = get_logger(__name__)
27
+
25
28
 
26
29
  class ApiGenerator(BaseGenerator, ABC):
27
30
  """Provides the majority of the CLI generation functions.
@@ -46,6 +49,7 @@ class ApiGenerator(BaseGenerator, ABC):
46
49
  api_gen = Path(__file__).parent
47
50
  base_gen = Path(__file__).parent.parent / "base_gen"
48
51
  return {
52
+ **super().default_infra_files(),
49
53
  base_gen / "_logging.py": "_logging.py",
50
54
  base_gen / "_requests.py": "_requests.py",
51
55
  api_gen / "_environment.py": "_environment.py",
@@ -54,6 +58,7 @@ class ApiGenerator(BaseGenerator, ABC):
54
58
  def default_infra_replacements(self) -> dict[str, str]:
55
59
  """Default infrastructure line replacements."""
56
60
  return {
61
+ **super().default_infra_replacements(),
57
62
  "openapi_spec_tools.api_gen": self.package_name,
58
63
  "openapi_spec_tools.base_gen": self.package_name,
59
64
  __package__: self.package_name,
@@ -101,6 +106,7 @@ from datetime import datetime # noqa: F401
101
106
  from enum import Enum # noqa: F401
102
107
  from typing import Any
103
108
 
109
+ from {self.package_name} import _constants as _c
104
110
  from {self.package_name} import _environment as _e
105
111
  from {self.package_name} import _logging as _l
106
112
  from {self.package_name} import _requests as _r
@@ -110,7 +116,7 @@ from {self.package_name} import _requests as _r
110
116
  """Provide initialization of standard arguments inside body."""
111
117
  host_default = (
112
118
  f'_e.env_string({maybe_quoted(self.env_host)}, '
113
- f'default={quoted(self.default_host)}, except_missing=True)'
119
+ f'default=_c.DEFAULT_HOST, except_missing=True)'
114
120
  )
115
121
  key_default = f'_e.env_string({maybe_quoted(self.env_key)}, except_missing=True)'
116
122
  timeout_default = f'_e.env_int({maybe_quoted(self.env_timeout)}, default={self.default_timeout})'
@@ -153,7 +159,7 @@ from {self.package_name} import _requests as _r
153
159
  py_type = self.get_parameter_pytype(prop)
154
160
  if not py_type:
155
161
  # log an error and use 'Any'
156
- self.logger.error(f"Unable to determine Python type for {prop}")
162
+ logger.error(f"Unable to determine Python type for {prop}")
157
163
  py_type = 'Any'
158
164
 
159
165
  if collection:
@@ -201,7 +207,7 @@ from {self.package_name} import _requests as _r
201
207
  """Create a module for the current node, and recursively generate sub-commands."""
202
208
  if node.operations():
203
209
  module_name = to_snake_case(node.identifier)
204
- self.logger.info(f"Generating {module_name} module")
210
+ logger.info(f"Generating {module_name} module")
205
211
  text = self.copyright
206
212
  text += self.standard_imports()
207
213
  for command in node.operations():
@@ -9,6 +9,9 @@ from openapi_spec_tools.base_gen import SEP1
9
9
  from openapi_spec_tools.base_gen import quoted
10
10
  from openapi_spec_tools.layout import LayoutNode
11
11
  from openapi_spec_tools.types import OasField
12
+ from openapi_spec_tools.utils import get_logger
13
+
14
+ logger = get_logger(__name__)
12
15
 
13
16
 
14
17
  class FlatApiGenerator(ApiGenerator):
@@ -59,7 +62,8 @@ class FlatApiGenerator(ApiGenerator):
59
62
  func_args.extend(self.command_infra_arguments(node))
60
63
  args_str = SEP1 + SEP1.join(func_args) + NL
61
64
 
62
- self.logger.debug(f"{func_name}({len(path_params)} path, {len(query_params)} query, {len(body_params)} body)")
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)
63
67
 
64
68
  user_header_init = ""
65
69
  user_header_arg = ""
@@ -7,6 +7,9 @@ from openapi_spec_tools.base_gen import SEP1
7
7
  from openapi_spec_tools.base_gen import quoted
8
8
  from openapi_spec_tools.layout import LayoutNode
9
9
  from openapi_spec_tools.types import OasField
10
+ from openapi_spec_tools.utils import get_logger
11
+
12
+ logger = get_logger(__name__)
10
13
 
11
14
 
12
15
  class OpaqueApiGenerator(ApiGenerator):
@@ -77,7 +80,8 @@ class OpaqueApiGenerator(ApiGenerator):
77
80
  func_args.extend(self.command_infra_arguments(node))
78
81
  args_str = SEP1 + SEP1.join(func_args) + NL
79
82
 
80
- self.logger.debug(f"{func_name}({len(path_params)} path, {len(query_params)} query")
83
+ logger.debug(f"{func_name}({len(path_params)} path, {len(query_params)} query")
84
+ self.check_duplicates(node.identifier, func_args)
81
85
 
82
86
  user_header_init = ""
83
87
  user_header_arg = ""
@@ -11,6 +11,9 @@ from openapi_spec_tools.flatten import apply_one_of
11
11
  from openapi_spec_tools.flatten import flatten_collection
12
12
  from openapi_spec_tools.layout import LayoutNode
13
13
  from openapi_spec_tools.types import OasField
14
+ from openapi_spec_tools.utils import get_logger
15
+
16
+ logger = get_logger(__name__)
14
17
 
15
18
 
16
19
  class PropertyApiGenerator(ApiGenerator):
@@ -113,7 +116,8 @@ class PropertyApiGenerator(ApiGenerator):
113
116
  func_args.extend(self.command_infra_arguments(node))
114
117
  args_str = SEP1 + SEP1.join(func_args) + NL
115
118
 
116
- self.logger.debug(f"{func_name}({len(path_params)} path, {len(query_params)} query")
119
+ logger.debug(f"{func_name}({len(path_params)} path, {len(query_params)} query")
120
+ self.check_duplicates(node.identifier, func_args)
117
121
 
118
122
  user_header_init = ""
119
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 = ""
@@ -14,12 +14,14 @@ class LogLevel(str, Enum):
14
14
  DEBUG = "debug"
15
15
 
16
16
 
17
- def get_logger(name: str | None = LOG_CLASS) -> logging.Logger:
18
- return logging.getLogger(name=name)
17
+ def get_logger() -> logging.Logger:
18
+ """Get the logger for LOG_CLASS."""
19
+ return logging.getLogger(name=LOG_CLASS)
19
20
 
20
21
 
21
- def init_logging(level: LogLevel, name: str | None = LOG_CLASS) -> logging.Logger:
22
+ def init_logging(level: LogLevel) -> logging.Logger:
23
+ """Initialize the LOG_CLASS logger and sets the level."""
22
24
  logging.basicConfig(format=LOG_FORMAT, datefmt=LOG_DATE_FMT)
23
- logger = get_logger(name)
25
+ logger = get_logger()
24
26
  logger.setLevel(level.upper())
25
27
  return logger
@@ -1,11 +1,10 @@
1
1
  """Declares the Generator class that is used for most of the CLi generation capability."""
2
- import logging
3
2
  import textwrap
4
3
  from copy import deepcopy
5
4
  from pathlib import Path
6
5
  from typing import Any
7
6
 
8
- from openapi_spec_tools.base_gen._logging import init_logging
7
+ from openapi_spec_tools.base_gen.config import ErrorHandling
9
8
  from openapi_spec_tools.base_gen.config import GeneratorConfig
10
9
  from openapi_spec_tools.base_gen.constants import COLLECTIONS
11
10
  from openapi_spec_tools.base_gen.constants import DEFAULT_CONFLICT_SUFFIX
@@ -22,6 +21,7 @@ from openapi_spec_tools.base_gen.constants import DEFAULT_VAR_TIMEOUT
22
21
  from openapi_spec_tools.base_gen.constants import NL
23
22
  from openapi_spec_tools.base_gen.constants import SEP1
24
23
  from openapi_spec_tools.base_gen.constants import SEP2
24
+ from openapi_spec_tools.base_gen.exceptions import CodeGeneration
25
25
  from openapi_spec_tools.base_gen.files import copy_and_update
26
26
  from openapi_spec_tools.base_gen.utils import maybe_quoted
27
27
  from openapi_spec_tools.base_gen.utils import quoted
@@ -36,10 +36,11 @@ from openapi_spec_tools.flatten import is_simple_type
36
36
  from openapi_spec_tools.types import ContentType
37
37
  from openapi_spec_tools.types import OasField
38
38
  from openapi_spec_tools.utils import _or
39
+ from openapi_spec_tools.utils import get_logger
39
40
  from openapi_spec_tools.utils import map_operations
40
41
  from openapi_spec_tools.utils import reference_classname
41
42
 
42
- LOG_CLASS = "base-gen"
43
+ logger = get_logger(__name__)
43
44
 
44
45
 
45
46
  class BaseGenerator:
@@ -53,7 +54,6 @@ class BaseGenerator:
53
54
  def __init__(
54
55
  self,
55
56
  oas: dict[str, Any],
56
- logger: logging.Logger | None = None,
57
57
  config: GeneratorConfig | None = None,
58
58
  package_name: str | None = None,
59
59
  supported_content: list[ContentType] | None = None,
@@ -72,6 +72,7 @@ class BaseGenerator:
72
72
  default_host: str | None = None,
73
73
  default_log_level: str | None = None,
74
74
  default_timeout: int | None = None,
75
+ error_handling: ErrorHandling | None = None,
75
76
  ):
76
77
  """Initialize with the OpenAPI spec and other data for generating multiple modules.
77
78
 
@@ -97,11 +98,11 @@ class BaseGenerator:
97
98
  * default_host - empty string
98
99
  * default_log_level - DEFAULT_VALUE_LOG_LEVEL
99
100
  * default_timeout - DEFAULT_VALUE_TIMEOUT
101
+ * error_handling - ErrorHandling.DEFER
100
102
  """
101
103
  config = config or GeneratorConfig() # reduce logic by creating a default (if no config provided)
102
104
  self.operations = map_operations(oas.get(OasField.PATHS, {}))
103
105
  self.components = oas.get(OasField.COMPONENTS, {})
104
- self.logger = logger or init_logging("INFO", LOG_CLASS)
105
106
 
106
107
  self.package_name = _or(package_name, config.package_name, ValueError("Missing package_name"))
107
108
  self.default_host = _or(default_host, config.default_host, "")
@@ -120,6 +121,8 @@ class BaseGenerator:
120
121
  self.env_log_level = _or(env_log_level, config.env_log_level, DEFAULT_VAR_LOG_LEVEL)
121
122
  self.default_log = _or(default_log_level, config.default_log_level, DEFAULT_VALUE_LOG_LEVEL)
122
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] = []
123
126
 
124
127
  if not self.default_host:
125
128
  servers = oas.get(OasField.SERVERS)
@@ -145,11 +148,20 @@ class BaseGenerator:
145
148
 
146
149
  def default_infra_files(self) -> dict[Path, str]:
147
150
  """Default map of infrastructure files to copy."""
148
- return {}
151
+ base_gen = Path(__file__).parent
152
+ return {
153
+ base_gen / "_constants.py": "_constants.py",
154
+ }
149
155
 
150
156
  def default_infra_replacements(self) -> dict[str, str]:
151
157
  """Default map of infrastructure file line replacements."""
152
- 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
+ }
153
165
 
154
166
  def default_test_files(self) -> dict[Path, str]:
155
167
  """Default map of test files to copy."""
@@ -223,7 +235,10 @@ class BaseGenerator:
223
235
  if not line:
224
236
  result += NL
225
237
  else:
226
- inner = textwrap.wrap(line, width=self.max_help_length, replace_whitespace=False)
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
241
+ inner = textwrap.wrap(_line, width=self.max_help_length, replace_whitespace=False)
227
242
  result += SEP1 + SEP1.join(inner)
228
243
  result += f"{SEP1}'''{SEP1}"
229
244
  return result
@@ -368,10 +383,10 @@ class BaseGenerator:
368
383
  # find first item from schema this is a non-null type
369
384
  item = next((item for item in schema if item in reduced), None)
370
385
  if item is not None:
371
- self.logger.debug(f"Choosing {item} type from {', '.join(schema)}")
386
+ logger.debug(f"Choosing {item} type from {', '.join(schema)}")
372
387
  return item
373
388
 
374
- self.logger.warning(f"Unable to simplify type for {schema}")
389
+ logger.warning(f"Unable to simplify type for {schema}")
375
390
  return None
376
391
 
377
392
 
@@ -538,6 +553,8 @@ class BaseGenerator:
538
553
  lines = ["body = {}"]
539
554
  found = set()
540
555
  forced_single = set()
556
+ # The body schema itself is a list of one complex item.
557
+ body_forced_single = False
541
558
  lineage = []
542
559
  for prop_data in body_params.values():
543
560
  parents = prop_data.get(OasField.X_PARENTS, [])
@@ -545,7 +562,10 @@ class BaseGenerator:
545
562
  lineage.append(parents)
546
563
 
547
564
  if prop_data.get(OasField.X_SINGLE):
548
- forced_single.add(parents[-1])
565
+ if parents:
566
+ forced_single.add(parents[-1])
567
+ else:
568
+ body_forced_single = True
549
569
 
550
570
  for parent in parents:
551
571
  if parent not in found:
@@ -607,17 +627,19 @@ class BaseGenerator:
607
627
  for r in removal:
608
628
  depends.pop(r)
609
629
 
630
+ if body_forced_single:
631
+ lines.append("if body:")
632
+ lines.append(" body = [body] # convert to list")
633
+
610
634
  return SEP1 + SEP1.join(lines)
611
635
 
612
636
  def clean_enum_name(self, value: str) -> bool:
613
637
  """Check to see if value can be directly used as a variable name."""
614
638
  if not isinstance(value, str):
615
639
  return False
616
- try:
617
- float(value)
640
+ # Names cannot start with a digit, including values like "1", "1.0", "1st" or "1.2.3".
641
+ if value[:1].isdigit():
618
642
  return False
619
- except ValueError:
620
- pass
621
643
 
622
644
  return True
623
645
 
@@ -689,7 +711,8 @@ class BaseGenerator:
689
711
  dup_counts = dict.fromkeys(duplicates, 0)
690
712
  declarations = []
691
713
  for v in values:
692
- base_name = self.variable_name(str(v)).upper()
714
+ var_name = self.variable_name(str(v)) or "empty"
715
+ base_name = var_name.upper()
693
716
  suffix = ""
694
717
  if base_name in dup_counts:
695
718
  suffix = dup_counts[base_name]
@@ -752,7 +775,10 @@ class BaseGenerator:
752
775
  )
753
776
  for src, dst in files.items():
754
777
  dfile = dpath / dst
755
- copy_and_update(src.as_posix(), dfile.as_posix(), replacements, self.copyright)
778
+ file_replacements = replacements
779
+ if Path(dst).name == "_constants.py":
780
+ file_replacements = {**replacements, **self._constants_replacements()}
781
+ copy_and_update(src.as_posix(), dfile.as_posix(), file_replacements, self.copyright)
756
782
 
757
783
  def copy_test_files(self, dst_dir: str) -> None:
758
784
  """Iterate over the test_files and copy from local to dst."""
@@ -778,3 +804,32 @@ class BaseGenerator:
778
804
  return
779
805
 
780
806
  dfile.write_text(content, encoding="utf-8", newline="\n")
807
+
808
+ def add_error(self, message: str) -> None:
809
+ """Log a generation error and apply the configured error handling."""
810
+ logger.error(message)
811
+
812
+ if self.error_handling == ErrorHandling.IGNORE:
813
+ return
814
+
815
+ if self.error_handling == ErrorHandling.IMMEDIATE:
816
+ raise CodeGeneration(message)
817
+
818
+ self.errors.append(message)
819
+
820
+ def check_duplicates(self, op_id: str, arguments: list[str]) -> None:
821
+ """Record duplicate argument names for one generated function.
822
+
823
+ Every mode logs the error. Ignore then continues. Immediate raises
824
+ CodeGeneration. Defer stores the message for the caller to report.
825
+ """
826
+ names = [
827
+ line.split(":", 1)[0].strip()
828
+ for line in arguments
829
+ ]
830
+ duplicates = sorted({name for name in names if names.count(name) > 1})
831
+ if not duplicates:
832
+ return
833
+
834
+ message = f"Duplicate arguments for {op_id}: {', '.join(duplicates)}"
835
+ 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:
@@ -33,28 +33,61 @@ DEFAULT_VALUE_TIMEOUT = 5
33
33
  # This is an incomplete list of Python builtins and imports that should avoided in variable names
34
34
  DEFAULT_RESERVED = {
35
35
  "all",
36
+ "Annotated",
37
+ "and",
36
38
  "any",
39
+ "as",
40
+ "assert",
41
+ "async",
42
+ "await",
37
43
  "bool",
44
+ "break",
38
45
  "breakpoint",
46
+ "case",
39
47
  "class",
40
48
  "continue",
41
49
  "date",
42
50
  "datetime",
51
+ "def",
43
52
  "dict",
53
+ "del",
54
+ "else",
55
+ "elif",
44
56
  "except",
57
+ "False",
58
+ "finally",
45
59
  "float",
46
60
  "for",
47
61
  "format",
62
+ "from",
63
+ "global",
64
+ "if",
65
+ "import",
48
66
  "in",
49
67
  "input",
50
68
  "int",
69
+ "is",
70
+ "lambda",
51
71
  "list",
72
+ "match",
52
73
  "max",
53
74
  "min",
75
+ "None",
76
+ "none",
77
+ "nonlocal",
78
+ "not",
79
+ "or",
80
+ "pass",
54
81
  "print",
82
+ "raise",
83
+ "return",
55
84
  "set",
85
+ "str",
86
+ "True",
56
87
  "try",
57
88
  "type",
58
89
  "typer",
59
90
  "while",
91
+ "with",
92
+ "yeild",
60
93
  }
@@ -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."""
@@ -17,11 +17,11 @@ 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
23
24
  from openapi_spec_tools.cli.utils import open_oas_with_error_handling
24
- from openapi_spec_tools.constants import LOG_CLASS
25
25
  from openapi_spec_tools.layout import DEFAULT_START
26
26
  from openapi_spec_tools.layout import LayoutGenerator
27
27
 
@@ -61,11 +61,11 @@ def generate_api(
61
61
  The body-type only applies to functions with a request body. It determines the granularity of
62
62
  the function arguments, and the amount of work done to form the body.
63
63
  """
64
- logger = init_logging(log_level, LOG_CLASS)
64
+ init_logging(log_level)
65
65
 
66
- oas = open_oas_with_error_handling(openapi_file, logger)
66
+ oas = open_oas_with_error_handling(openapi_file)
67
67
  if layout_file:
68
- commands = layout_tree_with_error_handling(layout_file, start, logger)
68
+ commands = layout_tree_with_error_handling(layout_file, start)
69
69
  else:
70
70
  layout_gen = LayoutGenerator(oas, prefix=prefix or None)
71
71
  commands = layout_gen.generate()
@@ -76,7 +76,7 @@ def generate_api(
76
76
  typer.echo("Must specify package_name in arguments or configuration.")
77
77
  raise typer.Exit(1)
78
78
 
79
- kwargs = {"package_name": package_name, "oas": oas, "logger": logger, "config": config}
79
+ kwargs = {"package_name": package_name, "oas": oas, "config": config}
80
80
  if body_type == BodyType.FLAT:
81
81
  generator = FlatApiGenerator(**kwargs)
82
82
  elif body_type == BodyType.PROPERTY:
@@ -91,6 +91,7 @@ def generate_api(
91
91
  generator.add_init_file(code_dir)
92
92
  generator.copy_infrastructure_files(code_dir)
93
93
  generator.generate_files(commands, code_dir)
94
+ check_errors(generator)
94
95
 
95
96
  typer.echo("Generated API files")
96
97