Skip to content
Navigation Menu
Toggle navigation
Sign in
Appearance settings
Platform
AI CODE CREATION
GitHub Copilot
Write better code with AI
GitHub Spark
Build and deploy intelligent apps
GitHub Models
Manage and compare prompts
MCP Registry
New
Integrate external tools
DEVELOPER WORKFLOWS
Actions
Automate any workflow
Codespaces
Instant dev environments
Issues
Plan and track work
Code Review
Manage code changes
APPLICATION SECURITY
GitHub Advanced Security
Find and fix vulnerabilities
Code security
Secure your code as you build
Secret protection
Stop leaks before they start
EXPLORE
Why GitHub
Documentation
Blog
Changelog
Marketplace
View all features
Solutions
BY COMPANY SIZE
Enterprises
Small and medium teams
Startups
Nonprofits
BY USE CASE
App Modernization
DevSecOps
DevOps
CI/CD
View all use cases
BY INDUSTRY
Healthcare
Financial services
Manufacturing
Government
View all industries
View all solutions
Resources
EXPLORE BY TOPIC
AI
Software Development
DevOps
Security
View all topics
EXPLORE BY TYPE
Customer stories
Events & webinars
Ebooks & reports
Business insights
GitHub Skills
SUPPORT & SERVICES
Documentation
Customer support
Community forum
Trust center
Partners
View all resources
Open Source
COMMUNITY
GitHub Sponsors
Fund open source developers
PROGRAMS
Security Lab
Maintainer Community
Accelerator
GitHub Stars
Archive Program
REPOSITORIES
Topics
Trending
Collections
Enterprise
ENTERPRISE SOLUTIONS
Enterprise platform
AI-powered developer platform
AVAILABLE ADD-ONS
GitHub Advanced Security
Enterprise-grade security features
Copilot for Business
Enterprise-grade AI features
Premium Support
Enterprise-grade 24/7 support
Pricing
Search or jump to...
Clear
Search syntax tips
Name
Query
To see all available qualifiers, see our
documentation
.
Sign in
Sign up
Appearance settings
Resetting focus
You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.
You switched accounts on another tab or window.
Reload
to refresh your session.
Dismiss alert
{{ message }}
jdkent
/
openapi-python-client
Public
forked from
openapi-generators/openapi-python-client
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Files
Expand file tree
Breadcrumbs
openapi-python-client
/
openapi_python_client
/
cli.py
Copy path
Blame
More file actions
Blame
More file actions
Latest commit
History
History
History
193 lines (157 loc) · 6.25 KB
Breadcrumbs
openapi-python-client
/
openapi_python_client
/
cli.py
Top
File metadata and controls
Code
Blame
193 lines (157 loc) · 6.25 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
import codecs
import pathlib
from pprint import pformat
from typing import Optional, Sequence
import typer
from openapi_python_client import MetaType
from openapi_python_client.config import Config
from openapi_python_client.parser.errors import ErrorLevel, GeneratorError, ParseError
app = typer.Typer()
def _version_callback(value: bool) -> None:
from openapi_python_client import __version__
if value:
typer.echo(f"openapi-python-client version: {__version__}")
raise typer.Exit()
def _process_config(path: Optional[pathlib.Path]) -> Config:
if not path:
return Config()
try:
return Config.load_from_path(path=path)
except Exception as err:
raise typer.BadParameter("Unable to parse config") from err
# noinspection PyUnusedLocal
# pylint: disable=unused-argument
@app.callback(name="openapi-python-client")
def cli(
version: bool = typer.Option(False, "--version", callback=_version_callback, help="Print the version and exit"),
) -> None:
"""Generate a Python client from an OpenAPI JSON document"""
def _print_parser_error(err: GeneratorError, color: str) -> None:
typer.secho(err.header, bold=True, fg=color, err=True)
typer.echo()
if err.detail:
typer.secho(err.detail, fg=color, err=True)
typer.echo()
if isinstance(err, ParseError) and err.data is not None:
formatted_data = pformat(err.data)
typer.secho(formatted_data, fg=color, err=True)
typer.echo()
def handle_errors(errors: Sequence[GeneratorError], fail_on_warning: bool = False) -> None:
"""Turn custom errors into formatted error messages"""
if len(errors) == 0:
return
error_level = ErrorLevel.WARNING
message = "Warning(s) encountered while generating. Client was generated, but some pieces may be missing"
header_color = typer.colors.BRIGHT_YELLOW
color = typer.colors.YELLOW
for error in errors:
if error.level == ErrorLevel.ERROR:
error_level = ErrorLevel.ERROR
message = "Error(s) encountered while generating, client was not created"
color = typer.colors.RED
header_color = typer.colors.BRIGHT_RED
break
typer.secho(
message,
underline=True,
bold=True,
fg=header_color,
err=True,
)
typer.echo()
for err in errors:
_print_parser_error(err, color)
gh_link = typer.style(
"https://github.com/openapi-generators/openapi-python-client/issues/new/choose", fg=typer.colors.BRIGHT_BLUE
)
typer.secho(
f"If you believe this was a mistake or this tool is missing a feature you need, "
f"please open an issue at {gh_link}",
fg=typer.colors.BLUE,
err=True,
)
if error_level == ErrorLevel.ERROR or fail_on_warning:
raise typer.Exit(code=1)
custom_template_path_options = {
"help": "A path to a directory containing custom template(s)",
"file_okay": False,
"dir_okay": True,
"readable": True,
"resolve_path": True,
}
_meta_option = typer.Option(
MetaType.POETRY,
help="The type of metadata you want to generate.",
)
CONFIG_OPTION = typer.Option(None, "--config", help="Path to the config file to use")
# pylint: disable=too-many-arguments
@app.command()
def generate(
url: Optional[str] = typer.Option(None, help="A URL to read the JSON from"),
path: Optional[pathlib.Path] = typer.Option(None, help="A path to the JSON file"),
custom_template_path: Optional[pathlib.Path] = typer.Option(None, **custom_template_path_options), # type: ignore
meta: MetaType = _meta_option,
file_encoding: str = typer.Option("utf-8", help="Encoding used when writing generated"),
config_path: Optional[pathlib.Path] = CONFIG_OPTION,
fail_on_warning: bool = False,
) -> None:
"""Generate a new OpenAPI Client library"""
from . import create_new_client
if not url and not path:
typer.secho("You must either provide --url or --path", fg=typer.colors.RED)
raise typer.Exit(code=1)
if url and path:
typer.secho("Provide either --url or --path, not both", fg=typer.colors.RED)
raise typer.Exit(code=1)
try:
codecs.getencoder(file_encoding)
except LookupError as err:
typer.secho("Unknown encoding : {}".format(file_encoding), fg=typer.colors.RED)
raise typer.Exit(code=1) from err
config = _process_config(config_path)
errors = create_new_client(
url=url,
path=path,
meta=meta,
custom_template_path=custom_template_path,
file_encoding=file_encoding,
config=config,
)
handle_errors(errors, fail_on_warning)
# pylint: disable=too-many-arguments
@app.command()
def update(
url: Optional[str] = typer.Option(None, help="A URL to read the JSON from"),
path: Optional[pathlib.Path] = typer.Option(None, help="A path to the JSON file"),
custom_template_path: Optional[pathlib.Path] = typer.Option(None, **custom_template_path_options), # type: ignore
meta: MetaType = _meta_option,
file_encoding: str = typer.Option("utf-8", help="Encoding used when writing generated"),
config_path: Optional[pathlib.Path] = CONFIG_OPTION,
fail_on_warning: bool = False,
) -> None:
"""Update an existing OpenAPI Client library
The update command performs the same operations as generate except it does not overwrite specific metadata for the
generated client such as the README.md, .gitignore, and pyproject.toml.
"""
from . import update_existing_client
if not url and not path:
typer.secho("You must either provide --url or --path", fg=typer.colors.RED)
raise typer.Exit(code=1)
if url and path:
typer.secho("Provide either --url or --path, not both", fg=typer.colors.RED)
raise typer.Exit(code=1)
try:
codecs.getencoder(file_encoding)
except LookupError as err:
typer.secho("Unknown encoding : {}".format(file_encoding), fg=typer.colors.RED)
raise typer.Exit(code=1) from err
config = _process_config(config_path)
errors = update_existing_client(
url=url,
path=path,
meta=meta,
custom_template_path=custom_template_path,
file_encoding=file_encoding,
config=config,
)
handle_errors(errors, fail_on_warning)
You can’t perform that action at this time.