Skip to content

Commit 3404660

Browse files
wing328Daiki Matsudate
authored andcommitted
Add file post-processing to Swift 3.x, 4.x generators (#1069)
* update all swift samples * format swift code with swiftformat * minor format fix * rename environment variable
1 parent ca9a4a2 commit 3404660

File tree

73 files changed

+598
-789
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

73 files changed

+598
-789
lines changed

modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift3Codegen.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919

2020
import io.swagger.v3.oas.models.media.ArraySchema;
2121
import io.swagger.v3.oas.models.media.Schema;
22+
import org.apache.commons.io.FilenameUtils;
2223
import org.apache.commons.lang3.ArrayUtils;
2324
import org.apache.commons.lang3.StringUtils;
2425
import org.apache.commons.lang3.text.WordUtils;
@@ -242,6 +243,10 @@ protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, Sc
242243
public void processOpts() {
243244
super.processOpts();
244245

246+
if (StringUtils.isEmpty(System.getenv("SWIFT_POST_PROCESS_FILE"))) {
247+
LOGGER.info("Environment variable SWIFT_POST_PROCESS_FILE not defined so the Swift code may not be properly formatted. To define it, try 'export SWIFT_POST_PROCESS_FILE=/usr/local/bin/swiftformat' (Linux/Mac)");
248+
}
249+
245250
// Setup project name
246251
if (additionalProperties.containsKey(PROJECT_NAME)) {
247252
setProjectName((String) additionalProperties.get(PROJECT_NAME));
@@ -681,4 +686,31 @@ public String escapeQuotationMark(String input) {
681686
public String escapeUnsafeCharacters(String input) {
682687
return input.replace("*/", "*_/").replace("/*", "/_*");
683688
}
689+
690+
@Override
691+
public void postProcessFile(File file, String fileType) {
692+
if (file == null) {
693+
return;
694+
}
695+
String swiftPostProcessFile = System.getenv("SWIFT_POST_PROCESS_FILE");
696+
if (StringUtils.isEmpty(swiftPostProcessFile)) {
697+
return; // skip if SWIFT_POST_PROCESS_FILE env variable is not defined
698+
}
699+
700+
// only process files with swift extension
701+
if ("swift".equals(FilenameUtils.getExtension(file.toString()))) {
702+
String command = swiftPostProcessFile + " " + file.toString();
703+
try {
704+
Process p = Runtime.getRuntime().exec(command);
705+
int exitValue = p.waitFor();
706+
if (exitValue != 0) {
707+
LOGGER.error("Error running the command ({}). Exit value: {}", command, exitValue);
708+
} else {
709+
LOGGER.info("Successfully executed: " + command);
710+
}
711+
} catch (Exception e) {
712+
LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage());
713+
}
714+
}
715+
}
684716
}

modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift4Codegen.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,15 @@
1919

2020
import io.swagger.v3.oas.models.media.ArraySchema;
2121
import io.swagger.v3.oas.models.media.Schema;
22+
import org.apache.commons.io.FilenameUtils;
2223
import org.apache.commons.lang3.ArrayUtils;
2324
import org.apache.commons.lang3.StringUtils;
2425
import org.apache.commons.lang3.text.WordUtils;
2526
import org.openapitools.codegen.*;
2627
import org.openapitools.codegen.utils.ModelUtils;
2728
import org.slf4j.Logger;
2829
import org.slf4j.LoggerFactory;
30+
import org.apache.commons.io.FilenameUtils;
2931

3032
import java.io.File;
3133
import java.util.*;
@@ -296,6 +298,10 @@ protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel,
296298
public void processOpts() {
297299
super.processOpts();
298300

301+
if (StringUtils.isEmpty(System.getenv("SWIFT_POST_PROCESS_FILE"))) {
302+
LOGGER.info("Environment variable SWIFT_POST_PROCESS_FILE not defined so the Swift code may not be properly formatted. To define it, try 'export SWIFT_POST_PROCESS_FILE=/usr/local/bin/swiftformat' (Linux/Mac)");
303+
}
304+
299305
// Setup project name
300306
if (additionalProperties.containsKey(PROJECT_NAME)) {
301307
setProjectName((String) additionalProperties.get(PROJECT_NAME));
@@ -836,4 +842,30 @@ public String escapeQuotationMark(String input) {
836842
public String escapeUnsafeCharacters(String input) {
837843
return input.replace("*/", "*_/").replace("/*", "/_*");
838844
}
845+
846+
@Override
847+
public void postProcessFile(File file, String fileType) {
848+
if (file == null) {
849+
return;
850+
}
851+
String swiftPostProcessFile = System.getenv("SWIFT_POST_PROCESS_FILE");
852+
if (StringUtils.isEmpty(swiftPostProcessFile)) {
853+
return; // skip if SWIFT_POST_PROCESS_FILE env variable is not defined
854+
}
855+
// only process files with swift extension
856+
if ("swift".equals(FilenameUtils.getExtension(file.toString()))) {
857+
String command = swiftPostProcessFile + " " + file.toString();
858+
try {
859+
Process p = Runtime.getRuntime().exec(command);
860+
int exitValue = p.waitFor();
861+
if (exitValue != 0) {
862+
LOGGER.error("Error running the command ({}). Exit value: {}", command, exitValue);
863+
} else {
864+
LOGGER.info("Successfully executed: " + command);
865+
}
866+
} catch (Exception e) {
867+
LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage());
868+
}
869+
}
870+
}
839871
}
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
3.0.0-SNAPSHOT
1+
3.3.0-SNAPSHOT
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
3.0.0-SNAPSHOT
1+
3.3.0-SNAPSHOT
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
3.0.0-SNAPSHOT
1+
3.3.0-SNAPSHOT
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
3.2.3-SNAPSHOT
1+
3.3.0-SNAPSHOT
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
3.2.3-SNAPSHOT
1+
3.3.0-SNAPSHOT
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
3.2.3-SNAPSHOT
1+
3.3.0-SNAPSHOT
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
3.2.3-SNAPSHOT
1+
3.3.0-SNAPSHOT
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
3.2.3-SNAPSHOT
1+
3.3.0-SNAPSHOT

samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIHelper.swift

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@
77
import Foundation
88

99
public struct APIHelper {
10-
public static func rejectNil(_ source: [String:Any?]) -> [String:Any]? {
11-
let destination = source.reduce(into: [String: Any]()) { (result, item) in
10+
public static func rejectNil(_ source: [String: Any?]) -> [String: Any]? {
11+
let destination = source.reduce(into: [String: Any]()) { result, item in
1212
if let value = item.value {
1313
result[item.key] = value
1414
}
@@ -20,22 +20,22 @@ public struct APIHelper {
2020
return destination
2121
}
2222

23-
public static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] {
24-
return source.reduce(into: [String: String]()) { (result, item) in
23+
public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] {
24+
return source.reduce(into: [String: String]()) { result, item in
2525
if let collection = item.value as? Array<Any?> {
26-
result[item.key] = collection.filter({ $0 != nil }).map{ "\($0!)" }.joined(separator: ",")
26+
result[item.key] = collection.filter({ $0 != nil }).map { "\($0!)" }.joined(separator: ",")
2727
} else if let value: Any = item.value {
2828
result[item.key] = "\(value)"
2929
}
3030
}
3131
}
3232

33-
public static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? {
33+
public static func convertBoolToString(_ source: [String: Any]?) -> [String: Any]? {
3434
guard let source = source else {
3535
return nil
3636
}
3737

38-
return source.reduce(into: [String: Any](), { (result, item) in
38+
return source.reduce(into: [String: Any](), { result, item in
3939
switch item.value {
4040
case let x as Bool:
4141
result[item.key] = x.description
@@ -45,11 +45,10 @@ public struct APIHelper {
4545
})
4646
}
4747

48-
49-
public static func mapValuesToQueryItems(_ source: [String:Any?]) -> [URLQueryItem]? {
50-
let destination = source.filter({ $0.value != nil}).reduce(into: [URLQueryItem]()) { (result, item) in
48+
public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? {
49+
let destination = source.filter({ $0.value != nil }).reduce(into: [URLQueryItem]()) { result, item in
5150
if let collection = item.value as? Array<Any?> {
52-
let value = collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",")
51+
let value = collection.filter({ $0 != nil }).map({ "\($0!)" }).joined(separator: ",")
5352
result.append(URLQueryItem(name: item.key, value: value))
5453
} else if let value = item.value {
5554
result.append(URLQueryItem(name: item.key, value: "\(value)"))
@@ -62,4 +61,3 @@ public struct APIHelper {
6261
return destination
6362
}
6463
}
65-

samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs.swift

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,22 +9,22 @@ import Foundation
99
open class PetstoreClientAPI {
1010
open static var basePath = "http://petstore.swagger.io:80/v2"
1111
open static var credential: URLCredential?
12-
open static var customHeaders: [String:String] = [:]
12+
open static var customHeaders: [String: String] = [:]
1313
open static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory()
1414
}
1515

1616
open class RequestBuilder<T> {
1717
var credential: URLCredential?
18-
var headers: [String:String]
19-
public let parameters: [String:Any]?
18+
var headers: [String: String]
19+
public let parameters: [String: Any]?
2020
public let isBody: Bool
2121
public let method: String
2222
public let URLString: String
2323

2424
/// Optional block to obtain a reference to the request's progress instance when available.
25-
public var onProgressReady: ((Progress) -> ())?
25+
public var onProgressReady: ((Progress) -> Void)?
2626

27-
required public init(method: String, URLString: String, parameters: [String:Any]?, isBody: Bool, headers: [String:String] = [:]) {
27+
public required init(method: String, URLString: String, parameters: [String: Any]?, isBody: Bool, headers: [String: String] = [:]) {
2828
self.method = method
2929
self.URLString = URLString
3030
self.parameters = parameters
@@ -34,13 +34,13 @@ open class RequestBuilder<T> {
3434
addHeaders(PetstoreClientAPI.customHeaders)
3535
}
3636

37-
open func addHeaders(_ aHeaders:[String:String]) {
37+
open func addHeaders(_ aHeaders: [String: String]) {
3838
for (header, value) in aHeaders {
3939
headers[header] = value
4040
}
4141
}
4242

43-
open func execute(_ completion: @escaping (_ response: Response<T>?, _ error: Error?) -> Void) { }
43+
open func execute(_: @escaping (_ response: Response<T>?, _ error: Error?) -> Void) {}
4444

4545
public func addHeader(name: String, value: String) -> Self {
4646
if !value.isEmpty {
@@ -50,12 +50,12 @@ open class RequestBuilder<T> {
5050
}
5151

5252
open func addCredential() -> Self {
53-
self.credential = PetstoreClientAPI.credential
53+
credential = PetstoreClientAPI.credential
5454
return self
5555
}
5656
}
5757

5858
public protocol RequestBuilderFactory {
5959
func getNonDecodableBuilder<T>() -> RequestBuilder<T>.Type
60-
func getBuilder<T:Decodable>() -> RequestBuilder<T>.Type
60+
func getBuilder<T: Decodable>() -> RequestBuilder<T>.Type
6161
}

samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,31 +5,28 @@
55
// https://openapi-generator.tech
66
//
77

8-
import Foundation
98
import Alamofire
10-
11-
9+
import Foundation
1210

1311
open class AnotherFakeAPI {
1412
/**
1513
To test special tags
16-
17-
- parameter client: (body) client model
14+
15+
- parameter client: (body) client model
1816
- parameter completion: completion handler to receive the data and the error objects
1917
*/
20-
open class func call123testSpecialTags(client: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) {
18+
open class func call123testSpecialTags(client: Client, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) {
2119
call123testSpecialTagsWithRequestBuilder(client: client).execute { (response, error) -> Void in
2220
completion(response?.body, error)
2321
}
2422
}
2523

26-
2724
/**
2825
To test special tags
2926
- PATCH /another-fake/dummy
3027
- To test special tags and operation ID starting with number
31-
- parameter client: (body) client model
32-
- returns: RequestBuilder<Client>
28+
- parameter client: (body) client model
29+
- returns: RequestBuilder<Client>
3330
*/
3431
open class func call123testSpecialTagsWithRequestBuilder(client: Client) -> RequestBuilder<Client> {
3532
let path = "/another-fake/dummy"
@@ -42,5 +39,4 @@ open class AnotherFakeAPI {
4239

4340
return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true)
4441
}
45-
4642
}

0 commit comments

Comments
 (0)