Compare commits
30 Commits
v1.1
...
abb7c8f8c8
Author | SHA1 | Date | |
---|---|---|---|
abb7c8f8c8 | |||
92626b76ad | |||
449f16499b | |||
cd873ca5d9 | |||
6f8e3b6664 | |||
1f2933950b | |||
3b90387e10 | |||
1ee4998ec6 | |||
ca763cd5d0 | |||
3fc2fd9bac | |||
09c153ba65 | |||
2a144fc00e | |||
6aef8bc2de | |||
3e133773a9 | |||
5fd680110c | |||
ce274219fc | |||
fa5bf192e8 | |||
1a45ec7b0d | |||
7d6bb4fcb9 | |||
844a8aec45 | |||
beb28e652d | |||
78be15d57d | |||
d6c4702390 | |||
1e073af5df | |||
188178fe6a | |||
c31d0b1618 | |||
b662fc64f3 | |||
9ab7e74991 | |||
fc427733ee | |||
5a3d273acc |
@ -102,6 +102,20 @@
|
||||
ReferencedContainer = "container:">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
<CommandLineArguments>
|
||||
<CommandLineArgument
|
||||
argument = "generate"
|
||||
isEnabled = "YES">
|
||||
</CommandLineArgument>
|
||||
<CommandLineArgument
|
||||
argument = ""$(PROJECT_DIR)/../SampleFiles/resgenConfiguration.yml""
|
||||
isEnabled = "YES">
|
||||
</CommandLineArgument>
|
||||
<CommandLineArgument
|
||||
argument = "--project-directory "$(PROJECT_DIR)""
|
||||
isEnabled = "YES">
|
||||
</CommandLineArgument>
|
||||
</CommandLineArguments>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
|
34
CHANGELOG.md
34
CHANGELOG.md
@ -0,0 +1,34 @@
|
||||
# v1.2 - Architecture generation
|
||||
|
||||
## New
|
||||
- New section in configuration file: `architecture`. Define your ressources accessors achitecture and let ResgenSwift generate it for you. Check out Readme to know more.
|
||||
|
||||
## Fixes
|
||||
- Errors and Warnings are now shown in Xcode Issue Navigator
|
||||
|
||||
---
|
||||
# v1.1 - SwiftUI compatibility
|
||||
|
||||
## New
|
||||
- Update plist `UIAppFonts` when generated fonts (use plistBuddy)
|
||||
- New parameter: `infoPlistPaths`
|
||||
- Generate SwiftUI extensions for colors, fonts and images
|
||||
- New parameter: `extensionNameUIKit`
|
||||
- Adding Makefile to install, unsintall and create man page.
|
||||
|
||||
## Fixes
|
||||
Fix SwiftLint rule `trailing_newline`
|
||||
|
||||
---
|
||||
# v1.0 - Configuration file
|
||||
|
||||
## Major
|
||||
- A new command has been added: `generate`. Instead of runnning every single command, it will run all necessary command based on a `yaml` configuration file. Check out Readme to know more.
|
||||
|
||||
## Minors
|
||||
- Code refactoring
|
||||
- Huge performance improvements
|
||||
- Readme.md update
|
||||
- Add option to generate static properties/methods (`staticMembers`)
|
||||
- Add option to specify the project directory (`--project-directory`). It allows to run ResgenSwift from anywhere
|
||||
- Add `install.sh` script to install ResgenSwift in `/usr/local/bin`
|
||||
|
2
Jenkinsfile
vendored
2
Jenkinsfile
vendored
@ -1,6 +1,6 @@
|
||||
library "openiumpipeline"
|
||||
|
||||
env.DEVELOPER_DIR="/Applications/Xcode_13.3.0.app/Contents/Developer"
|
||||
env.DEVELOPER_DIR="/Applications/Xcode-15.0.1.app/Contents/Developer"
|
||||
//env.SIMULATOR_DEVICE_TYPES="iPad--7th-generation-"
|
||||
env.IS_PACKAGE_SWIFT=1
|
||||
env.TARGETS_MACOS=1
|
||||
|
@ -1,12 +1,75 @@
|
||||
{
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "collectionconcurrencykit",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/JohnSundell/CollectionConcurrencyKit.git",
|
||||
"state" : {
|
||||
"revision" : "b4f23e24b5a1bff301efc5e70871083ca029ff95",
|
||||
"version" : "0.2.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "cryptoswift",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/krzyzanowskim/CryptoSwift.git",
|
||||
"state" : {
|
||||
"revision" : "db51c407d3be4a051484a141bf0bff36c43d3b1e",
|
||||
"version" : "1.8.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "sourcekitten",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/jpsim/SourceKitten.git",
|
||||
"state" : {
|
||||
"revision" : "b6dc09ee51dfb0c66e042d2328c017483a1a5d56",
|
||||
"version" : "0.34.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swift-argument-parser",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/apple/swift-argument-parser",
|
||||
"state" : {
|
||||
"revision" : "9f39744e025c7d377987f30b03770805dcb0bcd1",
|
||||
"version" : "1.1.4"
|
||||
"revision" : "8f4d2753f0e4778c76d5f05ad16c74f707390531",
|
||||
"version" : "1.2.3"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swift-syntax",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/apple/swift-syntax.git",
|
||||
"state" : {
|
||||
"revision" : "6ad4ea24b01559dde0773e3d091f1b9e36175036",
|
||||
"version" : "509.0.2"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swiftlint",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/realm/SwiftLint.git",
|
||||
"state" : {
|
||||
"revision" : "f17a4f9dfb6a6afb0408426354e4180daaf49cee",
|
||||
"version" : "0.54.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swiftytexttable",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/scottrhoyt/SwiftyTextTable.git",
|
||||
"state" : {
|
||||
"revision" : "c6df6cf533d120716bff38f8ff9885e1ce2a4ac3",
|
||||
"version" : "0.9.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "swxmlhash",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/drmohundro/SWXMLHash.git",
|
||||
"state" : {
|
||||
"revision" : "a853604c9e9a83ad9954c7e3d2a565273982471f",
|
||||
"version" : "7.0.2"
|
||||
}
|
||||
},
|
||||
{
|
||||
@ -14,8 +77,8 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/jpsim/Yams.git",
|
||||
"state" : {
|
||||
"revision" : "01835dc202670b5bb90d07f3eae41867e9ed29f6",
|
||||
"version" : "5.0.1"
|
||||
"revision" : "0d9ee7ea8c4ebd4a489ad7a73d5c6cad55d6fed3",
|
||||
"version" : "5.0.6"
|
||||
}
|
||||
}
|
||||
],
|
||||
|
@ -9,7 +9,8 @@ let package = Package(
|
||||
dependencies: [
|
||||
// Dependencies declare other packages that this package depends on.
|
||||
.package(url: "https://github.com/apple/swift-argument-parser", from: "1.0.0"),
|
||||
.package(url: "https://github.com/jpsim/Yams.git", from: "5.0.1")
|
||||
.package(url: "https://github.com/jpsim/Yams.git", from: "5.0.1"),
|
||||
.package(url: "https://github.com/realm/SwiftLint.git", .upToNextMajor(from: "0.54.0")),
|
||||
],
|
||||
targets: [
|
||||
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
|
||||
@ -20,7 +21,8 @@ let package = Package(
|
||||
"ToolCore",
|
||||
.product(name: "ArgumentParser", package: "swift-argument-parser"),
|
||||
"Yams"
|
||||
]
|
||||
],
|
||||
plugins: [.plugin(name: "SwiftLintPlugin", package: "SwiftLint")]
|
||||
),
|
||||
|
||||
// Helper targets
|
||||
|
89
README.md
89
README.md
@ -16,7 +16,7 @@ iOS required to use the **real name** of the font, this name can be different fr
|
||||
swift run -c release ResgenSwift fonts $FORCE_FLAG "./Fonts/fonts.txt" \
|
||||
--extension-output-path "./Fonts/Generated" \
|
||||
--extension-name "AppFont" \
|
||||
--extension-name-swift-ui "SUIAppFont" \
|
||||
--extension-name-ui-kit "UIAppFont" \
|
||||
--extension-suffix "GreatApp" \
|
||||
--static-members true \
|
||||
--info-plist-paths "./path/one/to/Info.plist ./path/two/to/Info.plist"
|
||||
@ -27,8 +27,8 @@ swift run -c release ResgenSwift fonts $FORCE_FLAG "./Fonts/fonts.txt" \
|
||||
1. `-f`: force generation
|
||||
2. Font input folder, it will search for every `.ttf` and `.otf` files specified in `fonts.txt`
|
||||
3. `--extension-output-path`: path where to generate generated extension
|
||||
4. `--extension-name` *(optional)* : name of the class to add UIKit getters
|
||||
5. `--extension-name-swift-ui` *(optional)* : name of the class to add SwiftUI getters
|
||||
4. `--extension-name` *(optional)* : name of the class to add SwiftUI getters
|
||||
5. `--extension-name-ui-kit` *(optional)* : name of the class to add UIKit getters
|
||||
6. `--extension-suffix` *(optional)* : additional text which is added to the filename (ex: `AppFont+GreatApp.swift`)
|
||||
7. `--static-members` *(optional)*: generate static properties or not
|
||||
8. `--info-plist-paths` *(optional)*: array of `.plist`, you can specify multiple `Info.plist` for multiple targets
|
||||
@ -44,7 +44,7 @@ swift run -c release ResgenSwift colors $FORCE_FLAG "./Colors/colors.txt" \
|
||||
--xcassets-path "./Colors/colors.xcassets" \
|
||||
--extension-output-path "./Colors/Generated/" \
|
||||
--extension-name "AppColor" \
|
||||
--extension-name-swift-ui "SUIAppColor" \
|
||||
--extension-name-ui-kit "UIAppColor" \
|
||||
--extension-suffix "GreatApp" \
|
||||
--static-members true
|
||||
```
|
||||
@ -55,8 +55,8 @@ swift run -c release ResgenSwift colors $FORCE_FLAG "./Colors/colors.txt" \
|
||||
2. Input colors file
|
||||
3. `--style` can be `all` or `light`
|
||||
4. `--extension-output-path`: path where to generate generated extension
|
||||
5. `--extension-name` *(optional)* : name of the class to add UIKit getters
|
||||
6. `--extension-name-swift-ui` *(optional)* : name of the class to add SwiftUI getters
|
||||
5. `--extension-name` *(optional)* : name of the class to add SwiftUI getters
|
||||
6. `--extension-name-ui-kit` *(optional)* : name of the class to add UIKit getters
|
||||
7. `--extension-suffix` *(optional)* : additional text which is added to filename (ex: `AppColor+GreatApp.swift`)
|
||||
8. `--static-members` *(optional)*: generate static properties or not
|
||||
|
||||
@ -142,7 +142,7 @@ swift run -c release ResgenSwift images $FORCE_FLAG "./Images/images.txt" \
|
||||
--xcassets-path "./Images/app.xcassets" \
|
||||
--extension-output-path "./Images/Generated" \
|
||||
--extension-name "AppImage" \
|
||||
--extension-name-swift-ui "SUIAppImage" \
|
||||
--extension-name-ui-kit "UIAppImage" \
|
||||
--extension-suffix "GreatApp" \
|
||||
--static-members true
|
||||
```
|
||||
@ -153,8 +153,8 @@ swift run -c release ResgenSwift images $FORCE_FLAG "./Images/images.txt" \
|
||||
2. Input images definitions file
|
||||
3. `--xcassets-path`: xcasset path where to generate imagesets
|
||||
4. `--extension-output-path`: path where to generate generated extension
|
||||
5. `--extension-name` *(optional)* : name of the class to add UIKit getters
|
||||
6. `--extension-name-swift-ui` *(optional)* : name of the class to add SwiftUI getters
|
||||
5. `--extension-name` *(optional)* : name of the class to add SwiftUI getters
|
||||
6. `--extension-name-ui-kit` *(optional)* : name of the class to add UIKit getters
|
||||
6. `--extension-suffix` *(optional)* : additional text which is added to filename (ex: `AppImage+GreatApp.swift`)
|
||||
7. `--static-members` *(optional)*: generate static properties or not
|
||||
|
||||
@ -176,7 +176,7 @@ colors:
|
||||
xcassetsPath: String
|
||||
extensionOutputPath: String
|
||||
extensionName: String?
|
||||
extensionNameSwiftUI: String?
|
||||
extensionNameUIKit: String?
|
||||
extensionSuffix: String?
|
||||
staticMembers: Bool?
|
||||
|
||||
@ -185,7 +185,7 @@ fonts:
|
||||
inputFile: String
|
||||
extensionOutputPath: String
|
||||
extensionName: String?
|
||||
extensionNameSwiftUI: String?
|
||||
extensionNameUIKit: String?
|
||||
extensionSuffix: String?
|
||||
staticMembers: Bool?
|
||||
infoPlistPaths: [String]
|
||||
@ -196,7 +196,7 @@ images:
|
||||
xcassetsPath: String
|
||||
extensionOutputPath: String
|
||||
extensionName: String?
|
||||
extensionNameSwiftUI: String?
|
||||
extensionNameUIKit: String?
|
||||
extensionSuffix: String?
|
||||
staticMembers: Bool?
|
||||
|
||||
@ -236,7 +236,7 @@ colors:
|
||||
xcassetsPath: String
|
||||
extensionOutputPath: String
|
||||
extensionName: String?
|
||||
extensionNameSwiftUI: String?
|
||||
extensionNameUIKit: String?
|
||||
extensionSuffix: String?
|
||||
staticMembers: Bool?
|
||||
-
|
||||
@ -245,7 +245,7 @@ colors:
|
||||
xcassetsPath: String
|
||||
extensionOutputPath: String
|
||||
extensionName: String?
|
||||
extensionNameSwiftUI: String?
|
||||
extensionNameUIKit: String?
|
||||
extensionSuffix: String?
|
||||
staticMembers: Bool?
|
||||
...
|
||||
@ -261,6 +261,67 @@ tags: []
|
||||
...
|
||||
```
|
||||
|
||||
### File architecture
|
||||
|
||||
ResgenSwift generate extension of classes. Those classes must exists in your project. You can create them yourself OR you can let ResgenSwift create them by specifying what you want. Do as follow:
|
||||
|
||||
```
|
||||
architecture:
|
||||
property: R *(required but not used)*
|
||||
classname: R
|
||||
path: ./path/to/generate
|
||||
children:
|
||||
- property: images
|
||||
classname: R2Image
|
||||
- property: strings
|
||||
classname: R2String
|
||||
- property: fonts
|
||||
classname: R2Font
|
||||
- property: images
|
||||
classname: R2Image
|
||||
- property: uikit
|
||||
classname: R2UI
|
||||
children:
|
||||
- property: images
|
||||
classname: R2UIImage
|
||||
- property: fonts
|
||||
classname: R2UIFont
|
||||
- property: images
|
||||
classname: R2UIImage
|
||||
```
|
||||
|
||||
This will generate a file named as the architecture classname: `R.swift`. Based on the previous architecture, it will generate:
|
||||
```
|
||||
class R {
|
||||
static let images = R2Image()
|
||||
static let strings = R2String()
|
||||
static let fonts = R2Font()
|
||||
static let images = R2Image()
|
||||
static let uikit = R2UI()
|
||||
}
|
||||
|
||||
class R2Image {}
|
||||
|
||||
class R2String {}
|
||||
|
||||
class R2Font {}
|
||||
|
||||
class R2Image {}
|
||||
|
||||
class R2UI {
|
||||
let images = R2UIImage()
|
||||
let fonts = R2UIFont()
|
||||
let images = R2UIImage()
|
||||
}
|
||||
|
||||
class R2UIImage {}
|
||||
|
||||
class R2UIFont {}
|
||||
|
||||
class R2UIImage {}
|
||||
```
|
||||
|
||||
|
||||
### Usage
|
||||
|
||||
```sh
|
||||
|
@ -1,4 +1,4 @@
|
||||
// Generated by ResgenSwift.Color 1.0
|
||||
// Generated by ResgenSwift.Color 1.2
|
||||
|
||||
import SwiftUI
|
||||
|
||||
|
@ -1,4 +1,4 @@
|
||||
// Generated by ResgenSwift.Color 1.0
|
||||
// Generated by ResgenSwift.Color 1.2
|
||||
|
||||
import UIKit
|
||||
|
||||
|
@ -1,4 +1,4 @@
|
||||
// Generated by ResgenSwift.Fonts 1.0
|
||||
// Generated by ResgenSwift.Fonts 1.2
|
||||
|
||||
import SwiftUI
|
||||
|
||||
|
@ -1,4 +1,4 @@
|
||||
// Generated by ResgenSwift.Fonts 1.0
|
||||
// Generated by ResgenSwift.Fonts 1.2
|
||||
|
||||
import UIKit
|
||||
|
||||
|
@ -1,4 +1,4 @@
|
||||
// Generated by ResgenSwift.Images 1.0
|
||||
// Generated by ResgenSwift.Images 1.2
|
||||
// Images from sampleImages
|
||||
|
||||
import SwiftUI
|
||||
|
@ -1,4 +1,4 @@
|
||||
// Generated by ResgenSwift.Images 1.0
|
||||
// Generated by ResgenSwift.Images 1.2
|
||||
// Images from sampleImages
|
||||
|
||||
import UIKit
|
||||
|
@ -1,4 +1,4 @@
|
||||
// Generated by ResgenSwift.Strings.Stringium 1.0
|
||||
// Generated by ResgenSwift.Strings.Stringium 1.2
|
||||
|
||||
import UIKit
|
||||
|
||||
@ -6,6 +6,26 @@ fileprivate let kStringsFileName = "sampleStrings"
|
||||
|
||||
extension String {
|
||||
|
||||
enum KeyGenAllScript: String {
|
||||
case param_lang = "param_lang"
|
||||
case generic_back = "generic_back"
|
||||
case generic_loading_data = "generic_loading_data"
|
||||
case generic_welcome_firstname_format = "generic_welcome_firstname_format"
|
||||
case test_equal_symbol = "test_equal_symbol"
|
||||
case placeholders_test_one = "placeholders_test_one"
|
||||
|
||||
var keyPath: KeyPath<String, String> {
|
||||
switch self {
|
||||
case .param_lang: return \String.param_lang
|
||||
case .generic_back: return \String.generic_back
|
||||
case .generic_loading_data: return \String.generic_loading_data
|
||||
case .generic_welcome_firstname_format: return \String.generic_welcome_firstname_format
|
||||
case .test_equal_symbol: return \String.test_equal_symbol
|
||||
case .placeholders_test_one: return \String.placeholders_test_one
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Webservice
|
||||
|
||||
/// Translation in en :
|
||||
|
@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Apple Strings File
|
||||
* Generated by ResgenSwift 1.0
|
||||
* Generated by ResgenSwift 1.2
|
||||
* Language: en-us
|
||||
*/
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Apple Strings File
|
||||
* Generated by ResgenSwift 1.0
|
||||
* Generated by ResgenSwift 1.2
|
||||
* Language: en
|
||||
*/
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Apple Strings File
|
||||
* Generated by ResgenSwift 1.0
|
||||
* Generated by ResgenSwift 1.2
|
||||
* Language: fr
|
||||
*/
|
||||
|
||||
|
196
SampleFiles/Tags/Generated/Analytics+GenAllScript.swift
Normal file
196
SampleFiles/Tags/Generated/Analytics+GenAllScript.swift
Normal file
@ -0,0 +1,196 @@
|
||||
// Generated by ResgenSwift.Analytics 1.2
|
||||
|
||||
import MatomoTracker
|
||||
import FirebaseAnalytics
|
||||
|
||||
// MARK: - Protocol
|
||||
|
||||
protocol AnalyticsManagerProtocol {
|
||||
func logScreen(name: String, path: String)
|
||||
func logEvent(
|
||||
name: String,
|
||||
action: String,
|
||||
category: String,
|
||||
params: [String: Any]?
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Matomo
|
||||
|
||||
class MatomoAnalyticsManager: AnalyticsManagerProtocol {
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
private var tracker: MatomoTracker
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
init(siteId: String, url: String) {
|
||||
debugPrint("[Matomo service] Server URL: \(url)")
|
||||
debugPrint("[Matomo service] Site ID: \(siteId)")
|
||||
tracker = MatomoTracker(
|
||||
siteId: siteId,
|
||||
baseURL: URL(string: url)!
|
||||
)
|
||||
|
||||
#if DEBUG
|
||||
tracker.dispatchInterval = 5
|
||||
#endif
|
||||
|
||||
#if DEBUG
|
||||
tracker.logger = DefaultLogger(minLevel: .verbose)
|
||||
#endif
|
||||
|
||||
debugPrint("[Matomo service] Configured with content base: \(tracker.contentBase?.absoluteString ?? "-")")
|
||||
debugPrint("[Matomo service] Opt out: \(tracker.isOptedOut)")
|
||||
}
|
||||
|
||||
// MARK: - Methods
|
||||
|
||||
func logScreen(name: String, path: String) {
|
||||
guard !tracker.isOptedOut else { return }
|
||||
guard let trackerUrl = tracker.contentBase?.absoluteString else { return }
|
||||
|
||||
let urlString = URL(string: "\(trackerUrl)" + "/" + "\(path)" + "iOS")
|
||||
tracker.track(
|
||||
view: [name],
|
||||
url: urlString
|
||||
)
|
||||
}
|
||||
|
||||
func logEvent(
|
||||
name: String,
|
||||
action: String,
|
||||
category: String,
|
||||
params: [String: Any]?
|
||||
) {
|
||||
guard !tracker.isOptedOut else { return }
|
||||
|
||||
tracker.track(
|
||||
eventWithCategory: category,
|
||||
action: action,
|
||||
name: name,
|
||||
number: nil,
|
||||
url: nil
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Firebase
|
||||
|
||||
class FirebaseAnalyticsManager: AnalyticsManagerProtocol {
|
||||
func logScreen(name: String, path: String) {
|
||||
var parameters = [
|
||||
AnalyticsParameterScreenName: name
|
||||
]
|
||||
|
||||
Analytics.logEvent(
|
||||
AnalyticsEventScreenView,
|
||||
parameters: parameters
|
||||
)
|
||||
}
|
||||
|
||||
func logEvent(
|
||||
name: String,
|
||||
action: String,
|
||||
category: String,
|
||||
params: [String: Any]?
|
||||
) {
|
||||
var parameters: [String:Any] = [
|
||||
"action": action,
|
||||
"category": category,
|
||||
]
|
||||
|
||||
if let supplementaryParameters = params {
|
||||
parameters.merge(supplementaryParameters) { (origin, new) -> Any in
|
||||
return origin
|
||||
}
|
||||
}
|
||||
|
||||
Analytics.logEvent(
|
||||
name,
|
||||
parameters: parameters
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Manager
|
||||
|
||||
class AnalyticsManager {
|
||||
static var shared = AnalyticsManager()
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
var managers: [AnalyticsManagerProtocol] = []
|
||||
|
||||
private var isEnabled: Bool = true
|
||||
|
||||
// MARK: - Methods
|
||||
|
||||
func setAnalyticsEnabled(_ enable: Bool) {
|
||||
isEnabled = enable
|
||||
}
|
||||
|
||||
func configure(siteId: String, url: String) {
|
||||
managers.append(
|
||||
MatomoAnalyticsManager(
|
||||
siteId: siteId,
|
||||
url: url
|
||||
)
|
||||
)
|
||||
managers.append(FirebaseAnalyticsManager())
|
||||
}
|
||||
|
||||
private func logScreen(name: String, path: String) {
|
||||
guard isEnabled else { return }
|
||||
|
||||
managers.forEach { manager in
|
||||
manager.logScreen(name: name, path: path)
|
||||
}
|
||||
}
|
||||
|
||||
private func logEvent(
|
||||
name: String,
|
||||
action: String,
|
||||
category: String,
|
||||
params: [String: Any]?
|
||||
) {
|
||||
guard isEnabled else { return }
|
||||
|
||||
managers.forEach { manager in
|
||||
manager.logEvent(
|
||||
name: name,
|
||||
action: action,
|
||||
category: category,
|
||||
params: params
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - section_one
|
||||
|
||||
func logScreenS1DefOne() {
|
||||
logScreen(
|
||||
name: "s1 def one",
|
||||
path: "s1_def_one/"
|
||||
)
|
||||
}
|
||||
|
||||
func logEventS1DefTwo() {
|
||||
logEvent(
|
||||
name: "s1 def two",
|
||||
action: "test",
|
||||
category: "test",
|
||||
params: [:]
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - section_two
|
||||
|
||||
func logScreenS2DefOne() {
|
||||
logScreen(
|
||||
name: "s2 def one",
|
||||
path: "s2_def_one/"
|
||||
)
|
||||
}
|
||||
}
|
@ -1,4 +1,4 @@
|
||||
// Generated by ResgenSwift.Strings.Tags 1.0
|
||||
// Generated by ResgenSwift.Strings.Tags 1.2
|
||||
|
||||
import UIKit
|
||||
|
||||
|
43
SampleFiles/Tags/sampleTags.yml
Normal file
43
SampleFiles/Tags/sampleTags.yml
Normal file
@ -0,0 +1,43 @@
|
||||
---
|
||||
categories:
|
||||
- id: section_one
|
||||
screens:
|
||||
- id: s1_def_one
|
||||
name: s1 def one
|
||||
path: s1_def_one/
|
||||
tags: ios
|
||||
|
||||
events:
|
||||
- id: s1_def_two
|
||||
name: s1 def two
|
||||
action: test
|
||||
category: test
|
||||
tags: ios
|
||||
|
||||
- id: section_two
|
||||
screens:
|
||||
- id: s2_def_one
|
||||
name: s2 def one
|
||||
path: s2_def_one/
|
||||
tags: ios
|
||||
|
||||
events:
|
||||
- id: s2_def_two
|
||||
name: s2 def two
|
||||
action: test
|
||||
category: test
|
||||
tags: droid
|
||||
|
||||
- id: section_three
|
||||
screens:
|
||||
- id: s3_def_one
|
||||
name: s3 def one
|
||||
path: s3_def_one/
|
||||
tags: droid
|
||||
|
||||
events:
|
||||
- id: s3_def_two
|
||||
name: s3 def two
|
||||
action: test
|
||||
category: test
|
||||
tags: droid
|
@ -2,60 +2,69 @@
|
||||
|
||||
FORCE_FLAG="$1"
|
||||
|
||||
# Font
|
||||
swift run -c release ResgenSwift fonts $FORCE_FLAG "./Fonts/sampleFontsAll.txt" \
|
||||
--extension-output-path "./Fonts/Generated" \
|
||||
--extension-name "UIFontYolo" \
|
||||
--extension-name-swift-ui "FontYolo" \
|
||||
--extension-suffix "GenAllScript" \
|
||||
--info-plist-paths "./Fonts/Generated/test.plist ./Fonts/Generated/test2.plist"
|
||||
## Font
|
||||
#swift run -c release ResgenSwift fonts $FORCE_FLAG "./Fonts/sampleFontsAll.txt" \
|
||||
# --extension-output-path "./Fonts/Generated" \
|
||||
# --extension-name "FontYolo" \
|
||||
# --extension-name-ui-kit "UIFontYolo" \
|
||||
# --extension-suffix "GenAllScript" \
|
||||
# --info-plist-paths "./Fonts/Generated/test.plist ./Fonts/Generated/test2.plist"
|
||||
#
|
||||
#echo "\n-------------------------\n"
|
||||
#
|
||||
## Color
|
||||
#swift run -c release ResgenSwift colors $FORCE_FLAG "./Colors/sampleColors1.txt" \
|
||||
# --style all \
|
||||
# --xcassets-path "./Colors/colors.xcassets" \
|
||||
# --extension-output-path "./Colors/Generated/" \
|
||||
# --extension-name "ColorYolo" \
|
||||
# --extension-name-ui-kit "UIhkjhkColorYolo" \
|
||||
# --extension-suffix "GenAllScript"
|
||||
#
|
||||
#echo "\n-------------------------\n"
|
||||
#
|
||||
## Twine
|
||||
#swift run -c release ResgenSwift strings twine $FORCE_FLAG "./Twine/sampleStrings.txt" \
|
||||
# --output-path "./Twine/Generated" \
|
||||
# --langs "fr en en-us" \
|
||||
# --default-lang "en" \
|
||||
# --extension-output-path "./Twine/Generated"
|
||||
|
||||
echo "\n-------------------------\n"
|
||||
#echo "\n-------------------------\n"
|
||||
|
||||
# Color
|
||||
swift run -c release ResgenSwift colors $FORCE_FLAG "./Colors/sampleColors1.txt" \
|
||||
--style all \
|
||||
--xcassets-path "./Colors/colors.xcassets" \
|
||||
--extension-output-path "./Colors/Generated/" \
|
||||
--extension-name "UIColorYolo" \
|
||||
--extension-name-swift-ui "ColorYolo" \
|
||||
--extension-suffix "GenAllScript"
|
||||
## Strings
|
||||
#swift run -c release ResgenSwift strings stringium $FORCE_FLAG "./Strings/sampleStrings.txt" \
|
||||
# --output-path "./Strings/Generated" \
|
||||
# --langs "fr en en-us" \
|
||||
# --default-lang "en" \
|
||||
# --extension-output-path "./Strings/Generated" \
|
||||
# --extension-name "String" \
|
||||
# --extension-suffix "GenAllScript"
|
||||
|
||||
echo "\n-------------------------\n"
|
||||
#echo "\n-------------------------\n"
|
||||
|
||||
# Twine
|
||||
swift run -c release ResgenSwift strings twine $FORCE_FLAG "./Twine/sampleStrings.txt" \
|
||||
--output-path "./Twine/Generated" \
|
||||
--langs "fr en en-us" \
|
||||
--default-lang "en" \
|
||||
--extension-output-path "./Twine/Generated"
|
||||
## Tags
|
||||
#swift run -c release ResgenSwift strings tags $FORCE_FLAG "./Tags/sampleTags.txt" \
|
||||
# --lang "ium" \
|
||||
# --extension-output-path "./Tags/Generated" \
|
||||
# --extension-name "Tags" \
|
||||
# --extension-suffix "GenAllScript"
|
||||
|
||||
echo "\n-------------------------\n"
|
||||
#echo "\n-------------------------\n"
|
||||
|
||||
# Strings
|
||||
swift run -c release ResgenSwift strings stringium $FORCE_FLAG "./Strings/sampleStrings.txt" \
|
||||
--output-path "./Strings/Generated" \
|
||||
--langs "fr en en-us" \
|
||||
--default-lang "en" \
|
||||
--extension-output-path "./Strings/Generated" \
|
||||
--extension-name "String" \
|
||||
--extension-suffix "GenAllScript"
|
||||
|
||||
echo "\n-------------------------\n"
|
||||
|
||||
# Tags
|
||||
swift run -c release ResgenSwift strings tags $FORCE_FLAG "./Tags/sampleTags.txt" \
|
||||
--lang "ium" \
|
||||
--extension-output-path "./Tags/Generated" \
|
||||
--extension-name "Tags" \
|
||||
--extension-suffix "GenAllScript"
|
||||
|
||||
echo "\n-------------------------\n"
|
||||
## Analytics
|
||||
#swift run -c release ResgenSwift analytics $FORCE_FLAG "./Tags/sampleTags.yml" \
|
||||
# --target "matomo firebase" \
|
||||
# --extension-output-path "./Tags/Generated" \
|
||||
# --extension-name "Analytics" \
|
||||
# --extension-suffix "GenAllScript"
|
||||
|
||||
#echo "\n-------------------------\n"
|
||||
#
|
||||
# Images
|
||||
swift run -c release ResgenSwift images $FORCE_FLAG "./Images/sampleImages.txt" \
|
||||
--xcassets-path "./Images/imagium.xcassets" \
|
||||
--extension-output-path "./Images/Generated" \
|
||||
--extension-name "UIImage" \
|
||||
--extension-name-swift-ui "ImageYolo" \
|
||||
--extension-name "ImageYolo" \
|
||||
--extension-name-ui-kit "UIImageYolo" \
|
||||
--extension-suffix "GenAllScript"
|
||||
|
@ -1,4 +1,30 @@
|
||||
---
|
||||
#
|
||||
# Class architecture
|
||||
#
|
||||
architecture:
|
||||
property: R
|
||||
classname: R
|
||||
path: ./Tags
|
||||
children:
|
||||
- property: images
|
||||
classname: R2Image
|
||||
- property: strings
|
||||
classname: R2String
|
||||
- property: fonts
|
||||
classname: R2Font
|
||||
- property: images
|
||||
classname: R2Image
|
||||
- property: ui
|
||||
classname: R2UI
|
||||
children:
|
||||
- property: images
|
||||
classname: R2UIImage
|
||||
- property: fonts
|
||||
classname: R2UIFont
|
||||
- property: images
|
||||
classname: R2UIImage
|
||||
|
||||
#
|
||||
# Strings
|
||||
#
|
||||
@ -21,8 +47,8 @@ images:
|
||||
inputFile: ./Images/sampleImages.txt
|
||||
xcassetsPath: ./Images/imagium.xcassets
|
||||
extensionOutputPath: ./Images/Generated
|
||||
extensionName: UIImage
|
||||
extensionNameSwiftUI: ImageYolo
|
||||
extensionName: ImageYolo
|
||||
extensionNameUIKit: UIImageYolo
|
||||
extensionSuffix: GenAllScript
|
||||
|
||||
|
||||
@ -35,8 +61,8 @@ colors:
|
||||
style: all
|
||||
xcassetsPath: ./Colors/colors.xcassets
|
||||
extensionOutputPath: ./Colors/Generated/
|
||||
extensionName: UIColorYolo
|
||||
extensionNameSwiftUI: ColorYolo
|
||||
extensionName: ColorYolo
|
||||
extensionNameUIKit: UIColorYolo
|
||||
extensionSuffix: GenAllScript
|
||||
|
||||
|
||||
@ -52,6 +78,18 @@ tags:
|
||||
extensionSuffix: GenAllScript
|
||||
|
||||
|
||||
#
|
||||
# Analytics
|
||||
#
|
||||
analytics:
|
||||
-
|
||||
inputFile: ./Tags/sampleTags.yml
|
||||
target: "matomo firebase"
|
||||
extensionOutputPath: ./Tags/Generated
|
||||
extensionName: Analytics
|
||||
extensionSuffix: GenAllScript
|
||||
|
||||
|
||||
#
|
||||
# Fonts
|
||||
#
|
||||
@ -59,7 +97,7 @@ fonts:
|
||||
-
|
||||
inputFile: ./Fonts/sampleFontsAll.txt
|
||||
extensionOutputPath: ./Fonts/Generated
|
||||
extensionName: UIFontYolo
|
||||
extensionNameSwiftUI: FontYolo
|
||||
extensionName: FontYolo
|
||||
extensionNameUIKit: UIFontYolo
|
||||
extensionSuffix: GenAllScript
|
||||
infoPlistPaths: "./Fonts/Generated/test.plist ./Fonts/Generated/test2.plist"
|
||||
|
92
Sources/ResgenSwift/Analytics/Analytics.swift
Normal file
92
Sources/ResgenSwift/Analytics/Analytics.swift
Normal file
@ -0,0 +1,92 @@
|
||||
//
|
||||
// Analytics.swift
|
||||
//
|
||||
//
|
||||
// Created by Loris Perret on 08/12/2023.
|
||||
//
|
||||
|
||||
import ToolCore
|
||||
import Foundation
|
||||
import ArgumentParser
|
||||
|
||||
struct Analytics: ParsableCommand {
|
||||
|
||||
// MARK: - Command Configuration
|
||||
|
||||
static var configuration = CommandConfiguration(
|
||||
abstract: "Generate analytics extension file.",
|
||||
version: ResgenSwiftVersion
|
||||
)
|
||||
|
||||
// MARK: - Static
|
||||
|
||||
static let toolName = "Analytics"
|
||||
static let defaultExtensionName = "Analytics"
|
||||
|
||||
// MARK: - Command Options
|
||||
|
||||
@OptionGroup var options: AnalyticsOptions
|
||||
|
||||
// MARK: - Run
|
||||
|
||||
mutating func run() {
|
||||
print("[\(Self.toolName)] Starting analytics generation")
|
||||
print("[\(Self.toolName)] Will use inputFile \(options.inputFile) to generate analytics for target: \(options.target)")
|
||||
print("[\(Self.toolName)] Will generate analytics")
|
||||
|
||||
// Check requirements
|
||||
guard checkRequirements() else { return }
|
||||
|
||||
// Parse input file
|
||||
let sections = AnalyticsFileParser.parse(options.inputFile, target: options.target)
|
||||
|
||||
// Generate extension
|
||||
AnalyticsGenerator.writeExtensionFiles(sections: sections,
|
||||
target: options.target,
|
||||
tags: ["ios", "iosonly"],
|
||||
staticVar: options.staticMembers,
|
||||
extensionName: options.extensionName,
|
||||
extensionFilePath: options.extensionFilePath)
|
||||
|
||||
print("[\(Self.toolName)] Analytics generated")
|
||||
}
|
||||
|
||||
// MARK: - Requirements
|
||||
|
||||
private func checkRequirements() -> Bool {
|
||||
let fileManager = FileManager()
|
||||
|
||||
// Input file
|
||||
guard fileManager.fileExists(atPath: options.inputFile) else {
|
||||
let error = AnalyticsError.fileNotExists(options.inputFile)
|
||||
print(error.description)
|
||||
Analytics.exit(withError: error)
|
||||
}
|
||||
|
||||
// Check if needed to regenerate
|
||||
guard GeneratorChecker.shouldGenerate(force: options.forceGeneration,
|
||||
inputFilePath: options.inputFile,
|
||||
extensionFilePath: options.extensionFilePath) else {
|
||||
print("[\(Self.toolName)] Analytics are already up to date :) ")
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
extension Analytics {
|
||||
enum TargetType: CaseIterable {
|
||||
case matomo
|
||||
case firebase
|
||||
|
||||
var value: String {
|
||||
switch self {
|
||||
case .matomo:
|
||||
"matomo"
|
||||
case .firebase:
|
||||
"firebase"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
32
Sources/ResgenSwift/Analytics/AnalyticsError.swift
Normal file
32
Sources/ResgenSwift/Analytics/AnalyticsError.swift
Normal file
@ -0,0 +1,32 @@
|
||||
//
|
||||
// AnalyticsError.swift
|
||||
//
|
||||
//
|
||||
// Created by Loris Perret on 11/12/2023.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
enum AnalyticsError: Error {
|
||||
case fileNotExists(String)
|
||||
case missingElement(String)
|
||||
case invalidParameter(String)
|
||||
|
||||
case writeFile(String, String)
|
||||
|
||||
var description: String {
|
||||
switch self {
|
||||
case .fileNotExists(let filename):
|
||||
return "error: [\(Analytics.toolName)] File \(filename) does not exists "
|
||||
|
||||
case .missingElement(let element):
|
||||
return "error: [\(Analytics.toolName)] Missing \(element) for Matomo"
|
||||
|
||||
case .invalidParameter(let reason):
|
||||
return "error: [\(Analytics.toolName)] Invalid parameter \(reason)"
|
||||
|
||||
case .writeFile(let subErrorDescription, let filename):
|
||||
return "error: [\(Analytics.toolName)] An error occured while writing content to \(filename): \(subErrorDescription)"
|
||||
}
|
||||
}
|
||||
}
|
47
Sources/ResgenSwift/Analytics/AnalyticsOptions.swift
Normal file
47
Sources/ResgenSwift/Analytics/AnalyticsOptions.swift
Normal file
@ -0,0 +1,47 @@
|
||||
//
|
||||
// AnalyticsOptions.swift
|
||||
//
|
||||
//
|
||||
// Created by Loris Perret on 08/12/2023.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import ArgumentParser
|
||||
|
||||
struct AnalyticsOptions: ParsableArguments {
|
||||
@Flag(name: [.customShort("f"), .customShort("F")], help: "Should force generation")
|
||||
var forceGeneration = false
|
||||
|
||||
@Argument(help: "Input files where tags ared defined.", transform: { $0.replaceTiltWithHomeDirectoryPath() })
|
||||
var inputFile: String
|
||||
|
||||
@Option(help: "Target(s) analytics to generate. (\"matomo\" | \"firebase\")")
|
||||
var target: String
|
||||
|
||||
@Option(help: "Path where to generate the extension.", transform: { $0.replaceTiltWithHomeDirectoryPath() })
|
||||
var extensionOutputPath: String
|
||||
|
||||
@Option(help: "Tell if it will generate static properties or not")
|
||||
var staticMembers: Bool = false
|
||||
|
||||
@Option(help: "Extension name. If not specified, it will generate a Analytics extension.")
|
||||
var extensionName: String = Analytics.defaultExtensionName
|
||||
|
||||
@Option(help: "Extension suffix. Ex: MyApp, it will generate {extensionName}+Analytics{extensionSuffix}.swift")
|
||||
var extensionSuffix: String?
|
||||
}
|
||||
|
||||
// MARK: - Computed var
|
||||
|
||||
extension AnalyticsOptions {
|
||||
var extensionFileName: String {
|
||||
if let extensionSuffix = extensionSuffix {
|
||||
return "\(extensionName)+\(extensionSuffix).swift"
|
||||
}
|
||||
return "\(extensionName).swift"
|
||||
}
|
||||
|
||||
var extensionFilePath: String {
|
||||
"\(extensionOutputPath)/\(extensionFileName)"
|
||||
}
|
||||
}
|
227
Sources/ResgenSwift/Analytics/Generator/AnalyticsGenerator.swift
Normal file
227
Sources/ResgenSwift/Analytics/Generator/AnalyticsGenerator.swift
Normal file
@ -0,0 +1,227 @@
|
||||
//
|
||||
// AnalyticsGenerator.swift
|
||||
//
|
||||
//
|
||||
// Created by Loris Perret on 08/12/2023.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import ToolCore
|
||||
import CoreVideo
|
||||
|
||||
class AnalyticsGenerator {
|
||||
static var targets: [Analytics.TargetType] = []
|
||||
|
||||
static func writeExtensionFiles(sections: [AnalyticsCategory], target: String, tags: [String], staticVar: Bool, extensionName: String, extensionFilePath: String) {
|
||||
// Get target type from enum
|
||||
let targetsString: [String] = target.components(separatedBy: " ")
|
||||
|
||||
Analytics.TargetType.allCases.forEach { enumTarget in
|
||||
if targetsString.contains(enumTarget.value) {
|
||||
targets.append(enumTarget)
|
||||
}
|
||||
}
|
||||
|
||||
// Get extension content
|
||||
let extensionFileContent = Self.getExtensionContent(sections: sections,
|
||||
tags: tags,
|
||||
staticVar: staticVar,
|
||||
extensionName: extensionName)
|
||||
|
||||
// Write content
|
||||
let extensionFilePathURL = URL(fileURLWithPath: extensionFilePath)
|
||||
do {
|
||||
try extensionFileContent.write(to: extensionFilePathURL, atomically: false, encoding: .utf8)
|
||||
} catch (let error) {
|
||||
let error = AnalyticsError.writeFile(extensionFilePath, error.localizedDescription)
|
||||
print(error.description)
|
||||
Analytics.exit(withError: error)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Extension content
|
||||
|
||||
static func getExtensionContent(sections: [AnalyticsCategory], tags: [String], staticVar: Bool, extensionName: String) -> String {
|
||||
[
|
||||
Self.getHeader(extensionClassname: extensionName, staticVar: staticVar),
|
||||
Self.getProperties(sections: sections, tags: tags, staticVar: staticVar),
|
||||
Self.getFooter()
|
||||
]
|
||||
.joined(separator: "\n")
|
||||
}
|
||||
|
||||
// MARK: - Extension part
|
||||
|
||||
private static func getHeader(extensionClassname: String, staticVar: Bool) -> String {
|
||||
"""
|
||||
// Generated by ResgenSwift.\(Analytics.toolName) \(ResgenSwiftVersion)
|
||||
|
||||
\(Self.getImport())
|
||||
|
||||
\(Self.getAnalytics())
|
||||
// MARK: - Manager
|
||||
|
||||
class AnalyticsManager {
|
||||
static var shared = AnalyticsManager()
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
var managers: [AnalyticsManagerProtocol] = []
|
||||
|
||||
\(Self.getEnabledContent())
|
||||
|
||||
\(Self.getAnalyticsProperties())
|
||||
|
||||
\(Self.getPrivateLogFunction())
|
||||
"""
|
||||
}
|
||||
|
||||
private static func getEnabledContent() -> String {
|
||||
"""
|
||||
private var isEnabled: Bool = true
|
||||
|
||||
// MARK: - Methods
|
||||
|
||||
func setAnalyticsEnabled(_ enable: Bool) {
|
||||
isEnabled = enable
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
private static func getImport() -> String {
|
||||
var result: [String] = []
|
||||
|
||||
if targets.contains(Analytics.TargetType.matomo) {
|
||||
result.append("import MatomoTracker")
|
||||
}
|
||||
if targets.contains(Analytics.TargetType.firebase) {
|
||||
result.append("import FirebaseAnalytics")
|
||||
}
|
||||
|
||||
return result.joined(separator: "\n")
|
||||
}
|
||||
|
||||
private static func getPrivateLogFunction() -> String {
|
||||
"""
|
||||
private func logScreen(name: String, path: String) {
|
||||
guard isEnabled else { return }
|
||||
|
||||
managers.forEach { manager in
|
||||
manager.logScreen(name: name, path: path)
|
||||
}
|
||||
}
|
||||
|
||||
private func logEvent(
|
||||
name: String,
|
||||
action: String,
|
||||
category: String,
|
||||
params: [String: Any]?
|
||||
) {
|
||||
guard isEnabled else { return }
|
||||
|
||||
managers.forEach { manager in
|
||||
manager.logEvent(
|
||||
name: name,
|
||||
action: action,
|
||||
category: category,
|
||||
params: params
|
||||
)
|
||||
}
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
private static func getAnalyticsProperties() -> String {
|
||||
var header = ""
|
||||
var content: [String] = []
|
||||
let footer = " }"
|
||||
|
||||
if targets.contains(Analytics.TargetType.matomo) {
|
||||
header = "func configure(siteId: String, url: String) {"
|
||||
} else if targets.contains(Analytics.TargetType.firebase) {
|
||||
header = "func configure() {"
|
||||
}
|
||||
|
||||
if targets.contains(Analytics.TargetType.matomo) {
|
||||
content.append("""
|
||||
managers.append(
|
||||
MatomoAnalyticsManager(
|
||||
siteId: siteId,
|
||||
url: url
|
||||
)
|
||||
)
|
||||
""")
|
||||
}
|
||||
if targets.contains(Analytics.TargetType.firebase) {
|
||||
content.append(" managers.append(FirebaseAnalyticsManager())")
|
||||
}
|
||||
|
||||
return [
|
||||
header,
|
||||
content.joined(separator: "\n"),
|
||||
footer
|
||||
]
|
||||
.joined(separator: "\n")
|
||||
}
|
||||
|
||||
private static func getAnalytics() -> String {
|
||||
let proto = """
|
||||
// MARK: - Protocol
|
||||
|
||||
protocol AnalyticsManagerProtocol {
|
||||
func logScreen(name: String, path: String)
|
||||
func logEvent(
|
||||
name: String,
|
||||
action: String,
|
||||
category: String,
|
||||
params: [String: Any]?
|
||||
)
|
||||
}
|
||||
|
||||
"""
|
||||
|
||||
var result: [String] = [proto]
|
||||
|
||||
if targets.contains(Analytics.TargetType.matomo) {
|
||||
result.append(MatomoGenerator.service.content)
|
||||
}
|
||||
|
||||
if targets.contains(Analytics.TargetType.firebase) {
|
||||
result.append(FirebaseGenerator.service.content)
|
||||
}
|
||||
|
||||
return result.joined(separator: "\n")
|
||||
}
|
||||
|
||||
private static func getProperties(sections: [AnalyticsCategory], tags: [String], staticVar: Bool) -> String {
|
||||
sections
|
||||
.compactMap { section in
|
||||
// Check that at least one string will be generated
|
||||
guard section.hasOneOrMoreMatchingTags(tags: tags) else {
|
||||
return nil// Go to next section
|
||||
}
|
||||
|
||||
var res = "\n // MARK: - \(section.id)"
|
||||
section.definitions.forEach { definition in
|
||||
guard definition.hasOneOrMoreMatchingTags(inputTags: tags) == true else {
|
||||
return // Go to next definition
|
||||
}
|
||||
|
||||
if staticVar {
|
||||
res += "\n\n\(definition.getStaticProperty())"
|
||||
} else {
|
||||
res += "\n\n\(definition.getProperty())"
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
.joined(separator: "\n")
|
||||
}
|
||||
|
||||
private static func getFooter() -> String {
|
||||
"""
|
||||
}
|
||||
|
||||
"""
|
||||
}
|
||||
}
|
@ -0,0 +1,80 @@
|
||||
//
|
||||
// FirebaseGenerator.swift
|
||||
//
|
||||
//
|
||||
// Created by Loris Perret on 05/12/2023.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
enum FirebaseGenerator {
|
||||
case service
|
||||
|
||||
var content: String {
|
||||
[
|
||||
FirebaseGenerator.service.header,
|
||||
FirebaseGenerator.service.logScreen,
|
||||
FirebaseGenerator.service.logEvent,
|
||||
FirebaseGenerator.service.footer
|
||||
]
|
||||
.joined(separator: "\n")
|
||||
}
|
||||
|
||||
private var header: String {
|
||||
"""
|
||||
// MARK: - Firebase
|
||||
|
||||
class FirebaseAnalyticsManager: AnalyticsManagerProtocol {
|
||||
"""
|
||||
}
|
||||
|
||||
private var logScreen: String {
|
||||
"""
|
||||
func logScreen(name: String, path: String) {
|
||||
var parameters = [
|
||||
AnalyticsParameterScreenName: name
|
||||
]
|
||||
|
||||
Analytics.logEvent(
|
||||
AnalyticsEventScreenView,
|
||||
parameters: parameters
|
||||
)
|
||||
}
|
||||
|
||||
"""
|
||||
}
|
||||
|
||||
private var logEvent: String {
|
||||
"""
|
||||
func logEvent(
|
||||
name: String,
|
||||
action: String,
|
||||
category: String,
|
||||
params: [String: Any]?
|
||||
) {
|
||||
var parameters: [String:Any] = [
|
||||
"action": action,
|
||||
"category": category,
|
||||
]
|
||||
|
||||
if let supplementaryParameters = params {
|
||||
parameters.merge(supplementaryParameters) { (origin, new) -> Any in
|
||||
return origin
|
||||
}
|
||||
}
|
||||
|
||||
Analytics.logEvent(
|
||||
name,
|
||||
parameters: parameters
|
||||
)
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
private var footer: String {
|
||||
"""
|
||||
}
|
||||
|
||||
"""
|
||||
}
|
||||
}
|
109
Sources/ResgenSwift/Analytics/Generator/MatomoGenerator.swift
Normal file
109
Sources/ResgenSwift/Analytics/Generator/MatomoGenerator.swift
Normal file
@ -0,0 +1,109 @@
|
||||
//
|
||||
// MatomoGenerator.swift
|
||||
//
|
||||
//
|
||||
// Created by Loris Perret on 05/12/2023.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
enum MatomoGenerator {
|
||||
case service
|
||||
|
||||
var content: String {
|
||||
[
|
||||
MatomoGenerator.service.header,
|
||||
MatomoGenerator.service.setup,
|
||||
MatomoGenerator.service.logScreen,
|
||||
MatomoGenerator.service.logEvent,
|
||||
MatomoGenerator.service.footer
|
||||
]
|
||||
.joined(separator: "\n")
|
||||
}
|
||||
|
||||
private var header: String {
|
||||
"""
|
||||
// MARK: - Matomo
|
||||
|
||||
class MatomoAnalyticsManager: AnalyticsManagerProtocol {
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
private var tracker: MatomoTracker
|
||||
|
||||
"""
|
||||
}
|
||||
|
||||
private var setup: String {
|
||||
"""
|
||||
// MARK: - Init
|
||||
|
||||
init(siteId: String, url: String) {
|
||||
debugPrint("[Matomo service] Server URL: \\(url)")
|
||||
debugPrint("[Matomo service] Site ID: \\(siteId)")
|
||||
tracker = MatomoTracker(
|
||||
siteId: siteId,
|
||||
baseURL: URL(string: url)!
|
||||
)
|
||||
|
||||
#if DEBUG
|
||||
tracker.dispatchInterval = 5
|
||||
#endif
|
||||
|
||||
#if DEBUG
|
||||
tracker.logger = DefaultLogger(minLevel: .verbose)
|
||||
#endif
|
||||
|
||||
debugPrint("[Matomo service] Configured with content base: \\(tracker.contentBase?.absoluteString ?? "-")")
|
||||
debugPrint("[Matomo service] Opt out: \\(tracker.isOptedOut)")
|
||||
}
|
||||
|
||||
// MARK: - Methods
|
||||
|
||||
"""
|
||||
}
|
||||
|
||||
private var logScreen: String {
|
||||
"""
|
||||
func logScreen(name: String, path: String) {
|
||||
guard !tracker.isOptedOut else { return }
|
||||
guard let trackerUrl = tracker.contentBase?.absoluteString else { return }
|
||||
|
||||
let urlString = URL(string: "\\(trackerUrl)" + "/" + "\\(path)" + "iOS")
|
||||
tracker.track(
|
||||
view: [name],
|
||||
url: urlString
|
||||
)
|
||||
}
|
||||
|
||||
"""
|
||||
}
|
||||
|
||||
private var logEvent: String {
|
||||
"""
|
||||
func logEvent(
|
||||
name: String,
|
||||
action: String,
|
||||
category: String,
|
||||
params: [String: Any]?
|
||||
) {
|
||||
guard !tracker.isOptedOut else { return }
|
||||
|
||||
tracker.track(
|
||||
eventWithCategory: category,
|
||||
action: action,
|
||||
name: name,
|
||||
number: nil,
|
||||
url: nil
|
||||
)
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
private var footer: String {
|
||||
"""
|
||||
}
|
||||
|
||||
"""
|
||||
}
|
||||
}
|
28
Sources/ResgenSwift/Analytics/Model/AnalyticsCategory.swift
Normal file
28
Sources/ResgenSwift/Analytics/Model/AnalyticsCategory.swift
Normal file
@ -0,0 +1,28 @@
|
||||
//
|
||||
// AnalyticsCategory.swift
|
||||
//
|
||||
//
|
||||
// Created by Loris Perret on 05/12/2023.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
class AnalyticsCategory {
|
||||
let id: String // OnBoarding
|
||||
var definitions = [AnalyticsDefinition]()
|
||||
|
||||
init(id: String) {
|
||||
self.id = id
|
||||
}
|
||||
|
||||
func hasOneOrMoreMatchingTags(tags: [String]) -> Bool {
|
||||
let allTags = definitions.flatMap { $0.tags }
|
||||
let allTagsSet = Set(allTags)
|
||||
|
||||
let intersection = Set(tags).intersection(allTagsSet)
|
||||
if intersection.isEmpty {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
176
Sources/ResgenSwift/Analytics/Model/AnalyticsDefinition.swift
Normal file
176
Sources/ResgenSwift/Analytics/Model/AnalyticsDefinition.swift
Normal file
@ -0,0 +1,176 @@
|
||||
//
|
||||
// AnalyticsDefinition.swift
|
||||
//
|
||||
//
|
||||
// Created by Loris Perret on 05/12/2023.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
class AnalyticsDefinition {
|
||||
let id: String
|
||||
var name: String
|
||||
var path: String = ""
|
||||
var category: String = ""
|
||||
var action: String = ""
|
||||
var comments: String = ""
|
||||
var tags: [String] = []
|
||||
var parameters: [AnalyticsParameter] = []
|
||||
var type: TagType
|
||||
|
||||
init(id: String, name: String, type: TagType) {
|
||||
self.id = id
|
||||
self.name = name
|
||||
self.type = type
|
||||
}
|
||||
|
||||
func hasOneOrMoreMatchingTags(inputTags: [String]) -> Bool {
|
||||
if Set(inputTags).isDisjoint(with: tags) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// MARK: - Methods
|
||||
|
||||
private func getFuncName() -> String {
|
||||
var pascalCaseTitle: String = ""
|
||||
id.components(separatedBy: "_").forEach { word in
|
||||
pascalCaseTitle.append(contentsOf: word.uppercasedFirst())
|
||||
}
|
||||
|
||||
return "log\(type == .screen ? "Screen" : "Event")\(pascalCaseTitle)"
|
||||
}
|
||||
|
||||
private func getParameters() -> String {
|
||||
var params = parameters
|
||||
var result: String
|
||||
|
||||
if type == .screen {
|
||||
params = params.filter { param in
|
||||
!param.replaceIn.isEmpty
|
||||
}
|
||||
}
|
||||
|
||||
let paramsString = params.map { parameter in
|
||||
"\(parameter.name): \(parameter.type)"
|
||||
}
|
||||
|
||||
if paramsString.count > 2 {
|
||||
result = """
|
||||
(
|
||||
\(paramsString.joined(separator: ",\n\t\t"))
|
||||
)
|
||||
"""
|
||||
} else {
|
||||
result = """
|
||||
(\(paramsString.joined(separator: ", ")))
|
||||
"""
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
private func replaceIn() {
|
||||
for parameter in parameters {
|
||||
for rep in parameter.replaceIn {
|
||||
switch rep {
|
||||
case "name": name = name.replacingFirstOccurrence(of: "_\(parameter.name.uppercased())_", with: "\\(\(parameter.name))")
|
||||
case "path": path = path.replacingFirstOccurrence(of: "_\(parameter.name.uppercased())_", with: "\\(\(parameter.name))")
|
||||
case "category": category = category.replacingFirstOccurrence(of: "_\(parameter.name.uppercased())_", with: "\\(\(parameter.name))")
|
||||
case "action": action = action.replacingFirstOccurrence(of: "_\(parameter.name.uppercased())_", with: "\\(\(parameter.name))")
|
||||
default: break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func getlogFunction() -> String {
|
||||
var params: [String] = []
|
||||
var result: String
|
||||
|
||||
let supplementaryParams = parameters.filter { param in
|
||||
param.replaceIn.isEmpty
|
||||
}
|
||||
|
||||
supplementaryParams.forEach { param in
|
||||
params.append("\"\(param.name)\": \(param.name)")
|
||||
}
|
||||
|
||||
if params.count > 1 {
|
||||
result = """
|
||||
[
|
||||
\(params.joined(separator: ",\n\t\t\t\t"))
|
||||
]
|
||||
"""
|
||||
} else if params.count == 1 {
|
||||
result = """
|
||||
[\(params.joined(separator: ", "))]
|
||||
"""
|
||||
} else {
|
||||
result = "[:]"
|
||||
}
|
||||
|
||||
if type == .screen {
|
||||
return """
|
||||
logScreen(
|
||||
name: "\(name)",
|
||||
path: "\(path)"
|
||||
)
|
||||
"""
|
||||
} else {
|
||||
return """
|
||||
logEvent(
|
||||
name: "\(name)",
|
||||
action: "\(action)",
|
||||
category: "\(category)",
|
||||
params: \(result)
|
||||
)
|
||||
"""
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Raw strings
|
||||
|
||||
func getProperty() -> String {
|
||||
replaceIn()
|
||||
return """
|
||||
func \(getFuncName())\(getParameters()) {
|
||||
\(getlogFunction())
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
func getStaticProperty() -> String {
|
||||
replaceIn()
|
||||
return """
|
||||
static func \(getFuncName())\(getParameters()) {
|
||||
\(getlogFunction())
|
||||
}
|
||||
"""
|
||||
}
|
||||
}
|
||||
|
||||
extension AnalyticsDefinition {
|
||||
enum TagType {
|
||||
case screen
|
||||
case event
|
||||
}
|
||||
}
|
||||
|
||||
extension String {
|
||||
func replacingFirstOccurrence(of: String, with: String) -> Self {
|
||||
if let range = self.range(of: of) {
|
||||
let tmp = self.replacingOccurrences(
|
||||
of: of,
|
||||
with: with,
|
||||
options: .literal,
|
||||
range: range
|
||||
)
|
||||
|
||||
return tmp
|
||||
}
|
||||
|
||||
return self
|
||||
}
|
||||
}
|
47
Sources/ResgenSwift/Analytics/Model/AnalyticsFile.swift
Normal file
47
Sources/ResgenSwift/Analytics/Model/AnalyticsFile.swift
Normal file
@ -0,0 +1,47 @@
|
||||
//
|
||||
// AnalyticsFile.swift
|
||||
//
|
||||
//
|
||||
// Created by Loris Perret on 06/12/2023.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
struct AnalyticsFile: Codable {
|
||||
var categories: [AnalyticsCategoryDTO]
|
||||
}
|
||||
|
||||
struct AnalyticsCategoryDTO: Codable {
|
||||
var id: String
|
||||
var screens: [AnalyticsDefinitionScreenDTO]?
|
||||
var events: [AnalyticsDefinitionEventDTO]?
|
||||
}
|
||||
|
||||
protocol AnalyticsDefinitionDTO: Codable {}
|
||||
|
||||
struct AnalyticsDefinitionScreenDTO: AnalyticsDefinitionDTO {
|
||||
var id: String
|
||||
var name: String
|
||||
var tags: String
|
||||
var comments: String?
|
||||
var parameters: [AnalyticsParameterDTO]?
|
||||
|
||||
var path: String?
|
||||
}
|
||||
|
||||
struct AnalyticsDefinitionEventDTO: AnalyticsDefinitionDTO {
|
||||
var id: String
|
||||
var name: String
|
||||
var tags: String
|
||||
var comments: String?
|
||||
var parameters: [AnalyticsParameterDTO]?
|
||||
|
||||
var category: String?
|
||||
var action: String?
|
||||
}
|
||||
|
||||
struct AnalyticsParameterDTO: Codable {
|
||||
var name: String
|
||||
var type: String
|
||||
var replaceIn: String?
|
||||
}
|
19
Sources/ResgenSwift/Analytics/Model/AnalyticsParameter.swift
Normal file
19
Sources/ResgenSwift/Analytics/Model/AnalyticsParameter.swift
Normal file
@ -0,0 +1,19 @@
|
||||
//
|
||||
// AnalyticsParameter.swift
|
||||
//
|
||||
//
|
||||
// Created by Loris Perret on 06/12/2023.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
class AnalyticsParameter {
|
||||
var name: String
|
||||
var type: String
|
||||
var replaceIn: [String] = []
|
||||
|
||||
init(name: String, type: String) {
|
||||
self.name = name
|
||||
self.type = type
|
||||
}
|
||||
}
|
173
Sources/ResgenSwift/Analytics/Parser/AnalyticsFileParser.swift
Normal file
173
Sources/ResgenSwift/Analytics/Parser/AnalyticsFileParser.swift
Normal file
@ -0,0 +1,173 @@
|
||||
//
|
||||
// AnalyticsFileParser.swift
|
||||
//
|
||||
//
|
||||
// Created by Loris Perret on 06/12/2023.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Yams
|
||||
|
||||
class AnalyticsFileParser {
|
||||
private static var inputFile: String = ""
|
||||
private static var target: String = ""
|
||||
|
||||
private static func parseYaml() -> AnalyticsFile {
|
||||
guard let data = FileManager().contents(atPath: inputFile) else {
|
||||
let error = AnalyticsError.fileNotExists(inputFile)
|
||||
Analytics.exit(withError: error)
|
||||
}
|
||||
|
||||
do {
|
||||
let tagFile = try YAMLDecoder().decode(AnalyticsFile.self, from: data)
|
||||
return tagFile
|
||||
} catch let error {
|
||||
Analytics.exit(withError: error)
|
||||
}
|
||||
}
|
||||
|
||||
private static func getParameters(fromData data: [AnalyticsParameterDTO]) -> [AnalyticsParameter] {
|
||||
var parameters: [AnalyticsParameter] = []
|
||||
|
||||
data.forEach { value in
|
||||
// Type
|
||||
|
||||
let type = value.type.uppercasedFirst()
|
||||
|
||||
guard
|
||||
type == "String" ||
|
||||
type == "Int" ||
|
||||
type == "Double" ||
|
||||
type == "Bool"
|
||||
else {
|
||||
let error = AnalyticsError.invalidParameter("type of \(value.name)")
|
||||
Analytics.exit(withError: error)
|
||||
}
|
||||
|
||||
let parameter: AnalyticsParameter = AnalyticsParameter(name: value.name, type: type)
|
||||
|
||||
if let replaceIn = value.replaceIn {
|
||||
parameter.replaceIn = replaceIn.components(separatedBy: ",")
|
||||
}
|
||||
|
||||
parameters.append(parameter)
|
||||
}
|
||||
|
||||
return parameters
|
||||
}
|
||||
|
||||
private static func getTagDefinition(
|
||||
id: String,
|
||||
name: String,
|
||||
type: AnalyticsDefinition.TagType,
|
||||
tags: String,
|
||||
comments: String?,
|
||||
parameters: [AnalyticsParameterDTO]?
|
||||
) -> AnalyticsDefinition {
|
||||
let definition: AnalyticsDefinition = AnalyticsDefinition(id: id, name: name, type: type)
|
||||
definition.tags = tags.components(separatedBy: ",")
|
||||
|
||||
if let comments = comments {
|
||||
definition.comments = comments
|
||||
}
|
||||
|
||||
if let parameters = parameters {
|
||||
definition.parameters = Self.getParameters(fromData: parameters)
|
||||
}
|
||||
|
||||
return definition
|
||||
}
|
||||
|
||||
private static func getTagDefinitionScreen(fromData screens: [AnalyticsDefinitionScreenDTO]) -> [AnalyticsDefinition] {
|
||||
var definitions: [AnalyticsDefinition] = []
|
||||
|
||||
for screen in screens {
|
||||
let definition: AnalyticsDefinition = Self.getTagDefinition(
|
||||
id: screen.id,
|
||||
name: screen.name,
|
||||
type: .screen,
|
||||
tags: screen.tags,
|
||||
comments: screen.comments,
|
||||
parameters: screen.parameters
|
||||
)
|
||||
|
||||
if target.contains(Analytics.TargetType.matomo.value) {
|
||||
// Path
|
||||
|
||||
guard let path = screen.path else {
|
||||
let error = AnalyticsError.missingElement("screen path")
|
||||
Analytics.exit(withError: error)
|
||||
}
|
||||
|
||||
definition.path = path
|
||||
}
|
||||
|
||||
definitions.append(definition)
|
||||
}
|
||||
|
||||
return definitions
|
||||
}
|
||||
|
||||
private static func getTagDefinitionEvent(fromData events: [AnalyticsDefinitionEventDTO]) -> [AnalyticsDefinition] {
|
||||
var definitions: [AnalyticsDefinition] = []
|
||||
|
||||
for event in events {
|
||||
let definition: AnalyticsDefinition = Self.getTagDefinition(
|
||||
id: event.id,
|
||||
name: event.name,
|
||||
type: .event,
|
||||
tags: event.tags,
|
||||
comments: event.comments,
|
||||
parameters: event.parameters
|
||||
)
|
||||
|
||||
if target.contains(Analytics.TargetType.matomo.value) {
|
||||
// Category
|
||||
|
||||
guard let category = event.category else {
|
||||
let error = AnalyticsError.missingElement("event category")
|
||||
Analytics.exit(withError: error)
|
||||
}
|
||||
|
||||
definition.category = category
|
||||
|
||||
// Action
|
||||
|
||||
guard let action = event.action else {
|
||||
let error = AnalyticsError.missingElement("event action")
|
||||
Analytics.exit(withError: error)
|
||||
}
|
||||
|
||||
definition.action = action
|
||||
}
|
||||
|
||||
definitions.append(definition)
|
||||
}
|
||||
|
||||
return definitions
|
||||
}
|
||||
|
||||
static func parse(_ inputFile: String, target: String) -> [AnalyticsCategory] {
|
||||
self.inputFile = inputFile
|
||||
self.target = target
|
||||
|
||||
let tagFile: AnalyticsFile = Self.parseYaml()
|
||||
var sections: [AnalyticsCategory] = []
|
||||
|
||||
tagFile.categories.forEach { categorie in
|
||||
let section: AnalyticsCategory = AnalyticsCategory(id: categorie.id)
|
||||
|
||||
if let screens = categorie.screens {
|
||||
section.definitions.append(contentsOf: Self.getTagDefinitionScreen(fromData: screens))
|
||||
}
|
||||
|
||||
if let events = categorie.events {
|
||||
section.definitions.append(contentsOf: Self.getTagDefinitionEvent(fromData: events))
|
||||
}
|
||||
|
||||
sections.append(section)
|
||||
}
|
||||
|
||||
return sections
|
||||
}
|
||||
}
|
@ -21,8 +21,8 @@ struct Colors: ParsableCommand {
|
||||
// MARK: - Static
|
||||
|
||||
static let toolName = "Color"
|
||||
static let defaultExtensionName = "UIColor"
|
||||
static let defaultExtensionNameSUI = "Color"
|
||||
static let defaultExtensionName = "Color"
|
||||
static let defaultExtensionNameUIKit = "UIColor"
|
||||
static let assetsColorsFolderName = "Colors"
|
||||
|
||||
// MARK: - Command options
|
||||
@ -57,14 +57,14 @@ struct Colors: ParsableCommand {
|
||||
staticVar: options.staticMembers,
|
||||
extensionName: options.extensionName,
|
||||
extensionFilePath: options.extensionFilePath,
|
||||
isSwiftUI: false)
|
||||
isSwiftUI: true)
|
||||
|
||||
// Generate extension
|
||||
ColorExtensionGenerator.writeExtensionFile(colors: parsedColors,
|
||||
staticVar: options.staticMembers,
|
||||
extensionName: options.extensionNameSwiftUI,
|
||||
extensionFilePath: options.extensionFilePathSwiftUI,
|
||||
isSwiftUI: true)
|
||||
extensionName: options.extensionNameUIKit,
|
||||
extensionFilePath: options.extensionFilePathUIKit,
|
||||
isSwiftUI: false)
|
||||
|
||||
print("[\(Self.toolName)] Colors generated")
|
||||
}
|
||||
@ -77,21 +77,21 @@ struct Colors: ParsableCommand {
|
||||
// Check if input file exists
|
||||
guard fileManager.fileExists(atPath: options.inputFile) else {
|
||||
let error = ColorsToolError.fileNotExists(options.inputFile)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Colors.exit(withError: error)
|
||||
}
|
||||
|
||||
// Check if xcassets file exists
|
||||
guard fileManager.fileExists(atPath: options.xcassetsPath) else {
|
||||
let error = ColorsToolError.fileNotExists(options.xcassetsPath)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Colors.exit(withError: error)
|
||||
}
|
||||
|
||||
// Extension for UIKit and SwiftUI should have different name
|
||||
guard options.extensionName != options.extensionNameSwiftUI else {
|
||||
guard options.extensionName != options.extensionNameUIKit else {
|
||||
let error = ColorsToolError.extensionNamesCollision(options.extensionName)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Colors.exit(withError: error)
|
||||
}
|
||||
|
||||
@ -117,7 +117,7 @@ struct Colors: ParsableCommand {
|
||||
try fileManager.removeItem(atPath: assetsColorPath)
|
||||
} catch {
|
||||
let error = ColorsToolError.deleteExistingColors("\(options.xcassetsPath)/Colors")
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Colors.exit(withError: error)
|
||||
}
|
||||
}
|
||||
|
@ -20,28 +20,28 @@ enum ColorsToolError: Error {
|
||||
var description: String {
|
||||
switch self {
|
||||
case .extensionNamesCollision(let extensionName):
|
||||
return "error:[\(Fonts.toolName)] Error on extension names, extension name and SwiftUI extension name should be different (\(extensionName) is used on both)"
|
||||
return "error: [\(Fonts.toolName)] Error on extension names, extension name and SwiftUI extension name should be different (\(extensionName) is used on both)"
|
||||
|
||||
case .badFormat(let info):
|
||||
return "error:[\(Colors.toolName)] Bad line format: \(info). Accepted format are: colorName=\"#RGB/#ARGB\"; colorName \"#RGB/#ARGB\"; colorName \"#RGB/#ARGB\" \"#RGB/#ARGB\""
|
||||
return "error: [\(Colors.toolName)] Bad line format: \(info). Accepted format are: colorName=\"#RGB/#ARGB\"; colorName \"#RGB/#ARGB\"; colorName \"#RGB/#ARGB\" \"#RGB/#ARGB\""
|
||||
|
||||
case .writeAsset(let info):
|
||||
return "error:[\(Colors.toolName)] An error occured while writing color in Xcasset: \(info)"
|
||||
return "error: [\(Colors.toolName)] An error occured while writing color in Xcasset: \(info)"
|
||||
|
||||
case .createAssetFolder(let assetsFolder):
|
||||
return "error:[\(Colors.toolName)] An error occured while creating colors folder `\(assetsFolder)`"
|
||||
return "error: [\(Colors.toolName)] An error occured while creating colors folder `\(assetsFolder)`"
|
||||
|
||||
case .writeExtension(let filename, let info):
|
||||
return "error:[\(Colors.toolName)] An error occured while writing extension in \(filename): \(info)"
|
||||
return "error: [\(Colors.toolName)] An error occured while writing extension in \(filename): \(info)"
|
||||
|
||||
case .fileNotExists(let filename):
|
||||
return "error:[\(Colors.toolName)] File \(filename) does not exists"
|
||||
return "error: [\(Colors.toolName)] File \(filename) does not exists"
|
||||
|
||||
case .badColorDefinition(let lightColor, let darkColor):
|
||||
return "error:[\(Colors.toolName)] One of these two colors has invalid synthax: -\(lightColor)- or -\(darkColor)-"
|
||||
return "error: [\(Colors.toolName)] One of these two colors has invalid synthax: -\(lightColor)- or -\(darkColor)-"
|
||||
|
||||
case .deleteExistingColors(let assetsFolder):
|
||||
return "error:[\(Colors.toolName)] An error occured while deleting colors folder `\(assetsFolder)`"
|
||||
return "error: [\(Colors.toolName)] An error occured while deleting colors folder `\(assetsFolder)`"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -27,11 +27,11 @@ struct ColorsToolOptions: ParsableArguments {
|
||||
@Option(help: "Tell if it will generate static properties or not")
|
||||
var staticMembers: Bool = false
|
||||
|
||||
@Option(help: "Extension name. If not specified, it will generate an UIColor extension.")
|
||||
@Option(help: "Extension name. If not specified, it will generate an Color extension.")
|
||||
var extensionName: String = Colors.defaultExtensionName
|
||||
|
||||
@Option(help: "SwiftUI Extension name. If not specified, it will generate an Color extension.")
|
||||
var extensionNameSwiftUI: String = Colors.defaultExtensionNameSUI
|
||||
@Option(help: "SwiftUI Extension name. If not specified, it will generate an UIColor extension.")
|
||||
var extensionNameUIKit: String = Colors.defaultExtensionNameUIKit
|
||||
|
||||
@Option(help: "Extension suffix. Ex: MyApp, it will generate {extensionName}+ColorsMyApp.swift")
|
||||
var extensionSuffix: String?
|
||||
@ -41,7 +41,7 @@ struct ColorsToolOptions: ParsableArguments {
|
||||
|
||||
extension ColorsToolOptions {
|
||||
|
||||
// MARK: - UIKit
|
||||
// MARK: - SwiftUI
|
||||
|
||||
var extensionFileName: String {
|
||||
if let extensionSuffix = extensionSuffix {
|
||||
@ -54,16 +54,16 @@ extension ColorsToolOptions {
|
||||
"\(extensionOutputPath)/\(extensionFileName)"
|
||||
}
|
||||
|
||||
// MARK: - SwiftUI
|
||||
// MARK: - UIKit
|
||||
|
||||
var extensionFileNameSwiftUI: String {
|
||||
var extensionFileNameUIKit: String {
|
||||
if let extensionSuffix = extensionSuffix {
|
||||
return "\(extensionNameSwiftUI)+\(extensionSuffix).swift"
|
||||
return "\(extensionNameUIKit)+\(extensionSuffix).swift"
|
||||
}
|
||||
return "\(extensionNameSwiftUI).swift"
|
||||
return "\(extensionNameUIKit).swift"
|
||||
}
|
||||
|
||||
var extensionFilePathSwiftUI: String {
|
||||
"\(extensionOutputPath)/\(extensionFileNameSwiftUI)"
|
||||
var extensionFilePathUIKit: String {
|
||||
"\(extensionOutputPath)/\(extensionFileNameUIKit)"
|
||||
}
|
||||
}
|
||||
|
@ -30,9 +30,9 @@ struct ColorExtensionGenerator {
|
||||
let extensionFilePathURL = URL(fileURLWithPath: extensionFilePath)
|
||||
do {
|
||||
try extensionContent.write(to: extensionFilePathURL, atomically: false, encoding: .utf8)
|
||||
} catch (let error) {
|
||||
} catch let error {
|
||||
let error = ColorsToolError.writeExtension(extensionFilePath, error.localizedDescription)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Colors.exit(withError: error)
|
||||
}
|
||||
}
|
||||
|
@ -29,7 +29,7 @@ struct ColorXcassetHelper {
|
||||
withIntermediateDirectories: true)
|
||||
} catch {
|
||||
let error = ColorsToolError.createAssetFolder(colorSetPath)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Colors.exit(withError: error)
|
||||
}
|
||||
}
|
||||
@ -38,9 +38,9 @@ struct ColorXcassetHelper {
|
||||
let contentsJsonPathURL = URL(fileURLWithPath: contentsJsonPath)
|
||||
do {
|
||||
try color.contentsJSON().write(to: contentsJsonPathURL, atomically: false, encoding: .utf8)
|
||||
} catch (let error) {
|
||||
} catch let error {
|
||||
let error = ColorsToolError.writeAsset(error.localizedDescription)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Colors.exit(withError: error)
|
||||
}
|
||||
}
|
||||
|
@ -26,7 +26,7 @@ struct ParsedColor {
|
||||
|
||||
guard allComponents.contains(true) == false else {
|
||||
let error = ColorsToolError.badColorDefinition(light, dark)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Colors.exit(withError: error)
|
||||
}
|
||||
|
||||
|
@ -37,7 +37,7 @@ class ColorFileParser {
|
||||
|
||||
guard colorContent.count >= 2 else {
|
||||
let error = ColorsToolError.badFormat(colorLine)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Colors.exit(withError: error)
|
||||
}
|
||||
|
||||
|
@ -21,11 +21,11 @@ struct FontsOptions: ParsableArguments {
|
||||
@Option(help: "Tell if it will generate static properties or methods")
|
||||
var staticMembers: Bool = false
|
||||
|
||||
@Option(help: "Extension name. If not specified, it will generate an UIFont extension.")
|
||||
@Option(help: "Extension name. If not specified, it will generate an Font extension.")
|
||||
var extensionName: String = Fonts.defaultExtensionName
|
||||
|
||||
@Option(help: "Extension name. If not specified, it will generate an Font extension.")
|
||||
var extensionNameSwiftUI: String = Fonts.defaultExtensionNameSUI
|
||||
@Option(help: "Extension name. If not specified, it will generate an UIFont extension.")
|
||||
var extensionNameUIKit: String = Fonts.defaultExtensionNameUIKit
|
||||
|
||||
@Option(help: "Extension suffix. Ex: MyApp, it will generate {extensionName}+FontsMyApp.swift")
|
||||
var extensionSuffix: String = ""
|
||||
@ -38,7 +38,7 @@ struct FontsOptions: ParsableArguments {
|
||||
|
||||
extension FontsOptions {
|
||||
|
||||
// MARK: - UIKit
|
||||
// MARK: - SwiftUI
|
||||
|
||||
var extensionFileName: String {
|
||||
if extensionSuffix.isEmpty == false {
|
||||
@ -51,17 +51,17 @@ extension FontsOptions {
|
||||
"\(extensionOutputPath)/\(extensionFileName)"
|
||||
}
|
||||
|
||||
// MARK: - SwiftUI
|
||||
// MARK: - UIKit
|
||||
|
||||
var extensionFileNameSwiftUI: String {
|
||||
var extensionFileNameUIKit: String {
|
||||
if extensionSuffix.isEmpty == false {
|
||||
return "\(extensionNameSwiftUI)+\(extensionSuffix).swift"
|
||||
return "\(extensionNameUIKit)+\(extensionSuffix).swift"
|
||||
}
|
||||
return "\(extensionNameSwiftUI).swift"
|
||||
return "\(extensionNameUIKit).swift"
|
||||
}
|
||||
|
||||
var extensionFilePathSwiftUI: String {
|
||||
"\(extensionOutputPath)/\(extensionFileNameSwiftUI)"
|
||||
var extensionFilePathUIKit: String {
|
||||
"\(extensionOutputPath)/\(extensionFileNameUIKit)"
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
@ -21,8 +21,8 @@ struct Fonts: ParsableCommand {
|
||||
// MARK: - Static
|
||||
|
||||
static let toolName = "Fonts"
|
||||
static let defaultExtensionName = "UIFont"
|
||||
static let defaultExtensionNameSUI = "Font"
|
||||
static let defaultExtensionName = "Font"
|
||||
static let defaultExtensionNameUIKit = "UIFont"
|
||||
|
||||
// MARK: - Command Options
|
||||
|
||||
@ -52,13 +52,13 @@ struct Fonts: ParsableCommand {
|
||||
staticVar: options.staticMembers,
|
||||
extensionName: options.extensionName,
|
||||
extensionFilePath: options.extensionFilePath,
|
||||
isSwiftUI: false)
|
||||
isSwiftUI: true)
|
||||
|
||||
FontExtensionGenerator.writeExtensionFile(fontsNames: fontsNames,
|
||||
staticVar: options.staticMembers,
|
||||
extensionName: options.extensionNameSwiftUI,
|
||||
extensionFilePath: options.extensionFilePathSwiftUI,
|
||||
isSwiftUI: true)
|
||||
extensionName: options.extensionNameUIKit,
|
||||
extensionFilePath: options.extensionFilePathUIKit,
|
||||
isSwiftUI: false)
|
||||
|
||||
print("Info.plist has been updated with:")
|
||||
print("\(FontPlistGenerator.generatePlistUIAppsFontContent(for: fontsNames, infoPlistPaths: options.infoPlistPaths))")
|
||||
@ -74,14 +74,14 @@ struct Fonts: ParsableCommand {
|
||||
// Check input file exists
|
||||
guard fileManager.fileExists(atPath: options.inputFile) else {
|
||||
let error = FontsToolError.fileNotExists(options.inputFile)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Fonts.exit(withError: error)
|
||||
}
|
||||
|
||||
// Extension for UIKit and SwiftUI should have different name
|
||||
guard options.extensionName != options.extensionNameSwiftUI else {
|
||||
guard options.extensionName != options.extensionNameUIKit else {
|
||||
let error = FontsToolError.extensionNamesCollision(options.extensionName)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Fonts.exit(withError: error)
|
||||
}
|
||||
|
||||
|
@ -14,22 +14,22 @@ enum FontsToolError: Error {
|
||||
case fileNotExists(String)
|
||||
case writeExtension(String, String)
|
||||
|
||||
var localizedDescription: String {
|
||||
var description: String {
|
||||
switch self {
|
||||
case .extensionNamesCollision(let extensionName):
|
||||
return "error:[\(Fonts.toolName)] Error on extension names, extension name and SwiftUI extension name should be different (\(extensionName) is used on both)"
|
||||
return "error: [\(Fonts.toolName)] Error on extension names, extension name and SwiftUI extension name should be different (\(extensionName) is used on both)"
|
||||
|
||||
case .fcScan(let path, let code, let output):
|
||||
return "error:[\(Fonts.toolName)] Error while getting fontName (fc-scan --format %{postscriptname} \(path). fc-scan exit with \(code) and output is: \(output ?? "no output")"
|
||||
return "error: [\(Fonts.toolName)] Error while getting fontName (fc-scan --format %{postscriptname} \(path). fc-scan exit with \(code) and output is: \(output ?? "no output")"
|
||||
|
||||
case .inputFolderNotFound(let inputFolder):
|
||||
return " error:[\(Fonts.toolName)] Input folder not found: \(inputFolder)"
|
||||
return "error: [\(Fonts.toolName)] Input folder not found: \(inputFolder)"
|
||||
|
||||
case .fileNotExists(let filename):
|
||||
return " error:[\(Fonts.toolName)] File \(filename) does not exists"
|
||||
return "error: [\(Fonts.toolName)] File \(filename) does not exists"
|
||||
|
||||
case .writeExtension(let filename, let info):
|
||||
return "error:[\(Fonts.toolName)] An error occured while writing extension in \(filename): \(info)"
|
||||
return "error: [\(Fonts.toolName)] An error occured while writing extension in \(filename): \(info)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -39,7 +39,7 @@ class FontsToolHelper {
|
||||
let fileManager = FileManager()
|
||||
guard fileManager.fileExists(atPath: inputFolder) else {
|
||||
let error = FontsToolError.inputFolderNotFound(inputFolder)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Fonts.exit(withError: error)
|
||||
}
|
||||
|
||||
@ -64,7 +64,7 @@ class FontsToolHelper {
|
||||
|
||||
guard let fontName = task.output, task.terminationStatus == 0 else {
|
||||
let error = FontsToolError.fcScan(path, task.terminationStatus, task.output)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Fonts.exit(withError: error)
|
||||
}
|
||||
|
||||
|
@ -36,9 +36,9 @@ class FontExtensionGenerator {
|
||||
let extensionFilePathURL = URL(fileURLWithPath: extensionFilePath)
|
||||
do {
|
||||
try extensionContent.write(to: extensionFilePathURL, atomically: false, encoding: .utf8)
|
||||
} catch (let error) {
|
||||
} catch let error {
|
||||
let error = FontsToolError.writeExtension(extensionFilePath, error.localizedDescription)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Fonts.exit(withError: error)
|
||||
}
|
||||
}
|
||||
|
@ -34,6 +34,7 @@ struct Generate: ParsableCommand {
|
||||
// Parse
|
||||
let configuration = ConfigurationFileParser.parse(options.configurationFile)
|
||||
print("Found configurations :")
|
||||
print(" - \(configuration.analytics.count) analytics configuration(s)")
|
||||
print(" - \(configuration.colors.count) colors configuration(s)")
|
||||
print(" - \(configuration.fonts.count) fonts configuration(s)")
|
||||
print(" - \(configuration.images.count) images configuration(s)")
|
||||
@ -41,7 +42,10 @@ struct Generate: ParsableCommand {
|
||||
print(" - \(configuration.tags.count) tags configuration(s)")
|
||||
print()
|
||||
|
||||
print("Input file: \(configuration.colors.first?.inputFile ?? "no input file")")
|
||||
if let architecture = configuration.architecture {
|
||||
ArchitectureGenerator.writeArchitecture(architecture,
|
||||
projectDirectory: options.projectDirectory)
|
||||
}
|
||||
|
||||
// Execute commands
|
||||
configuration.runnableConfigurations
|
||||
|
@ -11,20 +11,24 @@ enum GenerateError: Error {
|
||||
case fileNotExists(String)
|
||||
case invalidConfigurationFile(String)
|
||||
case commandError([String], String)
|
||||
case writeFile(String, String)
|
||||
|
||||
var localizedDescription: String {
|
||||
var description: String {
|
||||
switch self {
|
||||
case .fileNotExists(let filename):
|
||||
return " error:[\(Generate.toolName)] File \(filename) does not exists"
|
||||
return "error: [\(Generate.toolName)] File \(filename) does not exists"
|
||||
|
||||
case .invalidConfigurationFile(let filename):
|
||||
return " error:[\(Generate.toolName)] File \(filename) is not a valid configuration file"
|
||||
return "error: [\(Generate.toolName)] File \(filename) is not a valid configuration file"
|
||||
|
||||
case .commandError(let command, let terminationStatus):
|
||||
let readableCommand = command
|
||||
.map { $0 }
|
||||
.joined(separator: " ")
|
||||
return "error:[\(Generate.toolName)] An error occured while running command '\(readableCommand)'. Command terminate with status code: \(terminationStatus)"
|
||||
return "error: [\(Generate.toolName)] An error occured while running command '\(readableCommand)'. Command terminate with status code: \(terminationStatus)"
|
||||
|
||||
case .writeFile(let filename, let info):
|
||||
return "error: [\(Generate.toolName)] An error occured while writing file in \(filename): \(info)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -5,8 +5,6 @@
|
||||
// Created by Thibaut Schmitt on 30/08/2022.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
import Foundation
|
||||
import ArgumentParser
|
||||
|
||||
|
@ -0,0 +1,39 @@
|
||||
//
|
||||
// ArchitectureGenerator.swift
|
||||
//
|
||||
//
|
||||
// Created by Thibaut Schmitt on 18/11/2022.
|
||||
//
|
||||
|
||||
import ToolCore
|
||||
import Foundation
|
||||
|
||||
struct ArchitectureGenerator {
|
||||
static func writeArchitecture(_ architecture: ConfigurationArchitecture, projectDirectory: String) {
|
||||
// Create extension content
|
||||
var architectureContent = [
|
||||
"// Generated by ResgenSwift.\(Generate.toolName) \(ResgenSwiftVersion)",
|
||||
architecture.getClass()
|
||||
]
|
||||
.joined(separator: "\n\n")
|
||||
|
||||
architectureContent += "\n"
|
||||
|
||||
let filename = "\(architecture.classname).swift"
|
||||
guard let filePath = architecture.path?.prependIfRelativePath(projectDirectory) else {
|
||||
let error = GenerateError.writeFile(filename, "Path of file is not defined.")
|
||||
print(error.description)
|
||||
Generate.exit(withError: error)
|
||||
}
|
||||
|
||||
// Write content
|
||||
let architectureFilePathURL = URL(fileURLWithPath: "\(filePath)/\(filename)")
|
||||
do {
|
||||
try architectureContent.write(to: architectureFilePathURL, atomically: false, encoding: .utf8)
|
||||
} catch let error {
|
||||
let error = GenerateError.writeFile(filename, error.localizedDescription)
|
||||
print(error.description)
|
||||
Generate.exit(withError: error)
|
||||
}
|
||||
}
|
||||
}
|
@ -8,6 +8,8 @@
|
||||
import Foundation
|
||||
|
||||
struct ConfigurationFile: Codable, CustomDebugStringConvertible {
|
||||
var architecture: ConfigurationArchitecture?
|
||||
var analytics: [AnalyticsConfiguration]
|
||||
var colors: [ColorsConfiguration]
|
||||
var fonts: [FontsConfiguration]
|
||||
var images: [ImagesConfiguration]
|
||||
@ -15,12 +17,15 @@ struct ConfigurationFile: Codable, CustomDebugStringConvertible {
|
||||
var tags: [TagsConfiguration]
|
||||
|
||||
var runnableConfigurations: [Runnable] {
|
||||
let runnables: [[Runnable]] = [colors, fonts, images, strings, tags]
|
||||
let runnables: [[Runnable]] = [analytics, colors, fonts, images, strings, tags]
|
||||
return Array(runnables.joined())
|
||||
}
|
||||
|
||||
var debugDescription: String {
|
||||
"""
|
||||
\(analytics)
|
||||
-----------
|
||||
-----------
|
||||
\(colors)
|
||||
-----------
|
||||
-----------
|
||||
@ -38,6 +43,83 @@ struct ConfigurationFile: Codable, CustomDebugStringConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
struct ConfigurationArchitecture: Codable {
|
||||
let property: String
|
||||
let classname: String
|
||||
let path: String?
|
||||
let children: [ConfigurationArchitecture]?
|
||||
|
||||
func getProperty(isStatic: Bool) -> String {
|
||||
" \(isStatic ? "static " : "")let \(property) = \(classname)()"
|
||||
}
|
||||
|
||||
func getClass(generateStaticProperty: Bool = true) -> String {
|
||||
guard children?.isEmpty == false else {
|
||||
return "class \(classname) {}"
|
||||
}
|
||||
|
||||
let classDefinition = [
|
||||
"class \(classname) {",
|
||||
children?.map { $0.getProperty(isStatic: generateStaticProperty) }.joined(separator: "\n"),
|
||||
"}"
|
||||
]
|
||||
.compactMap { $0 }
|
||||
.joined(separator: "\n")
|
||||
|
||||
return [classDefinition, "", getSubclass()]
|
||||
.compactMap { $0 }
|
||||
.joined(separator: "\n")
|
||||
}
|
||||
|
||||
func getSubclass() -> String? {
|
||||
guard let children else { return nil }
|
||||
return children.compactMap { arch in
|
||||
arch.getClass(generateStaticProperty: false)
|
||||
}
|
||||
.joined(separator: "\n\n")
|
||||
}
|
||||
}
|
||||
|
||||
struct AnalyticsConfiguration: Codable, CustomDebugStringConvertible {
|
||||
let inputFile: String
|
||||
let target: String
|
||||
let extensionOutputPath: String
|
||||
let extensionName: String?
|
||||
let extensionSuffix: String?
|
||||
private let staticMembers: Bool?
|
||||
|
||||
var staticMembersOptions: Bool {
|
||||
if let staticMembers = staticMembers {
|
||||
return staticMembers
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
internal init(inputFile: String,
|
||||
target: String,
|
||||
extensionOutputPath: String,
|
||||
extensionName: String?,
|
||||
extensionSuffix: String?,
|
||||
staticMembers: Bool?) {
|
||||
self.inputFile = inputFile
|
||||
self.target = target
|
||||
self.extensionOutputPath = extensionOutputPath
|
||||
self.extensionName = extensionName
|
||||
self.extensionSuffix = extensionSuffix
|
||||
self.staticMembers = staticMembers
|
||||
}
|
||||
|
||||
var debugDescription: String {
|
||||
"""
|
||||
Analytics configuration:
|
||||
- Input file: \(inputFile)
|
||||
- Target: \(target)
|
||||
- Extension output path: \(extensionOutputPath)
|
||||
- Extension name: \(extensionName ?? "-")
|
||||
- Extension suffix: \(extensionSuffix ?? "-")
|
||||
"""
|
||||
}
|
||||
}
|
||||
|
||||
struct ColorsConfiguration: Codable, CustomDebugStringConvertible {
|
||||
let inputFile: String
|
||||
@ -45,7 +127,7 @@ struct ColorsConfiguration: Codable, CustomDebugStringConvertible {
|
||||
let xcassetsPath: String
|
||||
let extensionOutputPath: String
|
||||
let extensionName: String?
|
||||
let extensionNameSwiftUI: String?
|
||||
let extensionNameUIKit: String?
|
||||
let extensionSuffix: String?
|
||||
private let staticMembers: Bool?
|
||||
|
||||
@ -61,7 +143,7 @@ struct ColorsConfiguration: Codable, CustomDebugStringConvertible {
|
||||
xcassetsPath: String,
|
||||
extensionOutputPath: String,
|
||||
extensionName: String?,
|
||||
extensionNameSwiftUI: String?,
|
||||
extensionNameUIKit: String?,
|
||||
extensionSuffix: String?,
|
||||
staticMembers: Bool?) {
|
||||
self.inputFile = inputFile
|
||||
@ -69,7 +151,7 @@ struct ColorsConfiguration: Codable, CustomDebugStringConvertible {
|
||||
self.xcassetsPath = xcassetsPath
|
||||
self.extensionOutputPath = extensionOutputPath
|
||||
self.extensionName = extensionName
|
||||
self.extensionNameSwiftUI = extensionNameSwiftUI
|
||||
self.extensionNameUIKit = extensionNameUIKit
|
||||
self.extensionSuffix = extensionSuffix
|
||||
self.staticMembers = staticMembers
|
||||
}
|
||||
@ -82,7 +164,7 @@ struct ColorsConfiguration: Codable, CustomDebugStringConvertible {
|
||||
- Xcassets path: \(xcassetsPath)
|
||||
- Extension output path: \(extensionOutputPath)
|
||||
- Extension name: \(extensionName ?? "-")
|
||||
- Extension name SwiftUI: \(extensionNameSwiftUI ?? "-")
|
||||
- Extension name UIKit: \(extensionNameUIKit ?? "-")
|
||||
- Extension suffix: \(extensionSuffix ?? "-")
|
||||
"""
|
||||
}
|
||||
@ -92,7 +174,7 @@ struct FontsConfiguration: Codable, CustomDebugStringConvertible {
|
||||
let inputFile: String
|
||||
let extensionOutputPath: String
|
||||
let extensionName: String?
|
||||
let extensionNameSwiftUI: String?
|
||||
let extensionNameUIKit: String?
|
||||
let extensionSuffix: String?
|
||||
let infoPlistPaths: String?
|
||||
private let staticMembers: Bool?
|
||||
@ -107,14 +189,14 @@ struct FontsConfiguration: Codable, CustomDebugStringConvertible {
|
||||
internal init(inputFile: String,
|
||||
extensionOutputPath: String,
|
||||
extensionName: String?,
|
||||
extensionNameSwiftUI: String?,
|
||||
extensionNameUIKit: String?,
|
||||
extensionSuffix: String?,
|
||||
infoPlistPaths: String?,
|
||||
staticMembers: Bool?) {
|
||||
self.inputFile = inputFile
|
||||
self.extensionOutputPath = extensionOutputPath
|
||||
self.extensionName = extensionName
|
||||
self.extensionNameSwiftUI = extensionNameSwiftUI
|
||||
self.extensionNameUIKit = extensionNameUIKit
|
||||
self.extensionSuffix = extensionSuffix
|
||||
self.infoPlistPaths = infoPlistPaths
|
||||
self.staticMembers = staticMembers
|
||||
@ -126,7 +208,7 @@ struct FontsConfiguration: Codable, CustomDebugStringConvertible {
|
||||
- Input file: \(inputFile)
|
||||
- Extension output path: \(extensionOutputPath)
|
||||
- Extension name: \(extensionName ?? "-")
|
||||
- Extension name SwiftUI: \(extensionNameSwiftUI ?? "-")
|
||||
- Extension name UIKit: \(extensionNameUIKit ?? "-")
|
||||
- Extension suffix: \(extensionSuffix ?? "-")
|
||||
- InfoPlistPaths: \(infoPlistPaths ?? "-")
|
||||
"""
|
||||
@ -138,7 +220,7 @@ struct ImagesConfiguration: Codable, CustomDebugStringConvertible {
|
||||
let xcassetsPath: String
|
||||
let extensionOutputPath: String
|
||||
let extensionName: String?
|
||||
let extensionNameSwiftUI: String?
|
||||
let extensionNameUIKit: String?
|
||||
let extensionSuffix: String?
|
||||
private let staticMembers: Bool?
|
||||
|
||||
@ -153,14 +235,14 @@ struct ImagesConfiguration: Codable, CustomDebugStringConvertible {
|
||||
xcassetsPath: String,
|
||||
extensionOutputPath: String,
|
||||
extensionName: String?,
|
||||
extensionNameSwiftUI: String?,
|
||||
extensionNameUIKit: String?,
|
||||
extensionSuffix: String?,
|
||||
staticMembers: Bool?) {
|
||||
self.inputFile = inputFile
|
||||
self.xcassetsPath = xcassetsPath
|
||||
self.extensionOutputPath = extensionOutputPath
|
||||
self.extensionName = extensionName
|
||||
self.extensionNameSwiftUI = extensionNameSwiftUI
|
||||
self.extensionNameUIKit = extensionNameUIKit
|
||||
self.extensionSuffix = extensionSuffix
|
||||
self.staticMembers = staticMembers
|
||||
}
|
||||
@ -172,7 +254,7 @@ struct ImagesConfiguration: Codable, CustomDebugStringConvertible {
|
||||
- Xcassets path: \(xcassetsPath)
|
||||
- Extension output path: \(extensionOutputPath)
|
||||
- Extension name: \(extensionName ?? "-")
|
||||
- Extension name SwiftUI: \(extensionNameSwiftUI ?? "-")
|
||||
- Extension name UIKit: \(extensionNameUIKit ?? "-")
|
||||
- Extension suffix: \(extensionSuffix ?? "-")
|
||||
"""
|
||||
}
|
||||
@ -267,4 +349,3 @@ struct TagsConfiguration: Codable, CustomDebugStringConvertible {
|
||||
"""
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -12,13 +12,13 @@ class ConfigurationFileParser {
|
||||
static func parse(_ configurationFile: String) -> ConfigurationFile {
|
||||
guard let data = FileManager().contents(atPath: configurationFile) else {
|
||||
let error = GenerateError.fileNotExists(configurationFile)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Generate.exit(withError: error)
|
||||
}
|
||||
|
||||
guard let configuration = try? YAMLDecoder().decode(ConfigurationFile.self, from: data) else {
|
||||
let error = GenerateError.invalidConfigurationFile(configurationFile)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Generate.exit(withError: error)
|
||||
}
|
||||
|
||||
|
@ -0,0 +1,43 @@
|
||||
//
|
||||
// AnalyticsConfiguration+Runnable.swift
|
||||
//
|
||||
//
|
||||
// Created by Loris Perret on 08/12/2023.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
extension AnalyticsConfiguration: Runnable {
|
||||
func run(projectDirectory: String, force: Bool) {
|
||||
var args = [String]()
|
||||
|
||||
if force {
|
||||
args += ["-f"]
|
||||
}
|
||||
|
||||
args += [
|
||||
inputFile.prependIfRelativePath(projectDirectory),
|
||||
"--target",
|
||||
target,
|
||||
"--extension-output-path",
|
||||
extensionOutputPath.prependIfRelativePath(projectDirectory),
|
||||
"--static-members",
|
||||
"\(staticMembersOptions)"
|
||||
]
|
||||
|
||||
if let extensionName = extensionName {
|
||||
args += [
|
||||
"--extension-name",
|
||||
extensionName
|
||||
]
|
||||
}
|
||||
if let extensionSuffix = extensionSuffix {
|
||||
args += [
|
||||
"--extension-suffix",
|
||||
extensionSuffix
|
||||
]
|
||||
}
|
||||
|
||||
Analytics.main(args)
|
||||
}
|
||||
}
|
@ -38,10 +38,10 @@ extension ColorsConfiguration: Runnable {
|
||||
extensionName
|
||||
]
|
||||
}
|
||||
if let extensionNameSwiftUI = extensionNameSwiftUI {
|
||||
if let extensionNameUIKit = extensionNameUIKit {
|
||||
args += [
|
||||
"--extension-name-swift-ui",
|
||||
extensionNameSwiftUI
|
||||
"--extension-name-ui-kit",
|
||||
extensionNameUIKit
|
||||
]
|
||||
}
|
||||
if let extensionSuffix = extensionSuffix {
|
||||
|
@ -34,10 +34,10 @@ extension FontsConfiguration: Runnable {
|
||||
extensionName
|
||||
]
|
||||
}
|
||||
if let extensionNameSwiftUI = extensionNameSwiftUI {
|
||||
if let extensionNameUIKit = extensionNameUIKit {
|
||||
args += [
|
||||
"--extension-name-swift-ui",
|
||||
extensionNameSwiftUI
|
||||
"--extension-name-ui-kit",
|
||||
extensionNameUIKit
|
||||
]
|
||||
}
|
||||
|
||||
|
@ -36,10 +36,10 @@ extension ImagesConfiguration: Runnable {
|
||||
extensionName
|
||||
]
|
||||
}
|
||||
if let extensionNameSwiftUI = extensionNameSwiftUI {
|
||||
if let extensionNameUIKit = extensionNameUIKit {
|
||||
args += [
|
||||
"--extension-name-swift-ui",
|
||||
extensionNameSwiftUI
|
||||
"--extension-name-ui-kit",
|
||||
extensionNameUIKit
|
||||
]
|
||||
}
|
||||
if let extensionSuffix = extensionSuffix {
|
||||
|
@ -10,4 +10,3 @@ import Foundation
|
||||
protocol Runnable {
|
||||
func run(projectDirectory: String, force: Bool)
|
||||
}
|
||||
|
||||
|
@ -12,19 +12,19 @@ extension FileManager {
|
||||
var files = [String]()
|
||||
guard let enumerator = self.enumerator(at: URL(string: directory)!, includingPropertiesForKeys: [.isRegularFileKey], options: [.skipsHiddenFiles, .skipsPackageDescendants]) else {
|
||||
let error = ImagesError.unknown("Cannot enumerate file in \(directory)")
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Images.exit(withError: error)
|
||||
}
|
||||
|
||||
for case let fileURL as URL in enumerator {
|
||||
do {
|
||||
let fileAttributes = try fileURL.resourceValues(forKeys:[.isRegularFileKey])
|
||||
let fileAttributes = try fileURL.resourceValues(forKeys: [.isRegularFileKey])
|
||||
if fileAttributes.isRegularFile! {
|
||||
files.append(fileURL.relativePath)
|
||||
}
|
||||
} catch {
|
||||
let error = ImagesError.getFileAttributed(fileURL.relativePath, error.localizedDescription)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Images.exit(withError: error)
|
||||
}
|
||||
}
|
||||
@ -35,19 +35,19 @@ extension FileManager {
|
||||
var files = [String]()
|
||||
guard let enumerator = self.enumerator(at: URL(string: directory)!, includingPropertiesForKeys: [.isDirectoryKey], options: [.skipsHiddenFiles, .skipsPackageDescendants]) else {
|
||||
let error = ImagesError.unknown("Cannot enumerate imageset directory in \(directory)")
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Images.exit(withError: error)
|
||||
}
|
||||
|
||||
for case let fileURL as URL in enumerator {
|
||||
do {
|
||||
let fileAttributes = try fileURL.resourceValues(forKeys:[.isDirectoryKey])
|
||||
let fileAttributes = try fileURL.resourceValues(forKeys: [.isDirectoryKey])
|
||||
if fileAttributes.isDirectory! && fileURL.lastPathComponent.hasSuffix(".imageset") {
|
||||
files.append(fileURL.lastPathComponent)
|
||||
}
|
||||
} catch {
|
||||
let error = ImagesError.getFileAttributed(fileURL.relativePath, error.localizedDescription)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Images.exit(withError: error)
|
||||
}
|
||||
}
|
||||
|
@ -29,9 +29,9 @@ class ImageExtensionGenerator {
|
||||
let extensionFilePathURL = URL(fileURLWithPath: extensionFilePath)
|
||||
do {
|
||||
try extensionContent.write(to: extensionFilePathURL, atomically: false, encoding: .utf8)
|
||||
} catch (let error) {
|
||||
} catch let error {
|
||||
let error = ImagesError.writeFile(extensionFilePath, error.localizedDescription)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Images.exit(withError: error)
|
||||
}
|
||||
}
|
||||
|
@ -48,7 +48,7 @@ class XcassetsGenerator {
|
||||
}
|
||||
}
|
||||
let error = ImagesError.unknownImageExtension(parsedImage.name)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Images.exit(withError: error)
|
||||
}()
|
||||
|
||||
@ -77,7 +77,7 @@ class XcassetsGenerator {
|
||||
withIntermediateDirectories: true)
|
||||
} catch {
|
||||
let error = ImagesError.createAssetFolder(imagesetPath)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Images.exit(withError: error)
|
||||
}
|
||||
}
|
||||
|
@ -21,8 +21,8 @@ struct Images: ParsableCommand {
|
||||
// MARK: - Static
|
||||
|
||||
static let toolName = "Images"
|
||||
static let defaultExtensionName = "UIImage"
|
||||
static let defaultExtensionNameSUI = "Image"
|
||||
static let defaultExtensionName = "Image"
|
||||
static let defaultExtensionNameUIKit = "UIImage"
|
||||
|
||||
// MARK: - Command Options
|
||||
|
||||
@ -58,14 +58,14 @@ struct Images: ParsableCommand {
|
||||
inputFilename: options.inputFilenameWithoutExt,
|
||||
extensionName: options.extensionName,
|
||||
extensionFilePath: options.extensionFilePath,
|
||||
isSwiftUI: false)
|
||||
isSwiftUI: true)
|
||||
|
||||
ImageExtensionGenerator.generateExtensionFile(images: imagesToGenerate,
|
||||
staticVar: options.staticMembers,
|
||||
inputFilename: options.inputFilenameWithoutExt,
|
||||
extensionName: options.extensionNameSwiftUI,
|
||||
extensionFilePath: options.extensionFilePathSwiftUI,
|
||||
isSwiftUI: true)
|
||||
extensionName: options.extensionNameUIKit,
|
||||
extensionFilePath: options.extensionFilePathUIKit,
|
||||
isSwiftUI: false)
|
||||
|
||||
print("[\(Self.toolName)] Images generated")
|
||||
}
|
||||
@ -82,7 +82,7 @@ struct Images: ParsableCommand {
|
||||
// Input file
|
||||
guard fileManager.fileExists(atPath: options.inputFile) else {
|
||||
let error = ImagesError.fileNotExists(options.inputFile)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Images.exit(withError: error)
|
||||
}
|
||||
|
||||
@ -90,9 +90,9 @@ struct Images: ParsableCommand {
|
||||
_ = Images.getSvgConverterPath()
|
||||
|
||||
// Extension for UIKit and SwiftUI should have different name
|
||||
guard options.extensionName != options.extensionNameSwiftUI else {
|
||||
guard options.extensionName != options.extensionNameUIKit else {
|
||||
let error = ImagesError.extensionNamesCollision(options.extensionName)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Images.exit(withError: error)
|
||||
}
|
||||
|
||||
@ -117,7 +117,7 @@ struct Images: ParsableCommand {
|
||||
}
|
||||
|
||||
let error = ImagesError.rsvgConvertNotFound
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Images.exit(withError: error)
|
||||
}
|
||||
}
|
||||
|
@ -18,34 +18,34 @@ enum ImagesError: Error {
|
||||
case createAssetFolder(String)
|
||||
case unknown(String)
|
||||
|
||||
var localizedDescription: String {
|
||||
var description: String {
|
||||
switch self {
|
||||
case .extensionNamesCollision(let extensionName):
|
||||
return "error:[\(Fonts.toolName)] Error on extension names, extension name and SwiftUI extension name should be different (\(extensionName) is used on both)"
|
||||
return "error: [\(Fonts.toolName)] Error on extension names, extension name and SwiftUI extension name should be different (\(extensionName) is used on both)"
|
||||
|
||||
case .inputFolderNotFound(let inputFolder):
|
||||
return " error:[\(Images.toolName)] Input folder not found: \(inputFolder)"
|
||||
return "error: [\(Images.toolName)] Input folder not found: \(inputFolder)"
|
||||
|
||||
case .fileNotExists(let filename):
|
||||
return " error:[\(Images.toolName)] File \(filename) does not exists"
|
||||
return "error: [\(Images.toolName)] File \(filename) does not exists"
|
||||
|
||||
case .unknownImageExtension(let filename):
|
||||
return " error:[\(Images.toolName)] File \(filename) have an unhandled file extension. Cannot generate image."
|
||||
return "error: [\(Images.toolName)] File \(filename) have an unhandled file extension. Cannot generate image."
|
||||
|
||||
case .getFileAttributed(let filename, let errorDescription):
|
||||
return " error:[\(Images.toolName)] Getting file attributes of \(filename) failed with error: \(errorDescription)"
|
||||
return "error: [\(Images.toolName)] Getting file attributes of \(filename) failed with error: \(errorDescription)"
|
||||
|
||||
case .rsvgConvertNotFound:
|
||||
return " error:[\(Images.toolName)] Can't find rsvg-convert (can be installed with 'brew remove imagemagick && brew install imagemagick --with-librsvg')"
|
||||
return "error: [\(Images.toolName)] Can't find rsvg-convert (can be installed with 'brew remove imagemagick && brew install imagemagick --with-librsvg')"
|
||||
|
||||
case .writeFile(let subErrorDescription, let filename):
|
||||
return " error:[\(Images.toolName)] An error occured while writing content to \(filename): \(subErrorDescription)"
|
||||
return "error: [\(Images.toolName)] An error occured while writing content to \(filename): \(subErrorDescription)"
|
||||
|
||||
case .createAssetFolder(let folder):
|
||||
return "error:[\(Colors.toolName)] An error occured while creating folder `\(folder)`"
|
||||
return "error: [\(Colors.toolName)] An error occured while creating folder `\(folder)`"
|
||||
|
||||
case .unknown(let errorDescription):
|
||||
return " error:[\(Images.toolName)] Unknown error: \(errorDescription)"
|
||||
return "error: [\(Images.toolName)] Unknown error: \(errorDescription)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -27,11 +27,11 @@ struct ImagesOptions: ParsableArguments {
|
||||
@Option(help: "Tell if it will generate static properties or not")
|
||||
var staticMembers: Bool = false
|
||||
|
||||
@Option(help: "Extension name. If not specified, it will generate an UIImage extension.")
|
||||
@Option(help: "Extension name. If not specified, it will generate an Image extension.")
|
||||
var extensionName: String = Images.defaultExtensionName
|
||||
|
||||
@Option(help: "Extension name. If not specified, it will generate an Image extension.")
|
||||
var extensionNameSwiftUI: String = Images.defaultExtensionNameSUI
|
||||
@Option(help: "Extension name. If not specified, it will generate an UIImage extension.")
|
||||
var extensionNameUIKit: String = Images.defaultExtensionNameUIKit
|
||||
|
||||
@Option(help: "Extension suffix. Ex: MyApp, it will generate {extensionName}+Image{extensionSuffix}.swift")
|
||||
var extensionSuffix: String?
|
||||
@ -41,7 +41,7 @@ struct ImagesOptions: ParsableArguments {
|
||||
|
||||
extension ImagesOptions {
|
||||
|
||||
// MARK: - UIKit
|
||||
// MARK: - SwiftUI
|
||||
|
||||
var extensionFileName: String {
|
||||
if let extensionSuffix = extensionSuffix {
|
||||
@ -54,17 +54,17 @@ extension ImagesOptions {
|
||||
"\(extensionOutputPath)/\(extensionFileName)"
|
||||
}
|
||||
|
||||
// MARK: - SwiftUI
|
||||
// MARK: - UIKit
|
||||
|
||||
var extensionFileNameSwiftUI: String {
|
||||
var extensionFileNameUIKit: String {
|
||||
if let extensionSuffix = extensionSuffix {
|
||||
return "\(extensionNameSwiftUI)+\(extensionSuffix).swift"
|
||||
return "\(extensionNameUIKit)+\(extensionSuffix).swift"
|
||||
}
|
||||
return "\(extensionNameSwiftUI).swift"
|
||||
return "\(extensionNameUIKit).swift"
|
||||
}
|
||||
|
||||
var extensionFilePathSwiftUI: String {
|
||||
"\(extensionOutputPath)/\(extensionFileNameSwiftUI)"
|
||||
var extensionFilePathUIKit: String {
|
||||
"\(extensionOutputPath)/\(extensionFileNameUIKit)"
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
@ -12,7 +12,12 @@ class StringsFileGenerator {
|
||||
|
||||
// MARK: - Strings Files
|
||||
|
||||
static func writeStringsFiles(sections: [Section], langs: [String], defaultLang: String, tags: [String], outputPath: String, inputFilenameWithoutExt: String) {
|
||||
static func writeStringsFiles(sections: [Section],
|
||||
langs: [String],
|
||||
defaultLang: String,
|
||||
tags: [String],
|
||||
outputPath: String,
|
||||
inputFilenameWithoutExt: String) {
|
||||
var stringsFilesContent = [String: String]()
|
||||
for lang in langs {
|
||||
stringsFilesContent[lang] = Self.generateStringsFileContent(lang: lang,
|
||||
@ -29,15 +34,18 @@ class StringsFileGenerator {
|
||||
let stringsFilePathURL = URL(fileURLWithPath: stringsFilePath)
|
||||
do {
|
||||
try fileContent.write(to: stringsFilePathURL, atomically: false, encoding: .utf8)
|
||||
} catch (let error) {
|
||||
} catch let error {
|
||||
let error = StringiumError.writeFile(error.localizedDescription, stringsFilePath)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Stringium.exit(withError: error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static func generateStringsFileContent(lang: String, defaultLang: String, tags inputTags: [String], sections: [Section]) -> String {
|
||||
static func generateStringsFileContent(lang: String,
|
||||
defaultLang: String,
|
||||
tags inputTags: [String],
|
||||
sections: [Section]) -> String {
|
||||
var stringsFileContent = """
|
||||
/**
|
||||
* Apple Strings File
|
||||
@ -75,7 +83,7 @@ class StringsFileGenerator {
|
||||
stringsFileContent += "\"\(definition.name)\" = \"\(translation)\";\n\n"
|
||||
} else if skipDefinition == false {
|
||||
let error = StringiumError.langNotDefined(lang, definition.name, definition.reference != nil)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Stringium.exit(withError: error)
|
||||
}
|
||||
}
|
||||
@ -86,31 +94,46 @@ class StringsFileGenerator {
|
||||
|
||||
// MARK: - Extension file
|
||||
|
||||
static func writeExtensionFiles(sections: [Section], defaultLang lang: String, tags: [String], staticVar: Bool, inputFilename: String, extensionName: String, extensionFilePath: String) {
|
||||
static func writeExtensionFiles(sections: [Section],
|
||||
defaultLang lang: String,
|
||||
tags: [String],
|
||||
staticVar: Bool,
|
||||
inputFilename: String,
|
||||
extensionName: String,
|
||||
extensionFilePath: String,
|
||||
extensionSuffix: String) {
|
||||
// Get extension content
|
||||
let extensionFileContent = Self.getExtensionContent(sections: sections,
|
||||
defaultLang: lang,
|
||||
tags: tags,
|
||||
staticVar: staticVar,
|
||||
inputFilename: inputFilename,
|
||||
extensionName: extensionName)
|
||||
extensionName: extensionName,
|
||||
extensionSuffix: extensionSuffix)
|
||||
|
||||
// Write content
|
||||
let extensionFilePathURL = URL(fileURLWithPath: extensionFilePath)
|
||||
do {
|
||||
try extensionFileContent.write(to: extensionFilePathURL, atomically: false, encoding: .utf8)
|
||||
} catch (let error) {
|
||||
} catch let error {
|
||||
let error = StringiumError.writeFile(extensionFilePath, error.localizedDescription)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Stringium.exit(withError: error)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Extension content
|
||||
|
||||
static func getExtensionContent(sections: [Section], defaultLang lang: String, tags: [String], staticVar: Bool, inputFilename: String, extensionName: String) -> String {
|
||||
static func getExtensionContent(sections: [Section],
|
||||
defaultLang lang: String,
|
||||
tags: [String],
|
||||
staticVar: Bool,
|
||||
inputFilename: String,
|
||||
extensionName: String,
|
||||
extensionSuffix: String) -> String {
|
||||
[
|
||||
Self.getHeader(stringsFilename: inputFilename, extensionClassname: extensionName),
|
||||
Self.getEnumKey(sections: sections, tags: tags, extensionClassname: extensionName, extensionSuffix: extensionSuffix),
|
||||
Self.getProperties(sections: sections, defaultLang: lang, tags: tags, staticVar: staticVar),
|
||||
Self.getFooter()
|
||||
]
|
||||
@ -131,6 +154,50 @@ class StringsFileGenerator {
|
||||
"""
|
||||
}
|
||||
|
||||
private static func getEnumKey(sections: [Section], tags: [String], extensionClassname: String, extensionSuffix: String) -> String {
|
||||
var enumDefinition = "\n enum Key\(extensionSuffix.uppercasedFirst()): String {\n"
|
||||
|
||||
// Enum
|
||||
sections.forEach { section in
|
||||
// Check that at least one string will be generated
|
||||
guard section.hasOneOrMoreMatchingTags(tags: tags) else {
|
||||
return // Go to next section
|
||||
}
|
||||
|
||||
section.definitions.forEach { definition in
|
||||
guard definition.hasOneOrMoreMatchingTags(inputTags: tags) == true else {
|
||||
return // Go to next definition
|
||||
}
|
||||
debugPrint("Found definition")
|
||||
enumDefinition += " case \(definition.name) = \"\(definition.name)\"\n"
|
||||
}
|
||||
}
|
||||
|
||||
// KeyPath accessors
|
||||
enumDefinition += "\n"
|
||||
enumDefinition += " var keyPath: KeyPath<\(extensionClassname), String> {\n"
|
||||
enumDefinition += " switch self {\n"
|
||||
sections.forEach { section in
|
||||
// Check that at least one string will be generated
|
||||
guard section.hasOneOrMoreMatchingTags(tags: tags) else {
|
||||
return // Go to next section
|
||||
}
|
||||
|
||||
section.definitions.forEach { definition in
|
||||
guard definition.hasOneOrMoreMatchingTags(inputTags: tags) == true else {
|
||||
return // Go to next definition
|
||||
}
|
||||
debugPrint("Found definition")
|
||||
enumDefinition += " case .\(definition.name): return \\\(extensionClassname).\(definition.name)\n"
|
||||
}
|
||||
}
|
||||
enumDefinition += " }\n" // Switch
|
||||
enumDefinition += " }\n" // var keyPath
|
||||
enumDefinition += " }" // Enum
|
||||
|
||||
return enumDefinition
|
||||
}
|
||||
|
||||
private static func getProperties(sections: [Section], defaultLang lang: String, tags: [String], staticVar: Bool) -> String {
|
||||
sections.compactMap { section in
|
||||
// Check that at least one string will be generated
|
||||
|
@ -22,9 +22,9 @@ class TagsGenerator {
|
||||
let extensionFilePathURL = URL(fileURLWithPath: extensionFilePath)
|
||||
do {
|
||||
try extensionFileContent.write(to: extensionFilePathURL, atomically: false, encoding: .utf8)
|
||||
} catch (let error) {
|
||||
} catch let error {
|
||||
let error = StringiumError.writeFile(extensionFilePath, error.localizedDescription)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Stringium.exit(withError: error)
|
||||
}
|
||||
}
|
||||
|
@ -37,7 +37,7 @@ class Definition {
|
||||
}
|
||||
|
||||
func hasOneOrMoreMatchingTags(inputTags: [String]) -> Bool {
|
||||
if Set(inputTags).intersection(Set(self.tags)).isEmpty {
|
||||
if Set(inputTags).isDisjoint(with: tags) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
@ -109,7 +109,7 @@ class Definition {
|
||||
func getNSLocalizedStringProperty(forLang lang: String) -> String {
|
||||
guard let translation = translations[lang] else {
|
||||
let error = StringiumError.langNotDefined(lang, name, reference != nil)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Stringium.exit(withError: error)
|
||||
}
|
||||
|
||||
@ -132,7 +132,7 @@ class Definition {
|
||||
func getNSLocalizedStringStaticProperty(forLang lang: String) -> String {
|
||||
guard let translation = translations[lang] else {
|
||||
let error = StringiumError.langNotDefined(lang, name, reference != nil)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Stringium.exit(withError: error)
|
||||
}
|
||||
|
||||
@ -157,7 +157,7 @@ class Definition {
|
||||
func getProperty(forLang lang: String) -> String {
|
||||
guard let translation = translations[lang] else {
|
||||
let error = StringiumError.langNotDefined(lang, name, reference != nil)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Stringium.exit(withError: error)
|
||||
}
|
||||
|
||||
@ -173,7 +173,7 @@ class Definition {
|
||||
func getStaticProperty(forLang lang: String) -> String {
|
||||
guard let translation = translations[lang] else {
|
||||
let error = StringiumError.langNotDefined(lang, name, reference != nil)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Stringium.exit(withError: error)
|
||||
}
|
||||
|
||||
|
@ -84,7 +84,7 @@ class TwineFileParser {
|
||||
}
|
||||
}
|
||||
if invalidDefinitionNames.count > 0 {
|
||||
print(" warning:[\(Stringium.toolName)] Found \(invalidDefinitionNames.count) definition (\(invalidDefinitionNames.joined(separator: ", "))")
|
||||
print("warning: [\(Stringium.toolName)] Found \(invalidDefinitionNames.count) definition (\(invalidDefinitionNames.joined(separator: ", "))")
|
||||
}
|
||||
|
||||
return sections
|
||||
|
@ -57,7 +57,8 @@ struct Stringium: ParsableCommand {
|
||||
staticVar: options.staticMembers,
|
||||
inputFilename: options.inputFilenameWithoutExt,
|
||||
extensionName: options.extensionName,
|
||||
extensionFilePath: options.extensionFilePath)
|
||||
extensionFilePath: options.extensionFilePath,
|
||||
extensionSuffix: options.extensionSuffix)
|
||||
|
||||
print("[\(Self.toolName)] Strings generated")
|
||||
}
|
||||
@ -70,20 +71,20 @@ struct Stringium: ParsableCommand {
|
||||
// Input file
|
||||
guard fileManager.fileExists(atPath: options.inputFile) else {
|
||||
let error = StringiumError.fileNotExists(options.inputFile)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Stringium.exit(withError: error)
|
||||
}
|
||||
|
||||
// Langs
|
||||
guard options.langs.isEmpty == false else {
|
||||
let error = StringiumError.langsListEmpty
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Stringium.exit(withError: error)
|
||||
}
|
||||
|
||||
guard options.langs.contains(options.defaultLang) else {
|
||||
let error = StringiumError.defaultLangsNotInLangs
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Stringium.exit(withError: error)
|
||||
}
|
||||
|
||||
|
@ -14,25 +14,25 @@ enum StringiumError: Error {
|
||||
case writeFile(String, String)
|
||||
case langNotDefined(String, String, Bool)
|
||||
|
||||
var localizedDescription: String {
|
||||
var description: String {
|
||||
switch self {
|
||||
case .fileNotExists(let filename):
|
||||
return " error:[\(Stringium.toolName)] File \(filename) does not exists "
|
||||
return "error: [\(Stringium.toolName)] File \(filename) does not exists "
|
||||
|
||||
case .langsListEmpty:
|
||||
return " error:[\(Stringium.toolName)] Langs list is empty"
|
||||
return "error: [\(Stringium.toolName)] Langs list is empty"
|
||||
|
||||
case .defaultLangsNotInLangs:
|
||||
return " error:[\(Stringium.toolName)] Langs list does not contains the default lang"
|
||||
return "error: [\(Stringium.toolName)] Langs list does not contains the default lang"
|
||||
|
||||
case .writeFile(let subErrorDescription, let filename):
|
||||
return " error:[\(Stringium.toolName)] An error occured while writing content to \(filename): \(subErrorDescription)"
|
||||
return "error: [\(Stringium.toolName)] An error occured while writing content to \(filename): \(subErrorDescription)"
|
||||
|
||||
case .langNotDefined(let lang, let definitionName, let isReference):
|
||||
if isReference {
|
||||
return " error:[\(Stringium.toolName)] Reference are handled only by TwineTool. Please use it or remove reference from you strings file."
|
||||
return "error: [\(Stringium.toolName)] Reference are handled only by Twine. Please use it or remove reference from you strings file."
|
||||
}
|
||||
return " error:[\(Stringium.toolName)] Lang \"\(lang)\" not found for \"\(definitionName)\""
|
||||
return "error: [\(Stringium.toolName)] Lang \"\(lang)\" not found for \"\(definitionName)\""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -36,8 +36,8 @@ struct StringiumOptions: ParsableArguments {
|
||||
@Option(help: "Extension name. If not specified, it will generate an String extension.")
|
||||
var extensionName: String = Stringium.defaultExtensionName
|
||||
|
||||
@Option(help: "Extension suffix. Ex: MyApp, it will generate {extensionName}+{extensionSuffix}.swift")
|
||||
var extensionSuffix: String?
|
||||
@Option(help: "Extension suffix: {extensionName}+{extensionSuffix}.swift")
|
||||
var extensionSuffix: String
|
||||
}
|
||||
|
||||
// MARK: - Private var getter
|
||||
@ -68,10 +68,7 @@ extension StringiumOptions {
|
||||
|
||||
extension StringiumOptions {
|
||||
var extensionFileName: String {
|
||||
if let extensionSuffix = extensionSuffix {
|
||||
return "\(extensionName)+\(extensionSuffix).swift"
|
||||
}
|
||||
return "\(extensionName).swift"
|
||||
"\(extensionName)+\(extensionSuffix).swift"
|
||||
}
|
||||
|
||||
var extensionFilePath: String {
|
||||
|
@ -27,4 +27,3 @@ struct Strings: ParsableCommand {
|
||||
}
|
||||
|
||||
//Strings.main()
|
||||
|
||||
|
@ -18,7 +18,6 @@ struct Tags: ParsableCommand {
|
||||
version: ResgenSwiftVersion
|
||||
)
|
||||
|
||||
|
||||
// MARK: - Static
|
||||
|
||||
static let toolName = "Tags"
|
||||
@ -62,7 +61,7 @@ struct Tags: ParsableCommand {
|
||||
// Input file
|
||||
guard fileManager.fileExists(atPath: options.inputFile) else {
|
||||
let error = StringiumError.fileNotExists(options.inputFile)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Stringium.exit(withError: error)
|
||||
}
|
||||
|
||||
|
@ -66,20 +66,20 @@ struct Twine: ParsableCommand {
|
||||
// Input file
|
||||
guard fileManager.fileExists(atPath: options.inputFile) else {
|
||||
let error = TwineError.fileNotExists(options.inputFile)
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Twine.exit(withError: error)
|
||||
}
|
||||
|
||||
// Langs
|
||||
guard options.langs.isEmpty == false else {
|
||||
let error = TwineError.langsListEmpty
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Twine.exit(withError: error)
|
||||
}
|
||||
|
||||
guard options.langs.contains(options.defaultLang) else {
|
||||
let error = TwineError.defaultLangsNotInLangs
|
||||
print(error.localizedDescription)
|
||||
print(error.description)
|
||||
Twine.exit(withError: error)
|
||||
}
|
||||
|
||||
|
@ -12,16 +12,16 @@ enum TwineError: Error {
|
||||
case langsListEmpty
|
||||
case defaultLangsNotInLangs
|
||||
|
||||
var localizedDescription: String {
|
||||
var description: String {
|
||||
switch self {
|
||||
case .fileNotExists(let filename):
|
||||
return " error:[\(Twine.toolName)] File \(filename) does not exists "
|
||||
return "error: [\(Twine.toolName)] File \(filename) does not exists "
|
||||
|
||||
case .langsListEmpty:
|
||||
return " error:[\(Twine.toolName)] Langs list is empty"
|
||||
return "error: [\(Twine.toolName)] Langs list is empty"
|
||||
|
||||
case .defaultLangsNotInLangs:
|
||||
return " error:[\(Twine.toolName)] Langs list does not contains the default lang"
|
||||
return "error: [\(Twine.toolName)] Langs list does not contains the default lang"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -19,10 +19,12 @@ struct ResgenSwift: ParsableCommand {
|
||||
// With language support for type-level introspection, this could be
|
||||
// provided by automatically finding nested `ParsableCommand` types.
|
||||
subcommands: [
|
||||
Analytics.self,
|
||||
Colors.self,
|
||||
Fonts.self,
|
||||
Images.self,
|
||||
Strings.self,
|
||||
Tags.self,
|
||||
Generate.self
|
||||
]
|
||||
|
||||
|
@ -85,4 +85,8 @@ public extension String {
|
||||
blue = String(colorClean.prefix(2))
|
||||
return (alpha: alpha, red: red, green: green, blue: blue)
|
||||
}
|
||||
|
||||
func uppercasedFirst() -> String {
|
||||
prefix(1).uppercased() + dropFirst()
|
||||
}
|
||||
}
|
||||
|
@ -7,4 +7,4 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
public let ResgenSwiftVersion = "1.1"
|
||||
public let ResgenSwiftVersion = "1.2"
|
||||
|
137
Tests/ResgenSwiftTests/Analytics/AnalyticsDefinitionTests.swift
Normal file
137
Tests/ResgenSwiftTests/Analytics/AnalyticsDefinitionTests.swift
Normal file
@ -0,0 +1,137 @@
|
||||
//
|
||||
// AnalyticsDefinitionTests.swift
|
||||
//
|
||||
//
|
||||
// Created by Loris Perret on 06/12/2023.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import XCTest
|
||||
|
||||
@testable import ResgenSwift
|
||||
|
||||
final class AnalyticsDefinitionTests: XCTestCase {
|
||||
|
||||
// MARK: - Matching tags
|
||||
|
||||
func testMatchingAnalyticss() {
|
||||
// Given
|
||||
let definition = AnalyticsDefinition(id: "definition_name", name: "", type: .screen)
|
||||
definition.tags = ["ios","iosonly","notranslation"]
|
||||
|
||||
// When
|
||||
let match1 = definition.hasOneOrMoreMatchingTags(inputTags: ["ios"])
|
||||
let match2 = definition.hasOneOrMoreMatchingTags(inputTags: ["iosonly"])
|
||||
let match3 = definition.hasOneOrMoreMatchingTags(inputTags: ["notranslation"])
|
||||
|
||||
|
||||
// Expect
|
||||
XCTAssertTrue(match1)
|
||||
XCTAssertTrue(match2)
|
||||
XCTAssertTrue(match3)
|
||||
}
|
||||
|
||||
func testNotMatchingAnalyticss() {
|
||||
// Given
|
||||
let definition = AnalyticsDefinition(id: "definition_name", name: "", type: .screen)
|
||||
definition.tags = ["ios","iosonly","notranslation"]
|
||||
|
||||
// When
|
||||
let match1 = definition.hasOneOrMoreMatchingTags(inputTags: ["droid"])
|
||||
let match2 = definition.hasOneOrMoreMatchingTags(inputTags: ["droidonly"])
|
||||
let match3 = definition.hasOneOrMoreMatchingTags(inputTags: ["azerty"])
|
||||
|
||||
// Expect
|
||||
XCTAssertFalse(match1)
|
||||
XCTAssertFalse(match2)
|
||||
XCTAssertFalse(match3)
|
||||
}
|
||||
|
||||
// MARK: - Raw properties
|
||||
|
||||
func testGeneratedRawPropertyScreen() {
|
||||
// Given
|
||||
let definition = AnalyticsDefinition(id: "definition_name", name: "Ecran un", type: .screen)
|
||||
definition.path = "ecran_un/"
|
||||
|
||||
// When
|
||||
let propertyScreen = definition.getProperty()
|
||||
|
||||
// Expect
|
||||
let expectScreen = """
|
||||
func logScreenDefinitionName() {
|
||||
logScreen(
|
||||
name: "Ecran un",
|
||||
path: "ecran_un/"
|
||||
)
|
||||
}
|
||||
"""
|
||||
|
||||
XCTAssertEqual(propertyScreen.adaptForXCTest(), expectScreen.adaptForXCTest())
|
||||
}
|
||||
|
||||
func testGeneratedRawPropertyEvent() {
|
||||
// Given
|
||||
let definition = AnalyticsDefinition(id: "definition_name", name: "Ecran un", type: .event)
|
||||
|
||||
// When
|
||||
let propertyEvent = definition.getProperty()
|
||||
|
||||
// Expect
|
||||
let expectEvent = """
|
||||
func logEventDefinitionName() {
|
||||
logEvent(
|
||||
name: "Ecran un",
|
||||
action: "",
|
||||
category: "",
|
||||
params: []
|
||||
)
|
||||
}
|
||||
"""
|
||||
|
||||
XCTAssertEqual(propertyEvent.adaptForXCTest(), expectEvent.adaptForXCTest())
|
||||
}
|
||||
|
||||
func testGeneratedRawStaticPropertyScreen() {
|
||||
// Given
|
||||
let definition = AnalyticsDefinition(id: "definition_name", name: "Ecran un", type: .screen)
|
||||
definition.path = "ecran_un/"
|
||||
|
||||
// When
|
||||
let propertyScreen = definition.getStaticProperty()
|
||||
|
||||
// Expect
|
||||
let expectScreen = """
|
||||
static func logScreenDefinitionName() {
|
||||
logScreen(
|
||||
name: "Ecran un",
|
||||
path: "ecran_un/"
|
||||
)
|
||||
}
|
||||
"""
|
||||
|
||||
XCTAssertEqual(propertyScreen.adaptForXCTest(), expectScreen.adaptForXCTest())
|
||||
}
|
||||
|
||||
func testGeneratedRawStaticPropertyEvent() {
|
||||
// Given
|
||||
let definition = AnalyticsDefinition(id: "definition_name", name: "Ecran un", type: .event)
|
||||
|
||||
// When
|
||||
let propertyEvent = definition.getStaticProperty()
|
||||
|
||||
// Expect
|
||||
let expectEvent = """
|
||||
static func logEventDefinitionName() {
|
||||
logEvent(
|
||||
name: "Ecran un",
|
||||
action: "",
|
||||
category: "",
|
||||
params: []
|
||||
)
|
||||
}
|
||||
"""
|
||||
|
||||
XCTAssertEqual(propertyEvent.adaptForXCTest(), expectEvent.adaptForXCTest())
|
||||
}
|
||||
}
|
623
Tests/ResgenSwiftTests/Analytics/AnalyticsGeneratorTests.swift
Normal file
623
Tests/ResgenSwiftTests/Analytics/AnalyticsGeneratorTests.swift
Normal file
@ -0,0 +1,623 @@
|
||||
//
|
||||
// AnalyticsGeneratorTests.swift
|
||||
//
|
||||
//
|
||||
// Created by Thibaut Schmitt on 06/09/2022.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import XCTest
|
||||
import ToolCore
|
||||
|
||||
@testable import ResgenSwift
|
||||
|
||||
final class AnalyticsGeneratorTests: XCTestCase {
|
||||
|
||||
private func getAnalyticsDefinition(
|
||||
id: String,
|
||||
path: String = "",
|
||||
action: String = "",
|
||||
category: String = "",
|
||||
name: String,
|
||||
type: AnalyticsDefinition.TagType,
|
||||
tags: [String]
|
||||
) -> AnalyticsDefinition {
|
||||
let definition = AnalyticsDefinition(id: id, name: name, type: type)
|
||||
definition.tags = tags
|
||||
definition.path = path
|
||||
definition.action = action
|
||||
definition.category = category
|
||||
return definition
|
||||
}
|
||||
|
||||
func testGeneratedExtensionContentFirebase() {
|
||||
// Given
|
||||
let sectionOne = AnalyticsCategory(id: "section_one")
|
||||
sectionOne.definitions = [
|
||||
getAnalyticsDefinition(id: "s1_def_one", name: "s1 def one", type: .screen, tags: ["ios", "iosonly"]),
|
||||
getAnalyticsDefinition(id: "s1_def_two", name: "s1 def two", type: .event, tags: ["ios", "iosonly"]),
|
||||
]
|
||||
|
||||
let sectionTwo = AnalyticsCategory(id: "section_two")
|
||||
sectionTwo.definitions = [
|
||||
getAnalyticsDefinition(id: "s2_def_one", name: "s2 def one", type: .screen, tags: ["ios","iosonly"]),
|
||||
getAnalyticsDefinition(id: "s2_def_two", name: "s2 def two", type: .event, tags: ["droid","droidonly"]),
|
||||
]
|
||||
|
||||
let sectionThree = AnalyticsCategory(id: "section_three")
|
||||
sectionThree.definitions = [
|
||||
getAnalyticsDefinition(id: "s3_def_one", name: "s3 def one", type: .screen, tags: ["droid","droidonly"]),
|
||||
getAnalyticsDefinition(id: "s3_def_two", name: "s3 def two", type: .event, tags: ["droid","droidonly"]),
|
||||
]
|
||||
|
||||
// When
|
||||
AnalyticsGenerator.targets = [Analytics.TargetType.firebase]
|
||||
let extensionContent = AnalyticsGenerator.getExtensionContent(sections: [sectionOne, sectionTwo, sectionThree],
|
||||
tags: ["ios", "iosonly"],
|
||||
staticVar: false,
|
||||
extensionName: "GenAnalytics")
|
||||
// Expect Analytics
|
||||
let expect = """
|
||||
// Generated by ResgenSwift.Analytics 1.2
|
||||
|
||||
import Firebase
|
||||
|
||||
// MARK: - Protocol
|
||||
|
||||
protocol AnalyticsManagerProtocol {
|
||||
func logScreen(name: String, path: String)
|
||||
func logEvent(
|
||||
name: String,
|
||||
action: String,
|
||||
category: String,
|
||||
params: [String: Any]?
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Firebase
|
||||
|
||||
class FirebaseAnalyticsManager: AnalyticsManagerProtocol {
|
||||
func logScreen(name: String, path: String) {
|
||||
var parameters = [
|
||||
AnalyticsParameterScreenName: name
|
||||
]
|
||||
|
||||
Analytics.logEvent(
|
||||
AnalyticsEventScreenView,
|
||||
parameters: parameters
|
||||
)
|
||||
}
|
||||
|
||||
func logEvent(
|
||||
name: String,
|
||||
action: String,
|
||||
category: String,
|
||||
params: [String: Any]?
|
||||
) {
|
||||
var parameters: [String:Any] = [
|
||||
"action": action,
|
||||
"category": category,
|
||||
]
|
||||
|
||||
if let supplementaryParameters = params {
|
||||
parameters.merge(supplementaryParameters) { (origin, new) -> Any in
|
||||
return origin
|
||||
}
|
||||
}
|
||||
|
||||
Analytics.logEvent(
|
||||
name,
|
||||
parameters: parameters
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Manager
|
||||
|
||||
class AnalyticsManager {
|
||||
static var shared = AnalyticsManager()
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
var managers: [AnalyticsManagerProtocol] = []
|
||||
|
||||
private var isEnabled: Bool = true
|
||||
|
||||
// MARK: - Methods
|
||||
|
||||
func setAnalyticsEnabled(_ enable: Bool) {
|
||||
isEnabled = enable
|
||||
}
|
||||
|
||||
func configure() {
|
||||
managers.append(FirebaseAnalyticsManager())
|
||||
}
|
||||
|
||||
private func logScreen(name: String, path: String) {
|
||||
guard isEnabled else { return }
|
||||
|
||||
managers.forEach { manager in
|
||||
manager.logScreen(name: name, path: path)
|
||||
}
|
||||
}
|
||||
|
||||
private func logEvent(
|
||||
name: String,
|
||||
action: String,
|
||||
category: String,
|
||||
params: [String: Any]?
|
||||
) {
|
||||
guard isEnabled else { return }
|
||||
|
||||
managers.forEach { manager in
|
||||
manager.logEvent(
|
||||
name: name,
|
||||
action: action,
|
||||
category: category,
|
||||
params: params
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - section_one
|
||||
|
||||
func logScreenS1DefOne() {
|
||||
logScreen(
|
||||
name: "s1 def one",
|
||||
path: ""
|
||||
)
|
||||
}
|
||||
|
||||
func logEventS1DefTwo() {
|
||||
logEvent(
|
||||
name: "s1 def two",
|
||||
action: "",
|
||||
category: "",
|
||||
params: []
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - section_two
|
||||
|
||||
func logScreenS2DefOne() {
|
||||
logScreen(
|
||||
name: "s2 def one",
|
||||
path: ""
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
"""
|
||||
|
||||
if extensionContent != expect {
|
||||
print(prettyFirstDifferenceBetweenStrings(s1: extensionContent, s2: expect))
|
||||
}
|
||||
XCTAssertEqual(extensionContent.adaptForXCTest(), expect.adaptForXCTest())
|
||||
}
|
||||
|
||||
func testGeneratedExtensionContentMatomo() {
|
||||
// Given
|
||||
let sectionOne = AnalyticsCategory(id: "section_one")
|
||||
sectionOne.definitions = [
|
||||
getAnalyticsDefinition(id: "s1_def_one", path: "s1_def_one/", name: "s1 def one", type: .screen, tags: ["ios", "iosonly"]),
|
||||
getAnalyticsDefinition(id: "s1_def_two", action: "test", category: "test", name: "s1 def two", type: .event, tags: ["ios", "iosonly"]),
|
||||
]
|
||||
|
||||
let sectionTwo = AnalyticsCategory(id: "section_two")
|
||||
sectionTwo.definitions = [
|
||||
getAnalyticsDefinition(id: "s2_def_one", path: "s2_def_one/", name: "s2 def one", type: .screen, tags: ["ios","iosonly"]),
|
||||
getAnalyticsDefinition(id: "s2_def_two", action: "test", category: "test", name: "s2 def two", type: .event, tags: ["droid","droidonly"]),
|
||||
]
|
||||
|
||||
let sectionThree = AnalyticsCategory(id: "section_three")
|
||||
sectionThree.definitions = [
|
||||
getAnalyticsDefinition(id: "s3_def_one", path: "s3_def_one/", name: "s3 def one", type: .screen, tags: ["droid","droidonly"]),
|
||||
getAnalyticsDefinition(id: "s3_def_two", action: "test", category: "test", name: "s3 def two", type: .event, tags: ["droid","droidonly"]),
|
||||
]
|
||||
|
||||
// When
|
||||
AnalyticsGenerator.targets = [Analytics.TargetType.matomo]
|
||||
let extensionContent = AnalyticsGenerator.getExtensionContent(sections: [sectionOne, sectionTwo, sectionThree],
|
||||
tags: ["ios", "iosonly"],
|
||||
staticVar: false,
|
||||
extensionName: "GenAnalytics")
|
||||
// Expect Analytics
|
||||
let expect = """
|
||||
// Generated by ResgenSwift.Analytics 1.2
|
||||
|
||||
import MatomoTracker
|
||||
|
||||
// MARK: - Protocol
|
||||
|
||||
protocol AnalyticsManagerProtocol {
|
||||
func logScreen(name: String, path: String)
|
||||
func logEvent(
|
||||
name: String,
|
||||
action: String,
|
||||
category: String,
|
||||
params: [String: Any]?
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Matomo
|
||||
|
||||
class MatomoAnalyticsManager: AnalyticsManagerProtocol {
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
private var tracker: MatomoTracker
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
init(siteId: String, url: String) {
|
||||
debugPrint("[Matomo service] Server URL: \\(url)")
|
||||
debugPrint("[Matomo service] Site ID: \\(siteId)")
|
||||
tracker = MatomoTracker(
|
||||
siteId: siteId,
|
||||
baseURL: URL(string: url)!
|
||||
)
|
||||
|
||||
#if DEBUG
|
||||
tracker.dispatchInterval = 5
|
||||
#endif
|
||||
|
||||
#if DEBUG
|
||||
tracker.logger = DefaultLogger(minLevel: .verbose)
|
||||
#endif
|
||||
|
||||
debugPrint("[Matomo service] Configured with content base: \\(tracker.contentBase?.absoluteString ?? "-")")
|
||||
debugPrint("[Matomo service] Opt out: \\(tracker.isOptedOut)")
|
||||
}
|
||||
|
||||
// MARK: - Methods
|
||||
|
||||
func logScreen(name: String, path: String) {
|
||||
guard !tracker.isOptedOut else { return }
|
||||
guard let trackerUrl = tracker.contentBase?.absoluteString else { return }
|
||||
|
||||
let urlString = URL(string: "\\(trackerUrl)" + "/" + "\\(path)" + "iOS")
|
||||
tracker.track(
|
||||
view: [name],
|
||||
url: urlString
|
||||
)
|
||||
}
|
||||
|
||||
func logEvent(
|
||||
name: String,
|
||||
action: String,
|
||||
category: String,
|
||||
params: [String: Any]?
|
||||
) {
|
||||
guard !tracker.isOptedOut else { return }
|
||||
|
||||
tracker.track(
|
||||
eventWithCategory: category,
|
||||
action: action,
|
||||
name: name,
|
||||
number: nil,
|
||||
url: nil
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Manager
|
||||
|
||||
class AnalyticsManager {
|
||||
static var shared = AnalyticsManager()
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
var managers: [AnalyticsManagerProtocol] = []
|
||||
|
||||
private var isEnabled: Bool = true
|
||||
|
||||
// MARK: - Methods
|
||||
|
||||
func setAnalyticsEnabled(_ enable: Bool) {
|
||||
isEnabled = enable
|
||||
}
|
||||
|
||||
func configure(siteId: String, url: String) {
|
||||
managers.append(
|
||||
MatomoAnalyticsManager(
|
||||
siteId: siteId,
|
||||
url: url
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
private func logScreen(name: String, path: String) {
|
||||
guard isEnabled else { return }
|
||||
|
||||
managers.forEach { manager in
|
||||
manager.logScreen(name: name, path: path)
|
||||
}
|
||||
}
|
||||
|
||||
private func logEvent(
|
||||
name: String,
|
||||
action: String,
|
||||
category: String,
|
||||
params: [String: Any]?
|
||||
) {
|
||||
guard isEnabled else { return }
|
||||
|
||||
managers.forEach { manager in
|
||||
manager.logEvent(
|
||||
name: name,
|
||||
action: action,
|
||||
category: category,
|
||||
params: params
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - section_one
|
||||
|
||||
func logScreenS1DefOne() {
|
||||
logScreen(
|
||||
name: "s1 def one",
|
||||
path: "s1_def_one/"
|
||||
)
|
||||
}
|
||||
|
||||
func logEventS1DefTwo() {
|
||||
logEvent(
|
||||
name: "s1 def two",
|
||||
action: "test",
|
||||
category: "test",
|
||||
params: []
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - section_two
|
||||
|
||||
func logScreenS2DefOne() {
|
||||
logScreen(
|
||||
name: "s2 def one",
|
||||
path: "s2_def_one/"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
"""
|
||||
|
||||
if extensionContent != expect {
|
||||
print(prettyFirstDifferenceBetweenStrings(s1: extensionContent, s2: expect))
|
||||
}
|
||||
XCTAssertEqual(extensionContent.adaptForXCTest(), expect.adaptForXCTest())
|
||||
}
|
||||
|
||||
func testGeneratedExtensionContentMatomoAndFirebase() {
|
||||
// Given
|
||||
let sectionOne = AnalyticsCategory(id: "section_one")
|
||||
sectionOne.definitions = [
|
||||
getAnalyticsDefinition(id: "s1_def_one", path: "s1_def_one/", name: "s1 def one", type: .screen, tags: ["ios", "iosonly"]),
|
||||
getAnalyticsDefinition(id: "s1_def_two", action: "test", category: "test", name: "s1 def two", type: .event, tags: ["ios", "iosonly"]),
|
||||
]
|
||||
|
||||
let sectionTwo = AnalyticsCategory(id: "section_two")
|
||||
sectionTwo.definitions = [
|
||||
getAnalyticsDefinition(id: "s2_def_one", path: "s2_def_one/", name: "s2 def one", type: .screen, tags: ["ios","iosonly"]),
|
||||
getAnalyticsDefinition(id: "s2_def_two", action: "test", category: "test", name: "s2 def two", type: .event, tags: ["droid","droidonly"]),
|
||||
]
|
||||
|
||||
let sectionThree = AnalyticsCategory(id: "section_three")
|
||||
sectionThree.definitions = [
|
||||
getAnalyticsDefinition(id: "s3_def_one", path: "s3_def_one/", name: "s3 def one", type: .screen, tags: ["droid","droidonly"]),
|
||||
getAnalyticsDefinition(id: "s3_def_two", action: "test", category: "test", name: "s3 def two", type: .event, tags: ["droid","droidonly"]),
|
||||
]
|
||||
|
||||
// When
|
||||
AnalyticsGenerator.targets = [Analytics.TargetType.matomo, Analytics.TargetType.firebase]
|
||||
let extensionContent = AnalyticsGenerator.getExtensionContent(sections: [sectionOne, sectionTwo, sectionThree],
|
||||
tags: ["ios", "iosonly"],
|
||||
staticVar: false,
|
||||
extensionName: "GenAnalytics")
|
||||
// Expect Analytics
|
||||
let expect = """
|
||||
// Generated by ResgenSwift.Analytics 1.2
|
||||
|
||||
import MatomoTracker
|
||||
import Firebase
|
||||
|
||||
// MARK: - Protocol
|
||||
|
||||
protocol AnalyticsManagerProtocol {
|
||||
func logScreen(name: String, path: String)
|
||||
func logEvent(
|
||||
name: String,
|
||||
action: String,
|
||||
category: String,
|
||||
params: [String: Any]?
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Matomo
|
||||
|
||||
class MatomoAnalyticsManager: AnalyticsManagerProtocol {
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
private var tracker: MatomoTracker
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
init(siteId: String, url: String) {
|
||||
debugPrint("[Matomo service] Server URL: \\(url)")
|
||||
debugPrint("[Matomo service] Site ID: \\(siteId)")
|
||||
tracker = MatomoTracker(
|
||||
siteId: siteId,
|
||||
baseURL: URL(string: url)!
|
||||
)
|
||||
|
||||
#if DEBUG
|
||||
tracker.dispatchInterval = 5
|
||||
#endif
|
||||
|
||||
#if DEBUG
|
||||
tracker.logger = DefaultLogger(minLevel: .verbose)
|
||||
#endif
|
||||
|
||||
debugPrint("[Matomo service] Configured with content base: \\(tracker.contentBase?.absoluteString ?? "-")")
|
||||
debugPrint("[Matomo service] Opt out: \\(tracker.isOptedOut)")
|
||||
}
|
||||
|
||||
// MARK: - Methods
|
||||
|
||||
func logScreen(name: String, path: String) {
|
||||
guard !tracker.isOptedOut else { return }
|
||||
guard let trackerUrl = tracker.contentBase?.absoluteString else { return }
|
||||
|
||||
let urlString = URL(string: "\\(trackerUrl)" + "/" + "\\(path)" + "iOS")
|
||||
tracker.track(
|
||||
view: [name],
|
||||
url: urlString
|
||||
)
|
||||
}
|
||||
|
||||
func logEvent(
|
||||
name: String,
|
||||
action: String,
|
||||
category: String,
|
||||
params: [String: Any]?
|
||||
) {
|
||||
guard !tracker.isOptedOut else { return }
|
||||
|
||||
tracker.track(
|
||||
eventWithCategory: category,
|
||||
action: action,
|
||||
name: name,
|
||||
number: nil,
|
||||
url: nil
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Firebase
|
||||
|
||||
class FirebaseAnalyticsManager: AnalyticsManagerProtocol {
|
||||
func logScreen(name: String, path: String) {
|
||||
var parameters = [
|
||||
AnalyticsParameterScreenName: name
|
||||
]
|
||||
|
||||
Analytics.logEvent(
|
||||
AnalyticsEventScreenView,
|
||||
parameters: parameters
|
||||
)
|
||||
}
|
||||
|
||||
func logEvent(
|
||||
name: String,
|
||||
action: String,
|
||||
category: String,
|
||||
params: [String: Any]?
|
||||
) {
|
||||
var parameters: [String:Any] = [
|
||||
"action": action,
|
||||
"category": category,
|
||||
]
|
||||
|
||||
if let supplementaryParameters = params {
|
||||
parameters.merge(supplementaryParameters) { (origin, new) -> Any in
|
||||
return origin
|
||||
}
|
||||
}
|
||||
|
||||
Analytics.logEvent(
|
||||
name,
|
||||
parameters: parameters
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Manager
|
||||
|
||||
class AnalyticsManager {
|
||||
static var shared = AnalyticsManager()
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
var managers: [AnalyticsManagerProtocol] = []
|
||||
|
||||
private var isEnabled: Bool = true
|
||||
|
||||
// MARK: - Methods
|
||||
|
||||
func setAnalyticsEnabled(_ enable: Bool) {
|
||||
isEnabled = enable
|
||||
}
|
||||
|
||||
func configure(siteId: String, url: String) {
|
||||
managers.append(
|
||||
MatomoAnalyticsManager(
|
||||
siteId: siteId,
|
||||
url: url
|
||||
)
|
||||
)
|
||||
managers.append(FirebaseAnalyticsManager())
|
||||
}
|
||||
|
||||
private func logScreen(name: String, path: String) {
|
||||
guard isEnabled else { return }
|
||||
|
||||
managers.forEach { manager in
|
||||
manager.logScreen(name: name, path: path)
|
||||
}
|
||||
}
|
||||
|
||||
private func logEvent(
|
||||
name: String,
|
||||
action: String,
|
||||
category: String,
|
||||
params: [String: Any]?
|
||||
) {
|
||||
guard isEnabled else { return }
|
||||
|
||||
managers.forEach { manager in
|
||||
manager.logEvent(
|
||||
name: name,
|
||||
action: action,
|
||||
category: category,
|
||||
params: params
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - section_one
|
||||
|
||||
func logScreenS1DefOne() {
|
||||
logScreen(
|
||||
name: "s1 def one",
|
||||
path: "s1_def_one/"
|
||||
)
|
||||
}
|
||||
|
||||
func logEventS1DefTwo() {
|
||||
logEvent(
|
||||
name: "s1 def two",
|
||||
action: "test",
|
||||
category: "test",
|
||||
params: []
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - section_two
|
||||
|
||||
func logScreenS2DefOne() {
|
||||
logScreen(
|
||||
name: "s2 def one",
|
||||
path: "s2_def_one/"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
"""
|
||||
|
||||
if extensionContent != expect {
|
||||
print(prettyFirstDifferenceBetweenStrings(s1: extensionContent, s2: expect))
|
||||
}
|
||||
XCTAssertEqual(extensionContent.adaptForXCTest(), expect.adaptForXCTest())
|
||||
}
|
||||
}
|
72
Tests/ResgenSwiftTests/Analytics/AnalyticsSectionTests.swift
Normal file
72
Tests/ResgenSwiftTests/Analytics/AnalyticsSectionTests.swift
Normal file
@ -0,0 +1,72 @@
|
||||
//
|
||||
// AnalyticsSectionTests.swift
|
||||
//
|
||||
//
|
||||
// Created by Loris Perret on 06/12/2023.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import XCTest
|
||||
|
||||
@testable import ResgenSwift
|
||||
|
||||
final class AnalyticsSectionTests: XCTestCase {
|
||||
|
||||
// MARK: - Matching tags
|
||||
|
||||
func testMatchingAnalytics() {
|
||||
// Given
|
||||
let section = AnalyticsCategory(id: "section_name")
|
||||
section.definitions = [
|
||||
{
|
||||
let def = AnalyticsDefinition(id: "definition_name", name: "", type: .screen)
|
||||
def.tags = ["ios","iosonly"]
|
||||
return def
|
||||
}(),
|
||||
{
|
||||
let def = AnalyticsDefinition(id: "definition_name_two", name: "", type: .screen)
|
||||
def.tags = ["droid","droidonly"]
|
||||
return def
|
||||
}()
|
||||
]
|
||||
|
||||
// When
|
||||
let match1 = section.hasOneOrMoreMatchingTags(tags: ["ios"])
|
||||
let match2 = section.hasOneOrMoreMatchingTags(tags: ["iosonly"])
|
||||
let match3 = section.hasOneOrMoreMatchingTags(tags: ["droid"])
|
||||
let match4 = section.hasOneOrMoreMatchingTags(tags: ["droidonly"])
|
||||
|
||||
// Expect
|
||||
XCTAssertTrue(match1)
|
||||
XCTAssertTrue(match2)
|
||||
XCTAssertTrue(match3)
|
||||
XCTAssertTrue(match4)
|
||||
}
|
||||
|
||||
func testNotMatchingAnalytics() {
|
||||
// Given
|
||||
let section = AnalyticsCategory(id: "section_name")
|
||||
section.definitions = [
|
||||
{
|
||||
let def = AnalyticsDefinition(id: "definition_name", name: "", type: .screen)
|
||||
def.tags = ["ios","iosonly"]
|
||||
return def
|
||||
}(),
|
||||
{
|
||||
let def = AnalyticsDefinition(id: "definition_name_two", name: "", type: .screen)
|
||||
def.tags = ["droid","droidonly"]
|
||||
return def
|
||||
}()
|
||||
]
|
||||
|
||||
// When
|
||||
let match1 = section.hasOneOrMoreMatchingTags(tags: ["web"])
|
||||
let match2 = section.hasOneOrMoreMatchingTags(tags: ["webonly"])
|
||||
let match3 = section.hasOneOrMoreMatchingTags(tags: ["azerty"])
|
||||
|
||||
// Expect
|
||||
XCTAssertFalse(match1)
|
||||
XCTAssertFalse(match2)
|
||||
XCTAssertFalse(match3)
|
||||
}
|
||||
}
|
135
Tests/ResgenSwiftTests/Analytics/DiffString.swift
Normal file
135
Tests/ResgenSwiftTests/Analytics/DiffString.swift
Normal file
@ -0,0 +1,135 @@
|
||||
//
|
||||
// File.swift
|
||||
//
|
||||
//
|
||||
// Created by Loris Perret on 06/12/2023.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
|
||||
/// Find first differing character between two strings
|
||||
///
|
||||
/// :param: s1 First String
|
||||
/// :param: s2 Second String
|
||||
///
|
||||
/// :returns: .DifferenceAtIndex(i) or .NoDifference
|
||||
public func firstDifferenceBetweenStrings(s1: NSString, s2: NSString) -> FirstDifferenceResult {
|
||||
let len1 = s1.length
|
||||
let len2 = s2.length
|
||||
|
||||
let lenMin = min(len1, len2)
|
||||
|
||||
for i in 0..<lenMin {
|
||||
if s1.character(at: i) != s2.character(at: i) {
|
||||
return .DifferenceAtIndex(i)
|
||||
}
|
||||
}
|
||||
|
||||
if len1 < len2 {
|
||||
return .DifferenceAtIndex(len1)
|
||||
}
|
||||
|
||||
if len2 < len1 {
|
||||
return .DifferenceAtIndex(len2)
|
||||
}
|
||||
|
||||
return .NoDifference
|
||||
}
|
||||
|
||||
|
||||
/// Create a formatted String representation of difference between strings
|
||||
///
|
||||
/// :param: s1 First string
|
||||
/// :param: s2 Second string
|
||||
///
|
||||
/// :returns: a string, possibly containing significant whitespace and newlines
|
||||
public func prettyFirstDifferenceBetweenStrings(s1: String, s2: String) -> String {
|
||||
let firstDifferenceResult = firstDifferenceBetweenStrings(s1: s1 as NSString, s2: s2 as NSString)
|
||||
return prettyDescriptionOfFirstDifferenceResult(firstDifferenceResult: firstDifferenceResult, s1: s1 as NSString, s2: s2 as NSString) as String
|
||||
}
|
||||
|
||||
|
||||
/// Create a formatted String representation of a FirstDifferenceResult for two strings
|
||||
///
|
||||
/// :param: firstDifferenceResult FirstDifferenceResult
|
||||
/// :param: s1 First string used in generation of firstDifferenceResult
|
||||
/// :param: s2 Second string used in generation of firstDifferenceResult
|
||||
///
|
||||
/// :returns: a printable string, possibly containing significant whitespace and newlines
|
||||
public func prettyDescriptionOfFirstDifferenceResult(firstDifferenceResult: FirstDifferenceResult, s1: NSString, s2: NSString) -> NSString {
|
||||
|
||||
func diffString(index: Int, s1: NSString, s2: NSString) -> NSString {
|
||||
let markerArrow = "\u{2b06}" // "⬆"
|
||||
let ellipsis = "\u{2026}" // "…"
|
||||
/// Given a string and a range, return a string representing that substring.
|
||||
///
|
||||
/// If the range starts at a position other than 0, an ellipsis
|
||||
/// will be included at the beginning.
|
||||
///
|
||||
/// If the range ends before the actual end of the string,
|
||||
/// an ellipsis is added at the end.
|
||||
func windowSubstring(s: NSString, range: NSRange) -> String {
|
||||
let validRange = NSMakeRange(range.location, min(range.length, s.length - range.location))
|
||||
let substring = s.substring(with: validRange)
|
||||
|
||||
let prefix = range.location > 0 ? ellipsis : ""
|
||||
let suffix = (s.length - range.location > range.length) ? ellipsis : ""
|
||||
|
||||
return "\(prefix)\(substring)\(suffix)"
|
||||
}
|
||||
|
||||
// Show this many characters before and after the first difference
|
||||
let windowPrefixLength = 10
|
||||
let windowSuffixLength = 10
|
||||
let windowLength = windowPrefixLength + 1 + windowSuffixLength
|
||||
|
||||
let windowIndex = max(index - windowPrefixLength, 0)
|
||||
let windowRange = NSMakeRange(windowIndex, windowLength)
|
||||
|
||||
let sub1 = windowSubstring(s: s1, range: windowRange)
|
||||
let sub2 = windowSubstring(s: s2, range: windowRange)
|
||||
|
||||
let markerPosition = min(windowSuffixLength, index) + (windowIndex > 0 ? 1 : 0)
|
||||
|
||||
let markerPrefix = String(repeating: " " as Character, count: markerPosition)
|
||||
let markerLine = "\(markerPrefix)\(markerArrow)"
|
||||
|
||||
return "Difference at index \(index):\n\(sub1)\n\(sub2)\n\(markerLine)" as NSString
|
||||
}
|
||||
|
||||
switch firstDifferenceResult {
|
||||
case .NoDifference: return "No difference"
|
||||
case .DifferenceAtIndex(let index): return diffString(index: index, s1: s1, s2: s2)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Result type for firstDifferenceBetweenStrings()
|
||||
public enum FirstDifferenceResult {
|
||||
/// Strings are identical
|
||||
case NoDifference
|
||||
|
||||
/// Strings differ at the specified index.
|
||||
///
|
||||
/// This could mean that characters at the specified index are different,
|
||||
/// or that one string is longer than the other
|
||||
case DifferenceAtIndex(Int)
|
||||
}
|
||||
|
||||
extension FirstDifferenceResult {
|
||||
/// Textual representation of a FirstDifferenceResult
|
||||
public var description: String {
|
||||
switch self {
|
||||
case .NoDifference:
|
||||
return "NoDifference"
|
||||
case .DifferenceAtIndex(let index):
|
||||
return "DifferenceAtIndex(\(index))"
|
||||
}
|
||||
}
|
||||
|
||||
/// Textual representation of a FirstDifferenceResult for debugging purposes
|
||||
public var debugDescription: String {
|
||||
return self.description
|
||||
}
|
||||
}
|
@ -21,7 +21,7 @@ final class ColorsConfigurationTests: XCTestCase {
|
||||
xcassetsPath: "path/to/assets.xcassets",
|
||||
extensionOutputPath: "Colors/Generated",
|
||||
extensionName: nil,
|
||||
extensionNameSwiftUI: nil,
|
||||
extensionNameUIKit: nil,
|
||||
extensionSuffix: nil,
|
||||
staticMembers: false)
|
||||
// When
|
||||
@ -50,7 +50,7 @@ final class ColorsConfigurationTests: XCTestCase {
|
||||
xcassetsPath: "path/to/assets.xcassets",
|
||||
extensionOutputPath: "Colors/Generated",
|
||||
extensionName: "AppUIColor",
|
||||
extensionNameSwiftUI: "AppColor",
|
||||
extensionNameUIKit: "AppColor",
|
||||
extensionSuffix: "Testing",
|
||||
staticMembers: false)
|
||||
// When
|
||||
@ -70,7 +70,7 @@ final class ColorsConfigurationTests: XCTestCase {
|
||||
"false",
|
||||
"--extension-name",
|
||||
"AppUIColor",
|
||||
"--extension-name-swift-ui",
|
||||
"--extension-name-ui-kit",
|
||||
"AppColor",
|
||||
"--extension-suffix",
|
||||
"Testing",
|
||||
|
@ -19,7 +19,7 @@ final class FontsConfigurationTests: XCTestCase {
|
||||
let testingConfiguration = FontsConfiguration(inputFile: "path/to/fonts.txt",
|
||||
extensionOutputPath: "Fonts/Generated",
|
||||
extensionName: nil,
|
||||
extensionNameSwiftUI: nil,
|
||||
extensionNameUIKit: nil,
|
||||
extensionSuffix: nil,
|
||||
infoPlistPaths: nil,
|
||||
staticMembers: nil)
|
||||
@ -43,7 +43,7 @@ final class FontsConfigurationTests: XCTestCase {
|
||||
let testingConfiguration = FontsConfiguration(inputFile: "path/to/fonts.txt",
|
||||
extensionOutputPath: "Fonts/Generated",
|
||||
extensionName: "AppUIFont",
|
||||
extensionNameSwiftUI: "AppFont",
|
||||
extensionNameUIKit: "AppFont",
|
||||
extensionSuffix: "Testing",
|
||||
infoPlistPaths: "path/to/plist1.plist path/to/plist2.plist",
|
||||
staticMembers: true)
|
||||
@ -60,7 +60,7 @@ final class FontsConfigurationTests: XCTestCase {
|
||||
"true",
|
||||
"--extension-name",
|
||||
"AppUIFont",
|
||||
"--extension-name-swift-ui",
|
||||
"--extension-name-ui-kit",
|
||||
"AppFont",
|
||||
"--extension-suffix",
|
||||
"Testing",
|
||||
|
@ -20,7 +20,7 @@ final class ImagesConfigurationTests: XCTestCase {
|
||||
xcassetsPath: "path/to/assets.xcassets",
|
||||
extensionOutputPath: "Images/Generated",
|
||||
extensionName: nil,
|
||||
extensionNameSwiftUI: nil,
|
||||
extensionNameUIKit: nil,
|
||||
extensionSuffix: nil,
|
||||
staticMembers: nil)
|
||||
|
||||
@ -47,7 +47,7 @@ final class ImagesConfigurationTests: XCTestCase {
|
||||
xcassetsPath: "path/to/assets.xcassets",
|
||||
extensionOutputPath: "Images/Generated",
|
||||
extensionName: "AppUIImage",
|
||||
extensionNameSwiftUI: "AppImage",
|
||||
extensionNameUIKit: "AppImage",
|
||||
extensionSuffix: "Testing",
|
||||
staticMembers: true)
|
||||
|
||||
@ -66,7 +66,7 @@ final class ImagesConfigurationTests: XCTestCase {
|
||||
"true",
|
||||
"--extension-name",
|
||||
"AppUIImage",
|
||||
"--extension-name-swift-ui",
|
||||
"--extension-name-ui-kit",
|
||||
"AppImage",
|
||||
"--extension-suffix",
|
||||
"Testing",
|
||||
|
@ -131,7 +131,8 @@ final class StringsFileGeneratorTests: XCTestCase {
|
||||
tags: ["ios", "iosonly", "notranslation"],
|
||||
staticVar: false,
|
||||
inputFilename: "myInputFilename",
|
||||
extensionName: "GenStrings")
|
||||
extensionName: "GenStrings",
|
||||
extensionSuffix: "strings")
|
||||
|
||||
// Expect
|
||||
let expect = """
|
||||
@ -143,6 +144,22 @@ final class StringsFileGeneratorTests: XCTestCase {
|
||||
|
||||
extension GenStrings {
|
||||
|
||||
enum KeyStrings: String {
|
||||
case s1_def_one = "s1_def_one"
|
||||
case s1_def_two = "s1_def_two"
|
||||
case s2_def_one = "s2_def_one"
|
||||
case s2_def_two = "s2_def_two"
|
||||
|
||||
var keyPath: KeyPath<GenStrings, String> {
|
||||
switch self {
|
||||
case .s1_def_one: return \\GenStrings.s1_def_one
|
||||
case .s1_def_two: return \\GenStrings.s1_def_two
|
||||
case .s2_def_one: return \\GenStrings.s2_def_one
|
||||
case .s2_def_two: return \\GenStrings.s2_def_two
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - section_one
|
||||
|
||||
/// Translation in fr :
|
||||
@ -173,6 +190,9 @@ final class StringsFileGeneratorTests: XCTestCase {
|
||||
}
|
||||
"""
|
||||
|
||||
if extensionContent != expect {
|
||||
print(prettyFirstDifferenceBetweenStrings(s1: extensionContent, s2: expect))
|
||||
}
|
||||
XCTAssertEqual(extensionContent.adaptForXCTest(), expect.adaptForXCTest())
|
||||
}
|
||||
|
||||
@ -207,7 +227,8 @@ final class StringsFileGeneratorTests: XCTestCase {
|
||||
tags: ["ios", "iosonly", "notranslation"],
|
||||
staticVar: true,
|
||||
inputFilename: "myInputFilename",
|
||||
extensionName: "GenStrings")
|
||||
extensionName: "GenStrings",
|
||||
extensionSuffix: "strings")
|
||||
|
||||
// Expect
|
||||
let expect = """
|
||||
@ -219,6 +240,22 @@ final class StringsFileGeneratorTests: XCTestCase {
|
||||
|
||||
extension GenStrings {
|
||||
|
||||
enum KeyStrings: String {
|
||||
case s1_def_one = "s1_def_one"
|
||||
case s1_def_two = "s1_def_two"
|
||||
case s2_def_one = "s2_def_one"
|
||||
case s2_def_two = "s2_def_two"
|
||||
|
||||
var keyPath: KeyPath<GenStrings, String> {
|
||||
switch self {
|
||||
case .s1_def_one: return \\GenStrings.s1_def_one
|
||||
case .s1_def_two: return \\GenStrings.s1_def_two
|
||||
case .s2_def_one: return \\GenStrings.s2_def_one
|
||||
case .s2_def_two: return \\GenStrings.s2_def_two
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - section_one
|
||||
|
||||
/// Translation in fr :
|
||||
@ -249,6 +286,9 @@ final class StringsFileGeneratorTests: XCTestCase {
|
||||
}
|
||||
"""
|
||||
|
||||
if extensionContent != expect {
|
||||
print(prettyFirstDifferenceBetweenStrings(s1: extensionContent, s2: expect))
|
||||
}
|
||||
XCTAssertEqual(extensionContent.adaptForXCTest(), expect.adaptForXCTest())
|
||||
}
|
||||
}
|
||||
|
48
script/swiftlint.sh
Executable file
48
script/swiftlint.sh
Executable file
@ -0,0 +1,48 @@
|
||||
#!/bin/sh
|
||||
|
||||
# Go to git repo root level
|
||||
cd $(git rev-parse --show-toplevel)
|
||||
|
||||
if [[ "$BUILD_DIR" == *"IBDesignables"* ]] || [[ "$BUILD_DIR" == *"Previews"* ]] ; then
|
||||
echo "not linting for IBDesignables/SwiftUI Previews builds";
|
||||
exit 0
|
||||
fi
|
||||
|
||||
SWIFT_LINT=$(which swiftlint)
|
||||
|
||||
if [[ -z $SWIFT_LINT ]] ; then
|
||||
echo "warning: SwiftLint not installed, please download it from https://github.com/realm/SwiftLint"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [[ $RUN_CLANG_STATIC_ANALYZER == "YES" ]] ; then
|
||||
time $SWIFT_LINT
|
||||
else
|
||||
COUNT=0
|
||||
|
||||
##### Check for modified git files #####
|
||||
FILES=$(git diff --name-only | grep -iv "^carthage" | grep -iv "^pods" | grep -iv "^vendor" | grep -v "R2" | grep ".swift$")
|
||||
if [ ! -z "$FILES" ]; then
|
||||
while read FILE_PATH; do
|
||||
export SCRIPT_INPUT_FILE_$COUNT=$FILE_PATH
|
||||
COUNT=$((COUNT + 1))
|
||||
done <<< "$FILES"
|
||||
fi
|
||||
|
||||
##### Check for modified files in unstaged/Staged area #####
|
||||
FILES=$(git diff --name-only --cached --diff-filter=d | grep -iv "^carthage" | grep -iv "^pods" | grep -iv "^vendor" | grep -v "R2" | grep ".swift$")
|
||||
if [ ! -z "$FILES" ]; then
|
||||
while read FILE_PATH; do
|
||||
export SCRIPT_INPUT_FILE_$COUNT=$FILE_PATH
|
||||
COUNT=$((COUNT + 1))
|
||||
done <<< "$FILES"
|
||||
fi
|
||||
|
||||
##### Make the count avilable as global variable #####
|
||||
export SCRIPT_INPUT_FILE_COUNT=$COUNT
|
||||
env | grep SCRIPT_INPUT_FILE_
|
||||
|
||||
if [[ COUNT -ne 0 ]] ; then
|
||||
time $SWIFT_LINT --use-script-input-files
|
||||
fi
|
||||
fi
|
Reference in New Issue
Block a user