File: cli.py

package info (click to toggle)
python-prance 25.4.8.0%2Bds1-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 6,144 kB
  • sloc: python: 3,381; makefile: 205
file content (306 lines) | stat: -rw-r--r-- 8,435 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
"""CLI for prance."""

__author__ = "Jens Finkhaeuser"
__copyright__ = "Copyright (c) 2016-2021 Jens Finkhaeuser"
__license__ = "MIT"
__all__ = ()


import click

import prance
from prance.util import default_validation_backend


def __write_to_file(filename, specs):  # noqa: N802
    """
    Write specs to the given filename.

    This takes into account file name extensions as per `fs.write_file`.
    """
    from prance.util import fs, formats

    contents = formats.serialize_spec(specs, filename)
    fs.write_file(filename, contents)


def __parser_for_url(url, resolve, backend, strict, encoding):  # noqa: N802
    """Return a parser instance for the URL and the given parameters."""
    # Try the URL
    formatted = click.format_filename(url)
    click.echo(f'Processing "{formatted}"...')

    from prance.util import fs

    fsurl = fs.abspath(url)
    import os.path

    if os.path.exists(fs.from_posix(fsurl)):
        url = fsurl

    # Create parser to use
    parser = None
    if resolve:
        click.echo(" -> Resolving external references.")
        parser = prance.ResolvingParser(
            url, lazy=True, backend=backend, strict=strict, encoding=encoding
        )
    else:
        click.echo(" -> Not resolving external references.")
        parser = prance.BaseParser(
            url, lazy=True, backend=backend, strict=strict, encoding=encoding
        )

    # XXX maybe enable this in debug mode or something.
    # click.echo(' -> Using backend: {0.backend}'.format(parser))
    return parser, formatted


def __validate(parser, name):  # noqa: N802
    """Validate a spec using this parser."""
    from prance.util.url import ResolutionError
    from prance import ValidationError

    try:
        parser.parse()
    except (ResolutionError, ValidationError) as err:
        msg = f'ERROR in "{name}" [{type(err).__name__}]: {str(err)}'
        click.secho(msg, err=True, fg="red")
        import sys

        sys.exit(1)

    # All good, next file.
    click.echo(f"Validates OK as {parser.version}!")


@click.group()
@click.version_option(version=prance.__version__)
def cli():
    pass  # pragma: no cover


class GroupWithCommandOptions(click.Group):
    """Allow application of options to group with multi command."""

    def add_command(self, cmd, name=None):
        click.Group.add_command(self, cmd, name=name)

        # add the group parameters to the command
        for param in self.params:
            cmd.params.append(param)

        # hook the commands invoke with our own
        cmd.invoke = self.build_command_invoke(cmd.invoke)
        self.invoke_without_command = True

    def build_command_invoke(self, original_invoke):
        def command_invoke(ctx):
            """Insert invocation of group function."""
            # separate the group parameters
            ctx.obj = dict(_params=dict())
            for param in self.params:
                name = param.name
                ctx.obj["_params"][name] = ctx.params[name]
                del ctx.params[name]

            # call the group function with its parameters
            params = ctx.params
            ctx.params = ctx.obj["_params"]
            self.invoke(ctx)
            ctx.params = params

            # now call the original invoke (the command)
            original_invoke(ctx)

        return command_invoke


@click.group(cls=GroupWithCommandOptions)
@click.option(
    "--resolve/--no-resolve",
    default=True,
    help="Resolve external references before validation. The default is to " "do so.",
)
@click.option(
    "--backend",
    default=default_validation_backend(),
    metavar="BACKEND",
    nargs=1,
    help='The validation backend to use. One of "flex", '
    '"swagger-spec-validator" or "openapi-spec-validator". The default'
    "is the best of the installed backends.",
)
@click.option(
    "--strict/--no-strict",
    default=True,
    help="Be strict or lenient in validating specs. Strict validation "
    "rejects non-string spec keys, for example in response codes. "
    'Does not apply to the "flex" backend.',
)
@click.option(
    "--encoding",
    default=None,
    help="If given, override file encoding detection and use the given "
    "encoding for all files. Does not work on remote URLs.",
)
@click.pass_context
def backend_options(ctx, resolve, backend, strict, encoding):
    ctx.obj["resolve"] = resolve
    ctx.obj["backend"] = backend
    ctx.obj["strict"] = strict
    ctx.obj["encoding"] = encoding


@backend_options.command()
@click.option(
    "--output-file",
    "-o",
    type=click.Path(exists=False),
    default=None,
    metavar="FILENAME",
    nargs=1,
    help='[DEPRECATED; see "compile" command] If given, write the '
    "validated specs to this file. Together with the --resolve "
    "option, the output file will be a resolved version of the input "
    "file.",
)
@click.argument(
    "urls",
    type=click.Path(exists=False),
    nargs=-1,
)
@click.pass_context
def validate(ctx, output_file, urls):
    """
    Validate the given spec or specs.

    If the --resolve option is set, references will be resolved before
    validation.

    Note that this merges referenced objects into the main specs. Validation
    backends used by prance cannot validate referenced objects, so resolving
    the references before validation allows for full spec validation.
    """
    # Ensure that when an output file is given, only one input file exists.
    if output_file:
        click.echo(
            "The --output-file parameter is deprecated; use "
            'the "compile" command instead.',
            err=True,
        )
    if output_file and len(urls) > 1:
        raise click.UsageError(
            "If --output-file is given, only one input URL " "is allowed!"
        )

    # Process files
    for url in urls:
        # Create parser to use
        parser, name = __parser_for_url(
            url,
            ctx.obj["resolve"],
            ctx.obj["backend"],
            ctx.obj["strict"],
            ctx.obj["encoding"],
        )

        # Try parsing
        __validate(parser, name)

        # If an output file is given, write the specs to it.
        if output_file:
            __write_to_file(output_file, parser.specification)


@backend_options.command()
@click.argument(
    "url_or_path",
    type=click.Path(exists=False),
    nargs=1,
)
@click.argument(
    "output_file",
    type=click.Path(exists=False),
    nargs=1,
    required=False,
)
@click.pass_context
def compile(ctx, url_or_path, output_file):
    """
    Compile the given spec, resolving references if required.

    Resolves references and uses backends exactly as in the "validate"
    command, but only works on single URLs.

    If an output file name is given, output is written there, otherwise
    it is written to the terminal.
    """
    # Create parser to use
    parser, name = __parser_for_url(
        url_or_path,
        ctx.obj["resolve"],
        ctx.obj["backend"],
        ctx.obj["strict"],
        ctx.obj["encoding"],
    )

    # Try parsing
    __validate(parser, name)

    # Write output
    from prance.util import formats

    contents = formats.serialize_spec(parser.specification, output_file)
    if output_file is None:
        click.echo(contents)
    else:
        from .util import fs

        fs.write_file(output_file, contents)
        click.echo(f'Output written to "{output_file}".')


@cli.command()
@click.argument(
    "url_or_path",
    type=click.Path(exists=False),
    nargs=1,
)
@click.argument(
    "output_file",
    type=click.Path(exists=False),
    nargs=1,
    required=False,
)
def convert(url_or_path, output_file):
    """
    Convert the given spec to OpenAPI 3.x.y.

    The conversion uses the web API provided by mermade.org.uk to perform the
    conversion. As long as that service is kept up-to-date and you have an
    internet connection, conversion should work and should convert to the latest
    version of the specs.
    """
    # Convert call
    from .util import url
    import os

    absurl = url.absurl(url_or_path, os.getcwd())

    from .convert import convert_url

    content, content_type = convert_url(absurl)

    # Write output
    if output_file is None:
        click.echo(content)
    else:
        from .util import fs

        fs.write_file(output_file, content)


cli.add_command(validate)
cli.add_command(compile)
cli.add_command(convert)