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 FormatOptions , 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 """
32- try :
33- 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- )
33+ if formatter == Formatter .BLACK :
34+ formatted_contend = format_using_black (content )
35+ elif formatter == Formatter .NONE :
36+ formatted_contend = content
37+ else :
38+ raise NotImplementedError (f"Missing implementation for formatter { formatter !r} ." )
39+ with open (path , "w" ) as f :
40+ f .write (formatted_contend )
41+
3842
39- except NothingChanged :
40- formatted_contend = content
41- formatted_contend = isort .code (formatted_contend , line_length = 120 )
42- f .write (formatted_contend )
43- except Exception as e :
44- raise e
43+ def format_using_black (content : str ) -> str :
44+ try :
45+ formatted_contend = black .format_file_contents (
46+ content , fast = FormatOptions .skip_validation , mode = black .FileMode (line_length = FormatOptions .line_length )
47+ )
48+ except NothingChanged :
49+ return content
50+ return isort .code (formatted_contend , line_length = FormatOptions .line_length )
4551
4652
4753def get_open_api (source : Union [str , Path ]) -> OpenAPI :
@@ -105,14 +111,14 @@ def get_open_api(source: Union[str, Path]) -> OpenAPI:
105111 raise
106112
107113
108- def write_data (data : ConversionResult , output : Union [str , Path ]) -> None :
114+ def write_data (data : ConversionResult , output : Union [str , Path ], formatter : Formatter ) -> None :
109115 """
110- This function will firstly create the folderstrucutre of output, if it doesn't exist. Then it will create the
116+ This function will firstly create the folder structure of output, if it doesn't exist. Then it will create the
111117 models from data.models into the models sub module of the output folder. After this, the services will be created
112118 into the services sub module of the output folder.
113- :param autoformat: The autoformat applied to the code written.
114119 :param data: The data to write.
115120 :param output: The path to the output folder.
121+ :param formatter: The formatter applied to the code written.
116122 """
117123
118124 # Create the folder structure of the output folder.
@@ -126,17 +132,18 @@ def write_data(data: ConversionResult, output: Union[str, Path]) -> None:
126132 services_path = Path (output ) / "services"
127133 services_path .mkdir (parents = True , exist_ok = True )
128134
129- files = []
135+ files : List [ str ] = []
130136
131137 # Write the models.
132138 for model in data .models :
133139 files .append (model .file_name )
134- write_code (models_path / f"{ model .file_name } .py" , model .content )
140+ write_code (models_path / f"{ model .file_name } .py" , model .content , formatter )
135141
136142 # Create models.__init__.py file containing imports to all models.
137143 write_code (
138144 models_path / "__init__.py" ,
139145 "\n " .join ([f"from .{ file } import *" for file in files ]),
146+ formatter ,
140147 )
141148
142149 files = []
@@ -150,18 +157,20 @@ def write_data(data: ConversionResult, output: Union[str, Path]) -> None:
150157 write_code (
151158 services_path / f"{ service .file_name } .py" ,
152159 jinja_env .get_template (SERVICE_TEMPLATE ).render (** service .dict ()),
160+ formatter ,
153161 )
154162
155163 # Create services.__init__.py file containing imports to all services.
156- write_code (services_path / "__init__.py" , "" )
164+ write_code (services_path / "__init__.py" , "" , formatter )
157165
158166 # Write the api_config.py file.
159- write_code (Path (output ) / "api_config.py" , data .api_config .content )
167+ write_code (Path (output ) / "api_config.py" , data .api_config .content , formatter )
160168
161169 # Write the __init__.py file.
162170 write_code (
163171 Path (output ) / "__init__.py" ,
164172 "from .models import *\n from .services import *\n from .api_config import *" ,
173+ formatter ,
165174 )
166175
167176
@@ -173,6 +182,7 @@ def generate_data(
173182 use_orjson : bool = False ,
174183 custom_template_path : Optional [str ] = None ,
175184 pydantic_version : PydanticVersion = PydanticVersion .V2 ,
185+ formatter : Formatter = Formatter .BLACK ,
176186) -> None :
177187 """
178188 Generate Python code from an OpenAPI 3.0 specification.
@@ -189,4 +199,4 @@ def generate_data(
189199 pydantic_version ,
190200 )
191201
192- write_data (result , output )
202+ write_data (result , output , formatter )
0 commit comments