openapi-spec-tools 0.23.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.
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/PKG-INFO +1 -1
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/base_gen/_requests.py +21 -8
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/base_gen/base_generator.py +3 -4
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/base_gen/constants.py +0 -5
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli/analyze.py +2 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli/cli_gen.py +3 -6
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli/oas.py +4 -2
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli/paths.py +1 -2
- openapi_spec_tools-0.24.0/openapi_spec_tools/cli/properties.py +159 -0
- openapi_spec_tools-0.24.0/openapi_spec_tools/cli/references.py +244 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli_gen/_display.py +7 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/constants.py +7 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/layout/config.py +4 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/layout/layout_generator.py +78 -10
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/layout/types.py +1 -1
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/layout/utils.py +1 -2
- openapi_spec_tools-0.24.0/openapi_spec_tools/properties.py +147 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/types.py +1 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/utils.py +47 -2
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/pyproject.toml +3 -1
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/tests/cli_gen/test_display.py +6 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/.gitignore +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/LICENSE +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/README.md +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/__init__.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/api_gen/__init__.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/api_gen/_environment.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/api_gen/api_generator.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/api_gen/flat_generator.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/api_gen/opaque_generator.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/api_gen/property_generator.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/base_gen/__init__.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/base_gen/_constants.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/base_gen/_logging.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/base_gen/config.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/base_gen/exceptions.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/base_gen/files.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/base_gen/utils.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli/__init__.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli/api_gen.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli/arguments.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli/constants.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli/content.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli/history.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli/layout.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli/models.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli/operations.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli/tags.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli/utils.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli_gen/__init__.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli_gen/_arguments.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli_gen/_exceptions.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli_gen/_tree.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli_gen/cli_generator.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli_gen/files.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/expand.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/flatten.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/layout/__init__.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/layout/merge.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/tests/cli_gen/__init__.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/tests/cli_gen/test_cli_generator.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/tests/cli_gen/test_exceptions.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/tests/cli_gen/test_files.py +0 -0
- {openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/tests/cli_gen/test_main.py +0 -0
- {openapi_spec_tools-0.23.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.
|
|
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
|
{openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/base_gen/_requests.py
RENAMED
|
@@ -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
|
|
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
|
|
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
|
|
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
|
|
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
|
-
|
|
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
|
|
277
|
-
_url =
|
|
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
|
|
@@ -11,7 +11,6 @@ from openapi_spec_tools.base_gen.constants import DEFAULT_CONFLICT_SUFFIX
|
|
|
11
11
|
from openapi_spec_tools.base_gen.constants import DEFAULT_COPYRIGHT
|
|
12
12
|
from openapi_spec_tools.base_gen.constants import DEFAULT_MAX_HELP_LENGTH
|
|
13
13
|
from openapi_spec_tools.base_gen.constants import DEFAULT_RESERVED
|
|
14
|
-
from openapi_spec_tools.base_gen.constants import DEFAULT_SUPPORTED_CONTENT
|
|
15
14
|
from openapi_spec_tools.base_gen.constants import DEFAULT_VALUE_LOG_LEVEL
|
|
16
15
|
from openapi_spec_tools.base_gen.constants import DEFAULT_VALUE_TIMEOUT
|
|
17
16
|
from openapi_spec_tools.base_gen.constants import DEFAULT_VAR_HOST
|
|
@@ -29,6 +28,7 @@ from openapi_spec_tools.base_gen.utils import replace_special
|
|
|
29
28
|
from openapi_spec_tools.base_gen.utils import simple_escape
|
|
30
29
|
from openapi_spec_tools.base_gen.utils import to_camel_case
|
|
31
30
|
from openapi_spec_tools.base_gen.utils import to_snake_case
|
|
31
|
+
from openapi_spec_tools.constants import DEFAULT_SUPPORTED_CONTENT
|
|
32
32
|
from openapi_spec_tools.constants import NULL_TYPES
|
|
33
33
|
from openapi_spec_tools.expand import expand_schema
|
|
34
34
|
from openapi_spec_tools.flatten import flatten_schema
|
|
@@ -84,7 +84,7 @@ class BaseGenerator:
|
|
|
84
84
|
|
|
85
85
|
Default values are as follows (see openapi_spec_tools.base_gen.constants for values):
|
|
86
86
|
* package_name - no default, required
|
|
87
|
-
* supported_content - DEFAULT_SUPPORTED_CONTENT
|
|
87
|
+
* supported_content - DEFAULT_SUPPORTED_CONTENT in openapi_spec_tools.constants
|
|
88
88
|
* max_help_length - DEFAULT_MAX_HELP_LENGTH
|
|
89
89
|
* reserved - DEFAULT_RESERVED
|
|
90
90
|
* conflict_suffix - DEFAULT_CONFLICT_SUFFIX
|
|
@@ -602,10 +602,9 @@ class BaseGenerator:
|
|
|
602
602
|
for parents in lineage:
|
|
603
603
|
prev = "body"
|
|
604
604
|
for curr in parents:
|
|
605
|
-
items = depends.
|
|
605
|
+
items = depends.setdefault(prev, [])
|
|
606
606
|
if curr not in items:
|
|
607
607
|
items.append(curr)
|
|
608
|
-
depends[prev] = items
|
|
609
608
|
prev = curr
|
|
610
609
|
|
|
611
610
|
while depends:
|
{openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/base_gen/constants.py
RENAMED
|
@@ -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"
|
|
@@ -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")
|
|
@@ -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
|
|
@@ -44,6 +43,7 @@ from openapi_spec_tools.utils import remove_property
|
|
|
44
43
|
from openapi_spec_tools.utils import remove_schema_tags
|
|
45
44
|
from openapi_spec_tools.utils import schema_operations_filter
|
|
46
45
|
from openapi_spec_tools.utils import set_nullable_not_required
|
|
46
|
+
from openapi_spec_tools.utils import write_oas
|
|
47
47
|
|
|
48
48
|
#################################################
|
|
49
49
|
# Utilities
|
|
@@ -191,9 +191,7 @@ def generate_unreferenced(
|
|
|
191
191
|
parts = path.split("/")
|
|
192
192
|
path = "/".join([p for p in parts if p and '{' not in p])
|
|
193
193
|
|
|
194
|
-
|
|
195
|
-
operations.append(op)
|
|
196
|
-
paths[path] = operations
|
|
194
|
+
paths.setdefault(path, []).append(op)
|
|
197
195
|
|
|
198
196
|
# display each operations below the path
|
|
199
197
|
for path, ops in paths.items():
|
|
@@ -361,8 +359,7 @@ def trim_oas(
|
|
|
361
359
|
updated = set_nullable_not_required(updated)
|
|
362
360
|
|
|
363
361
|
out_file = updated_file or openapi_file
|
|
364
|
-
|
|
365
|
-
yaml.dump(updated, fp, indent=indent, sort_keys=True)
|
|
362
|
+
write_oas(out_file, updated, indent=indent)
|
|
366
363
|
|
|
367
364
|
typer.echo(f"Wrote to {out_file}")
|
|
368
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
|
-
|
|
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
|
-
|
|
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}")
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Implement the 'oas analyze properties' CLI commands."""
|
|
3
|
+
from copy import deepcopy
|
|
4
|
+
from enum import Enum
|
|
5
|
+
from typing import Annotated
|
|
6
|
+
from typing import Any
|
|
7
|
+
from typing import Callable
|
|
8
|
+
|
|
9
|
+
import typer
|
|
10
|
+
from rich_objects import console_factory
|
|
11
|
+
|
|
12
|
+
from openapi_spec_tools.cli.arguments import ExpansionOption
|
|
13
|
+
from openapi_spec_tools.cli.arguments import ExpansionType
|
|
14
|
+
from openapi_spec_tools.cli.arguments import LogLevelOption
|
|
15
|
+
from openapi_spec_tools.cli.arguments import OpenApiFilenameArgument
|
|
16
|
+
from openapi_spec_tools.cli.constants import INDENT
|
|
17
|
+
from openapi_spec_tools.cli.utils import init_logging
|
|
18
|
+
from openapi_spec_tools.cli.utils import open_oas_with_error_handling
|
|
19
|
+
from openapi_spec_tools.cli.utils import perform_expansion
|
|
20
|
+
from openapi_spec_tools.properties import map_model_properties
|
|
21
|
+
from openapi_spec_tools.properties import map_parameter_properties
|
|
22
|
+
from openapi_spec_tools.properties import map_request_properties
|
|
23
|
+
from openapi_spec_tools.properties import map_response_properties
|
|
24
|
+
from openapi_spec_tools.types import OasField
|
|
25
|
+
|
|
26
|
+
app = typer.Typer(no_args_is_help=True, short_help="Inspect things related to properties")
|
|
27
|
+
|
|
28
|
+
PropertyMap = Callable[[dict[str, Any]], dict[str, set[str]]]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class PropertySource(str, Enum):
|
|
32
|
+
"""Kind of property to list."""
|
|
33
|
+
|
|
34
|
+
ALL = "all"
|
|
35
|
+
COMPONENTS = "components"
|
|
36
|
+
REQUESTS = "requests"
|
|
37
|
+
RESPONSES = "responses"
|
|
38
|
+
PARAMETERS = "parameters"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
_PROPERTY_MAPS: dict[PropertySource, PropertyMap] = {
|
|
42
|
+
PropertySource.COMPONENTS: map_model_properties,
|
|
43
|
+
PropertySource.REQUESTS: map_request_properties,
|
|
44
|
+
PropertySource.RESPONSES: map_response_properties,
|
|
45
|
+
PropertySource.PARAMETERS: map_parameter_properties,
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _expand_schema(schema: Any, expansion: ExpansionType, components: dict[str, Any], reference: str | None) -> Any:
|
|
50
|
+
"""Expand or flatten one schema object."""
|
|
51
|
+
if not isinstance(schema, dict):
|
|
52
|
+
return schema
|
|
53
|
+
return perform_expansion(expansion, schema, components, reference)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _expand_parameters(container: dict[str, Any], expansion: ExpansionType, components: dict[str, Any]) -> None:
|
|
57
|
+
"""Expand parameter schemas stored on a path item or operation."""
|
|
58
|
+
params = container.get(OasField.PARAMS)
|
|
59
|
+
if not isinstance(params, list):
|
|
60
|
+
return
|
|
61
|
+
|
|
62
|
+
expanded = []
|
|
63
|
+
for param in params:
|
|
64
|
+
expanded.append(_expand_schema(param, expansion, components, None))
|
|
65
|
+
container[OasField.PARAMS.value] = expanded
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _expand_spec(spec: dict[str, Any], expansion: ExpansionType) -> dict[str, Any]:
|
|
69
|
+
"""Return ``spec`` with component and operation schemas expanded or flattened.
|
|
70
|
+
|
|
71
|
+
References are resolved against the original components. ``none`` returns ``spec`` unchanged.
|
|
72
|
+
"""
|
|
73
|
+
if expansion == ExpansionType.NONE:
|
|
74
|
+
return spec
|
|
75
|
+
|
|
76
|
+
components = spec.get(OasField.COMPONENTS, {})
|
|
77
|
+
if not isinstance(components, dict):
|
|
78
|
+
components = {}
|
|
79
|
+
|
|
80
|
+
prepared = deepcopy(spec)
|
|
81
|
+
prepared_components = prepared.get(OasField.COMPONENTS)
|
|
82
|
+
if isinstance(prepared_components, dict):
|
|
83
|
+
for section, models in prepared_components.items():
|
|
84
|
+
if not isinstance(models, dict):
|
|
85
|
+
continue
|
|
86
|
+
for name, model in list(models.items()):
|
|
87
|
+
models[name] = _expand_schema(model, expansion, components, f"{section}/{name}")
|
|
88
|
+
|
|
89
|
+
paths = prepared.get(OasField.PATHS)
|
|
90
|
+
if isinstance(paths, dict):
|
|
91
|
+
for path_item in paths.values():
|
|
92
|
+
if not isinstance(path_item, dict):
|
|
93
|
+
continue
|
|
94
|
+
_expand_parameters(path_item, expansion, components)
|
|
95
|
+
for method, operation in list(path_item.items()):
|
|
96
|
+
if method == OasField.PARAMS or not isinstance(operation, dict):
|
|
97
|
+
continue
|
|
98
|
+
_expand_parameters(operation, expansion, components)
|
|
99
|
+
body = operation.get(OasField.REQ_BODY)
|
|
100
|
+
if isinstance(body, dict):
|
|
101
|
+
operation[OasField.REQ_BODY.value] = _expand_schema(body, expansion, components, None)
|
|
102
|
+
responses = operation.get(OasField.RESPONSES)
|
|
103
|
+
if not isinstance(responses, dict):
|
|
104
|
+
continue
|
|
105
|
+
for code, response in list(responses.items()):
|
|
106
|
+
responses[code] = _expand_schema(response, expansion, components, None)
|
|
107
|
+
return prepared
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _merge_property_maps(*prop_maps: dict[str, set[str]]) -> dict[str, set[str]]:
|
|
111
|
+
"""Combine property maps, keeping every owner for a shared property name."""
|
|
112
|
+
found: dict[str, set[str]] = {}
|
|
113
|
+
for prop_map in prop_maps:
|
|
114
|
+
for name, owners in prop_map.items():
|
|
115
|
+
found.setdefault(name, set()).update(owners)
|
|
116
|
+
return found
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@app.command(name="list", short_help="List properties in OpenAPI spec")
|
|
120
|
+
def properties_list(
|
|
121
|
+
filename: OpenApiFilenameArgument,
|
|
122
|
+
search: Annotated[
|
|
123
|
+
str | None,
|
|
124
|
+
typer.Option("--contains", help="Search for this value in the property names"),
|
|
125
|
+
] = None,
|
|
126
|
+
source: Annotated[
|
|
127
|
+
PropertySource,
|
|
128
|
+
typer.Option(
|
|
129
|
+
"--source",
|
|
130
|
+
case_sensitive=False,
|
|
131
|
+
help="Property sources to list. Models come from components, and others come from operations.",
|
|
132
|
+
),
|
|
133
|
+
] = PropertySource.ALL,
|
|
134
|
+
expansion: ExpansionOption = "none",
|
|
135
|
+
log_level: LogLevelOption = "info",
|
|
136
|
+
) -> None:
|
|
137
|
+
init_logging(log_level)
|
|
138
|
+
spec = _expand_spec(open_oas_with_error_handling(filename), expansion)
|
|
139
|
+
|
|
140
|
+
collectors = _PROPERTY_MAPS.values() if source == PropertySource.ALL else (_PROPERTY_MAPS[source],)
|
|
141
|
+
properties = _merge_property_maps(*(collector(spec) for collector in collectors))
|
|
142
|
+
names = sorted(properties)
|
|
143
|
+
if search:
|
|
144
|
+
needle = search.lower()
|
|
145
|
+
names = [_ for _ in names if needle in _.lower()]
|
|
146
|
+
|
|
147
|
+
console = console_factory()
|
|
148
|
+
match_info = f" matching '{search}'" if search else ""
|
|
149
|
+
if not names:
|
|
150
|
+
console.print(f"No properties found{match_info}")
|
|
151
|
+
return
|
|
152
|
+
|
|
153
|
+
console.print(f"Found {len(names)} properties{match_info}:")
|
|
154
|
+
for name in names:
|
|
155
|
+
console.print(f"{INDENT}{name}:")
|
|
156
|
+
for parent in sorted(properties[name]):
|
|
157
|
+
console.print(f"{INDENT}{INDENT}{parent}")
|
|
158
|
+
|
|
159
|
+
return
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Implement the 'references' CLI."""
|
|
3
|
+
import json
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from datetime import timezone
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Annotated
|
|
8
|
+
from typing import Any
|
|
9
|
+
from typing import Iterable
|
|
10
|
+
|
|
11
|
+
import requests
|
|
12
|
+
import typer
|
|
13
|
+
import yaml
|
|
14
|
+
from rich_objects import console_factory
|
|
15
|
+
from urllib3.util import parse_url
|
|
16
|
+
|
|
17
|
+
from openapi_spec_tools.cli.arguments import LogLevelOption
|
|
18
|
+
from openapi_spec_tools.cli.arguments import OpenApiFilenameArgument
|
|
19
|
+
from openapi_spec_tools.cli.arguments import UpdatedOpenApiFilenameOption
|
|
20
|
+
from openapi_spec_tools.cli.constants import INDENT
|
|
21
|
+
from openapi_spec_tools.cli.utils import error_out
|
|
22
|
+
from openapi_spec_tools.cli.utils import init_logging
|
|
23
|
+
from openapi_spec_tools.cli.utils import open_oas_with_error_handling
|
|
24
|
+
from openapi_spec_tools.types import OasField
|
|
25
|
+
from openapi_spec_tools.utils import add_models
|
|
26
|
+
from openapi_spec_tools.utils import find_references
|
|
27
|
+
from openapi_spec_tools.utils import get_logger
|
|
28
|
+
from openapi_spec_tools.utils import map_models
|
|
29
|
+
from openapi_spec_tools.utils import replace_references
|
|
30
|
+
from openapi_spec_tools.utils import unmap_models
|
|
31
|
+
from openapi_spec_tools.utils import write_oas
|
|
32
|
+
|
|
33
|
+
app = typer.Typer(
|
|
34
|
+
name="references",
|
|
35
|
+
no_args_is_help=True,
|
|
36
|
+
help="Utilities for working with external references (e.g. `$ref` fields) in an OpenAPI spec",
|
|
37
|
+
)
|
|
38
|
+
logger = get_logger(__name__)
|
|
39
|
+
_DOWNLOAD_TIMEOUT_SECONDS = 30
|
|
40
|
+
|
|
41
|
+
#################################################
|
|
42
|
+
# Reference stuff
|
|
43
|
+
|
|
44
|
+
def get_external_references(spec: dict[str, Any]) -> dict[str, list[str]]:
|
|
45
|
+
"""Get map of external references to referred to items in that reference."""
|
|
46
|
+
refs = find_references(spec)
|
|
47
|
+
external = {r for r in refs if not r.startswith("schemas/")}
|
|
48
|
+
if not external:
|
|
49
|
+
return {}
|
|
50
|
+
|
|
51
|
+
file_refs = {}
|
|
52
|
+
for ext in external:
|
|
53
|
+
file, separator, item = ext.partition("#")
|
|
54
|
+
if not separator or "#" in item:
|
|
55
|
+
logger.error(f"Invalid reference: {ext}")
|
|
56
|
+
continue
|
|
57
|
+
file_refs.setdefault(file, []).append(item)
|
|
58
|
+
|
|
59
|
+
return {file: sorted(items) for file, items in file_refs.items()}
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def is_url(value: str) -> bool:
|
|
63
|
+
"""Return whether ``value`` is a URL.
|
|
64
|
+
|
|
65
|
+
urllib3 records a scheme for a URL. A local filename has no scheme. A single-letter
|
|
66
|
+
scheme is a Windows drive letter, such as ``c:/foo``, not a URL.
|
|
67
|
+
"""
|
|
68
|
+
scheme = parse_url(value).scheme
|
|
69
|
+
return scheme is not None and len(scheme) != 1
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def extract_filename(url: str) -> str:
|
|
73
|
+
"""Extract the filename from the URL or local path.
|
|
74
|
+
|
|
75
|
+
The name is the final path segment. Query and fragment are left out. A value with no
|
|
76
|
+
path, such as ``common.yaml``, is returned as given. Local paths may use either slash,
|
|
77
|
+
including a Windows drive path such as ``c:/foo/pet.yaml``.
|
|
78
|
+
"""
|
|
79
|
+
if not is_url(url):
|
|
80
|
+
return url.replace("\\", "/").rsplit("/", maxsplit=1)[-1] or "local"
|
|
81
|
+
|
|
82
|
+
parsed = parse_url(url)
|
|
83
|
+
if parsed.path and parsed.path != "/":
|
|
84
|
+
return parsed.path.rsplit("/", maxsplit=1)[-1]
|
|
85
|
+
return parsed.host
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def check_duplicate_file_names(urls: Iterable) -> None:
|
|
89
|
+
"""Insure there are no duplicate filenames that would cause things to be overwritten."""
|
|
90
|
+
names = [extract_filename(url) for url in urls]
|
|
91
|
+
duplicates = sorted({name for name in names if names.count(name) > 1})
|
|
92
|
+
if not duplicates:
|
|
93
|
+
return
|
|
94
|
+
|
|
95
|
+
error_out(f"Duplicate filenames for: {', '.join(duplicates)}")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def get_spec_text(url: str, base_dir: Path | None = None) -> str:
|
|
99
|
+
"""Read external spec text.
|
|
100
|
+
|
|
101
|
+
A relative local path is resolved against ``base_dir`` when that is provided.
|
|
102
|
+
"""
|
|
103
|
+
if not is_url(url):
|
|
104
|
+
# if the local file does NOT exist, this is an error
|
|
105
|
+
file = Path(url)
|
|
106
|
+
if base_dir is not None and not file.is_absolute():
|
|
107
|
+
file = base_dir / file
|
|
108
|
+
if not file.exists():
|
|
109
|
+
error_out(f"Local file {url} does not exist!")
|
|
110
|
+
return file.read_text(encoding="utf-8", errors="ignore")
|
|
111
|
+
|
|
112
|
+
try:
|
|
113
|
+
start = datetime.now(tz=timezone.utc)
|
|
114
|
+
result = requests.get(url, timeout=_DOWNLOAD_TIMEOUT_SECONDS)
|
|
115
|
+
delta = datetime.now(tz=timezone.utc) - start
|
|
116
|
+
logger.info(f"Download of {url} too {delta.total_seconds()} seconds")
|
|
117
|
+
result.raise_for_status()
|
|
118
|
+
return result.text
|
|
119
|
+
except requests.RequestException as error:
|
|
120
|
+
error_out(f"Failed to download {url}: {error}")
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def get_spec_data(url: str, base_dir: Path | None = None) -> dict[str, Any]:
|
|
124
|
+
"""Read an external spec and parse it as JSON or YAML.
|
|
125
|
+
|
|
126
|
+
The file extension selects the parser. ``.json`` is JSON, and ``.yaml`` or ``.yml`` is YAML.
|
|
127
|
+
A relative local path is resolved against ``base_dir`` when that is provided.
|
|
128
|
+
"""
|
|
129
|
+
raw = get_spec_text(url, base_dir)
|
|
130
|
+
suffix = Path(extract_filename(url)).suffix.lower()
|
|
131
|
+
try:
|
|
132
|
+
if suffix == ".json":
|
|
133
|
+
data = json.loads(raw)
|
|
134
|
+
elif suffix in {".yaml", ".yml"}:
|
|
135
|
+
data = yaml.safe_load(raw)
|
|
136
|
+
else:
|
|
137
|
+
error_out(f"Unsupported spec file type for {url}")
|
|
138
|
+
except (json.JSONDecodeError, yaml.YAMLError, UnicodeDecodeError) as error:
|
|
139
|
+
error_out(f"Failed to parse {url}: {error}")
|
|
140
|
+
|
|
141
|
+
if not isinstance(data, dict):
|
|
142
|
+
error_out(f"Failed to parse {url}: expected an object")
|
|
143
|
+
return data
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
@app.command(
|
|
147
|
+
"find",
|
|
148
|
+
short_help="Look for external references in an OpenAPI spec"
|
|
149
|
+
)
|
|
150
|
+
def find_external_references(
|
|
151
|
+
filename: OpenApiFilenameArgument,
|
|
152
|
+
log_level: LogLevelOption = "info",
|
|
153
|
+
) -> None:
|
|
154
|
+
init_logging(log_level)
|
|
155
|
+
spec = open_oas_with_error_handling(filename)
|
|
156
|
+
|
|
157
|
+
external = get_external_references(spec)
|
|
158
|
+
if not external:
|
|
159
|
+
typer.echo(f"No external references found in {filename}")
|
|
160
|
+
return
|
|
161
|
+
|
|
162
|
+
console = console_factory()
|
|
163
|
+
console.print(yaml.dump(external, indent=len(INDENT)))
|
|
164
|
+
return
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
@app.command(
|
|
168
|
+
"download",
|
|
169
|
+
short_help="Download the external references from an OpenAPI spec"
|
|
170
|
+
)
|
|
171
|
+
def download_references(
|
|
172
|
+
filename: OpenApiFilenameArgument,
|
|
173
|
+
out_dir: Annotated[
|
|
174
|
+
str,
|
|
175
|
+
typer.Option(help="Directory to put the files into"),
|
|
176
|
+
] = ".",
|
|
177
|
+
log_level: LogLevelOption = "info",
|
|
178
|
+
) -> None:
|
|
179
|
+
init_logging(log_level)
|
|
180
|
+
spec = open_oas_with_error_handling(filename)
|
|
181
|
+
|
|
182
|
+
external = get_external_references(spec)
|
|
183
|
+
if not external:
|
|
184
|
+
typer.echo(f"No external references found in {filename}")
|
|
185
|
+
return
|
|
186
|
+
|
|
187
|
+
check_duplicate_file_names(external.keys())
|
|
188
|
+
|
|
189
|
+
dir_path = Path(out_dir)
|
|
190
|
+
dir_path.mkdir(parents=True, exist_ok=True)
|
|
191
|
+
base_dir = Path(filename).parent
|
|
192
|
+
for ext_url in sorted(external):
|
|
193
|
+
text = get_spec_text(ext_url, base_dir).replace("\r\n", "\n").replace("\r", "\n")
|
|
194
|
+
file = dir_path / extract_filename(ext_url)
|
|
195
|
+
file.write_text(text, encoding="utf-8", errors="ignore", newline="\n")
|
|
196
|
+
typer.echo(f"Wrote {file} for {ext_url}")
|
|
197
|
+
|
|
198
|
+
return
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
@app.command(
|
|
202
|
+
"update",
|
|
203
|
+
short_help="Resolve external references into one OpenAPI spec"
|
|
204
|
+
)
|
|
205
|
+
def update_references(
|
|
206
|
+
original_filename: OpenApiFilenameArgument,
|
|
207
|
+
updated_filename: UpdatedOpenApiFilenameOption = None,
|
|
208
|
+
log_level: LogLevelOption = "info",
|
|
209
|
+
) -> None:
|
|
210
|
+
init_logging(log_level)
|
|
211
|
+
spec = open_oas_with_error_handling(original_filename)
|
|
212
|
+
out_filename = updated_filename or original_filename # use current file, if new name not provided
|
|
213
|
+
|
|
214
|
+
external_refs = get_external_references(spec)
|
|
215
|
+
if not external_refs:
|
|
216
|
+
typer.echo(f"No external references found in {original_filename}")
|
|
217
|
+
return
|
|
218
|
+
|
|
219
|
+
base_dir = Path(original_filename).parent
|
|
220
|
+
for ext_url, ext_refs in external_refs.items():
|
|
221
|
+
data = get_spec_data(ext_url, base_dir)
|
|
222
|
+
components = data.pop(OasField.COMPONENTS, {})
|
|
223
|
+
models = map_models(components)
|
|
224
|
+
|
|
225
|
+
ext_short_refs = [_.replace("/components/", "") for _ in ext_refs]
|
|
226
|
+
used = {name: data for name, data in models.items() if name in ext_short_refs}
|
|
227
|
+
inner_refs = find_references(used)
|
|
228
|
+
for name in inner_refs:
|
|
229
|
+
extra_ref = models.get(name)
|
|
230
|
+
if not extra_ref:
|
|
231
|
+
logger.warning(f"Failed to find ref for {name}")
|
|
232
|
+
continue
|
|
233
|
+
used[name] = extra_ref
|
|
234
|
+
|
|
235
|
+
replacements = {f"{ext_url}#{name}": f"#{name}" for name in ext_refs}
|
|
236
|
+
add_models(spec, unmap_models(used))
|
|
237
|
+
replace_references(spec, replacements)
|
|
238
|
+
|
|
239
|
+
write_oas(out_filename, spec)
|
|
240
|
+
return
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
if __name__ == "__main__":
|
|
244
|
+
app()
|
{openapi_spec_tools-0.23.0 → openapi_spec_tools-0.24.0}/openapi_spec_tools/cli_gen/_display.py
RENAMED
|
@@ -11,6 +11,13 @@ def allowed(obj: Any, properties: list[str]) -> Any:
|
|
|
11
11
|
# recursively call for each object in list
|
|
12
12
|
return [allowed(item, properties) for item in obj]
|
|
13
13
|
|
|
14
|
+
# special handling if there's only one property (e.g. summary-field)
|
|
15
|
+
if len(properties) == 1:
|
|
16
|
+
# if the inner object is a dict, return that without the property as a key
|
|
17
|
+
inner = obj.get(properties[0])
|
|
18
|
+
if isinstance(inner, dict):
|
|
19
|
+
return inner
|
|
20
|
+
|
|
14
21
|
return {prop: obj.get(prop) for prop in properties}
|
|
15
22
|
|
|
16
23
|
|
|
@@ -1,7 +1,14 @@
|
|
|
1
1
|
"""Collection of common constants used in multiple files."""
|
|
2
2
|
|
|
3
|
+
from openapi_spec_tools.types import ContentType
|
|
4
|
+
|
|
3
5
|
LOG_CLASS = "oas"
|
|
4
6
|
|
|
5
7
|
NULL_TYPES = {'null', '"null"', "'null'"}
|
|
6
8
|
# NOTE: the 'integer' and 'float' values are not standard anymore, but were used a long time ago
|
|
7
9
|
SIMPLE_TYPES = {'string', 'boolean', 'number', 'integer', 'float'}
|
|
10
|
+
DEFAULT_SUPPORTED_CONTENT = [
|
|
11
|
+
ContentType.APP_JSON,
|
|
12
|
+
ContentType.APP_VJSON,
|
|
13
|
+
ContentType.APP_YAML,
|
|
14
|
+
]
|