openapi-spec-tools 0.18.0__tar.gz → 0.19.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 (56) hide show
  1. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/PKG-INFO +14 -5
  2. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/README.md +9 -0
  3. openapi_spec_tools-0.19.0/openapi_spec_tools/api_gen/__init__.py +5 -0
  4. openapi_spec_tools-0.19.0/openapi_spec_tools/api_gen/_environment.py +35 -0
  5. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/openapi_spec_tools/api_gen/api_generator.py +54 -32
  6. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/openapi_spec_tools/api_gen/flat_generator.py +4 -4
  7. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/openapi_spec_tools/api_gen/opaque_generator.py +4 -4
  8. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/openapi_spec_tools/api_gen/property_generator.py +5 -5
  9. openapi_spec_tools-0.19.0/openapi_spec_tools/base_gen/__init__.py +17 -0
  10. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/openapi_spec_tools/base_gen/_requests.py +5 -4
  11. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/openapi_spec_tools/base_gen/base_generator.py +160 -51
  12. openapi_spec_tools-0.19.0/openapi_spec_tools/base_gen/config.py +63 -0
  13. openapi_spec_tools-0.19.0/openapi_spec_tools/base_gen/constants.py +60 -0
  14. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/openapi_spec_tools/base_gen/files.py +7 -23
  15. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/openapi_spec_tools/base_gen/utils.py +4 -0
  16. openapi_spec_tools-0.19.0/openapi_spec_tools/cli/__init__.py +1 -0
  17. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/openapi_spec_tools/cli/api_gen.py +28 -33
  18. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/openapi_spec_tools/cli/arguments.py +6 -8
  19. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/openapi_spec_tools/cli/cli_gen.py +43 -54
  20. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/openapi_spec_tools/cli/history.py +3 -3
  21. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/openapi_spec_tools/cli/layout.py +20 -18
  22. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/openapi_spec_tools/cli/utils.py +43 -4
  23. openapi_spec_tools-0.19.0/openapi_spec_tools/cli_gen/__init__.py +7 -0
  24. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/openapi_spec_tools/cli_gen/_arguments.py +1 -0
  25. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/openapi_spec_tools/cli_gen/_tree.py +1 -4
  26. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/openapi_spec_tools/cli_gen/cli_generator.py +108 -23
  27. openapi_spec_tools-0.19.0/openapi_spec_tools/cli_gen/files.py +82 -0
  28. openapi_spec_tools-0.19.0/openapi_spec_tools/layout/__init__.py +25 -0
  29. openapi_spec_tools-0.19.0/openapi_spec_tools/layout/config.py +40 -0
  30. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/openapi_spec_tools/layout/layout_generator.py +54 -18
  31. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/openapi_spec_tools/layout/utils.py +7 -2
  32. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/openapi_spec_tools/utils.py +14 -0
  33. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/pyproject.toml +7 -8
  34. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/tests/cli_gen/test_cli_generator.py +74 -27
  35. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/tests/cli_gen/test_files.py +7 -64
  36. openapi_spec_tools-0.18.0/openapi_spec_tools/api_gen/_environment.py +0 -19
  37. openapi_spec_tools-0.18.0/openapi_spec_tools/api_gen/files.py +0 -54
  38. openapi_spec_tools-0.18.0/openapi_spec_tools/base_gen/constants.py +0 -9
  39. openapi_spec_tools-0.18.0/openapi_spec_tools/cli_gen/constants.py +0 -2
  40. openapi_spec_tools-0.18.0/openapi_spec_tools/cli_gen/files.py +0 -181
  41. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/.gitignore +0 -0
  42. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/LICENSE +0 -0
  43. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/openapi_spec_tools/__init__.py +0 -0
  44. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/openapi_spec_tools/base_gen/_logging.py +0 -0
  45. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/openapi_spec_tools/cli/oas.py +0 -0
  46. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/openapi_spec_tools/cli_gen/_display.py +0 -0
  47. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/openapi_spec_tools/cli_gen/_exceptions.py +0 -0
  48. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/openapi_spec_tools/layout/merge.py +0 -0
  49. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/openapi_spec_tools/layout/types.py +0 -0
  50. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/openapi_spec_tools/types.py +0 -0
  51. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/tests/cli_gen/__init__.py +0 -0
  52. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/tests/cli_gen/helpers.py +0 -0
  53. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/tests/cli_gen/test_display.py +0 -0
  54. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/tests/cli_gen/test_exceptions.py +0 -0
  55. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.0}/tests/cli_gen/test_main.py +0 -0
  56. {openapi_spec_tools-0.18.0 → openapi_spec_tools-0.19.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.18.0
3
+ Version: 0.19.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,12 +25,12 @@ 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<4,>=3.1.59
28
+ Requires-Dist: gitpython>=3.2.0
29
29
  Requires-Dist: pydantic<3,>=2.13.3
30
- Requires-Dist: pyyaml<7,>=6.0.3
31
- Requires-Dist: requests<3,>=2.33.1
30
+ Requires-Dist: pyyaml>=6.0.3
31
+ Requires-Dist: requests>=2.34.2
32
32
  Requires-Dist: rich-objects>=0.3.0
33
- Requires-Dist: rich<16,>=15.0.0
33
+ Requires-Dist: rich>=15.0.0
34
34
  Requires-Dist: typer>=0.27.2
35
35
  Description-Content-Type: text/markdown
36
36
 
@@ -75,6 +75,10 @@ Found Pet is used by 3 operations:
75
75
  (.env) %
76
76
  ```
77
77
 
78
+ ## Layout
79
+
80
+ The CLI and API generation allow users to specify a layout file to reduce assumptions. More information about the layout generation, format and schema are covered in [LAYOUT.md](LAYOUT.md).
81
+
78
82
  ## CLI Generation
79
83
 
80
84
  The `cli-gen` tool allows users to create a user-friendly CLI using the OpenAPI spec and a layout file. The layout file provides the CLI structure and refers to the OpenAPI spec for details of operations. [LAYOUT.md](LAYOUT.md) has more details about the layout file, and the [CLI_GEN.md](CLI_GEN.md) has more info about CLI generation.
@@ -114,10 +118,15 @@ Into code that produces a CLI that has commands like:
114
118
 
115
119
  See the examples in `examples/` for some more complete works.
116
120
 
121
+ The CLI generator can be configured using a YAML file. For more details, see [GEN_CONFIG.md](GEN_CONFIG.md).
122
+
123
+
117
124
  ## API Generation
118
125
 
119
126
  The `api-gen` tool allows users to generate API code using the OpenAPI spec. The generated Python code provides type hints and helpful comments, but does no real checking of the arguments and/or return values. The return values are typically dictionaries instead of a data class, such as the models provided in the standard OpenAPI generator.
120
127
 
128
+ The API generator can be configured using a YAML file. For more details, see [GEN_CONFIG.md](GEN_CONFIG.md).
129
+
121
130
  ## Contributing
122
131
 
123
132
  The [DEVELOPMENT.md](DEVELOPMENT.md) has more information about getting setup as a developer.
@@ -39,6 +39,10 @@ Found Pet is used by 3 operations:
39
39
  (.env) %
40
40
  ```
41
41
 
42
+ ## Layout
43
+
44
+ The CLI and API generation allow users to specify a layout file to reduce assumptions. More information about the layout generation, format and schema are covered in [LAYOUT.md](LAYOUT.md).
45
+
42
46
  ## CLI Generation
43
47
 
44
48
  The `cli-gen` tool allows users to create a user-friendly CLI using the OpenAPI spec and a layout file. The layout file provides the CLI structure and refers to the OpenAPI spec for details of operations. [LAYOUT.md](LAYOUT.md) has more details about the layout file, and the [CLI_GEN.md](CLI_GEN.md) has more info about CLI generation.
@@ -78,10 +82,15 @@ Into code that produces a CLI that has commands like:
78
82
 
79
83
  See the examples in `examples/` for some more complete works.
80
84
 
85
+ The CLI generator can be configured using a YAML file. For more details, see [GEN_CONFIG.md](GEN_CONFIG.md).
86
+
87
+
81
88
  ## API Generation
82
89
 
83
90
  The `api-gen` tool allows users to generate API code using the OpenAPI spec. The generated Python code provides type hints and helpful comments, but does no real checking of the arguments and/or return values. The return values are typically dictionaries instead of a data class, such as the models provided in the standard OpenAPI generator.
84
91
 
92
+ The API generator can be configured using a YAML file. For more details, see [GEN_CONFIG.md](GEN_CONFIG.md).
93
+
85
94
  ## Contributing
86
95
 
87
96
  The [DEVELOPMENT.md](DEVELOPMENT.md) has more information about getting setup as a developer.
@@ -0,0 +1,5 @@
1
+ """API generation code."""
2
+ from .api_generator import ApiGenerator
3
+ from .flat_generator import FlatApiGenerator
4
+ from .opaque_generator import OpaqueApiGenerator
5
+ from .property_generator import PropertyApiGenerator
@@ -0,0 +1,35 @@
1
+ import os
2
+
3
+
4
+ def env_string(varnames: str | list[str], default: str | None = None, except_missing: bool = False) -> str | None:
5
+ """Get string value from environment.
6
+
7
+ When no value is found, return the default or throw a ValueError (if except_missing is True).
8
+ """
9
+ varnames = [varnames] if isinstance(varnames, str) else varnames
10
+
11
+ for varname in varnames:
12
+ value = os.environ.get(varname)
13
+ if value is not None:
14
+ return value
15
+
16
+ if except_missing:
17
+ raise ValueError(f"Missing {', '.join(varnames)} value(s)")
18
+ return default
19
+
20
+
21
+ def env_int(varnames: str | list[str], default: int | None = None, except_missing: bool = False) -> int | None:
22
+ """Get integer value from environment.
23
+
24
+ When no value is found, return the default or throw a ValueError (if except_missing is True).
25
+ """
26
+ varnames = [varnames] if isinstance(varnames, str) else varnames
27
+
28
+ for varname in varnames:
29
+ value = os.environ.get(varname)
30
+ if value is not None:
31
+ return int(value)
32
+
33
+ if except_missing:
34
+ raise ValueError(f"Missing {', '.join(varnames)} value(s)")
35
+ return default
@@ -1,27 +1,26 @@
1
1
  """Declares the abstract ApiGenerator base class that is the basis for API generation.
2
2
 
3
- This functionality that is useful for all API generators, and forces addition of function_definition()
4
- for various. The abstract function allows the files.py to maintain the same interface.
3
+ Shared API generation behavior lives here. Subclasses implement function_definition(), which
4
+ generate_files() uses when writing modules.
5
5
  """
6
+ import os
6
7
  from abc import ABC
7
8
  from abc import abstractmethod
9
+ from pathlib import Path
8
10
  from typing import Any
9
11
 
10
- from openapi_spec_tools.base_gen.base_generator import BaseGenerator
11
- from openapi_spec_tools.base_gen.constants import COLLECTIONS
12
- from openapi_spec_tools.base_gen.constants import SEP1
13
- from openapi_spec_tools.base_gen.utils import maybe_quoted
14
- from openapi_spec_tools.base_gen.utils import quoted
15
- from openapi_spec_tools.base_gen.utils import simple_escape
16
- from openapi_spec_tools.layout.types import LayoutNode
12
+ from openapi_spec_tools.base_gen import COLLECTIONS
13
+ from openapi_spec_tools.base_gen import SEP1
14
+ from openapi_spec_tools.base_gen import BaseGenerator
15
+ from openapi_spec_tools.base_gen import maybe_quoted
16
+ from openapi_spec_tools.base_gen import quoted
17
+ from openapi_spec_tools.base_gen import simple_escape
18
+ from openapi_spec_tools.base_gen import to_snake_case
19
+ from openapi_spec_tools.layout import LayoutNode
17
20
  from openapi_spec_tools.types import OasField
18
21
 
19
- DEFAULT_VAR_HOST = "API_HOST"
20
- DEFAULT_VAR_KEY = "API_KEY"
21
- DEFAULT_VAR_TIMEOUT = "API_TIMEOUT"
22
22
  DEFAULT_VAR_LOG_LEVEL = "API_LOG_LEVEL"
23
23
  DEFAULT_VALUE_LOG_LEVEL = "info"
24
- DEFAULT_VALUE_TIMEOUT = 5
25
24
 
26
25
 
27
26
  class ApiGenerator(BaseGenerator, ABC):
@@ -34,25 +33,31 @@ class ApiGenerator(BaseGenerator, ABC):
34
33
 
35
34
  def __init__(
36
35
  self,
37
- package_name: str,
38
- oas: dict[str, Any],
39
- env_host: str = DEFAULT_VAR_HOST,
40
- env_key: str = DEFAULT_VAR_KEY,
41
- env_timeout: str = DEFAULT_VAR_TIMEOUT,
42
- env_log_level: str = DEFAULT_VAR_LOG_LEVEL,
36
+ *args,
37
+ env_log_level: str | list[str] = DEFAULT_VAR_LOG_LEVEL,
43
38
  default_log_level: str = DEFAULT_VALUE_LOG_LEVEL,
44
- default_timeout: int = DEFAULT_VALUE_TIMEOUT,
45
39
  **kwargs,
46
40
  ):
47
41
  """Initialize with the OpenAPI spec and other data for generating multiple modules."""
48
- super().__init__(oas, **kwargs)
49
- self.package_name = package_name
50
- self.env_host = env_host
51
- self.env_key = env_key
52
- self.env_timeout = env_timeout
53
- self.env_log_level = env_log_level
54
- self.default_log = default_log_level
55
- self.default_timeout = default_timeout
42
+ super().__init__(*args, env_log_level=env_log_level, default_log_level=default_log_level, **kwargs)
43
+
44
+ def default_infra_files(self) -> dict[Path, str]:
45
+ """Default files to copy from source."""
46
+ api_gen = Path(__file__).parent
47
+ base_gen = Path(__file__).parent.parent / "base_gen"
48
+ return {
49
+ base_gen / "_logging.py": "_logging.py",
50
+ base_gen / "_requests.py": "_requests.py",
51
+ api_gen / "_environment.py": "_environment.py",
52
+ }
53
+
54
+ def default_infra_replacements(self) -> dict[str, str]:
55
+ """Default infrastructure line replacements."""
56
+ return {
57
+ "openapi_spec_tools.api_gen": self.package_name,
58
+ "openapi_spec_tools.base_gen": self.package_name,
59
+ __package__: self.package_name,
60
+ }
56
61
 
57
62
  def property_help(self, prop: dict[str, Any]) -> str:
58
63
  """Get the short help string for the specified property."""
@@ -104,12 +109,12 @@ from {self.package_name} import _requests as _r # noqa: F401
104
109
  def init_infra_args(self, operation: dict[str, Any]) -> str:
105
110
  """Provide initialization of standard arguments inside body."""
106
111
  host_default = (
107
- f'_e.env_string({quoted(self.env_host)}, '
112
+ f'_e.env_string({maybe_quoted(self.env_host)}, '
108
113
  f'default={quoted(self.default_host)}, except_missing=True)'
109
114
  )
110
- key_default = f'_e.env_string({quoted(self.env_key)}, except_missing=True)'
111
- timeout_default = f'_e.env_int({quoted(self.env_timeout)}, default={self.default_timeout})'
112
- log_default = f'_e.env_string({quoted(self.env_log_level)}, default={quoted(self.default_log)})'
115
+ key_default = f'_e.env_string({maybe_quoted(self.env_key)}, except_missing=True)'
116
+ timeout_default = f'_e.env_int({maybe_quoted(self.env_timeout)}, default={self.default_timeout})'
117
+ log_default = f'_e.env_string({maybe_quoted(self.env_log_level)}, default={quoted(self.default_log)})'
113
118
  lines = [
114
119
  f'_api_host = _api_host or {host_default}',
115
120
  f'_api_key = _api_key or {key_default}',
@@ -191,3 +196,20 @@ from {self.package_name} import _requests as _r # noqa: F401
191
196
  def function_definition(self, command: LayoutNode) -> str:
192
197
  """Provide function definition for specified command."""
193
198
  pass # pragma: no cover
199
+
200
+ def generate_files(self, node: LayoutNode, directory: str) -> None:
201
+ """Create a module for the current node, and recursively generate sub-commands."""
202
+ if node.operations():
203
+ module_name = to_snake_case(node.identifier)
204
+ self.logger.info(f"Generating {module_name} module")
205
+ text = self.copyright
206
+ text += self.standard_imports()
207
+ for command in node.operations():
208
+ text += self.function_definition(command)
209
+
210
+ filename = os.path.join(directory, module_name + ".py")
211
+ with open(filename, "w", encoding="utf-8", newline="\n") as fp:
212
+ fp.write(text)
213
+
214
+ for command in node.subcommands():
215
+ self.generate_files(command, directory)
@@ -4,10 +4,10 @@ The bodies are "unrolled" to individual parameters (as best as possible), and pa
4
4
  parameters into the functions.
5
5
  """
6
6
  from openapi_spec_tools.api_gen.api_generator import ApiGenerator
7
- from openapi_spec_tools.base_gen.constants import NL
8
- from openapi_spec_tools.base_gen.constants import SEP1
9
- from openapi_spec_tools.base_gen.utils import quoted
10
- from openapi_spec_tools.layout.types import LayoutNode
7
+ from openapi_spec_tools.base_gen import NL
8
+ from openapi_spec_tools.base_gen import SEP1
9
+ from openapi_spec_tools.base_gen import quoted
10
+ from openapi_spec_tools.layout import LayoutNode
11
11
  from openapi_spec_tools.types import OasField
12
12
 
13
13
 
@@ -2,10 +2,10 @@
2
2
  from typing import Any
3
3
 
4
4
  from openapi_spec_tools.api_gen.api_generator import ApiGenerator
5
- from openapi_spec_tools.base_gen.constants import NL
6
- from openapi_spec_tools.base_gen.constants import SEP1
7
- from openapi_spec_tools.base_gen.utils import quoted
8
- from openapi_spec_tools.layout.types import LayoutNode
5
+ from openapi_spec_tools.base_gen import NL
6
+ from openapi_spec_tools.base_gen import SEP1
7
+ from openapi_spec_tools.base_gen import quoted
8
+ from openapi_spec_tools.layout import LayoutNode
9
9
  from openapi_spec_tools.types import OasField
10
10
 
11
11
 
@@ -3,11 +3,11 @@ from copy import deepcopy
3
3
  from typing import Any
4
4
 
5
5
  from openapi_spec_tools.api_gen.api_generator import ApiGenerator
6
- from openapi_spec_tools.base_gen.constants import NL
7
- from openapi_spec_tools.base_gen.constants import SEP1
8
- from openapi_spec_tools.base_gen.utils import quoted
9
- from openapi_spec_tools.base_gen.utils import shallow
10
- from openapi_spec_tools.layout.types import LayoutNode
6
+ from openapi_spec_tools.base_gen import NL
7
+ from openapi_spec_tools.base_gen import SEP1
8
+ from openapi_spec_tools.base_gen import quoted
9
+ from openapi_spec_tools.base_gen import shallow
10
+ from openapi_spec_tools.layout import LayoutNode
11
11
  from openapi_spec_tools.types import OasField
12
12
 
13
13
 
@@ -0,0 +1,17 @@
1
+ """Base generator which is the base class for API and CLI generoators."""
2
+ from .base_generator import BaseGenerator
3
+ from .config import GeneratorConfig
4
+ from .constants import COLLECTIONS
5
+ from .constants import NL
6
+ from .constants import SEP1
7
+ from .constants import SEP2
8
+ from .utils import is_case_sensitive
9
+ from .utils import maybe_quoted
10
+ from .utils import prepend
11
+ from .utils import quoted
12
+ from .utils import replace_special
13
+ from .utils import set_missing
14
+ from .utils import shallow
15
+ from .utils import simple_escape
16
+ from .utils import to_camel_case
17
+ from .utils import to_snake_case
@@ -8,6 +8,7 @@ import json
8
8
  from copy import deepcopy
9
9
  from datetime import datetime
10
10
  from datetime import timedelta
11
+ from datetime import timezone
11
12
  from typing import Any
12
13
 
13
14
  import requests
@@ -168,9 +169,9 @@ def request(
168
169
  params = params or {}
169
170
  pretty_url = url + _pretty_params(params)
170
171
  logger.debug(f"Requesting {method} {pretty_url}")
171
- start = datetime.now()
172
+ start = datetime.now(tz=timezone.utc)
172
173
  response = requests.request(method, url, params=params, headers=headers, json=body, timeout=timeout, **kwargs)
173
- delta = datetime.now() - start
174
+ delta = datetime.now(tz=timezone.utc) - start
174
175
  logger.info(f"Got {response.status_code} response from {method} {pretty_url} in {delta.total_seconds()}")
175
176
 
176
177
  raise_for_error(response)
@@ -256,9 +257,9 @@ def depaginate(
256
257
  pretty_url = _url + _pretty_params(_params)
257
258
 
258
259
  logger.debug(f"Requesting {GET} {pretty_url} count={page_count + 1}")
259
- start = datetime.now()
260
+ start = datetime.now(tz=timezone.utc)
260
261
  response = requests.get(_url, params=deepcopy(_params), headers=_headers, timeout=timeout)
261
- delta = datetime.now() - start
262
+ delta = datetime.now(tz=timezone.utc) - start
262
263
 
263
264
  raise_for_error(response)
264
265
 
@@ -2,13 +2,27 @@
2
2
  import logging
3
3
  import textwrap
4
4
  from copy import deepcopy
5
+ from pathlib import Path
5
6
  from typing import Any
6
7
 
7
8
  from openapi_spec_tools.base_gen._logging import init_logging
9
+ from openapi_spec_tools.base_gen.config import GeneratorConfig
8
10
  from openapi_spec_tools.base_gen.constants import COLLECTIONS
11
+ from openapi_spec_tools.base_gen.constants import DEFAULT_CONFLICT_SUFFIX
12
+ from openapi_spec_tools.base_gen.constants import DEFAULT_COPYRIGHT
13
+ from openapi_spec_tools.base_gen.constants import DEFAULT_MAX_HELP_LENGTH
14
+ from openapi_spec_tools.base_gen.constants import DEFAULT_RESERVED
15
+ from openapi_spec_tools.base_gen.constants import DEFAULT_SUPPORTED_CONTENT
16
+ from openapi_spec_tools.base_gen.constants import DEFAULT_VALUE_LOG_LEVEL
17
+ from openapi_spec_tools.base_gen.constants import DEFAULT_VALUE_TIMEOUT
18
+ from openapi_spec_tools.base_gen.constants import DEFAULT_VAR_HOST
19
+ from openapi_spec_tools.base_gen.constants import DEFAULT_VAR_KEY
20
+ from openapi_spec_tools.base_gen.constants import DEFAULT_VAR_LOG_LEVEL
21
+ from openapi_spec_tools.base_gen.constants import DEFAULT_VAR_TIMEOUT
9
22
  from openapi_spec_tools.base_gen.constants import NL
10
23
  from openapi_spec_tools.base_gen.constants import SEP1
11
24
  from openapi_spec_tools.base_gen.constants import SEP2
25
+ from openapi_spec_tools.base_gen.files import copy_and_update
12
26
  from openapi_spec_tools.base_gen.utils import maybe_quoted
13
27
  from openapi_spec_tools.base_gen.utils import prepend
14
28
  from openapi_spec_tools.base_gen.utils import quoted
@@ -21,43 +35,10 @@ from openapi_spec_tools.base_gen.utils import to_snake_case
21
35
  from openapi_spec_tools.types import ContentType
22
36
  from openapi_spec_tools.types import OasField
23
37
  from openapi_spec_tools.utils import NULL_TYPES
38
+ from openapi_spec_tools.utils import _or
24
39
  from openapi_spec_tools.utils import map_operations
25
40
 
26
41
  LOG_CLASS = "base-gen"
27
- DEFAULT_SUPPORTED_CONTENT = [
28
- ContentType.APP_JSON,
29
- ]
30
- DEFAULT_MAX_HELP_LENGTH = 120
31
- DEFAULT_CONFLICT_SUFFIX = "_"
32
-
33
- # This is an incomplete list of Python builtins and imports that should avoided in variable names
34
- DEFAULT_RESERVED = {
35
- "all",
36
- "any",
37
- "bool",
38
- "breakpoint",
39
- "class",
40
- "continue",
41
- "date",
42
- "datetime",
43
- "dict",
44
- "except",
45
- "float",
46
- "for",
47
- "format",
48
- "in",
49
- "input",
50
- "int",
51
- "list",
52
- "max",
53
- "min",
54
- "print",
55
- "set",
56
- "try",
57
- "type",
58
- "typer",
59
- "while",
60
- }
61
42
 
62
43
 
63
44
  class BaseGenerator:
@@ -72,25 +53,110 @@ class BaseGenerator:
72
53
  self,
73
54
  oas: dict[str, Any],
74
55
  logger: logging.Logger | None = None,
75
- supported_content: list[ContentType] = DEFAULT_SUPPORTED_CONTENT,
76
- max_help_length: int = DEFAULT_MAX_HELP_LENGTH,
77
- reserved: set[str] = DEFAULT_RESERVED,
78
- conflict_suffix: str = DEFAULT_CONFLICT_SUFFIX,
56
+ config: GeneratorConfig | None = None,
57
+ package_name: str | None = None,
58
+ supported_content: list[ContentType] | None = None,
59
+ max_help_length: int | None = None,
60
+ reserved: set[str] | None = None,
61
+ conflict_suffix: str | None = None,
62
+ copyright: str | Path | None = None,
63
+ infra_files: dict[Path, str] | None = None,
64
+ infra_replacements: dict[str, str] | None = None,
65
+ test_files: dict[Path, str] | None = None,
66
+ test_replacements: dict[str, str] | None = None,
67
+ env_host: str | list[str] | None = None,
68
+ env_key: str | list[str] | None = None,
69
+ env_timeout: str | list[str] | None = None,
70
+ env_log_level: str | list[str] | None = None,
71
+ default_host: str | None = None,
72
+ default_log_level: str | None = None,
73
+ default_timeout: int | None = None,
79
74
  ):
80
- """Initialize with the OpenAPI spec and other data for generating multiple modules."""
75
+ """Initialize with the OpenAPI spec and other data for generating multiple modules.
76
+
77
+ When copyright names an existing file, that file's contents are stored as copyright.
78
+ Otherwise the provided value is used as the copyright text. The default header is used
79
+ when copyright is omitted.
80
+
81
+ When the default_host is not provided, attempts to read from the OAS servers.
82
+
83
+ Default values are as follows (see openapi_spec_tools.base_gen.constants for values):
84
+ * package_name - no default, required
85
+ * supported_content - DEFAULT_SUPPORTED_CONTENT
86
+ * max_help_length - DEFAULT_MAX_HELP_LENGTH
87
+ * reserved - DEFAULT_RESERVED
88
+ * conflict_suffix - DEFAULT_CONFLICT_SUFFIX
89
+ * copyright - DEFAULT_COPYRIGHT
90
+ * infra_<files|replacements> - None, likely specified by derived class methods
91
+ * test_<files|replacements> - None, likely specified by derived class methods
92
+ * env_host - DEFAULT_VAR_HOST
93
+ * env_key - DEFAULT_VAR_KEY
94
+ * env_timeout - DEFAULT_VAR_TIMEOUT
95
+ * env_log_level - DEFAULT_VAR_LOG_LEVEL
96
+ * default_host - empty string
97
+ * default_log_level - DEFAULT_VALUE_LOG_LEVEL
98
+ * default_timeout - DEFAULT_VALUE_TIMEOUT
99
+ """
100
+ config = config or GeneratorConfig() # reduce logic by creating a default (if no config provided)
81
101
  self.operations = map_operations(oas.get(OasField.PATHS, {}))
82
102
  self.components = oas.get(OasField.COMPONENTS, {})
83
- self.default_host = ""
84
- servers = oas.get(OasField.SERVERS)
85
- if servers:
86
- self.default_host = servers[0].get(OasField.URL, "")
87
- # ordered list of supported types
88
- self.supported = supported_content
89
- self.max_help_length = max_help_length
90
103
  self.logger = logger or init_logging("INFO", LOG_CLASS)
91
104
 
92
- self.reserved = reserved
93
- self.conflict_suffix = conflict_suffix
105
+ self.package_name = _or(package_name, config.package_name, ValueError("Missing package_name"))
106
+ self.default_host = _or(default_host, config.default_host, "")
107
+ self.supported = _or(supported_content, config.supported_content, DEFAULT_SUPPORTED_CONTENT)
108
+ self.max_help_length = _or(max_help_length, config.max_help_length, DEFAULT_MAX_HELP_LENGTH)
109
+ self.reserved = _or(reserved, config.reserved, DEFAULT_RESERVED)
110
+ self.conflict_suffix = _or(conflict_suffix, config.conflict_suffix, DEFAULT_CONFLICT_SUFFIX)
111
+ self.copyright = self._resolve_copyright(_or(copyright, config.copyright))
112
+ self.infra_files = _or(infra_files, config.resolve_path_keys(config.infra_files))
113
+ self.infra_replacements = _or(infra_replacements, config.infra_replacements)
114
+ self.test_files = _or(test_files, config.resolve_path_keys(config.test_files))
115
+ self.test_replacements = _or(test_replacements, config.test_replacements)
116
+ self.env_host = _or(env_host, config.env_host, DEFAULT_VAR_HOST)
117
+ self.env_key = _or(env_key, config.env_key, DEFAULT_VAR_KEY)
118
+ self.env_timeout = _or(env_timeout, config.env_timeout, DEFAULT_VAR_TIMEOUT)
119
+ self.env_log_level = _or(env_log_level, config.env_log_level, DEFAULT_VAR_LOG_LEVEL)
120
+ self.default_log = _or(default_log_level, config.default_log_level, DEFAULT_VALUE_LOG_LEVEL)
121
+ self.default_timeout = _or(default_timeout, config.default_timeout, DEFAULT_VALUE_TIMEOUT)
122
+
123
+ if not self.default_host:
124
+ servers = oas.get(OasField.SERVERS)
125
+ if servers:
126
+ self.default_host = servers[0].get(OasField.URL, "")
127
+
128
+
129
+ @staticmethod
130
+ def _resolve_copyright(copyright: str | Path | None) -> str:
131
+ """Load copyright header text from a file, or use the provided text."""
132
+ if copyright is None:
133
+ return DEFAULT_COPYRIGHT
134
+
135
+ text = copyright if isinstance(copyright, str) else DEFAULT_COPYRIGHT
136
+ try:
137
+ path = Path(copyright)
138
+ if path.is_file():
139
+ return path.read_text(encoding="utf-8")
140
+ except (TypeError, ValueError, OSError):
141
+ pass
142
+
143
+ return text
144
+
145
+ def default_infra_files(self) -> dict[Path, str]:
146
+ """Default map of infrastructure files to copy."""
147
+ return {}
148
+
149
+ def default_infra_replacements(self) -> dict[str, str]:
150
+ """Default map of infrastructure file line replacements."""
151
+ return {}
152
+
153
+ def default_test_files(self) -> dict[Path, str]:
154
+ """Default map of test files to copy."""
155
+ return {}
156
+
157
+ def default_test_replacements(self) -> dict[str, str]:
158
+ """Default map of test file line replacements."""
159
+ return {}
94
160
 
95
161
  def class_name(self, s: str) -> str:
96
162
  """Get the class name for provided string."""
@@ -564,9 +630,11 @@ class BaseGenerator:
564
630
  else:
565
631
  oas_type = self.simplify_type(prop_data.get(OasField.TYPE))
566
632
  if oas_type == "object":
567
- add_prop_type = prop_data.get(OasField.ADDITIONAL_PROPS, {}).get(OasField.TYPE)
568
- if add_prop_type:
569
- prop_data.update({OasField.TYPE.value: add_prop_type})
633
+ add_props = prop_data.get(OasField.ADDITIONAL_PROPS)
634
+ if isinstance(add_props, dict):
635
+ add_prop_type = add_props.get(OasField.TYPE)
636
+ if add_prop_type:
637
+ prop_data.update({OasField.TYPE.value: add_prop_type})
570
638
 
571
639
  pytype = self.schema_to_pytype(prop_data)
572
640
  if not pytype:
@@ -946,3 +1014,44 @@ class BaseGenerator:
946
1014
 
947
1015
  return NL + NL.join(declarations)
948
1016
 
1017
+ def copy_infrastructure_files(self, dst_dir: str) -> None:
1018
+ """Iterate over the infra_files and copy from local to dst."""
1019
+ dpath = Path(dst_dir)
1020
+ files = (
1021
+ self.infra_files
1022
+ if self.infra_files is not None
1023
+ else self.default_infra_files()
1024
+ )
1025
+ replacements = (
1026
+ self.infra_replacements
1027
+ if self.infra_replacements is not None
1028
+ else self.default_infra_replacements()
1029
+ )
1030
+ for src, dst in files.items():
1031
+ dfile = dpath / dst
1032
+ copy_and_update(src.as_posix(), dfile.as_posix(), replacements, self.copyright)
1033
+
1034
+ def copy_test_files(self, dst_dir: str) -> None:
1035
+ """Iterate over the test_files and copy from local to dst."""
1036
+ dpath = Path(dst_dir)
1037
+ files = (
1038
+ self.test_files
1039
+ if self.test_files is not None
1040
+ else self.default_test_files()
1041
+ )
1042
+ replacements = (
1043
+ self.test_replacements
1044
+ if self.test_replacements is not None
1045
+ else self.default_test_replacements()
1046
+ )
1047
+ for src, dst in files.items():
1048
+ dfile = dpath / dst
1049
+ copy_and_update(src.as_posix(), dfile.as_posix(), replacements, self.copyright)
1050
+
1051
+ def add_init_file(self, dst_dir: str, content: str = "", overwrite: bool = False) -> None:
1052
+ """Add __init__.py according to parameters."""
1053
+ dfile = Path(dst_dir) / "__init__.py"
1054
+ if not overwrite and dfile.exists():
1055
+ return
1056
+
1057
+ dfile.write_text(content, encoding="utf-8", newline="\n")
@@ -0,0 +1,63 @@
1
+ """Configuration data used to construct a base generator."""
2
+ from __future__ import annotations
3
+
4
+ from pathlib import Path
5
+
6
+ import yaml
7
+ from pydantic import BaseModel
8
+
9
+ from openapi_spec_tools.types import ContentType
10
+
11
+
12
+ class GeneratorConfig(BaseModel):
13
+ """Data elements accepted by the BaseGenerator initializer.
14
+
15
+ Most of the data elements intentionally default to None -- this is done
16
+ to allow for determining which items are set vs just using default values.
17
+ """
18
+
19
+ package_name: str | None = None
20
+ supported_content: list[ContentType] | None = None
21
+ max_help_length: int | None = None
22
+ reserved: set[str] | None = None
23
+ conflict_suffix: str | None = None
24
+ copyright: str | None = None
25
+ infra_files: dict[str, str] | None = None
26
+ infra_replacements: dict[str, str] | None = None
27
+ test_files: dict[str, str] | None = None
28
+ test_replacements: dict[str, str] | None = None
29
+ env_host: str | list[str] | None = None
30
+ env_key: str | list[str] | None = None
31
+ env_timeout: str | list[str] | None = None
32
+ env_log_level: str | list[str] | None = None
33
+ default_host: str | None = None
34
+ default_log_level: str | None = None
35
+ default_timeout: int | None = None
36
+
37
+ @classmethod
38
+ def from_yaml(cls, filename: str | Path) -> GeneratorConfig:
39
+ """Read configuration properties from a YAML file."""
40
+ path = Path(filename)
41
+ if not path.exists():
42
+ raise FileNotFoundError(filename)
43
+
44
+ with open(path, encoding="utf-8", newline="\n") as fp:
45
+ data = yaml.safe_load(fp)
46
+
47
+ return cls.model_validate(data or {})
48
+
49
+ @staticmethod
50
+ def resolve_path_keys(original: dict[str, str] | None) -> dict[Path, str]:
51
+ """Resolve the key string to a Path."""
52
+ if not original:
53
+ return original
54
+
55
+ result: dict[Path, str] = {}
56
+ base_dir = Path(__file__).parent.parent
57
+ base_name = base_dir.name + "/"
58
+ for key, value in original.items():
59
+ updated_key = base_dir / key.split(base_name)[1] if base_name in key else Path(key)
60
+ # TODO: warn if updated key does not exist?
61
+ result[updated_key] = value
62
+
63
+ return result