Skip to content

Commit

Permalink
Feat/generate init function (#108)
Browse files Browse the repository at this point in the history
* Fix coverage-related issues (#105)
* fix: change output folder to see if it fixes coveralls
* feat: add codecov
* fix: add codecov badge
* Update README.md
* feat: add initializer function to the class declaration
* chore: bump the version number
* chore: update readme and version
  • Loading branch information
insanoid authored Oct 6, 2019
1 parent 336aa09 commit dc9e802
Show file tree
Hide file tree
Showing 13 changed files with 137 additions and 34 deletions.
11 changes: 11 additions & 0 deletions Core/Generator/FileGeneratorExtension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,19 @@ extension FileGenerator {

if modelFile.type == .classType {
content = content.replacingOccurrences(of: "{REQUIRED}", with: "required ")
if modelFile.configuration?.shouldGenerateInitMethod == true {
let assignment = modelFile.component.initialiserFunctionComponent.map { doubleTab + $0.assignmentString }.joined(separator: "\n")
let functionParameters = modelFile.component.initialiserFunctionComponent.map { $0.functionParameter }.joined(separator: ", ")
let initialiserFunctionStatement = "\n\(singleTab)init (\(functionParameters)) {"
content = content.replacingOccurrences(of: "{INITIALIZER_FUNCTION_DECLRATION}", with: initialiserFunctionStatement)
content = content.replacingOccurrences(of: "{INITIALISER_FUNCTION_ASSIGNMENT}", with: assignment)
content = content.replacingOccurrences(of: "{INITIALISER_FUNCTION_END}", with: "\(singleTab)}\n")
}
} else {
content = content.replacingOccurrences(of: "{REQUIRED}", with: "")
content = content.replacingOccurrences(of: "{INITIALIZER_FUNCTION_DECLRATION}", with: "")
content = content.replacingOccurrences(of: "{INITIALISER_FUNCTION_ASSIGNMENT}", with: "")
content = content.replacingOccurrences(of: "{INITIALISER_FUNCTION_END}", with: "")
}
return content
}
Expand Down
8 changes: 8 additions & 0 deletions Core/Generator/Model-File-Components/ModelComponent.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,19 @@ internal struct ModelComponent {
var stringConstants: [String]
/// Initialisers for the properties.
var initialisers: [String]
// Initialiser function's assignment and function parameters for classes.
var initialiserFunctionComponent: [InitialiserFunctionComponent]

/// Initialise a blank model component structure.
init() {
declarations = []
stringConstants = []
initialisers = []
initialiserFunctionComponent = []
}
}

internal struct InitialiserFunctionComponent {
var functionParameter: String
var assignmentString: String
}
22 changes: 19 additions & 3 deletions Core/Generator/Model-File-Components/SwiftJSONModelFile.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ struct SwiftJSONModelFile: ModelFile {
component.stringConstants.append(genStringConstant(property.constantName, property.key))
component.declarations.append(genVariableDeclaration(property.name, type, isArray, isOptional))
component.initialisers.append(genInitializerForVariable(name: property.name, type: property.type, constantName: property.constantName, isOptional: isOptional, isArray: isArray, isObject: isObject))
component.initialiserFunctionComponent.append(genInitaliserFunctionAssignmentAndParams(property.name, type, isArray, isOptional))
case .nullType:
// Currently we do not deal with null values.
break
Expand Down Expand Up @@ -77,18 +78,33 @@ struct SwiftJSONModelFile: ModelFile {
return genPrimitiveVariableDeclaration(name, internalType, isOptional)
}

func genPrimitiveVariableDeclaration(_ name: String, _ type: String, _ isOptional: Bool) -> String {
if isOptional {
return "var \(name): \(type)?"
}
return "var \(name): \(type)"
}

/// Generate the variable declaration string
///
/// - Parameters:
/// - name: variable name to be used
/// - type: variable type to use
/// - isArray: Is the value an object
/// - Returns: A string to use as the declration
func genPrimitiveVariableDeclaration(_ name: String, _ type: String, _ isOptional: Bool) -> String {
func genInitaliserFunctionAssignmentAndParams(_ name: String, _ type: String, _ isArray: Bool, _ isOptional: Bool) -> InitialiserFunctionComponent {
var result = InitialiserFunctionComponent(functionParameter: "", assignmentString: "")
result.assignmentString = "self.\(name) = \(name)"

var typeString = type
if isArray {
typeString = "[\(typeString)]"
}
if isOptional {
return "var \(name): \(type)?"
typeString = "\(typeString)?"
}
return "var \(name): \(type)"
result.functionParameter = "\(name): \(typeString)"
return result
}

func genInitializerForVariable(name: String, type: String, constantName: String, isOptional: Bool, isArray: Bool, isObject _: Bool) -> String {
Expand Down
3 changes: 3 additions & 0 deletions Core/Generator/ModelGenerationConfiguration.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ struct ModelGenerationConfiguration {
var separateCodingKeys: Bool
/// Should header be included.
var variablesOptional: Bool
/// Should generate a init method for the class (applicable only to class).
var shouldGenerateInitMethod: Bool

mutating func defaultConfig() {
variablesOptional = true
Expand All @@ -37,5 +39,6 @@ struct ModelGenerationConfiguration {
prefix = ""
filePath = ""
baseClassName = ""
shouldGenerateInitMethod = true
}
}
6 changes: 5 additions & 1 deletion Core/Generator/MultipleModelGenerator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,9 @@ struct MultipleModelGenerator {
if let type = fromJSON["construct_type"].string, type == "struct" {
constructType = ConstructType.structType
}

let initialiserParameter = fromJSON["initaliser_needed"].bool
let initialisersNeeded = initialiserParameter != nil ? initialiserParameter! : true
let jsonLibrary = JSONMappingMethod.swiftNormal
let config = ModelGenerationConfiguration(filePath: fromJSON["destination_path"].string ?? "",
baseClassName: "",
Expand All @@ -158,7 +161,8 @@ struct MultipleModelGenerator {
constructType: constructType,
modelMappingLibrary: jsonLibrary,
separateCodingKeys: fromJSON["separate_coding_keys"].boolValue,
variablesOptional: fromJSON["variable_option"].boolValue)
variablesOptional: fromJSON["variable_option"].boolValue,
shouldGenerateInitMethod: initialisersNeeded)
return config
}

Expand Down
4 changes: 3 additions & 1 deletion Core/Template/BaseTemplate.txt
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ import Foundation
}

{DECLARATION}

{INITIALIZER_FUNCTION_DECLRATION}
{INITIALISER_FUNCTION_ASSIGNMENT}
{INITIALISER_FUNCTION_END}
{REQUIRED}init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
{INITIALIZER}
Expand Down
13 changes: 8 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,23 @@ Status](https://travis-ci.org/insanoid/SwiftyJSONAccelerator.svg?branch=master)]
![codecov](https://codecov.io/gh/insanoid/SwiftyJSONAccelerator/branch/master/graph/badge.svg)


**Version v2.1 Released! (Swift 5)**
**Version v2.2**

- Generate initializer function for classes
- **Application Download:** [Download the .app (v2.2.0)](https://github.com/insanoid/SwiftyJSONAccelerator/releases/download/v2.2.0/SwiftyJSONAccelerator.app.zip)

**Version v2.1**

- Tests are back - major parts of the code is covered.
- Multiple file model generator is working again.

**Version v2.0 Released! (Swift 5)**
**Version v2.0 (Swift 5)**

- Generates Swift 5 `Codeable` version along with `CodingKeys`.
- Allows support to switch between `Optional` and non-optional variations.
- Temporarily support for CLI and tests have been removed.
- UI now supports Dark mode!

- **Application Download:** [Download the .app (v2.1.0)](https://github.com/insanoid/SwiftyJSONAccelerator/releases/download/v2.1.0/SwiftyJSONAccelerator.app.zip)

## Installing & Building

- **Building:**
Expand All @@ -30,7 +33,7 @@ Status](https://travis-ci.org/insanoid/SwiftyJSONAccelerator.svg?branch=master)]

You will also need to install `SwiftFormat` with `brew install swiftformat` and `SwiftLint` with `brew install swiftlint`.

- **Application Only:** [Download the .app (v2.1.0)](https://github.com/insanoid/SwiftyJSONAccelerator/releases/download/v2.1.0/SwiftyJSONAccelerator.app.zip)
- **Application Only:** [Download the .app (v2.2.0)](https://github.com/insanoid/SwiftyJSONAccelerator/releases/download/v2.2.0/SwiftyJSONAccelerator.app.zip)

## Features

Expand Down
4 changes: 4 additions & 0 deletions SwiftyJSONAccelerator.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -713,13 +713,15 @@
CODE_SIGN_ENTITLEMENTS = SwiftyJSONAccelerator/Support/SwiftyJSONAccelerator.entitlements;
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 14;
DEVELOPMENT_TEAM = UYGU8PDBPS;
INFOPLIST_FILE = SwiftyJSONAccelerator/Support/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 10.11;
MARKETING_VERSION = 2.2;
PRODUCT_BUNDLE_IDENTIFIER = com.karthik.SwiftyJSONAccelerator;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
Expand All @@ -734,13 +736,15 @@
CODE_SIGN_ENTITLEMENTS = SwiftyJSONAccelerator/Support/SwiftyJSONAccelerator.entitlements;
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 14;
DEVELOPMENT_TEAM = UYGU8PDBPS;
INFOPLIST_FILE = SwiftyJSONAccelerator/Support/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 10.11;
MARKETING_VERSION = 2.2;
PRODUCT_BUNDLE_IDENTIFIER = com.karthik.SwiftyJSONAccelerator;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
Expand Down
6 changes: 2 additions & 4 deletions SwiftyJSONAccelerator/Support/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele
NSUserNotificationCenter.default.delegate = self
}

func applicationWillTerminate(_: Notification) {
// Insert code here to tear down your application
}
func applicationWillTerminate(_: Notification) {}

func userNotificationCenter(_: NSUserNotificationCenter, shouldPresent _: NSUserNotification) -> Bool {
// Since our notification is to be shown when app is in focus, this function always returns true.
Expand All @@ -27,7 +25,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele
guard let pathString = notification.userInfo![Constants.filePathKey] as? String else {
return
}
// Open the path for the notification.
// Open the path mentioned in the notification.
let urlPath = URL(fileURLWithPath: pathString, isDirectory: true)
if notification.activationType == .actionButtonClicked {
NSWorkspace.shared.activateFileViewerSelecting([urlPath])
Expand Down
Loading

0 comments on commit dc9e802

Please sign in to comment.