Skip to content

Commit dc9e802

Browse files
authored
Feat/generate init function (#108)
* 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
1 parent 336aa09 commit dc9e802

File tree

13 files changed

+137
-34
lines changed

13 files changed

+137
-34
lines changed

Core/Generator/FileGeneratorExtension.swift

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,19 @@ extension FileGenerator {
3333

3434
if modelFile.type == .classType {
3535
content = content.replacingOccurrences(of: "{REQUIRED}", with: "required ")
36+
if modelFile.configuration?.shouldGenerateInitMethod == true {
37+
let assignment = modelFile.component.initialiserFunctionComponent.map { doubleTab + $0.assignmentString }.joined(separator: "\n")
38+
let functionParameters = modelFile.component.initialiserFunctionComponent.map { $0.functionParameter }.joined(separator: ", ")
39+
let initialiserFunctionStatement = "\n\(singleTab)init (\(functionParameters)) {"
40+
content = content.replacingOccurrences(of: "{INITIALIZER_FUNCTION_DECLRATION}", with: initialiserFunctionStatement)
41+
content = content.replacingOccurrences(of: "{INITIALISER_FUNCTION_ASSIGNMENT}", with: assignment)
42+
content = content.replacingOccurrences(of: "{INITIALISER_FUNCTION_END}", with: "\(singleTab)}\n")
43+
}
3644
} else {
3745
content = content.replacingOccurrences(of: "{REQUIRED}", with: "")
46+
content = content.replacingOccurrences(of: "{INITIALIZER_FUNCTION_DECLRATION}", with: "")
47+
content = content.replacingOccurrences(of: "{INITIALISER_FUNCTION_ASSIGNMENT}", with: "")
48+
content = content.replacingOccurrences(of: "{INITIALISER_FUNCTION_END}", with: "")
3849
}
3950
return content
4051
}

Core/Generator/Model-File-Components/ModelComponent.swift

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,19 @@ internal struct ModelComponent {
1616
var stringConstants: [String]
1717
/// Initialisers for the properties.
1818
var initialisers: [String]
19+
// Initialiser function's assignment and function parameters for classes.
20+
var initialiserFunctionComponent: [InitialiserFunctionComponent]
1921

2022
/// Initialise a blank model component structure.
2123
init() {
2224
declarations = []
2325
stringConstants = []
2426
initialisers = []
27+
initialiserFunctionComponent = []
2528
}
2629
}
30+
31+
internal struct InitialiserFunctionComponent {
32+
var functionParameter: String
33+
var assignmentString: String
34+
}

Core/Generator/Model-File-Components/SwiftJSONModelFile.swift

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ struct SwiftJSONModelFile: ModelFile {
4343
component.stringConstants.append(genStringConstant(property.constantName, property.key))
4444
component.declarations.append(genVariableDeclaration(property.name, type, isArray, isOptional))
4545
component.initialisers.append(genInitializerForVariable(name: property.name, type: property.type, constantName: property.constantName, isOptional: isOptional, isArray: isArray, isObject: isObject))
46+
component.initialiserFunctionComponent.append(genInitaliserFunctionAssignmentAndParams(property.name, type, isArray, isOptional))
4647
case .nullType:
4748
// Currently we do not deal with null values.
4849
break
@@ -77,18 +78,33 @@ struct SwiftJSONModelFile: ModelFile {
7778
return genPrimitiveVariableDeclaration(name, internalType, isOptional)
7879
}
7980

81+
func genPrimitiveVariableDeclaration(_ name: String, _ type: String, _ isOptional: Bool) -> String {
82+
if isOptional {
83+
return "var \(name): \(type)?"
84+
}
85+
return "var \(name): \(type)"
86+
}
87+
8088
/// Generate the variable declaration string
8189
///
8290
/// - Parameters:
8391
/// - name: variable name to be used
8492
/// - type: variable type to use
8593
/// - isArray: Is the value an object
8694
/// - Returns: A string to use as the declration
87-
func genPrimitiveVariableDeclaration(_ name: String, _ type: String, _ isOptional: Bool) -> String {
95+
func genInitaliserFunctionAssignmentAndParams(_ name: String, _ type: String, _ isArray: Bool, _ isOptional: Bool) -> InitialiserFunctionComponent {
96+
var result = InitialiserFunctionComponent(functionParameter: "", assignmentString: "")
97+
result.assignmentString = "self.\(name) = \(name)"
98+
99+
var typeString = type
100+
if isArray {
101+
typeString = "[\(typeString)]"
102+
}
88103
if isOptional {
89-
return "var \(name): \(type)?"
104+
typeString = "\(typeString)?"
90105
}
91-
return "var \(name): \(type)"
106+
result.functionParameter = "\(name): \(typeString)"
107+
return result
92108
}
93109

94110
func genInitializerForVariable(name: String, type: String, constantName: String, isOptional: Bool, isArray: Bool, isObject _: Bool) -> String {

Core/Generator/ModelGenerationConfiguration.swift

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ struct ModelGenerationConfiguration {
2828
var separateCodingKeys: Bool
2929
/// Should header be included.
3030
var variablesOptional: Bool
31+
/// Should generate a init method for the class (applicable only to class).
32+
var shouldGenerateInitMethod: Bool
3133

3234
mutating func defaultConfig() {
3335
variablesOptional = true
@@ -37,5 +39,6 @@ struct ModelGenerationConfiguration {
3739
prefix = ""
3840
filePath = ""
3941
baseClassName = ""
42+
shouldGenerateInitMethod = true
4043
}
4144
}

Core/Generator/MultipleModelGenerator.swift

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,9 @@ struct MultipleModelGenerator {
149149
if let type = fromJSON["construct_type"].string, type == "struct" {
150150
constructType = ConstructType.structType
151151
}
152+
153+
let initialiserParameter = fromJSON["initaliser_needed"].bool
154+
let initialisersNeeded = initialiserParameter != nil ? initialiserParameter! : true
152155
let jsonLibrary = JSONMappingMethod.swiftNormal
153156
let config = ModelGenerationConfiguration(filePath: fromJSON["destination_path"].string ?? "",
154157
baseClassName: "",
@@ -158,7 +161,8 @@ struct MultipleModelGenerator {
158161
constructType: constructType,
159162
modelMappingLibrary: jsonLibrary,
160163
separateCodingKeys: fromJSON["separate_coding_keys"].boolValue,
161-
variablesOptional: fromJSON["variable_option"].boolValue)
164+
variablesOptional: fromJSON["variable_option"].boolValue,
165+
shouldGenerateInitMethod: initialisersNeeded)
162166
return config
163167
}
164168

Core/Template/BaseTemplate.txt

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@ import Foundation
1414
}
1515

1616
{DECLARATION}
17-
17+
{INITIALIZER_FUNCTION_DECLRATION}
18+
{INITIALISER_FUNCTION_ASSIGNMENT}
19+
{INITIALISER_FUNCTION_END}
1820
{REQUIRED}init(from decoder: Decoder) throws {
1921
let container = try decoder.container(keyedBy: CodingKeys.self)
2022
{INITIALIZER}

README.md

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,20 +7,23 @@ Status](https://travis-ci.org/insanoid/SwiftyJSONAccelerator.svg?branch=master)]
77
![codecov](https://codecov.io/gh/insanoid/SwiftyJSONAccelerator/branch/master/graph/badge.svg)
88

99

10-
**Version v2.1 Released! (Swift 5)**
10+
**Version v2.2**
11+
12+
- Generate initializer function for classes
13+
- **Application Download:** [Download the .app (v2.2.0)](https://github.com/insanoid/SwiftyJSONAccelerator/releases/download/v2.2.0/SwiftyJSONAccelerator.app.zip)
14+
15+
**Version v2.1**
1116

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

15-
**Version v2.0 Released! (Swift 5)**
20+
**Version v2.0 (Swift 5)**
1621

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

22-
- **Application Download:** [Download the .app (v2.1.0)](https://github.com/insanoid/SwiftyJSONAccelerator/releases/download/v2.1.0/SwiftyJSONAccelerator.app.zip)
23-
2427
## Installing & Building
2528

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

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

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

3538
## Features
3639

SwiftyJSONAccelerator.xcodeproj/project.pbxproj

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -713,13 +713,15 @@
713713
CODE_SIGN_ENTITLEMENTS = SwiftyJSONAccelerator/Support/SwiftyJSONAccelerator.entitlements;
714714
CODE_SIGN_STYLE = Automatic;
715715
COMBINE_HIDPI_IMAGES = YES;
716+
CURRENT_PROJECT_VERSION = 14;
716717
DEVELOPMENT_TEAM = UYGU8PDBPS;
717718
INFOPLIST_FILE = SwiftyJSONAccelerator/Support/Info.plist;
718719
LD_RUNPATH_SEARCH_PATHS = (
719720
"$(inherited)",
720721
"@executable_path/../Frameworks",
721722
);
722723
MACOSX_DEPLOYMENT_TARGET = 10.11;
724+
MARKETING_VERSION = 2.2;
723725
PRODUCT_BUNDLE_IDENTIFIER = com.karthik.SwiftyJSONAccelerator;
724726
PRODUCT_NAME = "$(TARGET_NAME)";
725727
SWIFT_VERSION = 5.0;
@@ -734,13 +736,15 @@
734736
CODE_SIGN_ENTITLEMENTS = SwiftyJSONAccelerator/Support/SwiftyJSONAccelerator.entitlements;
735737
CODE_SIGN_STYLE = Automatic;
736738
COMBINE_HIDPI_IMAGES = YES;
739+
CURRENT_PROJECT_VERSION = 14;
737740
DEVELOPMENT_TEAM = UYGU8PDBPS;
738741
INFOPLIST_FILE = SwiftyJSONAccelerator/Support/Info.plist;
739742
LD_RUNPATH_SEARCH_PATHS = (
740743
"$(inherited)",
741744
"@executable_path/../Frameworks",
742745
);
743746
MACOSX_DEPLOYMENT_TARGET = 10.11;
747+
MARKETING_VERSION = 2.2;
744748
PRODUCT_BUNDLE_IDENTIFIER = com.karthik.SwiftyJSONAccelerator;
745749
PRODUCT_NAME = "$(TARGET_NAME)";
746750
SWIFT_VERSION = 5.0;

SwiftyJSONAccelerator/Support/AppDelegate.swift

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele
1414
NSUserNotificationCenter.default.delegate = self
1515
}
1616

17-
func applicationWillTerminate(_: Notification) {
18-
// Insert code here to tear down your application
19-
}
17+
func applicationWillTerminate(_: Notification) {}
2018

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

0 commit comments

Comments
 (0)