11from pathlib import Path
2+ from typing import List
23from typing import Optional
34from typing import Union
45
1415from openapi_pydantic .v3 .v3_0 import OpenAPI
1516from pydantic import ValidationError
1617
17- from .common import HTTPLibrary , PydanticVersion
18+ from .common import Formatter , HTTPLibrary , PydanticVersion
1819from .common import library_config_dict
1920from .language_converters .python .generator import generator
2021from .language_converters .python .jinja_config import SERVICE_TEMPLATE
2122from .language_converters .python .jinja_config import create_jinja_env
2223from .models import ConversionResult
2324
2425
25- def write_code (path : Path , content ) -> None :
26+ def write_code (path : Path , content : str , formatter : Formatter ) -> None :
2627 """
2728 Write the content to the file at the given path.
28- :param autoformat: The autoformat applied to the code written.
2929 :param path: The path to the file.
3030 :param content: The content to write.
31+ :param formatter: The formatter applied to the code written.
3132 """
3233 try :
3334 with open (path , "w" ) as f :
34- try :
35- formatted_contend = black .format_file_contents (
36- content , fast = False , mode = black .FileMode (line_length = 120 )
37- )
38-
39- except NothingChanged :
35+ if formatter == Formatter .BLACK :
36+ formatted_contend = format_using_black (content )
37+ elif formatter == Formatter .NONE :
4038 formatted_contend = content
41- formatted_contend = isort .code (formatted_contend , line_length = 120 )
39+ else :
40+ raise NotImplementedError (
41+ f"Missing implementation for formatter { formatter !r} ."
42+ )
4243 f .write (formatted_contend )
4344 except Exception as e :
4445 raise e
4546
4647
48+ def format_using_black (content : str ) -> str :
49+ try :
50+ formatted_contend = black .format_file_contents (
51+ content , fast = False , mode = black .FileMode (line_length = 120 )
52+ )
53+ except NothingChanged :
54+ return content
55+ return isort .code (formatted_contend , line_length = 120 )
56+
57+
4758def get_open_api (source : Union [str , Path ]) -> OpenAPI :
4859 """
4960 Tries to fetch the openapi specification file from the web or load from a local file.
@@ -105,14 +116,14 @@ def get_open_api(source: Union[str, Path]) -> OpenAPI:
105116 raise
106117
107118
108- def write_data (data : ConversionResult , output : Union [str , Path ]) -> None :
119+ def write_data (data : ConversionResult , output : Union [str , Path ], formatter : Formatter ) -> None :
109120 """
110- This function will firstly create the folderstrucutre of output, if it doesn't exist. Then it will create the
121+ This function will firstly create the folder structure of output, if it doesn't exist. Then it will create the
111122 models from data.models into the models sub module of the output folder. After this, the services will be created
112123 into the services sub module of the output folder.
113- :param autoformat: The autoformat applied to the code written.
114124 :param data: The data to write.
115125 :param output: The path to the output folder.
126+ :param formatter: The formatter applied to the code written.
116127 """
117128
118129 # Create the folder structure of the output folder.
@@ -126,17 +137,18 @@ def write_data(data: ConversionResult, output: Union[str, Path]) -> None:
126137 services_path = Path (output ) / "services"
127138 services_path .mkdir (parents = True , exist_ok = True )
128139
129- files = []
140+ files : List [ str ] = []
130141
131142 # Write the models.
132143 for model in data .models :
133144 files .append (model .file_name )
134- write_code (models_path / f"{ model .file_name } .py" , model .content )
145+ write_code (models_path / f"{ model .file_name } .py" , model .content , formatter )
135146
136147 # Create models.__init__.py file containing imports to all models.
137148 write_code (
138149 models_path / "__init__.py" ,
139150 "\n " .join ([f"from .{ file } import *" for file in files ]),
151+ formatter ,
140152 )
141153
142154 files = []
@@ -150,18 +162,20 @@ def write_data(data: ConversionResult, output: Union[str, Path]) -> None:
150162 write_code (
151163 services_path / f"{ service .file_name } .py" ,
152164 jinja_env .get_template (SERVICE_TEMPLATE ).render (** service .dict ()),
165+ formatter ,
153166 )
154167
155168 # Create services.__init__.py file containing imports to all services.
156- write_code (services_path / "__init__.py" , "" )
169+ write_code (services_path / "__init__.py" , "" , formatter )
157170
158171 # Write the api_config.py file.
159- write_code (Path (output ) / "api_config.py" , data .api_config .content )
172+ write_code (Path (output ) / "api_config.py" , data .api_config .content , formatter )
160173
161174 # Write the __init__.py file.
162175 write_code (
163176 Path (output ) / "__init__.py" ,
164177 "from .models import *\n from .services import *\n from .api_config import *" ,
178+ formatter ,
165179 )
166180
167181
@@ -173,6 +187,7 @@ def generate_data(
173187 use_orjson : bool = False ,
174188 custom_template_path : Optional [str ] = None ,
175189 pydantic_version : PydanticVersion = PydanticVersion .V2 ,
190+ formatter : Formatter = Formatter .BLACK ,
176191) -> None :
177192 """
178193 Generate Python code from an OpenAPI 3.0 specification.
@@ -189,4 +204,4 @@ def generate_data(
189204 pydantic_version ,
190205 )
191206
192- write_data (result , output )
207+ write_data (result , output , formatter )
0 commit comments