Skip to content

Add file post-processing to Swift 3.x, 4.x generators #1069

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Sep 20, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Schema;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.WordUtils;
Expand Down Expand Up @@ -242,6 +243,10 @@ protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, Sc
public void processOpts() {
super.processOpts();

if (StringUtils.isEmpty(System.getenv("SWIFT_POST_PROCESS_FILE"))) {
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)");
}

// Setup project name
if (additionalProperties.containsKey(PROJECT_NAME)) {
setProjectName((String) additionalProperties.get(PROJECT_NAME));
Expand Down Expand Up @@ -681,4 +686,31 @@ public String escapeQuotationMark(String input) {
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}

@Override
public void postProcessFile(File file, String fileType) {
if (file == null) {
return;
}
String swiftPostProcessFile = System.getenv("SWIFT_POST_PROCESS_FILE");
if (StringUtils.isEmpty(swiftPostProcessFile)) {
return; // skip if SWIFT_POST_PROCESS_FILE env variable is not defined
}

// only process files with swift extension
if ("swift".equals(FilenameUtils.getExtension(file.toString()))) {
String command = swiftPostProcessFile + " " + file.toString();
try {
Process p = Runtime.getRuntime().exec(command);
int exitValue = p.waitFor();
if (exitValue != 0) {
LOGGER.error("Error running the command ({}). Exit value: {}", command, exitValue);
} else {
LOGGER.info("Successfully executed: " + command);
}
} catch (Exception e) {
LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage());
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,15 @@

import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Schema;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.WordUtils;
import org.openapitools.codegen.*;
import org.openapitools.codegen.utils.ModelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.io.FilenameUtils;

import java.io.File;
import java.util.*;
Expand Down Expand Up @@ -296,6 +298,10 @@ protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel,
public void processOpts() {
super.processOpts();

if (StringUtils.isEmpty(System.getenv("SWIFT_POST_PROCESS_FILE"))) {
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)");
}

// Setup project name
if (additionalProperties.containsKey(PROJECT_NAME)) {
setProjectName((String) additionalProperties.get(PROJECT_NAME));
Expand Down Expand Up @@ -836,4 +842,30 @@ public String escapeQuotationMark(String input) {
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}

@Override
public void postProcessFile(File file, String fileType) {
if (file == null) {
return;
}
String swiftPostProcessFile = System.getenv("SWIFT_POST_PROCESS_FILE");
if (StringUtils.isEmpty(swiftPostProcessFile)) {
return; // skip if SWIFT_POST_PROCESS_FILE env variable is not defined
}
// only process files with swift extension
if ("swift".equals(FilenameUtils.getExtension(file.toString()))) {
String command = swiftPostProcessFile + " " + file.toString();
try {
Process p = Runtime.getRuntime().exec(command);
int exitValue = p.waitFor();
if (exitValue != 0) {
LOGGER.error("Error running the command ({}). Exit value: {}", command, exitValue);
} else {
LOGGER.info("Successfully executed: " + command);
}
} catch (Exception e) {
LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage());
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1 +1 @@
3.0.0-SNAPSHOT
3.3.0-SNAPSHOT
Original file line number Diff line number Diff line change
@@ -1 +1 @@
3.0.0-SNAPSHOT
3.3.0-SNAPSHOT
Original file line number Diff line number Diff line change
@@ -1 +1 @@
3.0.0-SNAPSHOT
3.3.0-SNAPSHOT
Original file line number Diff line number Diff line change
@@ -1 +1 @@
3.2.3-SNAPSHOT
3.3.0-SNAPSHOT
Original file line number Diff line number Diff line change
@@ -1 +1 @@
3.2.3-SNAPSHOT
3.3.0-SNAPSHOT
Original file line number Diff line number Diff line change
@@ -1 +1 @@
3.2.3-SNAPSHOT
3.3.0-SNAPSHOT
Original file line number Diff line number Diff line change
@@ -1 +1 @@
3.2.3-SNAPSHOT
3.3.0-SNAPSHOT
Original file line number Diff line number Diff line change
@@ -1 +1 @@
3.2.3-SNAPSHOT
3.3.0-SNAPSHOT
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
import Foundation

public struct APIHelper {
public static func rejectNil(_ source: [String:Any?]) -> [String:Any]? {
let destination = source.reduce(into: [String: Any]()) { (result, item) in
public static func rejectNil(_ source: [String: Any?]) -> [String: Any]? {
let destination = source.reduce(into: [String: Any]()) { result, item in
if let value = item.value {
result[item.key] = value
}
Expand All @@ -20,22 +20,22 @@ public struct APIHelper {
return destination
}

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

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

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


public static func mapValuesToQueryItems(_ source: [String:Any?]) -> [URLQueryItem]? {
let destination = source.filter({ $0.value != nil}).reduce(into: [URLQueryItem]()) { (result, item) in
public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? {
let destination = source.filter({ $0.value != nil }).reduce(into: [URLQueryItem]()) { result, item in
if let collection = item.value as? Array<Any?> {
let value = collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",")
let value = collection.filter({ $0 != nil }).map({ "\($0!)" }).joined(separator: ",")
result.append(URLQueryItem(name: item.key, value: value))
} else if let value = item.value {
result.append(URLQueryItem(name: item.key, value: "\(value)"))
Expand All @@ -62,4 +61,3 @@ public struct APIHelper {
return destination
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,22 @@ import Foundation
open class PetstoreClientAPI {
open static var basePath = "http://petstore.swagger.io:80/v2"
open static var credential: URLCredential?
open static var customHeaders: [String:String] = [:]
open static var customHeaders: [String: String] = [:]
open static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory()
}

open class RequestBuilder<T> {
var credential: URLCredential?
var headers: [String:String]
public let parameters: [String:Any]?
var headers: [String: String]
public let parameters: [String: Any]?
public let isBody: Bool
public let method: String
public let URLString: String

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

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

open func addHeaders(_ aHeaders:[String:String]) {
open func addHeaders(_ aHeaders: [String: String]) {
for (header, value) in aHeaders {
headers[header] = value
}
}

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

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

open func addCredential() -> Self {
self.credential = PetstoreClientAPI.credential
credential = PetstoreClientAPI.credential
return self
}
}

public protocol RequestBuilderFactory {
func getNonDecodableBuilder<T>() -> RequestBuilder<T>.Type
func getBuilder<T:Decodable>() -> RequestBuilder<T>.Type
func getBuilder<T: Decodable>() -> RequestBuilder<T>.Type
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,31 +5,28 @@
// https://openapi-generator.tech
//

import Foundation
import Alamofire


import Foundation

open class AnotherFakeAPI {
/**
To test special tags
- parameter client: (body) client model

- parameter client: (body) client model
- parameter completion: completion handler to receive the data and the error objects
*/
open class func call123testSpecialTags(client: Client, completion: @escaping ((_ data: Client?,_ error: Error?) -> Void)) {
open class func call123testSpecialTags(client: Client, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) {
call123testSpecialTagsWithRequestBuilder(client: client).execute { (response, error) -> Void in
completion(response?.body, error)
}
}


/**
To test special tags
- PATCH /another-fake/dummy
- To test special tags and operation ID starting with number
- parameter client: (body) client model
- returns: RequestBuilder<Client>
- parameter client: (body) client model
- returns: RequestBuilder<Client>
*/
open class func call123testSpecialTagsWithRequestBuilder(client: Client) -> RequestBuilder<Client> {
let path = "/another-fake/dummy"
Expand All @@ -42,5 +39,4 @@ open class AnotherFakeAPI {

return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true)
}

}
Loading