sc-oa 0.7.0.17__py3-none-any.whl

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.
@@ -0,0 +1,35 @@
1
+ Metadata-Version: 2.4
2
+ Name: sc-oa
3
+ Version: 0.7.0.17
4
+ Summary: Fork of the OpenAPI (fka Swagger) spec renderer for Sphinx
5
+ Home-page: https://github.com/olivier-heurtier/sphinxcontrib-openapi/tree/mymaster
6
+ Author: Olivier Heurtier
7
+ Author-email: olivier.heurtier@github.com
8
+ License: BSD
9
+ Classifier: Topic :: Documentation
10
+ Classifier: Topic :: Documentation :: Sphinx
11
+ Classifier: License :: OSI Approved :: BSD License
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: Implementation :: CPython
23
+ Classifier: Framework :: Sphinx
24
+ Classifier: Framework :: Sphinx :: Extension
25
+ Requires-Python: >=3.10
26
+ License-File: LICENSE
27
+ Requires-Dist: sphinx
28
+ Requires-Dist: sphinxcontrib-httpdomain
29
+ Requires-Dist: PyYAML
30
+ Requires-Dist: jsonschema
31
+ Requires-Dist: m2r2
32
+ Requires-Dist: picobox
33
+ Requires-Dist: deepmerge
34
+ Requires-Dist: setuptools
35
+ Dynamic: license-file
@@ -0,0 +1,26 @@
1
+ sc_oa-0.7.0.17.dist-info/licenses/LICENSE,sha256=Fe9eBZy-tUN-UOMSVfcr4c-MWpuWa4gTKTqH-kSeck4,1319
2
+ sphinxcontrib/__init__.py,sha256=Es10gRADmbGSJZnYYmhfgA_2QzHQDmhj0IAft3kS1Og,259
3
+ sphinxcontrib/openapi/__init__.py,sha256=x8cvrnXGqjZSc62nkeZC0KdCcCSXQY8uxv1kFhrPM18,3088
4
+ sphinxcontrib/openapi/__main__.py,sha256=cp8p7qGn8nH2W_aeD9sMTuqPwLV3ys8DtLYZnyF29pY,2436
5
+ sphinxcontrib/openapi/_lib2to3.py,sha256=mU2Dx78xEyiz0cfcj3R9eqiwHbCfspK5cDJ5ZwwQdA4,13624
6
+ sphinxcontrib/openapi/directive.py,sha256=J4T0n_KkM6SB1Mr9GeYCVqWZNp3BMSjEnVvLvwj8CoM,2059
7
+ sphinxcontrib/openapi/openapi20.py,sha256=FDdlcRIYKCynOZUjxQNoE8lCFRrZinmYu1khz8D18ZU,8984
8
+ sphinxcontrib/openapi/openapi30.py,sha256=zvFih09I9dVY0_YLJmoKSHPz0DynBKbc06rUfbYONWo,29212
9
+ sphinxcontrib/openapi/schema_utils.py,sha256=pxdB5qSTAtiCFmmF04R0zlOOG-Dxi98qwrA2uLZcNXA,4446
10
+ sphinxcontrib/openapi/utils.py,sha256=oRWNDb_5KWTXOVblFgvrLvmGATae8C7PYvk1xc464vY,4343
11
+ sphinxcontrib/openapi/locale/openapi.pot,sha256=sGo7dIRUUS6Ne4MRIU7PCphOoQG1AORgZhwwpD0nRfo,3831
12
+ sphinxcontrib/openapi/locale/es_ES/LC_MESSAGES/openapi.mo,sha256=qdW6yFaSVB_BsexvwM33U8X12yoHikgaI8N7a4U_gI4,1919
13
+ sphinxcontrib/openapi/locale/es_ES/LC_MESSAGES/openapi.po,sha256=dB6_HK0ubCauj1LZbs-zz0NNcPkm4eqKIuxZtqD71WU,4357
14
+ sphinxcontrib/openapi/locale/fr_FR/LC_MESSAGES/openapi.mo,sha256=YS2uZZZ4bHpDXJmShv33NZhtIWcir9-qERusNDR-vqY,1956
15
+ sphinxcontrib/openapi/locale/fr_FR/LC_MESSAGES/openapi.po,sha256=_rpbU9BhwTI2vXFcgj-BdiC-5LhUphYvHtoU1jPHT4Y,4400
16
+ sphinxcontrib/openapi/renderers/__init__.py,sha256=8hdY-sLK5kDbOL8Tqe55xEBphPFXVCNj6eUA3lTvD8s,408
17
+ sphinxcontrib/openapi/renderers/_description.py,sha256=FAklhEaMksCYU5bno3SO0RuQCcwVTXbqPmPN3PrRlTM,702
18
+ sphinxcontrib/openapi/renderers/_httpdomain.py,sha256=qx6pIVQF2BKWjrL1YOap1_2odtLAqk5SeuktofdOMRQ,24546
19
+ sphinxcontrib/openapi/renderers/_httpdomain_old.py,sha256=aiWafD8LdRmCtG6ewkU3xF-P1oWxxYxUNzdcUFW4hB4,2632
20
+ sphinxcontrib/openapi/renderers/_model.py,sha256=yoU265jAgkiW_Ew4EFiWuzA8Q56AsmYa4HBODJDA2bw,15441
21
+ sphinxcontrib/openapi/renderers/_toc.py,sha256=0cVLyKJBcu4ULkiBdlQ-oMBWV4DVCVM5-BgT07xG0Fc,1478
22
+ sphinxcontrib/openapi/renderers/abc.py,sha256=-irO9yVoHeygaMieq4DZMmWD0B5DkDu2mKuenGYopTI,1485
23
+ sc_oa-0.7.0.17.dist-info/METADATA,sha256=4tWFEZMwdtDJ2C76UGcDwj6NcouRccJaJZ_VPo5Uhkg,1312
24
+ sc_oa-0.7.0.17.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
25
+ sc_oa-0.7.0.17.dist-info/top_level.txt,sha256=VJrV3_vaiKQVgVpR0I1iecxoO0drzGu-M0j40PVP2QQ,14
26
+ sc_oa-0.7.0.17.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,23 @@
1
+ Copyright (c) 2016, Igor Kalnitsky <igor@kalnitsky.org>.
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions are met:
6
+
7
+ * Redistributions of source code must retain the above copyright notice, this
8
+ list of conditions and the following disclaimer.
9
+
10
+ * Redistributions in binary form must reproduce the above copyright notice,
11
+ this list of conditions and the following disclaimer in the documentation
12
+ and/or other materials provided with the distribution.
13
+
14
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
15
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
17
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
18
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
20
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
21
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
22
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1 @@
1
+ sphinxcontrib
@@ -0,0 +1,10 @@
1
+ """
2
+ sphinxcontrib
3
+ ~~~~~~~~~~~~~
4
+
5
+ This package is a namespace package that contains all extensions
6
+ distributed in the ``sphinx-contrib`` distribution.
7
+
8
+ :copyright: (c) 2016 by Igor Kalnitsky.
9
+ :license: BSD, see LICENSE for details.
10
+ """
@@ -0,0 +1,93 @@
1
+ """get_distribution
2
+ sphinxcontrib.openapi
3
+ ---------------------
4
+
5
+ The OpenAPI spec renderer for Sphinx. It's a new way to document your
6
+ RESTful API. Based on ``sphinxcontrib-httpdomain``.
7
+
8
+ :copyright: (c) 2016, Ihor Kalnytskyi.
9
+ :license: BSD, see LICENSE for details.
10
+ """
11
+
12
+ import os
13
+ from importlib.metadata import distribution, PackageNotFoundError
14
+ from sphinxcontrib.openapi import renderers, directive
15
+ from sphinx.domains import Domain
16
+ import yaml
17
+ from docutils import nodes
18
+
19
+ try:
20
+ __version__ = distribution(__name__).version
21
+ except PackageNotFoundError:
22
+ # package is not installed
23
+ __version__ = None
24
+
25
+
26
+ _DEFAULT_RENDERER_NAME = "httpdomain:old"
27
+
28
+
29
+ def oasversion_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
30
+ fn = text
31
+ env = inliner.document.settings.env
32
+ rel_fn, fn = env.relfn2path(fn)
33
+ y = yaml.load(open(fn, 'r').read(), Loader=yaml.FullLoader)
34
+ s = y['info']['version']
35
+ retnode = nodes.inline(text=s, role=typ.lower(), classes=[typ])
36
+ return [retnode], []
37
+
38
+
39
+ class OpenAPIDomain(Domain):
40
+ name = 'openapi'
41
+ label = 'OpenAPI Documentation'
42
+
43
+ directives = {
44
+ 'httpdomain:old': directive.create_directive_from_renderer(
45
+ renderers.HttpdomainOldRenderer),
46
+ 'httpdomain': directive.create_directive_from_renderer(renderers.HttpdomainRenderer),
47
+ 'model': directive.create_directive_from_renderer(renderers.ModelRenderer),
48
+ 'toc': directive.create_directive_from_renderer(renderers.TocRenderer),
49
+ 'description': directive.create_directive_from_renderer(renderers.DescriptionRenderer),
50
+ }
51
+
52
+ roles = {
53
+ 'version': oasversion_role
54
+ }
55
+
56
+
57
+ def setup(app):
58
+ app.add_config_value("openapi_default_renderer", _DEFAULT_RENDERER_NAME, "html")
59
+ app.add_config_value("openapi_renderers", {}, "html")
60
+
61
+ package_dir = os.path.abspath(os.path.dirname(__file__))
62
+ locale_dir = os.path.join(package_dir, 'locale')
63
+ app.add_message_catalog('openapi', locale_dir)
64
+
65
+ from sphinxcontrib import httpdomain
66
+
67
+ for idx, fieldtype in enumerate(httpdomain.HTTPResource.doc_field_types):
68
+ if fieldtype.name == 'requestheader':
69
+ httpdomain.HTTPResource.doc_field_types[idx] = httpdomain.TypedField(
70
+ fieldtype.name,
71
+ label=fieldtype.label,
72
+ names=fieldtype.names,
73
+ typerolename='header',
74
+ typenames=('reqheadertype', ),
75
+ )
76
+
77
+ if fieldtype.name == 'responseheader':
78
+ httpdomain.HTTPResource.doc_field_types[idx] = httpdomain.TypedField(
79
+ fieldtype.name,
80
+ label=fieldtype.label,
81
+ names=fieldtype.names,
82
+ typerolename='header',
83
+ typenames=('resheadertype', ),
84
+ )
85
+
86
+ app.setup_extension("sphinxcontrib.httpdomain")
87
+ app.add_domain(OpenAPIDomain)
88
+ app.add_directive(
89
+ "openapi",
90
+ directive.create_directive_from_renderer(renderers.HttpdomainOldRenderer)
91
+ )
92
+
93
+ return {"version": __version__, "parallel_read_safe": True}
@@ -0,0 +1,86 @@
1
+ import argparse
2
+ import logging
3
+
4
+ from sphinxcontrib.openapi import directive, renderers
5
+
6
+
7
+ def main():
8
+ parser = argparse.ArgumentParser(
9
+ prog='oas2rst',
10
+ description='Export OpenAPI Specification files to reStructuredText \
11
+ files')
12
+ parser.add_argument(
13
+ "-l", "--level",
14
+ action='store',
15
+ default=logging.INFO,
16
+ dest='level',
17
+ help="Logging level")
18
+ parser.add_argument(
19
+ "-e", "--encoding",
20
+ action='store',
21
+ default="UTF-8",
22
+ dest='encoding',
23
+ help="Source file encoding")
24
+ parser.add_argument(
25
+ "-p", "--paths",
26
+ action='append',
27
+ dest='paths',
28
+ help="Endpoints to be rendered")
29
+ parser.add_argument(
30
+ "-x", "--examples",
31
+ action='store_true',
32
+ dest='examples',
33
+ help="Include examples")
34
+ parser.add_argument(
35
+ "--group-examples",
36
+ action='store_true',
37
+ dest='group_examples',
38
+ help="Group examples after the operation description")
39
+ parser.add_argument(
40
+ "-E", "--entities",
41
+ action='store_true',
42
+ dest='entities',
43
+ help="Include links to entities")
44
+ parser.add_argument(
45
+ "-g", "--group",
46
+ action='store_true',
47
+ dest='group',
48
+ help="Group paths by tag")
49
+ parser.add_argument(
50
+ "-i", "--input",
51
+ dest='input',
52
+ required=True,
53
+ help="Input file")
54
+ parser.add_argument(
55
+ "-o", "--output",
56
+ type=argparse.FileType('w'),
57
+ required=True,
58
+ dest='output',
59
+ help="Output file")
60
+
61
+ options = parser.parse_args()
62
+ logging.getLogger().setLevel(options.level)
63
+
64
+ openapi_options = {}
65
+ if options.paths:
66
+ openapi_options['paths'] = options.paths
67
+ if options.examples:
68
+ openapi_options['examples'] = True
69
+ if options.group_examples:
70
+ openapi_options['group_examples'] = True
71
+ if options.entities:
72
+ openapi_options['entities'] = True
73
+ if options.group:
74
+ openapi_options['group'] = True
75
+
76
+ openapi_options.setdefault('uri', 'file://%s' % options.input)
77
+ spec = directive._get_spec(options.input, options.encoding)
78
+ renderer = renderers.HttpdomainOldRenderer(None, openapi_options)
79
+
80
+ for line in renderer.render_restructuredtext_markup(spec):
81
+ options.output.write(line+'\n')
82
+ logging.debug(line)
83
+
84
+
85
+ if __name__ == '__main__':
86
+ main()
@@ -0,0 +1,378 @@
1
+ """Partial OpenAPI v2.x (fka Swagger) to OpenAPI v3.x converter."""
2
+
3
+ import functools
4
+ import urllib
5
+
6
+ import picobox
7
+
8
+
9
+ __all__ = [
10
+ "convert",
11
+ ]
12
+
13
+
14
+ def convert(spec):
15
+ """Convert a given OAS 2 spec to OAS 3."""
16
+
17
+ return Lib2to3().convert(spec)
18
+
19
+
20
+ def _is_vendor_extension(key):
21
+ """Return 'True' if a given key is a vendor extension."""
22
+
23
+ return key.startswith("x-")
24
+
25
+
26
+ def _get_properties(node, properties, *, vendor_extensions=False):
27
+ """Return a subset of 'node' properties w/ or wo/ vendor extensions."""
28
+
29
+ return {
30
+ key: value
31
+ for key, value in node.items()
32
+ if any([key in properties, vendor_extensions and _is_vendor_extension(key)])
33
+ }
34
+
35
+
36
+ def _get_schema_properties(node, *, except_for=None):
37
+ """Find and return 'Schema Object' properties."""
38
+
39
+ except_for = except_for or set()
40
+ schema = _get_properties(
41
+ node,
42
+ {
43
+ "additionalProperties",
44
+ "allOf",
45
+ "default",
46
+ "description",
47
+ "discriminator",
48
+ "enum",
49
+ "example",
50
+ "exclusiveMaximum",
51
+ "exclusiveMinimum",
52
+ "externalDocs",
53
+ "format",
54
+ "items",
55
+ "maxItems",
56
+ "maxLength",
57
+ "maxProperties",
58
+ "maximum",
59
+ "minItems",
60
+ "minLength",
61
+ "minProperties",
62
+ "minimum",
63
+ "multipleOf",
64
+ "pattern",
65
+ "properties",
66
+ "readOnly",
67
+ "required",
68
+ "title",
69
+ "type",
70
+ "uniqueItems",
71
+ "xml",
72
+ }
73
+ - set(except_for),
74
+ )
75
+
76
+ if "discriminator" in schema:
77
+ schema["discriminator"] = {"propertyName": schema["discriminator"]}
78
+ return schema
79
+
80
+
81
+ def _items_wo_vendor_extensions(node):
82
+ """Iterate over 'node' properties excluding vendor extensions."""
83
+
84
+ for key, value in node.items():
85
+ if _is_vendor_extension(key):
86
+ continue
87
+ yield key, value
88
+
89
+
90
+ class Lib2to3:
91
+
92
+ _target_version = "3.0.3"
93
+ _injector = picobox.Stack()
94
+
95
+ def _insert_into_injector(name):
96
+ def decorator(fn):
97
+ @functools.wraps(fn)
98
+ def wrapper(self, node, *args, **kwargs):
99
+ with Lib2to3._injector.push(picobox.Box(), chain=True) as box:
100
+ box.put(name, factory=lambda: node, scope=picobox.threadlocal)
101
+ return fn(self, node, *args, **kwargs)
102
+
103
+ return wrapper
104
+
105
+ return decorator
106
+
107
+ def __init__(self):
108
+ self._schemes = set()
109
+
110
+ @_insert_into_injector("spec")
111
+ def convert(self, spec):
112
+ # The following OAS 2 fields are ignored and not converted. Mostly due
113
+ # to the fact that we expect *resolved* spec as input, and most of its
114
+ # fields are used to group shared (i.e. referenced) objects that will
115
+ # not exist in the resolved spec.
116
+ #
117
+ # - definitions
118
+ # - parameters
119
+ # - responses
120
+ # - securityDefinitions
121
+ # - security
122
+ #
123
+ # By no means one must assume that these fields will never be
124
+ # converted. I simply have no time to work on this, and for
125
+ # sphixcontrib-openapi purposes it's not actually needed.
126
+
127
+ converted = {
128
+ "info": spec["info"],
129
+ "openapi": self._target_version,
130
+ "paths": self.convert_paths(spec["paths"]),
131
+ }
132
+ converted.update(
133
+ _get_properties(spec, {"tags", "externalDocs"}, vendor_extensions=True),
134
+ )
135
+
136
+ servers = self.convert_servers(spec)
137
+ if servers:
138
+ converted["servers"] = servers
139
+
140
+ return converted
141
+
142
+ @_insert_into_injector("paths")
143
+ def convert_paths(self, paths):
144
+ converted = _get_properties(paths, {}, vendor_extensions=True)
145
+
146
+ for endpoint, path in _items_wo_vendor_extensions(paths):
147
+ converted[endpoint] = self.convert_path(path)
148
+
149
+ return converted
150
+
151
+ @_insert_into_injector("path")
152
+ def convert_path(self, path):
153
+ converted = _get_properties(path, {}, vendor_extensions=True)
154
+
155
+ for key, value in _items_wo_vendor_extensions(path):
156
+ if key == "parameters":
157
+ converted[key] = self.convert_parameters(value)
158
+ else:
159
+ converted[key] = self.convert_operation(value)
160
+
161
+ return converted
162
+
163
+ @_insert_into_injector("operation")
164
+ def convert_operation(self, operation):
165
+ converted = _get_properties(
166
+ operation,
167
+ {
168
+ "tags",
169
+ "summary",
170
+ "description",
171
+ "externalDocs",
172
+ "operationId",
173
+ "deprecated",
174
+ "security",
175
+ },
176
+ vendor_extensions=True,
177
+ )
178
+
179
+ # Memorize every encountered 'schemes'. Since this property does not
180
+ # exist in OAS 3, it seems the best we can do is to use them in OAS 3
181
+ # 'servers' object.
182
+ self._schemes.update(operation.get("schemes", []))
183
+
184
+ if "parameters" in operation:
185
+ parameters = self.convert_parameters(operation["parameters"])
186
+
187
+ # Both 'body' and 'formData' parameters are mutually exclusive,
188
+ # therefore there's no way we may end up with both kinds at once.
189
+ request_body = self.convert_request_body(operation)
190
+ request_body = request_body or self.convert_request_body_formdata(operation)
191
+
192
+ if parameters:
193
+ converted["parameters"] = parameters
194
+
195
+ if request_body:
196
+ converted["requestBody"] = request_body
197
+
198
+ converted["responses"] = self.convert_responses(operation["responses"])
199
+ return converted
200
+
201
+ @_injector.pass_("spec")
202
+ def convert_request_body(self, operation, *, spec):
203
+ # OAS 3 expects an explicitly specified mimetype of the request body.
204
+ # It's not clear what to do if OAS 2 'consumes' is not defined. Let's
205
+ # start with a glob pattern and figure out what a better option could
206
+ # be later on.
207
+ consumes = operation.get("consumes") or spec.get("consumes") or ["*/*"]
208
+
209
+ for parameter in operation["parameters"]:
210
+ if parameter["in"] == "body":
211
+ # Since 'requestBody' is completely new and nested object in
212
+ # OAS 3, it's not clear what should we insert possible vendor
213
+ # extensions. Thus, let's ignore them until we figure it out.
214
+ converted = _get_properties(parameter, {"description", "required"})
215
+ converted["content"] = {
216
+ consume: {"schema": parameter["schema"]} for consume in consumes
217
+ }
218
+ return converted
219
+
220
+ return None
221
+
222
+ @_injector.pass_("spec")
223
+ def convert_request_body_formdata(self, operation, *, spec):
224
+ consumes = (
225
+ operation.get("consumes")
226
+ or spec.get("consumes")
227
+ or ["application/x-www-form-urlencoded"]
228
+ )
229
+ supported = {
230
+ "application/x-www-form-urlencoded",
231
+ "multipart/form-data",
232
+ }
233
+ mimetypes = supported.intersection(consumes)
234
+ schema = {"type": "object", "properties": {}}
235
+
236
+ for parameter in operation["parameters"]:
237
+ if parameter["in"] == "formData":
238
+ schema["properties"][parameter["name"]] = _get_schema_properties(
239
+ parameter, except_for={"name", "in", "required"}
240
+ )
241
+
242
+ if parameter.get("required"):
243
+ schema.setdefault("required", []).append(parameter["name"])
244
+
245
+ # Excerpt from OpenAPI 2.x spec:
246
+ #
247
+ # > If type is "file", the consumes MUST be either
248
+ # > "multipart/form-data", "application/x-www-form-urlencoded"
249
+ # > or both and the parameter MUST be in "formData".
250
+ #
251
+ # This is weird since HTTP does not allow file uploading in
252
+ # 'application/x-www-form-urlencoded'. Moreover, Swagger
253
+ # editor complains if 'file' is detected and there's no
254
+ # 'multipart/form-data' in `consumes'.
255
+ if parameter["type"] == "file":
256
+ mimetypes = ["multipart/form-data"]
257
+
258
+ if not schema["properties"]:
259
+ return None
260
+ return {"content": {mimetype: {"schema": schema} for mimetype in mimetypes}}
261
+
262
+ @_insert_into_injector("parameters")
263
+ def convert_parameters(self, parameters):
264
+ return [
265
+ self.convert_parameter(parameter)
266
+ for parameter in parameters
267
+ # If a parameter is one of the backward compatible type, delegate
268
+ # the call to the converter function. Incompatible types, such as
269
+ # 'formData' and 'body', must be handled separately since they are
270
+ # reflected in 'Operation Object' in OAS 3.
271
+ if parameter["in"] in {"query", "header", "path"}
272
+ ]
273
+
274
+ @_insert_into_injector("parameter")
275
+ def convert_parameter(self, parameter):
276
+ schema = _get_schema_properties(
277
+ parameter,
278
+ # Some of 'Parameter Object' properties have the same name as some
279
+ # of 'Schema Object' properties. Since we know for sure that in
280
+ # this context they are part of 'Parameter Object', we should
281
+ # ignore their meaning as part of 'Schema Object'.
282
+ except_for={"name", "in", "description", "required"},
283
+ )
284
+ converted = {
285
+ key: value for key, value in parameter.items() if key not in schema
286
+ }
287
+ converted["schema"] = schema
288
+ collection_format = converted.pop("collectionFormat", None)
289
+
290
+ if converted["in"] in {"path", "header"} and collection_format == "csv":
291
+ converted["style"] = "simple"
292
+ elif converted["in"] in {"query"} and collection_format:
293
+ styles = {
294
+ "csv": {"style": "form", "explode": False},
295
+ "multi": {"style": "form", "explode": True},
296
+ "ssv": {"style": "spaceDelimited"},
297
+ "pipes": {"style": "pipeDelimited"},
298
+ # OAS 3 does not explicitly say what is the alternative to
299
+ # 'collectionFormat=tsv'. We have no other option but to ignore
300
+ # it. Fortunately, we don't care much as it's not used by the
301
+ # renderer.
302
+ "tsv": {},
303
+ }
304
+ converted.update(styles[collection_format])
305
+
306
+ return converted
307
+
308
+ @_insert_into_injector("responses")
309
+ def convert_responses(self, responses):
310
+ converted = _get_properties(responses, {}, vendor_extensions=True)
311
+
312
+ for status_code, response in _items_wo_vendor_extensions(responses):
313
+ converted[status_code] = self.convert_response(response)
314
+
315
+ return converted
316
+
317
+ @_injector.pass_("spec")
318
+ @_injector.pass_("operation")
319
+ @_insert_into_injector("response")
320
+ def convert_response(self, response, *, spec, operation):
321
+ converted = _get_properties(response, {"description"}, vendor_extensions=True)
322
+
323
+ # OAS 3 expects an explicitly specified mimetype in the response. It's
324
+ # not clear what to do if OAS 2 'produces' is not defined. Let's start
325
+ # with a glob pattern and figure out what a better option could be
326
+ # later on.
327
+ produces = operation.get("produces") or spec.get("produces") or ["*/*"]
328
+ schema = response.get("schema")
329
+ examples = response.get("examples")
330
+
331
+ if schema or examples:
332
+ content = converted.setdefault("content", {})
333
+
334
+ if schema is not None:
335
+ for mimetype in produces:
336
+ content.setdefault(mimetype, {})["schema"] = schema
337
+
338
+ if examples is not None:
339
+ # According to OAS2, mimetypes in 'examples' property MUST be
340
+ # one of the operation's 'produces'.
341
+ for mimetype, example in examples.items():
342
+ content.setdefault(mimetype, {})["example"] = example
343
+
344
+ if "headers" in response:
345
+ converted["headers"] = {
346
+ key: dict(
347
+ _get_properties(value, "description", vendor_extensions=True),
348
+ schema=_get_schema_properties(value, except_for={"description"}),
349
+ )
350
+ for key, value in response["headers"].items()
351
+ }
352
+
353
+ return converted
354
+
355
+ def convert_servers(self, spec):
356
+ """Convert OAS2 '(host, basePath, schemes)' triplet into OAS3 'servers' node."""
357
+
358
+ host = spec.get("host", "")
359
+ basepath = spec.get("basePath", "")
360
+ schemes = self._schemes.union(spec.get("schemes", set()))
361
+
362
+ # Since 'host', 'basePath' and 'schemes' are optional in OAS 2, there
363
+ # may be the case when they aren't set. If that's happened it means
364
+ # there's nothing to convert, and thus we simply return an empty list.
365
+ if not host and not basepath and not schemes:
366
+ return []
367
+
368
+ if not schemes:
369
+ # If 'host' is not set, the url will contain a bare basePath.
370
+ # According to OAS 3, it's a valid URL, and both the host and the
371
+ # scheme must be assumed to be the same as the server that shared
372
+ # this OAS 3 spec.
373
+ return [{"url": urllib.parse.urljoin(host, basepath)}]
374
+
375
+ return [
376
+ {"url": urllib.parse.urlunsplit([scheme, host, basepath, None, None])}
377
+ for scheme in sorted(schemes)
378
+ ]