30 Commits

Author SHA1 Message Date
239deb2b91 RES-32 Ajouter la possibilité désactiver des traqueurs spécifiques
Some checks failed
gitea-openium/resgen.swift/pipeline/pr-master There was a failure building this commit
2025-02-12 10:49:06 +01:00
9a05ce29b8 Disable tag for previews
Some checks failed
gitea-openium/resgen.swift/pipeline/pr-master There was a failure building this commit
2024-12-17 16:30:22 +01:00
2ec4ebcc66 Fix plugin swiftlint
Some checks failed
gitea-openium/resgen.swift/pipeline/pr-master There was a failure building this commit
2024-11-04 14:00:27 +01:00
6ea31a8030 Fix some error when value and replaceIn
Some checks failed
gitea-openium/resgen.swift/pipeline/pr-master There was a failure building this commit
2024-07-18 11:36:21 +02:00
df173406d4 Update README.md
Some checks failed
gitea-openium/resgen.swift/pipeline/pr-master There was a failure building this commit
2024-07-18 11:36:11 +02:00
922ed56959 Add parameter defaultValue and value and add replaceIn parameter in another parameter
Some checks failed
gitea-openium/resgen.swift/pipeline/pr-master There was a failure building this commit
2024-07-18 08:24:23 +02:00
ab91c1c277 Update README.md
Some checks failed
gitea-openium/resgen.swift/pipeline/pr-master There was a failure building this commit
2024-07-17 15:27:10 +02:00
aa64ce5cf7 fix: Static function 2024-07-17 15:26:39 +02:00
23bf3c3a82 fix: Use category and action if not matomo 2024-07-17 15:26:39 +02:00
09556ba6e0 [DEVTOOLS-186] Exporter les images de resgen en svg
Some checks failed
gitea-openium/resgen.swift/pipeline/head There was a failure building this commit
Reviewed-on: #12
Reviewed-by: Thibaut Schmitt <t.schmitt@openium.fr>
2024-07-17 15:18:13 +02:00
dea57dc1e2 Maj du readme
Some checks failed
gitea-openium/resgen.swift/pipeline/pr-master There was a failure building this commit
gitea-openium/resgen.swift/pipeline/head There was a failure building this commit
2024-07-11 10:29:32 +02:00
07575bd2bf DEVTOOLS-195 Ne pas générer les svg en template par défaut
Some checks failed
gitea-openium/resgen.swift/pipeline/pr-master There was a failure building this commit
2024-07-11 10:08:47 +02:00
8686ae974c Suppression des anciens assets si svg
Some checks failed
gitea-openium/resgen.swift/pipeline/pr-master There was a failure building this commit
2024-06-21 14:54:20 +02:00
be4c561ea8 DEVTOOLS-192 Resgen iOS vector
Some checks failed
gitea-openium/resgen.swift/pipeline/pr-master There was a failure building this commit
2024-06-21 09:18:51 +02:00
2357a40fff DEVTOOLS-186 Exporter les images de resgen en svg
Some checks failed
gitea-openium/resgen.swift/pipeline/head There was a failure building this commit
gitea-openium/resgen.swift/pipeline/pr-master There was a failure building this commit
2024-04-22 12:05:24 +02:00
d4afa9c9e9 Maj du Readme suite aux devs sur le fichier string catalog
Some checks failed
gitea-openium/resgen.swift/pipeline/head There was a failure building this commit
2024-04-22 09:48:21 +02:00
76ef0a2d59 Merge pull request 'DEVTOOLS-185 Remplacer le json en dur des images resgen' (#11) from DEVTOOLS-186/SVG_resgen into master
Some checks failed
gitea-openium/resgen.swift/pipeline/head There was a failure building this commit
Reviewed-on: #11
Reviewed-by: Thibaut Schmitt <t.schmitt@openium.fr>
2024-04-19 17:02:26 +02:00
129eb135f1 DEVTOOLS-185 Remplacer le json en dur des images resgen
Some checks are pending
gitea-openium/resgen.swift/pipeline/pr-master Build started...
2024-04-19 17:02:00 +02:00
4ad15fcded Merge pull request 'xcstrings' (#10) from xcstrings into master
Some checks failed
gitea-openium/resgen.swift/pipeline/head There was a failure building this commit
Reviewed-on: #10
Reviewed-by: Thibaut Schmitt <t.schmitt@openium.fr>
2024-04-19 16:59:03 +02:00
fb2ddb2227 DEVTOOLS-181 Gérer le tag noTranslation pour les xcstrings 2024-04-17 09:44:09 +02:00
27f86f5c4d Correction de l'option pour le fichier xcstrings 2024-04-15 16:51:18 +02:00
209ba49e3f Gestion des commentaires 2024-04-12 17:15:15 +02:00
ba07005b13 Fix equatable properties for arrays 2024-04-12 16:45:09 +02:00
6c3f3a8982 Correction du test testGenerateXcStringsRootObject 2024-04-12 16:25:10 +02:00
0d651b810f Première implémentation des xcstrings 2024-04-12 16:09:54 +02:00
1d7fc76340 Changed the condition for moe visibility 2024-04-11 15:49:07 +02:00
5d4e461933 Affichage du commentaire même si nil ou empty 2024-04-11 14:20:54 +02:00
55264d61ad Modification de l'affichage des commentaires
Some checks failed
gitea-openium/resgen.swift/pipeline/head There was a failure building this commit
gitea-openium/resgen.swift/pipeline/pr-master There was a failure building this commit
2024-04-11 11:18:57 +02:00
d21ad9d1ea Update JenkinsFile Xcode version
Some checks failed
gitea-openium/resgen.swift/pipeline/head There was a failure building this commit
2024-04-11 10:19:10 +02:00
0bd6c3c2d4 Correction des commentaires des strings
Some checks failed
gitea-openium/resgen.swift/pipeline/head There was a failure building this commit
2024-04-11 10:16:28 +02:00
33 changed files with 2744 additions and 377 deletions

2
Jenkinsfile vendored
View File

@ -1,6 +1,6 @@
library "openiumpipeline" library "openiumpipeline"
env.DEVELOPER_DIR="/Applications/Xcode-15.0.1.app/Contents/Developer" env.DEVELOPER_DIR="/Applications/Xcode-15.4.0.app/Contents/Developer"
//env.SIMULATOR_DEVICE_TYPES="iPad--7th-generation-" //env.SIMULATOR_DEVICE_TYPES="iPad--7th-generation-"
env.IS_PACKAGE_SWIFT=1 env.IS_PACKAGE_SWIFT=1
env.TARGETS_MACOS=1 env.TARGETS_MACOS=1

View File

@ -1,32 +1,5 @@
{ {
"pins" : [ "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", "identity" : "swift-argument-parser",
"kind" : "remoteSourceControl", "kind" : "remoteSourceControl",
@ -37,39 +10,12 @@
} }
}, },
{ {
"identity" : "swift-syntax", "identity" : "swiftlintplugin",
"kind" : "remoteSourceControl", "kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-syntax.git", "location" : "https://github.com/lukepistrol/SwiftLintPlugin",
"state" : { "state" : {
"revision" : "6ad4ea24b01559dde0773e3d091f1b9e36175036", "revision" : "5a65f4074975f811da666dfe31a19850950b1ea4",
"version" : "509.0.2" "version" : "0.56.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"
} }
}, },
{ {

View File

@ -10,7 +10,7 @@ let package = Package(
// Dependencies declare other packages that this package depends on. // 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/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")), .package(url: "https://github.com/lukepistrol/SwiftLintPlugin", exact: "0.56.2"),
], ],
targets: [ targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets are the basic building blocks of a package. A target can define a module or a test suite.
@ -22,7 +22,9 @@ let package = Package(
.product(name: "ArgumentParser", package: "swift-argument-parser"), .product(name: "ArgumentParser", package: "swift-argument-parser"),
"Yams" "Yams"
], ],
plugins: [.plugin(name: "SwiftLintPlugin", package: "SwiftLint")] plugins: [
.plugin(name: "SwiftLint", package: "SwiftLintPlugin")
]
), ),
// Helper targets // Helper targets

View File

@ -81,7 +81,7 @@ swift run -c release ResgenSwift strings twine $FORCE_FLAG "./Twine/strings.txt"
2. Input translations file (must be Twine formatted) 2. Input translations file (must be Twine formatted)
3. `--langs`: langs to generate (string with space between each lang) 3. `--langs`: langs to generate (string with space between each lang)
4. `--default-lang`: default lang that will be in `Base.lproj`. It must be in `langs` as well 4. `--default-lang`: default lang that will be in `Base.lproj`. It must be in `langs` as well
4. `--extension-output-path`: path where to generate generated extension 5. `--extension-output-path`: path where to generate generated extension
### Stringium (recommended) ### Stringium (recommended)
@ -93,6 +93,7 @@ swift run -c release ResgenSwift strings stringium $FORCE_FLAG "./Strings/string
--extension-output-path "./Strings/Generated" \ --extension-output-path "./Strings/Generated" \
--extension-name "AppString" \ --extension-name "AppString" \
--extension-suffix "GreatApp" \ --extension-suffix "GreatApp" \
--xcStrings true
--static-members true --static-members true
``` ```
@ -105,6 +106,7 @@ swift run -c release ResgenSwift strings stringium $FORCE_FLAG "./Strings/string
4. `--extension-output-path`: path where to generate generated extension 4. `--extension-output-path`: path where to generate generated extension
5. `--extension-name` *(optional)* : name of class to add the extension 5. `--extension-name` *(optional)* : name of class to add the extension
6. `--extension-suffix` *(optional)* : additional text which is added to filename (ex: `AppString+GreatApp.swift`) 6. `--extension-suffix` *(optional)* : additional text which is added to filename (ex: `AppString+GreatApp.swift`)
6. `--xcStrings`*(optional)* : generate string catalog
7. `--static-members` *(optional)*: generate static properties or not 7. `--static-members` *(optional)*: generate static properties or not
@ -131,7 +133,7 @@ swift run -c release ResgenSwift strings tags $FORCE_FLAG "./Tags/tags.txt" \
6. `--extension-suffix` *(optional)* : additional text which is added to filename (ex: `AppTags+GreatApp.swift`) 6. `--extension-suffix` *(optional)* : additional text which is added to filename (ex: `AppTags+GreatApp.swift`)
7. `--static-members` *(optional)*: generate static properties or not 7. `--static-members` *(optional)*: generate static properties or not
> ⚠️ If extension name is not set or is `Tags`, it will generate the following typaloas `typealias Tags = String`. > ⚠️ If extension name is not set or is `Tags`, it will generate the following typealias `typealias Tags = String`.
## Analytics ## Analytics
@ -139,7 +141,7 @@ swift run -c release ResgenSwift strings tags $FORCE_FLAG "./Tags/tags.txt" \
Analytics will generate all you need to analyze UX with Matomo or Firebase Analytics. Input files are formatted in YAML. This command will generate a manager for each target and an AnalyticsManager. This is this one you will need to use. And it will generate a method for all tags you have declared in the YAML file. Next, you will need to use the `configure()` method of AnalyticsManager and if you want to use matomo to set up the `siteId` and the `url` of the site. Analytics will generate all you need to analyze UX with Matomo or Firebase Analytics. Input files are formatted in YAML. This command will generate a manager for each target and an AnalyticsManager. This is this one you will need to use. And it will generate a method for all tags you have declared in the YAML file. Next, you will need to use the `configure()` method of AnalyticsManager and if you want to use matomo to set up the `siteId` and the `url` of the site.
```sh ```sh
swift run -c release ResgenSwift strings tags $FORCE_FLAG "./Tags/tags.txt" \ swift run -c release ResgenSwift analytics $FORCE_FLAG "./Tags/analytics.yml" \
--target "matomo firebase" \ --target "matomo firebase" \
--extension-output-path "./Analytics/Generated" \ --extension-output-path "./Analytics/Generated" \
--extension-name "AppAnalytics" \ --extension-name "AppAnalytics" \
@ -157,7 +159,7 @@ swift run -c release ResgenSwift strings tags $FORCE_FLAG "./Tags/tags.txt" \
6. `--extension-suffix` *(optional)* : additional text which is added to filename (ex: `AppAnalytics+GreatApp.swift`) 6. `--extension-suffix` *(optional)* : additional text which is added to filename (ex: `AppAnalytics+GreatApp.swift`)
7. `--static-members` *(optional)*: generate static properties or not 7. `--static-members` *(optional)*: generate static properties or not
> ⚠️ If extension name is not set or is `Analytics`, it will generate the following typaloas `typealias Analytics = String`. > ⚠️ If extension name is not set or is `Analytics`, it will generate the following typealias `typealias Analytics = String`.
### YAML ### YAML
@ -184,19 +186,83 @@ swift run -c release ResgenSwift strings tags $FORCE_FLAG "./Tags/tags.txt" \
7. `comments` *(optional)* 7. `comments` *(optional)*
8. `parameters` *(optional)* 8. `parameters` *(optional)*
**Parameters** **Parameters**
You can use parameters in generate methods. You can use parameters in generate methods.
1. `name`: name of the parameter 1. `name`: name of the parameter
2. `type`: type of the parameter (Int, String, Bool, Double) 2. `type`: type of the parameter (Int, String, Bool, Double)
3. `value`: value of the parameter
4. `defaultValue`: defaultValue of the parameter
3. `replaceIn` *(optional)* 3. `replaceIn` *(optional)*
**Value**
If you want to send another parameter with a static value. For example, you want to send to which screen the event is triggered.
You can add the parameter 'screenName' for example and its 'value' is 'Home'. With this, you do not need to specify the value in the function call.
**DefaultValue**
If you want ta add a parameter in the call of the function but you want to make it optionnal with a default value you need to use this property.
Example:
```
events:
id: id_of_tag
name: _TITLE_
tags: ios,droid
parameters:
- name: title
type: String
defaultValue: someTitle
```
The generated method will be:
```
logIdOfTag(title: String = "someTitle")
```
**Replace in** **Replace in**
This is section is equivalent of `%s | %d | %f | %@`. You can put the content of the parameter in *name*, *path*, *action*, *category*. This is section is equivalent of `%s | %d | %f | %@`. You can put the content of the parameter in *name*, *path*, *action*, *category*.
You need to put `_` + `NAME OF THE PARAMETER` + `_` in the target and which target you want in the value of `replaceIn`. (name need to be in uppercase) You need to put `_` + `NAME OF THE PARAMETER` + `_` in the target and which target you want in the value of `replaceIn`. (name need to be in uppercase).
You can't use `value`and `replaceIn`in thge same time.
Example:
```
events:
id: id_of_tag
name: _TITLE_
tags: ios,droid
parameters:
- name: title
type: String
replaceIn: name
```
In this sample, we want to add the parameter `title` in the field `name`. So, we need to place `_TITLE_` in the field `name`.
The generated method will be:
```
logIdOfTag(title: String)
```
You can also want to replace a parameter in an other parameter. You can do this with the `replaceIn` property. The condition is that the parameter which will use the `replaceIn`need to have the `value`property
Example:
```
events:
id: id_of_tag
name: title
tags: ios,droid
parameters:
- name: something
type: String
value: test _TEXT_
- name: text
type: String
replaceIn: something
```
## Images ## Images
@ -223,6 +289,7 @@ swift run -c release ResgenSwift images $FORCE_FLAG "./Images/images.txt" \
6. `--extension-suffix` *(optional)* : additional text which is added to filename (ex: `AppImage+GreatApp.swift`) 6. `--extension-suffix` *(optional)* : additional text which is added to filename (ex: `AppImage+GreatApp.swift`)
7. `--static-members` *(optional)*: generate static properties or not 7. `--static-members` *(optional)*: generate static properties or not
> ⚠️ Svg images will be copied in the assets and rendered as "Original", however if those images are not rendered correctly you can force the png generation by adding the key word "png" like this: id arrow_back 15 ? png
## All at once ## All at once
@ -284,6 +351,15 @@ tags:
extensionName: String? extensionName: String?
extensionSuffix: String? extensionSuffix: String?
staticMembers: Bool? staticMembers: Bool?
analytics:
-
inputFile: String
target: String
extensionOutputPath: String
extensionName: String?
extensionSuffix: String?
staticMembers: Bool?
``` ```
### Multiple configurations ### Multiple configurations

View File

@ -6,13 +6,20 @@ import FirebaseAnalytics
// MARK: - Protocol // MARK: - Protocol
protocol AnalyticsManagerProtocol { protocol AnalyticsManagerProtocol {
func logScreen(name: String, path: String) func logScreen(
name: String,
path: String,
params: [String: Any]?
)
func logEvent( func logEvent(
name: String, name: String,
action: String, action: String,
category: String, category: String,
params: [String: Any]? params: [String: Any]?
) )
func setEnable(_ enable: Bool)
} }
// MARK: - Matomo // MARK: - Matomo
@ -47,8 +54,11 @@ class MatomoAnalyticsManager: AnalyticsManagerProtocol {
// MARK: - Methods // MARK: - Methods
func logScreen(name: String, path: String) { func logScreen(
guard !tracker.isOptedOut else { return } name: String,
path: String,
params: [String: Any]?
) {
guard let trackerUrl = tracker.contentBase?.absoluteString else { return } guard let trackerUrl = tracker.contentBase?.absoluteString else { return }
let urlString = URL(string: "\(trackerUrl)" + "/" + "\(path)" + "iOS") let urlString = URL(string: "\(trackerUrl)" + "/" + "\(path)" + "iOS")
@ -64,8 +74,6 @@ class MatomoAnalyticsManager: AnalyticsManagerProtocol {
category: String, category: String,
params: [String: Any]? params: [String: Any]?
) { ) {
guard !tracker.isOptedOut else { return }
tracker.track( tracker.track(
eventWithCategory: category, eventWithCategory: category,
action: action, action: action,
@ -74,32 +82,27 @@ class MatomoAnalyticsManager: AnalyticsManagerProtocol {
url: nil url: nil
) )
} }
func setEnable(_ enable: Bool) {
tracker.isOptedOut = !enable
}
} }
// MARK: - Firebase // MARK: - Firebase
class FirebaseAnalyticsManager: AnalyticsManagerProtocol { class FirebaseAnalyticsManager: AnalyticsManagerProtocol {
func logScreen(name: String, path: String) { func logScreen(
name: String,
path: String,
params: [String: Any]?
) {
var parameters = [ var parameters = [
AnalyticsParameterScreenName: name as NSObject AnalyticsParameterScreenName: name as NSObject
] ]
Analytics.logEvent( if path.isEmpty == false {
AnalyticsEventScreenView, parameters["path"] = path + "/iOS" as NSObject
parameters: parameters }
)
}
func logEvent(
name: String,
action: String,
category: String,
params: [String: Any]?
) {
var parameters: [String:NSObject] = [
"action": action as NSObject,
"category": category as NSObject,
]
if let supplementaryParameters = params { if let supplementaryParameters = params {
for (newKey, newValue) in supplementaryParameters { for (newKey, newValue) in supplementaryParameters {
@ -114,10 +117,49 @@ class FirebaseAnalyticsManager: AnalyticsManagerProtocol {
} }
Analytics.logEvent( Analytics.logEvent(
name.replacingOccurrences(of: [" "], with: "_"), AnalyticsEventScreenView,
parameters: parameters parameters: parameters
) )
} }
func logEvent(
name: String,
action: String,
category: String,
params: [String: Any]?
) {
var parameters: [String:NSObject] = [
AnalyticsParameterItemName: name.replacingOccurrences(of: " ", with: "_") as NSObject
]
if category.isEmpty == false {
parameters["AnalyticsParameterItemCategory"] = category as NSObject
}
if action.isEmpty == false {
parameters["action"] = action as NSObject
}
if let supplementaryParameters = params {
for (newKey, newValue) in supplementaryParameters {
if parameters.contains(where: { (key: String, value: NSObject) in
key == newKey
}) {
continue
}
parameters[newKey] = newValue as? NSObject
}
}
Analytics.logEvent(
AnalyticsEventSelectContent,
parameters: parameters
)
}
func setEnable(_ enable: Bool) {
Analytics.setAnalyticsCollectionEnabled(enable)
}
} }
// MARK: - Manager // MARK: - Manager
@ -127,31 +169,57 @@ class AnalyticsManager {
// MARK: - Properties // MARK: - Properties
var managers: [AnalyticsManagerProtocol] = [] var managers: [TargetType: AnalyticsManagerProtocol] = []
private var isEnabled: Bool = true private var isEnabled: Bool {
if ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1" {
false
} else {
true
}
}
// MARK: - Methods // MARK: - Methods
func setAnalyticsEnabled(_ enable: Bool) { private func setAnalytics(enable: Bool) {
isEnabled = enable managers.forEach { (key, value) in
if analytics.contains(where: { type in
type == key
}) {
value.setEnable(enable)
}
}
}
func enableAnalytics(_ analytics: [TargetType] = TargetType.allCases) {
setAnalytics(enable: true)
}
func disableAnalytics(_ analytics: [TargetType] = TargetType.allCases) {
setAnalytics(enable: false)
} }
func configure(siteId: String, url: String) { func configure(siteId: String, url: String) {
managers.append( managers[TrackerType.matomo] = MatomoAnalyticsManager(
MatomoAnalyticsManager( siteId: siteId,
siteId: siteId, url: url
url: url
)
) )
managers.append(FirebaseAnalyticsManager()) managers[TrackerType.firebase] = FirebaseAnalyticsManager()
} }
private func logScreen(name: String, path: String) { private func logScreen(
name: String,
path: String,
params: [String: Any]?
) {
guard isEnabled else { return } guard isEnabled else { return }
managers.forEach { manager in managers.values.forEach { manager in
manager.logScreen(name: name, path: path) manager.logScreen(
name: name,
path: path,
params: params
)
} }
} }
@ -163,7 +231,7 @@ class AnalyticsManager {
) { ) {
guard isEnabled else { return } guard isEnabled else { return }
managers.forEach { manager in managers.values.forEach { manager in
manager.logEvent( manager.logEvent(
name: name, name: name,
action: action, action: action,
@ -175,31 +243,39 @@ class AnalyticsManager {
// MARK: - section_one // MARK: - section_one
func logScreenS1DefOne(title: String) { static func logScreenS1DefOne(title: String) {
logScreen( AnalyticsManager.shared.logScreen(
name: "s1 def one \(title)", name: "s1 def one \(title)",
path: "s1_def_one/\(title)" path: "s1_def_one/\(title)",
params: nil
) )
} }
func logEventS1DefTwo(title: String, count: String) { static func logEventS1DefTwo(
logEvent( title: String,
count: String,
test2: String = "test"
) {
AnalyticsManager.shared.logEvent(
name: "s1 def two", name: "s1 def two",
action: "test", action: "test",
category: "test", category: "test",
params: [ params: [
"title": title, "title": title,
"count": count "count": count,
"test": "test",
"test2": test2
] ]
) )
} }
// MARK: - section_two // MARK: - section_two
func logScreenS2DefOne() { static func logScreenS2DefOne() {
logScreen( AnalyticsManager.shared.logScreen(
name: "s2 def one", name: "s2 def one",
path: "s2_def_one/" path: "s2_def_one/",
params: nil
) )
} }
} }

View File

@ -22,6 +22,12 @@ categories:
type: String type: String
- name: count - name: count
type: String type: String
- name: test
type: String
value: test
- name: test2
type: String
defaultValue: test
- id: section_two - id: section_two
screens: screens:

View File

@ -54,10 +54,11 @@ FORCE_FLAG="$1"
# Analytics # Analytics
swift run -c release ResgenSwift analytics $FORCE_FLAG "./Tags/sampleTags.yml" \ swift run -c release ResgenSwift analytics $FORCE_FLAG "./Tags/sampleTags.yml" \
--target "matomo firebase" \ --target "firebase matomo" \
--extension-output-path "./Tags/Generated" \ --extension-output-path "./Tags/Generated" \
--extension-name "Analytics" \ --extension-name "Analytics" \
--extension-suffix "GenAllScript" --extension-suffix "GenAllScript" \
--static-members true
#echo "\n-------------------------\n" #echo "\n-------------------------\n"
# #

View File

@ -59,14 +59,18 @@ class AnalyticsGenerator {
\(Self.getImport()) \(Self.getImport())
\(Self.getAnalyticsProtocol()) \(Self.getAnalyticsProtocol())
\(Self.getTrackerTypeEnum())
// MARK: - Manager // MARK: - Manager
class AnalyticsManager { class AnalyticsManager {
static var shared = AnalyticsManager() static var shared = AnalyticsManager()
// MARK: - Properties // MARK: - Properties
var managers: [AnalyticsManagerProtocol] = [] var managers: [TrackerType: AnalyticsManagerProtocol] = [:]
\(Self.getEnabledContent()) \(Self.getEnabledContent())
@ -76,14 +80,49 @@ class AnalyticsGenerator {
""" """
} }
private static func getTrackerTypeEnum() -> String {
var result: [String] = []
TrackerType.allCases.forEach { type in
result.append(" case \(type)")
}
return """
// MARK: - Traker Type
enum TrackerType: CaseIterable {
\(result.joined(separator: "\n"))
}
"""
}
private static func getEnabledContent() -> String { private static func getEnabledContent() -> String {
""" """
private var isEnabled: Bool = true private var isEnabled: Bool {
if ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1" {
false
} else {
true
}
}
// MARK: - Methods // MARK: - Methods
func setAnalyticsEnabled(_ enable: Bool) { private func setAnalytics(enable: Bool, _ analytics: [TrackerType]) {
isEnabled = enable managers.forEach { (key, value) in
if analytics.contains(where: { type in
type == key
}) {
value.setEnable(enable)
}
}
}
func enableAnalytics(_ analytics: [TrackerType] = TrackerType.allCases) {
setAnalytics(enable: true, analytics)
}
func disableAnalytics(_ analytics: [TrackerType] = TrackerType.allCases) {
setAnalytics(enable: false, analytics)
} }
""" """
} }
@ -103,11 +142,19 @@ class AnalyticsGenerator {
private static func getPrivateLogFunction() -> String { private static func getPrivateLogFunction() -> String {
""" """
private func logScreen(name: String, path: String) { private func logScreen(
name: String,
path: String,
params: [String: Any]?
) {
guard isEnabled else { return } guard isEnabled else { return }
managers.forEach { manager in managers.values.forEach { manager in
manager.logScreen(name: name, path: path) manager.logScreen(
name: name,
path: path,
params: params
)
} }
} }
@ -119,7 +166,7 @@ class AnalyticsGenerator {
) { ) {
guard isEnabled else { return } guard isEnabled else { return }
managers.forEach { manager in managers.values.forEach { manager in
manager.logEvent( manager.logEvent(
name: name, name: name,
action: action, action: action,
@ -144,16 +191,14 @@ class AnalyticsGenerator {
if targets.contains(TrackerType.matomo) { if targets.contains(TrackerType.matomo) {
content.append(""" content.append("""
managers.append( managers[TrackerType.matomo] = MatomoAnalyticsManager(
MatomoAnalyticsManager( siteId: siteId,
siteId: siteId, url: url
url: url
)
) )
""") """)
} }
if targets.contains(TrackerType.firebase) { if targets.contains(TrackerType.firebase) {
content.append(" managers.append(FirebaseAnalyticsManager())") content.append(" managers[TrackerType.firebase] = FirebaseAnalyticsManager()")
} }
return [ return [
@ -169,13 +214,20 @@ class AnalyticsGenerator {
// MARK: - Protocol // MARK: - Protocol
protocol AnalyticsManagerProtocol { protocol AnalyticsManagerProtocol {
func logScreen(name: String, path: String) func logScreen(
name: String,
path: String,
params: [String: Any]?
)
func logEvent( func logEvent(
name: String, name: String,
action: String, action: String,
category: String, category: String,
params: [String: Any]? params: [String: Any]?
) )
func setEnable(_ enable: Bool)
} }
""" """

View File

@ -14,6 +14,7 @@ enum FirebaseGenerator {
FirebaseGenerator.header, FirebaseGenerator.header,
FirebaseGenerator.logScreen, FirebaseGenerator.logScreen,
FirebaseGenerator.logEvent, FirebaseGenerator.logEvent,
FirebaseGenerator.enable,
FirebaseGenerator.footer FirebaseGenerator.footer
] ]
.joined(separator: "\n") .joined(separator: "\n")
@ -31,11 +32,31 @@ enum FirebaseGenerator {
private static var logScreen: String { private static var logScreen: String {
""" """
func logScreen(name: String, path: String) { func logScreen(
name: String,
path: String,
params: [String: Any]?
) {
var parameters = [ var parameters = [
AnalyticsParameterScreenName: name as NSObject AnalyticsParameterScreenName: name as NSObject
] ]
if path.isEmpty == false {
parameters["path"] = path + "/iOS" as NSObject
}
if let supplementaryParameters = params {
for (newKey, newValue) in supplementaryParameters {
if parameters.contains(where: { (key: String, value: NSObject) in
key == newKey
}) {
continue
}
parameters[newKey] = newValue as? NSObject
}
}
Analytics.logEvent( Analytics.logEvent(
AnalyticsEventScreenView, AnalyticsEventScreenView,
parameters: parameters parameters: parameters
@ -54,10 +75,17 @@ enum FirebaseGenerator {
params: [String: Any]? params: [String: Any]?
) { ) {
var parameters: [String:NSObject] = [ var parameters: [String:NSObject] = [
"action": action as NSObject, AnalyticsParameterItemName: name.replacingOccurrences(of: " ", with: "_") as NSObject
"category": category as NSObject,
] ]
if category.isEmpty == false {
parameters["AnalyticsParameterItemCategory"] = category as NSObject
}
if action.isEmpty == false {
parameters["action"] = action as NSObject
}
if let supplementaryParameters = params { if let supplementaryParameters = params {
for (newKey, newValue) in supplementaryParameters { for (newKey, newValue) in supplementaryParameters {
if parameters.contains(where: { (key: String, value: NSObject) in if parameters.contains(where: { (key: String, value: NSObject) in
@ -71,13 +99,21 @@ enum FirebaseGenerator {
} }
Analytics.logEvent( Analytics.logEvent(
name.replacingOccurrences(of: [" "], with: "_"), AnalyticsEventSelectContent,
parameters: parameters parameters: parameters
) )
} }
""" """
} }
private static var enable: String {
"""
func setEnable(_ enable: Bool) {
Analytics.setAnalyticsCollectionEnabled(enable)
}
"""
}
private static var footer: String { private static var footer: String {
""" """
} }

View File

@ -15,6 +15,7 @@ enum MatomoGenerator {
MatomoGenerator.setup, MatomoGenerator.setup,
MatomoGenerator.logScreen, MatomoGenerator.logScreen,
MatomoGenerator.logEvent, MatomoGenerator.logEvent,
MatomoGenerator.enable,
MatomoGenerator.footer MatomoGenerator.footer
] ]
.joined(separator: "\n") .joined(separator: "\n")
@ -66,8 +67,11 @@ enum MatomoGenerator {
private static var logScreen: String { private static var logScreen: String {
""" """
func logScreen(name: String, path: String) { func logScreen(
guard !tracker.isOptedOut else { return } name: String,
path: String,
params: [String: Any]?
) {
guard let trackerUrl = tracker.contentBase?.absoluteString else { return } guard let trackerUrl = tracker.contentBase?.absoluteString else { return }
let urlString = URL(string: "\\(trackerUrl)" + "/" + "\\(path)" + "iOS") let urlString = URL(string: "\\(trackerUrl)" + "/" + "\\(path)" + "iOS")
@ -88,8 +92,6 @@ enum MatomoGenerator {
category: String, category: String,
params: [String: Any]? params: [String: Any]?
) { ) {
guard !tracker.isOptedOut else { return }
tracker.track( tracker.track(
eventWithCategory: category, eventWithCategory: category,
action: action, action: action,
@ -98,6 +100,15 @@ enum MatomoGenerator {
url: nil url: nil
) )
} }
"""
}
private static var enable: String {
"""
func setEnable(_ enable: Bool) {
tracker.isOptedOut = !enable
}
""" """
} }

View File

@ -48,17 +48,23 @@ class AnalyticsDefinition {
} }
private func getParameters() -> String { private func getParameters() -> String {
var params = parameters
var result: String var result: String
if type == .screen { let paramsString = parameters.compactMap { parameter -> String? in
params = params.filter { param in guard parameter.value.isEmpty else { return nil }
!param.replaceIn.isEmpty
}
}
let paramsString = params.map { parameter in let defaultValue: String
"\(parameter.name): \(parameter.type)" switch parameter.type {
case .bool:
defaultValue = "\(parameter.defaultValue.lowercased())"
case .int, .double:
defaultValue = "\(parameter.defaultValue)"
case .string:
defaultValue = "\"\(parameter.defaultValue)\""
}
let defaultValueString = parameter.defaultValue.isEmpty ? "" : " = \(defaultValue)"
return "\(parameter.name): \(parameter.type.rawValue)\(defaultValueString)"
} }
if paramsString.count > 2 { if paramsString.count > 2 {
@ -84,7 +90,10 @@ class AnalyticsDefinition {
case "path": path = path.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 "category": category = category.replacingFirstOccurrence(of: "_\(parameter.name.uppercased())_", with: "\\(\(parameter.name))")
case "action": action = action.replacingFirstOccurrence(of: "_\(parameter.name.uppercased())_", with: "\\(\(parameter.name))") case "action": action = action.replacingFirstOccurrence(of: "_\(parameter.name.uppercased())_", with: "\\(\(parameter.name))")
default: break default:
if let param = parameters.first(where: { $0.name == rep }), param.value.isEmpty == false {
param.value = param.value.replacingFirstOccurrence(of: "_\(parameter.name.uppercased())_", with: "\\(\(parameter.name))")
}
} }
} }
} }
@ -99,7 +108,18 @@ class AnalyticsDefinition {
} }
supplementaryParams.forEach { param in supplementaryParams.forEach { param in
params.append("\"\(param.name)\": \(param.name)") if param.value.isEmpty {
params.append("\"\(param.name)\": \(param.name)")
} else {
switch param.type {
case .bool:
params.append("\"\(param.name)\": \(param.value.lowercased())")
case .int, .double:
params.append("\"\(param.name)\": \(param.value)")
case .string:
params.append("\"\(param.name)\": \"\(param.value)\"")
}
}
} }
if params.count > 1 { if params.count > 1 {
@ -113,14 +133,15 @@ class AnalyticsDefinition {
[\(params.joined(separator: ", "))] [\(params.joined(separator: ", "))]
""" """
} else { } else {
result = "[:]" result = "nil"
} }
if type == .screen { if type == .screen {
return """ return """
logScreen( logScreen(
name: "\(name)", name: "\(name)",
path: "\(path)" path: "\(path)",
params: \(result)
) )
""" """
} else { } else {
@ -150,7 +171,7 @@ class AnalyticsDefinition {
replaceIn() replaceIn()
return """ return """
static func \(getFuncName())\(getParameters()) { static func \(getFuncName())\(getParameters()) {
\(getlogFunction()) AnalyticsManager.shared.\(getlogFunction())
} }
""" """
} }

View File

@ -41,5 +41,7 @@ struct AnalyticsDefinitionEventDTO: Codable {
struct AnalyticsParameterDTO: Codable { struct AnalyticsParameterDTO: Codable {
var name: String var name: String
var type: String var type: String
var value: String?
var defaultValue: String?
var replaceIn: String? var replaceIn: String?
} }

View File

@ -9,13 +9,17 @@ import Foundation
class AnalyticsParameter { class AnalyticsParameter {
var name: String var name: String
var type: String var type: ParameterType
var value: String
var defaultValue: String
var replaceIn: [String] = [] var replaceIn: [String] = []
// MARK: - Init // MARK: - Init
init(name: String, type: String) { init(name: String, type: ParameterType, value: String, defaultValue: String) {
self.name = name self.name = name
self.type = type self.type = type
self.value = value
self.defaultValue = defaultValue
} }
} }

View File

@ -0,0 +1,15 @@
//
// File.swift
//
//
// Created by Loris Perret on 17/07/2024.
//
import Foundation
enum ParameterType: String {
case string = "String"
case int = "Int"
case double = "Double"
case bool = "Bool"
}

View File

@ -30,25 +30,58 @@ class AnalyticsFileParser {
} }
private static func getParameters(from parameters: [AnalyticsParameterDTO]) -> [AnalyticsParameter] { private static func getParameters(from parameters: [AnalyticsParameterDTO]) -> [AnalyticsParameter] {
parameters.map { dtoParameter in func verify(value: String?, for type: ParameterType) {
guard let value, value.isEmpty == false else { return }
switch type {
case .int:
if Int(value) == nil {
let error = AnalyticsError.invalidParameter("type of \(value) is not \(type)")
print(error.description)
Analytics.exit(withError: error)
}
case .bool:
if Bool(value.lowercased()) == nil {
let error = AnalyticsError.invalidParameter("type of \(value) is not \(type)")
print(error.description)
Analytics.exit(withError: error)
}
case .double:
if Double(value) == nil {
let error = AnalyticsError.invalidParameter("type of \(value) is not \(type)")
print(error.description)
Analytics.exit(withError: error)
}
case .string:
break
}
}
return parameters.map { dtoParameter in
// Type // Type
let type = dtoParameter.type.uppercasedFirst() let type = dtoParameter.type.uppercasedFirst()
guard guard let typeEnum = ParameterType(rawValue: type) else {
type == "String" ||
type == "Int" ||
type == "Double" ||
type == "Bool"
else {
let error = AnalyticsError.invalidParameter("type of \(dtoParameter.name)") let error = AnalyticsError.invalidParameter("type of \(dtoParameter.name)")
print(error.description) print(error.description)
Analytics.exit(withError: error) Analytics.exit(withError: error)
} }
if dtoParameter.value != nil, dtoParameter.replaceIn != nil {
let error = AnalyticsError.invalidParameter("you can't set 'value' and 'replaceIn' for \(dtoParameter.name)")
print(error.description)
Analytics.exit(withError: error)
}
verify(value: dtoParameter.value, for: typeEnum)
verify(value: dtoParameter.defaultValue, for: typeEnum)
let parameter = AnalyticsParameter( let parameter = AnalyticsParameter(
name: dtoParameter.name, name: dtoParameter.name,
type: type type: typeEnum,
value: dtoParameter.value ?? "",
defaultValue: dtoParameter.defaultValue ?? ""
) )
if let replaceIn = dtoParameter.replaceIn { if let replaceIn = dtoParameter.replaceIn {
@ -103,6 +136,8 @@ class AnalyticsFileParser {
Analytics.exit(withError: error) Analytics.exit(withError: error)
} }
definition.path = path
} else if let path = screen.path {
definition.path = path definition.path = path
} }
@ -139,6 +174,14 @@ class AnalyticsFileParser {
} }
definition.action = action definition.action = action
} else {
if let category = event.category {
definition.category = category
}
if let action = event.action {
definition.action = action
}
} }
return definition return definition

View File

@ -9,7 +9,7 @@ import Foundation
enum GenerateError: Error { enum GenerateError: Error {
case fileNotExists(String) case fileNotExists(String)
case invalidConfigurationFile(String) case invalidConfigurationFile(String, String)
case commandError([String], String) case commandError([String], String)
case writeFile(String, String) case writeFile(String, String)
@ -18,8 +18,8 @@ enum GenerateError: Error {
case .fileNotExists(let filename): 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): case .invalidConfigurationFile(let filename, let underneathErrorDescription):
return "error: [\(Generate.toolName)] File \(filename) is not a valid configuration file" return "error: [\(Generate.toolName)] File \(filename) is not a valid configuration file. Underneath error: \(underneathErrorDescription)"
case .commandError(let command, let terminationStatus): case .commandError(let command, let terminationStatus):
let readableCommand = command let readableCommand = command

View File

@ -269,6 +269,7 @@ struct StringsConfiguration: Codable, CustomDebugStringConvertible {
let extensionName: String? let extensionName: String?
let extensionSuffix: String? let extensionSuffix: String?
private let staticMembers: Bool? private let staticMembers: Bool?
private let xcStrings: Bool?
var staticMembersOptions: Bool { var staticMembersOptions: Bool {
if let staticMembers = staticMembers { if let staticMembers = staticMembers {
@ -277,6 +278,13 @@ struct StringsConfiguration: Codable, CustomDebugStringConvertible {
return false return false
} }
var xcStringsOptions: Bool {
if let xcStrings = xcStrings {
return xcStrings
}
return false
}
internal init(inputFile: String, internal init(inputFile: String,
outputPath: String, outputPath: String,
langs: String, langs: String,
@ -284,7 +292,8 @@ struct StringsConfiguration: Codable, CustomDebugStringConvertible {
extensionOutputPath: String, extensionOutputPath: String,
extensionName: String?, extensionName: String?,
extensionSuffix: String?, extensionSuffix: String?,
staticMembers: Bool?) { staticMembers: Bool?,
xcStrings: Bool?) {
self.inputFile = inputFile self.inputFile = inputFile
self.outputPath = outputPath self.outputPath = outputPath
self.langs = langs self.langs = langs
@ -293,6 +302,7 @@ struct StringsConfiguration: Codable, CustomDebugStringConvertible {
self.extensionName = extensionName self.extensionName = extensionName
self.extensionSuffix = extensionSuffix self.extensionSuffix = extensionSuffix
self.staticMembers = staticMembers self.staticMembers = staticMembers
self.xcStrings = xcStrings
} }
var debugDescription: String { var debugDescription: String {

View File

@ -16,12 +16,15 @@ class ConfigurationFileParser {
Generate.exit(withError: error) Generate.exit(withError: error)
} }
guard let configuration = try? YAMLDecoder().decode(ConfigurationFile.self, from: data) else { do {
let error = GenerateError.invalidConfigurationFile(configurationFile) return try YAMLDecoder().decode(ConfigurationFile.self, from: data)
} catch {
let error = GenerateError.invalidConfigurationFile(
configurationFile,
error.localizedDescription.description
)
print(error.description) print(error.description)
Generate.exit(withError: error) Generate.exit(withError: error)
} }
return configuration
} }
} }

View File

@ -26,7 +26,9 @@ extension StringsConfiguration: Runnable {
"--extension-output-path", "--extension-output-path",
extensionOutputPath.prependIfRelativePath(projectDirectory), extensionOutputPath.prependIfRelativePath(projectDirectory),
"--static-members", "--static-members",
"\(staticMembersOptions)" "\(staticMembersOptions)",
"--xc-strings",
"\(xcStringsOptions)"
] ]
if let extensionName = extensionName { if let extensionName = extensionName {

View File

@ -8,9 +8,12 @@
import Foundation import Foundation
import ToolCore import ToolCore
class XcassetsGenerator { enum OutputImageExtension: String {
case png
case svg
}
static let outputImageExtension = "png" class XcassetsGenerator {
let forceGeneration: Bool let forceGeneration: Bool
@ -60,13 +63,20 @@ class XcassetsGenerator {
generatedAssetsPaths.append(imagesetName) generatedAssetsPaths.append(imagesetName)
// Generate output images path // Generate output images path
let output1x = "\(imagesetPath)/\(parsedImage.name).\(XcassetsGenerator.outputImageExtension)" let output1x = "\(imagesetPath)/\(parsedImage.name).\(OutputImageExtension.png.rawValue)"
let output2x = "\(imagesetPath)/\(parsedImage.name)@2x.\(XcassetsGenerator.outputImageExtension)" let output2x = "\(imagesetPath)/\(parsedImage.name)@2x.\(OutputImageExtension.png.rawValue)"
let output3x = "\(imagesetPath)/\(parsedImage.name)@3x.\(XcassetsGenerator.outputImageExtension)" let output3x = "\(imagesetPath)/\(parsedImage.name)@3x.\(OutputImageExtension.png.rawValue)"
// Check if we need to convert image // Check if we need to convert image
guard self.shouldGenerate(inputImagePath: imageData.path, xcassetImagePath: output1x) else {
//print("\(parsedImage.name) -> Not regenerating") var needToGenerateForSvg = false
if imageData.ext == "svg" && !parsedImage.imageExtensions.contains(.png) {
needToGenerateForSvg = true
}
guard self.shouldGenerate(inputImagePath: imageData.path, xcassetImagePath: output1x, needToGenerateForSvg: needToGenerateForSvg) else {
print("\(parsedImage.name) -> Not regenerating")
return return
} }
@ -80,29 +90,55 @@ class XcassetsGenerator {
print(error.description) print(error.description)
Images.exit(withError: error) Images.exit(withError: error)
} }
} else {
do {
let documentsDirectory = try fileManager.contentsOfDirectory(atPath: imagesetPath)
for filePath in documentsDirectory {
try fileManager.removeItem(atPath: "\(imagesetPath)/\(filePath)")
}
} catch {
print("Error deleting previous assets")
}
} }
// Convert image
let convertArguments = parsedImage.convertArguments let convertArguments = parsedImage.convertArguments
if imageData.ext == "svg" { if imageData.ext == "svg" {
// /usr/local/bin/rsvg-convert path/to/image.png -w 200 -h 300 -o path/to/output.png if parsedImage.imageExtensions.contains(.png) {
// /usr/local/bin/rsvg-convert path/to/image.png -w 200 -o path/to/output.png
// /usr/local/bin/rsvg-convert path/to/image.png -h 300 -o path/to/output.png
var command1x = ["\(svgConverter)", "\(imageData.path)"]
var command2x = ["\(svgConverter)", "\(imageData.path)"]
var command3x = ["\(svgConverter)", "\(imageData.path)"]
self.addConvertArgument(command: &command1x, convertArgument: convertArguments.x1) // /usr/local/bin/rsvg-convert path/to/image.png -w 200 -h 300 -o path/to/output.png
self.addConvertArgument(command: &command2x, convertArgument: convertArguments.x2) // /usr/local/bin/rsvg-convert path/to/image.png -w 200 -o path/to/output.png
self.addConvertArgument(command: &command3x, convertArgument: convertArguments.x3) // /usr/local/bin/rsvg-convert path/to/image.png -h 300 -o path/to/output.png
var command1x = ["\(svgConverter)", "\(imageData.path)"]
var command2x = ["\(svgConverter)", "\(imageData.path)"]
var command3x = ["\(svgConverter)", "\(imageData.path)"]
command1x.append(contentsOf: ["-o", output1x]) self.addConvertArgument(command: &command1x, convertArgument: convertArguments.x1)
command2x.append(contentsOf: ["-o", output2x]) self.addConvertArgument(command: &command2x, convertArgument: convertArguments.x2)
command3x.append(contentsOf: ["-o", output3x]) self.addConvertArgument(command: &command3x, convertArgument: convertArguments.x3)
Shell.shell(command1x) command1x.append(contentsOf: ["-o", output1x])
Shell.shell(command2x) command2x.append(contentsOf: ["-o", output2x])
Shell.shell(command3x) command3x.append(contentsOf: ["-o", output3x])
Shell.shell(command1x)
Shell.shell(command2x)
Shell.shell(command3x)
} else {
let output = "\(imagesetPath)/\(parsedImage.name).\(OutputImageExtension.svg.rawValue)"
let tempURL = URL(fileURLWithPath: output)
do {
if FileManager.default.fileExists(atPath: tempURL.path) {
try FileManager.default.removeItem(atPath: tempURL.path)
}
try FileManager.default.copyItem(atPath: imageData.path, toPath: tempURL.path)
} catch {
print(error.localizedDescription)
}
}
} else { } else {
// convert path/to/image.png -resize 200x300 path/to/output.png // convert path/to/image.png -resize 200x300 path/to/output.png
// convert path/to/image.png -resize 200x path/to/output.png // convert path/to/image.png -resize 200x path/to/output.png
@ -119,7 +155,7 @@ class XcassetsGenerator {
} }
// Write Content.json // Write Content.json
let imagesetContentJson = parsedImage.contentJson guard let imagesetContentJson = parsedImage.generateContentJson(isVector: imageData.ext == "svg") else { return }
let contentJsonFilePath = "\(imagesetPath)/Contents.json" let contentJsonFilePath = "\(imagesetPath)/Contents.json"
let contentJsonFilePathURL = URL(fileURLWithPath: contentJsonFilePath) let contentJsonFilePathURL = URL(fileURLWithPath: contentJsonFilePath)
@ -161,8 +197,8 @@ class XcassetsGenerator {
// MARK: - Helpers: bypass generation // MARK: - Helpers: bypass generation
private func shouldGenerate(inputImagePath: String, xcassetImagePath: String) -> Bool { private func shouldGenerate(inputImagePath: String, xcassetImagePath: String, needToGenerateForSvg: Bool) -> Bool {
if forceGeneration { if forceGeneration || needToGenerateForSvg {
return true return true
} }

View File

@ -0,0 +1,76 @@
//
// ImageContent.swift
//
//
// Created by Quentin Bandera on 19/04/2024.
//
import Foundation
enum TemplateRenderingIntent: String, Codable {
case template
case original
}
struct AssetContent: Codable, Equatable {
let images: [AssetImageDescription]
let info: AssetInfo
let properties: AssetProperties?
init(
images: [AssetImageDescription],
info: AssetInfo,
properties: AssetProperties? = nil
) {
self.images = images
self.info = info
self.properties = properties
}
static func == (lhs: AssetContent, rhs: AssetContent) -> Bool {
guard lhs.images.count == rhs.images.count else { return false }
let lhsImages = lhs.images.sorted(by: { $0.filename < $1.filename })
let rhsImages = rhs.images.sorted(by: { $0.filename < $1.filename })
return lhsImages == rhsImages
}
}
struct AssetImageDescription: Codable, Equatable {
let idiom: String
let scale: String?
let filename: String
init(
idiom: String,
scale: String? = nil,
filename: String
) {
self.idiom = idiom
self.scale = scale
self.filename = filename
}
}
struct AssetInfo: Codable, Equatable {
let version: Int
let author: String
}
struct AssetProperties: Codable, Equatable {
let preservesVectorRepresentation: Bool
let templateRenderingIntent: TemplateRenderingIntent?
init(
preservesVectorRepresentation: Bool,
templateRenderingIntent: TemplateRenderingIntent? = nil
) {
self.preservesVectorRepresentation = preservesVectorRepresentation
self.templateRenderingIntent = templateRenderingIntent
}
enum CodingKeys: String, CodingKey {
case preservesVectorRepresentation = "preserves-vector-representation"
case templateRenderingIntent = "template-rendering-intent"
}
}

View File

@ -7,11 +7,30 @@
import Foundation import Foundation
enum ImageExtension: String {
case png
}
struct ParsedImage { struct ParsedImage {
let name: String let name: String
let tags: String let tags: String
let width: Int let width: Int
let height: Int let height: Int
let imageExtensions: [ImageExtension]
init(
name: String,
tags: String,
width: Int,
height: Int,
imageExtensions: [ImageExtension] = []
) {
self.name = name
self.tags = tags
self.width = width
self.height = height
self.imageExtensions = imageExtensions
}
// MARK: - Convert // MARK: - Convert
@ -42,32 +61,67 @@ struct ParsedImage {
// MARK: - Assets // MARK: - Assets
var contentJson: String { func generateContentJson(isVector: Bool) -> String? {
""" let encoder = JSONEncoder()
{ encoder.outputFormatting = .prettyPrinted
"images" : [
{ let imageContent = generateImageContent(isVector: isVector)
"idiom" : "universal",
"scale" : "1x", guard let data = try? encoder.encode(imageContent) else {
"filename" : "\(name).\(XcassetsGenerator.outputImageExtension)" let error = ImagesError.writeFile("Contents.json", "Error encoding json file")
}, print(error.description)
{ Images.exit(withError: error)
"idiom" : "universal", }
"scale" : "2x",
"filename" : "\(name)@2x.\(XcassetsGenerator.outputImageExtension)" return String(data: data, encoding: .utf8)
}, }
{
"idiom" : "universal", func generateImageContent(isVector: Bool) -> AssetContent {
"scale" : "3x",
"filename" : "\(name)@3x.\(XcassetsGenerator.outputImageExtension)" if !imageExtensions.contains(.png) && isVector {
} //Generate svg
], return AssetContent(
"info" : { images: [
"version" : 1, AssetImageDescription(
"author" : "ResgenSwift-Imagium" idiom: "universal",
} filename: "\(name).\(OutputImageExtension.svg.rawValue)"
)
],
info: AssetInfo(
version: 1,
author: "ResgenSwift-Imagium"
),
properties: AssetProperties(
preservesVectorRepresentation: true,
templateRenderingIntent: .original
)
)
} else {
//Generate png
return AssetContent(
images: [
AssetImageDescription(
idiom: "universal",
scale: "1x",
filename: "\(name).\(OutputImageExtension.png.rawValue)"
),
AssetImageDescription(
idiom: "universal",
scale: "2x",
filename: "\(name)@2x.\(OutputImageExtension.png.rawValue)"
),
AssetImageDescription(
idiom: "universal",
scale: "3x",
filename: "\(name)@3x.\(OutputImageExtension.png.rawValue)"
)
],
info: AssetInfo(
version: 1,
author: "ResgenSwift-Imagium"
)
)
} }
"""
} }
// MARK: - Extension property // MARK: - Extension property

View File

@ -39,10 +39,20 @@ class ImageFileParser {
return Int(splittedLine[3])! return Int(splittedLine[3])!
}() }()
let image = ParsedImage(name: String(splittedLine[1]), tags: String(splittedLine[0]), width: width, height: height) var imageExtensions: [ImageExtension] = []
splittedLine.forEach { stringExtension in
if let imageExtension = ImageExtension(rawValue: String(stringExtension)) {
imageExtensions.append(imageExtension)
}
}
let image = ParsedImage(name: String(splittedLine[1]), tags: String(splittedLine[0]), width: width, height: height, imageExtensions: imageExtensions)
imagesToGenerate.append(image) imagesToGenerate.append(image)
} }
print(imagesToGenerate)
return imagesToGenerate.filter { return imagesToGenerate.filter {
$0.tags.contains(platform.rawValue) $0.tags.contains(platform.rawValue)
} }

View File

@ -18,6 +18,7 @@ class StringsFileGenerator {
tags: [String], tags: [String],
outputPath: String, outputPath: String,
inputFilenameWithoutExt: String) { inputFilenameWithoutExt: String) {
var stringsFilesContent = [String: String]() var stringsFilesContent = [String: String]()
for lang in langs { for lang in langs {
stringsFilesContent[lang] = Self.generateStringsFileContent(lang: lang, stringsFilesContent[lang] = Self.generateStringsFileContent(lang: lang,
@ -42,6 +43,31 @@ class StringsFileGenerator {
} }
} }
static func writeXcStringsFiles(sections: [Section],
langs: [String],
defaultLang: String,
tags: [String],
outputPath: String,
inputFilenameWithoutExt: String) {
let fileContent: String = Self.generateXcStringsFileContent(
langs: langs,
defaultLang: defaultLang,
tags: tags,
sections: sections
)
let stringsFilePath = "\(outputPath)/\(inputFilenameWithoutExt).xcstrings"
let stringsFilePathURL = URL(fileURLWithPath: stringsFilePath)
do {
try fileContent.write(to: stringsFilePathURL, atomically: false, encoding: .utf8)
} catch let error {
let error = StringiumError.writeFile(error.localizedDescription, stringsFilePath)
print(error.description)
Stringium.exit(withError: error)
}
}
static func generateStringsFileContent(lang: String, static func generateStringsFileContent(lang: String,
defaultLang: String, defaultLang: String,
tags inputTags: [String], tags inputTags: [String],
@ -92,6 +118,117 @@ class StringsFileGenerator {
return stringsFileContent return stringsFileContent
} }
// MARK: - XcStrings Generation
static func generateXcStringsFileContent(langs: [String],
defaultLang: String,
tags inputTags: [String],
sections: [Section]) -> String {
let rootObject = generateRootObject(langs: langs, defaultLang: defaultLang, tags: inputTags, sections: sections)
let file = generateXcStringsFileContentFromRootObject(rootObject: rootObject)
return file
}
static func generateXcStringsFileContentFromRootObject(rootObject: Root) -> String {
do {
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted]
let json = try encoder.encode(rootObject)
if let jsonString = String(data: json, encoding: .utf8) {
return jsonString
}
} catch {
debugPrint("Failed to encode: \(error)")
}
return ""
}
static func generateRootObject(langs: [String],
defaultLang: String,
tags inputTags: [String],
sections: [Section]) -> Root {
var xcStringDefinitionTab: [XCStringDefinition] = []
sections.forEach { section in
// Check that at least one string will be generated
guard section.hasOneOrMoreMatchingTags(tags: inputTags) else {
return // Go to next section
}
section.definitions.forEach { definition in
var skipDefinition = false
var isNoTranslation = false
var localizationTab: [XCStringLocalization] = []
if definition.hasOneOrMoreMatchingTags(inputTags: inputTags) == false {
skipDefinition = true
}
if definition.tags.contains(Stringium.noTranslationTag) {
isNoTranslation = true
}
if !skipDefinition {
if isNoTranslation {
// Search for langs in yaml
for lang in langs {
if let value = definition.translations[defaultLang], !value.isEmpty {
let localization = XCStringLocalization(
lang: lang,
content: XCStringLocalizationLangContent(
stringUnit: DefaultStringUnit(state: "translated", value: value)
)
)
localizationTab.append(localization)
}
}
} else {
// Search for langs in twine
for (lang, value) in definition.translations where !value.isEmpty {
let localization = XCStringLocalization(
lang: lang,
content: XCStringLocalizationLangContent(
stringUnit: DefaultStringUnit(state: "translated", value: value)
)
)
localizationTab.append(localization)
}
}
let xcStringDefinition = XCStringDefinition(
title: definition.name,
content: XCStringDefinitionContent(
comment: definition.comment,
extractionState: "manual",
localizations: XCStringLocalizationContainer(
localizations: localizationTab
)
)
)
xcStringDefinitionTab.append(xcStringDefinition)
}
}
}
let xcStringContainer = XCStringDefinitionContainer(strings: xcStringDefinitionTab)
return Root(
sourceLanguage: defaultLang,
strings: xcStringContainer,
version: "1.0"
)
}
// MARK: - Extension file // MARK: - Extension file
static func writeExtensionFiles(sections: [Section], static func writeExtensionFiles(sections: [Section],

View File

@ -84,22 +84,29 @@ class Definition {
return (inputParameters: inputParameters, translationArguments: translationArguments) return (inputParameters: inputParameters, translationArguments: translationArguments)
} }
private func getBaseProperty(lang: String, translation: String, isStatic: Bool) -> String { private func getBaseProperty(lang: String, translation: String, isStatic: Bool, comment: String?) -> String {
""" """
/// Translation in \(lang) : /// Translation in \(lang) :
/// \(translation) /// \(translation)
///
/// Comment :
/// \(comment?.isEmpty == false ? comment! : "No comment")
\(isStatic ? "static ": "")var \(name): String { \(isStatic ? "static ": "")var \(name): String {
NSLocalizedString("\(name)", tableName: kStringsFileName, bundle: Bundle.main, value: "\(translation)", comment: "") NSLocalizedString("\(name)", tableName: kStringsFileName, bundle: Bundle.main, value: "\(translation)", comment: "\(comment ?? "")")
} }
""" """
} }
private func getBaseMethod(lang: String, translation: String, isStatic: Bool, inputParameters: [String], translationArguments: [String]) -> String { private func getBaseMethod(lang: String, translation: String, isStatic: Bool, inputParameters: [String], translationArguments: [String], comment: String?) -> String {
"""
"""
/// Translation in \(lang) : /// Translation in \(lang) :
/// \(translation) /// \(translation)
///
/// Comment :
/// \(comment?.isEmpty == false ? comment! : "No comment")
\(isStatic ? "static ": "")func \(name)(\(inputParameters.joined(separator: ", "))) -> String { \(isStatic ? "static ": "")func \(name)(\(inputParameters.joined(separator: ", "))) -> String {
String(format: \(isStatic ? "Self" : "self").\(name), \(translationArguments.joined(separator: ", "))) String(format: \(isStatic ? "Self" : "self").\(name), \(translationArguments.joined(separator: ", ")))
} }
@ -114,7 +121,12 @@ class Definition {
} }
// Generate property // Generate property
let property = getBaseProperty(lang: lang, translation: translation, isStatic: false) let property = getBaseProperty(
lang: lang,
translation: translation,
isStatic: false,
comment: self.comment
)
// Generate method // Generate method
var method = "" var method = ""
@ -123,7 +135,8 @@ class Definition {
translation: translation, translation: translation,
isStatic: false, isStatic: false,
inputParameters: parameters.inputParameters, inputParameters: parameters.inputParameters,
translationArguments: parameters.translationArguments) translationArguments: parameters.translationArguments,
comment: self.comment)
} }
return property + method return property + method
@ -137,7 +150,12 @@ class Definition {
} }
// Generate property // Generate property
let property = getBaseProperty(lang: lang, translation: translation, isStatic: true) let property = getBaseProperty(
lang: lang,
translation: translation,
isStatic: true,
comment: self.comment
)
// Generate method // Generate method
var method = "" var method = ""
@ -146,7 +164,8 @@ class Definition {
translation: translation, translation: translation,
isStatic: true, isStatic: true,
inputParameters: parameters.inputParameters, inputParameters: parameters.inputParameters,
translationArguments: parameters.translationArguments) translationArguments: parameters.translationArguments,
comment: self.comment)
} }
return property + method return property + method
@ -164,6 +183,10 @@ class Definition {
return """ return """
/// Translation in \(lang) : /// Translation in \(lang) :
/// \(translation) /// \(translation)
///
/// Comment :
/// \(comment?.isEmpty == false ? comment! : "No comment")
var \(name): String { var \(name): String {
"\(translation)" "\(translation)"
} }
@ -180,6 +203,9 @@ class Definition {
return """ return """
/// Translation in \(lang) : /// Translation in \(lang) :
/// \(translation) /// \(translation)
///
/// Comment :
/// \(comment?.isEmpty == false ? comment! : "No comment")
static var \(name): String { static var \(name): String {
"\(translation)" "\(translation)"
} }

View File

@ -0,0 +1,109 @@
//
// XcString.swift
//
//
// Created by Quentin Bandera on 12/04/2024.
//
import SwiftUI
struct DynamicKey: CodingKey {
var intValue: Int?
init?(intValue: Int) {
self.intValue = intValue
self.stringValue = "\(intValue)"
}
var stringValue: String
init?(stringValue: String) {
self.stringValue = stringValue
}
}
struct Root: Codable, Equatable {
let sourceLanguage: String
let strings: XCStringDefinitionContainer
let version: String
}
struct XCStringDefinitionContainer: Codable, Equatable {
let strings: [XCStringDefinition]
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: DynamicKey.self)
for str in strings {
if let codingKey = DynamicKey(stringValue: str.title) {
try container.encode(str.content, forKey: codingKey)
}
}
}
static func == (lhs: XCStringDefinitionContainer, rhs: XCStringDefinitionContainer) -> Bool {
return lhs.strings.sorted(by: {
$0.title < $1.title
}) == rhs.strings.sorted(by: { $0.title < $1.title })
}
}
struct XCStringDefinition: Codable, Equatable {
let title: String // json key -> custom encoding methods
let content: XCStringDefinitionContent
}
struct XCStringDefinitionContent: Codable, Equatable {
let comment: String?
let extractionState: String
var localizations: XCStringLocalizationContainer
init(comment: String? = nil, extractionState: String, localizations: XCStringLocalizationContainer) {
self.comment = comment
self.extractionState = extractionState
self.localizations = localizations
}
}
struct XCStringLocalizationContainer: Codable, Equatable {
let localizations: [XCStringLocalization]
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: DynamicKey.self)
for loca in localizations {
if let codingKey = DynamicKey(stringValue: loca.lang) {
try container.encode(loca.content, forKey: codingKey)
}
}
}
static func == (lhs: XCStringLocalizationContainer, rhs: XCStringLocalizationContainer) -> Bool {
return lhs.localizations.count == rhs.localizations.count && lhs.localizations.sorted(by: { $0.lang < $1.lang }) == rhs.localizations.sorted(by: { $0.lang < $1.lang })
}
}
struct XCStringLocalization: Codable, Equatable {
let lang: String // json key -> custom encoding method
let content: XCStringLocalizationLangContent
}
struct XCStringLocalizationLangContent: Codable, Equatable {
let stringUnit: DefaultStringUnit
}
//enum VarationOrStringUnit: Encodable {
// case variations([Varation])
// case stringUnit: (DefaultStringUnit)
//
// func encode(to encoder: any Encoder) throws {
// if let varations {
//
// } else if let {
//
// }
// }
//}
struct DefaultStringUnit: Codable, Equatable {
let state: String
let value: String
}

View File

@ -43,12 +43,25 @@ struct Stringium: ParsableCommand {
let sections = TwineFileParser.parse(options.inputFile) let sections = TwineFileParser.parse(options.inputFile)
// Generate strings files // Generate strings files
StringsFileGenerator.writeStringsFiles(sections: sections, print(options.xcStrings)
langs: options.langs, if !options.xcStrings {
defaultLang: options.defaultLang, print("[\(Self.toolName)] Will generate strings")
tags: options.tags,
outputPath: options.stringsFileOutputPath, StringsFileGenerator.writeStringsFiles(sections: sections,
inputFilenameWithoutExt: options.inputFilenameWithoutExt) langs: options.langs,
defaultLang: options.defaultLang,
tags: options.tags,
outputPath: options.stringsFileOutputPath,
inputFilenameWithoutExt: options.inputFilenameWithoutExt)
} else {
print("[\(Self.toolName)] Will generate xcStrings")
StringsFileGenerator.writeXcStringsFiles(sections: sections,
langs: options.langs,
defaultLang: options.defaultLang,
tags: options.tags,
outputPath: options.stringsFileOutputPath,
inputFilenameWithoutExt: options.inputFilenameWithoutExt)
}
// Generate extension // Generate extension
StringsFileGenerator.writeExtensionFiles(sections: sections, StringsFileGenerator.writeExtensionFiles(sections: sections,

View File

@ -12,7 +12,7 @@ struct StringiumOptions: ParsableArguments {
@Flag(name: [.customShort("f"), .customShort("F")], help: "Should force generation") @Flag(name: [.customShort("f"), .customShort("F")], help: "Should force generation")
var forceGeneration = false var forceGeneration = false
@Argument(help: "Input files where strings ared defined.", transform: { $0.replaceTiltWithHomeDirectoryPath() }) @Argument(help: "Input files where strings are defined.", transform: { $0.replaceTiltWithHomeDirectoryPath() })
var inputFile: String var inputFile: String
@Option(name: .customLong("output-path"), help: "Path where to strings file.", transform: { $0.replaceTiltWithHomeDirectoryPath() }) @Option(name: .customLong("output-path"), help: "Path where to strings file.", transform: { $0.replaceTiltWithHomeDirectoryPath() })
@ -33,6 +33,9 @@ struct StringiumOptions: ParsableArguments {
@Option(help: "Tell if it will generate static properties or not") @Option(help: "Tell if it will generate static properties or not")
var staticMembers: Bool = false var staticMembers: Bool = false
@Option(help: "Tell if it will generate xcStrings file or not")
var xcStrings: Bool = false
@Option(help: "Extension name. If not specified, it will generate an String extension.") @Option(help: "Extension name. If not specified, it will generate an String extension.")
var extensionName: String = Stringium.defaultExtensionName var extensionName: String = Stringium.defaultExtensionName

View File

@ -91,7 +91,7 @@ final class ParsedColorTests: XCTestCase {
// When // When
let contentJson = color.contentsJSON() let contentJson = color.contentsJSON()
guard let data = contentJson.data(using: .utf8), guard let data = contentJson.data(using: .utf8),
let parsedJson = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { let parsedJson = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
XCTFail("Cannot convert `contentJSON` string to Data") XCTFail("Cannot convert `contentJSON` string to Data")
return return
} }

View File

@ -17,8 +17,8 @@ class ImageFileParserTests: XCTestCase {
# #
# SMAAS Support # SMAAS Support
# #
id image_one 25 ? id image_one 25 ? png
di image_two ? 50 di image_two ? 50 webp png
d image_three 25 ? d image_three 25 ?
d image_four 75 ? d image_four 75 ?
""" """
@ -38,6 +38,7 @@ class ImageFileParserTests: XCTestCase {
XCTAssertEqual(firstImage!.tags, "id") XCTAssertEqual(firstImage!.tags, "id")
XCTAssertEqual(firstImage!.width, 25) XCTAssertEqual(firstImage!.width, 25)
XCTAssertEqual(firstImage!.height, -1) XCTAssertEqual(firstImage!.height, -1)
XCTAssertEqual(firstImage!.imageExtensions, [.png])
let secondImage = parsedImages.first { let secondImage = parsedImages.first {
$0.name == "image_two" $0.name == "image_two"
@ -46,5 +47,6 @@ class ImageFileParserTests: XCTestCase {
XCTAssertEqual(secondImage!.tags, "di") XCTAssertEqual(secondImage!.tags, "di")
XCTAssertEqual(secondImage!.width, -1) XCTAssertEqual(secondImage!.width, -1)
XCTAssertEqual(secondImage!.height, 50) XCTAssertEqual(secondImage!.height, 50)
XCTAssertEqual(firstImage!.imageExtensions, [.png])
} }
} }

View File

@ -127,35 +127,77 @@ final class ParsedImageTests: XCTestCase {
height: 10) height: 10)
// When // When
let property = parsedImage.contentJson let property = parsedImage.generateImageContent(isVector: false)
// Expect // Expect
let expect = """ let expect = AssetContent(
{ images: [
"images" : [ AssetImageDescription(
{ idiom: "universal",
"idiom" : "universal", scale: "1x",
"scale" : "1x", filename: "\(parsedImage.name).\(OutputImageExtension.png.rawValue)"
"filename" : "\(imageName).\(XcassetsGenerator.outputImageExtension)" ),
}, AssetImageDescription(
{ idiom: "universal",
"idiom" : "universal", scale: "2x",
"scale" : "2x", filename: "\(parsedImage.name)@2x.\(OutputImageExtension.png.rawValue)"
"filename" : "\(imageName)@2x.\(XcassetsGenerator.outputImageExtension)" ),
}, AssetImageDescription(
{ idiom: "universal",
"idiom" : "universal", scale: "3x",
"scale" : "3x", filename: "\(parsedImage.name)@3x.\(OutputImageExtension.png.rawValue)"
"filename" : "\(imageName)@3x.\(XcassetsGenerator.outputImageExtension)" )
} ],
], info: AssetInfo(
"info" : { version: 1,
"version" : 1, author: "ResgenSwift-Imagium"
"author" : "ResgenSwift-Imagium" )
} )
}
"""
XCTAssertEqual(property.adaptForXCTest(), expect.adaptForXCTest()) XCTAssertEqual(property, expect)
}
func testAssetPng() {
// Given
let imageName = "the_name"
let parsedImage = ParsedImage(name: imageName,
tags: "id",
width: 10,
height: 10,
imageExtensions: [.png])
// When
let property = parsedImage.generateImageContent(isVector: false)
// Expect
let expect = AssetContent(
images: [
AssetImageDescription(
idiom: "universal",
scale: "1x",
filename: "\(parsedImage.name).\(OutputImageExtension.png.rawValue)"
),
AssetImageDescription(
idiom: "universal",
scale: "2x",
filename: "\(parsedImage.name)@2x.\(OutputImageExtension.png.rawValue)"
),
AssetImageDescription(
idiom: "universal",
scale: "3x",
filename: "\(parsedImage.name)@3x.\(OutputImageExtension.png.rawValue)"
)
],
info: AssetInfo(
version: 1,
author: "ResgenSwift-Imagium"
)
)
debugPrint(property)
debugPrint(expect)
XCTAssertEqual(property, expect)
} }
} }

View File

@ -100,6 +100,64 @@ final class DefinitionTests: XCTestCase {
let expectFr = """ let expectFr = """
/// Translation in fr : /// Translation in fr :
/// C'est la traduction francaise /// C'est la traduction francaise
///
/// Comment :
/// This is a comment
var definition_name: String {
NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "C'est la traduction francaise", comment: "This is a comment")
}
"""
let expectEn = """
/// Translation in en :
/// This is the english translation
///
/// Comment :
/// This is a comment
var definition_name: String {
NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "This is the english translation", comment: "This is a comment")
}
"""
let expectEnUs = """
/// Translation in en-us :
/// This is the english us translation
///
/// Comment :
/// This is a comment
var definition_name: String {
NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "This is the english us translation", comment: "This is a comment")
}
"""
XCTAssertEqual(propertyFr.adaptForXCTest(), expectFr.adaptForXCTest())
XCTAssertEqual(propertyEn.adaptForXCTest(), expectEn.adaptForXCTest())
XCTAssertEqual(propertyEnUs.adaptForXCTest(), expectEnUs.adaptForXCTest())
}
func testGeneratedNSLocalizedStringPropertyWithEmptyComment() {
// Given
let definition = Definition(name: "definition_name")
definition.tags = ["ios","iosonly","notranslation"]
definition.comment = ""
definition.translations = [
"fr": "C'est la traduction francaise",
"en": "This is the english translation",
"en-us": "This is the english us translation"
]
// When
let propertyFr = definition.getNSLocalizedStringProperty(forLang: "fr")
let propertyEn = definition.getNSLocalizedStringProperty(forLang: "en")
let propertyEnUs = definition.getNSLocalizedStringProperty(forLang: "en-us")
// Expect
let expectFr = """
/// Translation in fr :
/// C'est la traduction francaise
///
/// Comment :
/// No comment
var definition_name: String { var definition_name: String {
NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "C'est la traduction francaise", comment: "") NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "C'est la traduction francaise", comment: "")
} }
@ -108,6 +166,9 @@ final class DefinitionTests: XCTestCase {
let expectEn = """ let expectEn = """
/// Translation in en : /// Translation in en :
/// This is the english translation /// This is the english translation
///
/// Comment :
/// No comment
var definition_name: String { var definition_name: String {
NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "This is the english translation", comment: "") NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "This is the english translation", comment: "")
} }
@ -116,6 +177,9 @@ final class DefinitionTests: XCTestCase {
let expectEnUs = """ let expectEnUs = """
/// Translation in en-us : /// Translation in en-us :
/// This is the english us translation /// This is the english us translation
///
/// Comment :
/// No comment
var definition_name: String { var definition_name: String {
NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "This is the english us translation", comment: "") NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "This is the english us translation", comment: "")
} }
@ -126,6 +190,62 @@ final class DefinitionTests: XCTestCase {
XCTAssertEqual(propertyEnUs.adaptForXCTest(), expectEnUs.adaptForXCTest()) XCTAssertEqual(propertyEnUs.adaptForXCTest(), expectEnUs.adaptForXCTest())
} }
func testGeneratedNSLocalizedStringPropertyWithNoComment() {
// Given
let definition = Definition(name: "definition_name")
definition.tags = ["ios","iosonly","notranslation"]
definition.translations = [
"fr": "C'est la traduction francaise",
"en": "This is the english translation",
"en-us": "This is the english us translation"
]
// When
let propertyFr = definition.getNSLocalizedStringProperty(forLang: "fr")
let propertyEn = definition.getNSLocalizedStringProperty(forLang: "en")
let propertyEnUs = definition.getNSLocalizedStringProperty(forLang: "en-us")
// Expect
let expectFr = """
/// Translation in fr :
/// C'est la traduction francaise
///
/// Comment :
/// No comment
var definition_name: String {
NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "C'est la traduction francaise", comment: "")
}
"""
let expectEn = """
/// Translation in en :
/// This is the english translation
///
/// Comment :
/// No comment
var definition_name: String {
NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "This is the english translation", comment: "")
}
"""
let expectEnUs = """
/// Translation in en-us :
/// This is the english us translation
///
/// Comment :
/// No comment
var definition_name: String {
NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "This is the english us translation", comment: "")
}
"""
XCTAssertEqual(propertyFr.adaptForXCTest(), expectFr.adaptForXCTest())
XCTAssertEqual(propertyEn.adaptForXCTest(), expectEn.adaptForXCTest())
XCTAssertEqual(propertyEnUs.adaptForXCTest(), expectEnUs.adaptForXCTest())
}
// MARK: - getNSLocalizedStringStaticProperty
func testGeneratedNSLocalizedStringStaticProperty() { func testGeneratedNSLocalizedStringStaticProperty() {
// Given // Given
let definition = Definition(name: "definition_name") let definition = Definition(name: "definition_name")
@ -146,6 +266,64 @@ final class DefinitionTests: XCTestCase {
let expectFr = """ let expectFr = """
/// Translation in fr : /// Translation in fr :
/// C'est la traduction francaise /// C'est la traduction francaise
///
/// Comment :
/// This is a comment
static var definition_name: String {
NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "C'est la traduction francaise", comment: "This is a comment")
}
"""
let expectEn = """
/// Translation in en :
/// This is the english translation
///
/// Comment :
/// This is a comment
static var definition_name: String {
NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "This is the english translation", comment: "This is a comment")
}
"""
let expectEnUs = """
/// Translation in en-us :
/// This is the english us translation
///
/// Comment :
/// This is a comment
static var definition_name: String {
NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "This is the english us translation", comment: "This is a comment")
}
"""
XCTAssertEqual(propertyFr.adaptForXCTest(), expectFr.adaptForXCTest())
XCTAssertEqual(propertyEn.adaptForXCTest(), expectEn.adaptForXCTest())
XCTAssertEqual(propertyEnUs.adaptForXCTest(), expectEnUs.adaptForXCTest())
}
func testGeneratedNSLocalizedStringStaticPropertyWithEmptyComment() {
// Given
let definition = Definition(name: "definition_name")
definition.tags = ["ios","iosonly","notranslation"]
definition.comment = ""
definition.translations = [
"fr": "C'est la traduction francaise",
"en": "This is the english translation",
"en-us": "This is the english us translation"
]
// When
let propertyFr = definition.getNSLocalizedStringStaticProperty(forLang: "fr")
let propertyEn = definition.getNSLocalizedStringStaticProperty(forLang: "en")
let propertyEnUs = definition.getNSLocalizedStringStaticProperty(forLang: "en-us")
// Expect
let expectFr = """
/// Translation in fr :
/// C'est la traduction francaise
///
/// Comment :
/// No comment
static var definition_name: String { static var definition_name: String {
NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "C'est la traduction francaise", comment: "") NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "C'est la traduction francaise", comment: "")
} }
@ -154,6 +332,9 @@ final class DefinitionTests: XCTestCase {
let expectEn = """ let expectEn = """
/// Translation in en : /// Translation in en :
/// This is the english translation /// This is the english translation
///
/// Comment :
/// No comment
static var definition_name: String { static var definition_name: String {
NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "This is the english translation", comment: "") NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "This is the english translation", comment: "")
} }
@ -162,6 +343,63 @@ final class DefinitionTests: XCTestCase {
let expectEnUs = """ let expectEnUs = """
/// Translation in en-us : /// Translation in en-us :
/// This is the english us translation /// This is the english us translation
///
/// Comment :
/// No comment
static var definition_name: String {
NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "This is the english us translation", comment: "")
}
"""
XCTAssertEqual(propertyFr.adaptForXCTest(), expectFr.adaptForXCTest())
XCTAssertEqual(propertyEn.adaptForXCTest(), expectEn.adaptForXCTest())
XCTAssertEqual(propertyEnUs.adaptForXCTest(), expectEnUs.adaptForXCTest())
}
func testGeneratedNSLocalizedStringStaticPropertyWithNoComment() {
// Given
let definition = Definition(name: "definition_name")
definition.tags = ["ios","iosonly","notranslation"]
definition.translations = [
"fr": "C'est la traduction francaise",
"en": "This is the english translation",
"en-us": "This is the english us translation"
]
// When
let propertyFr = definition.getNSLocalizedStringStaticProperty(forLang: "fr")
let propertyEn = definition.getNSLocalizedStringStaticProperty(forLang: "en")
let propertyEnUs = definition.getNSLocalizedStringStaticProperty(forLang: "en-us")
// Expect
let expectFr = """
/// Translation in fr :
/// C'est la traduction francaise
///
/// Comment :
/// No comment
static var definition_name: String {
NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "C'est la traduction francaise", comment: "")
}
"""
let expectEn = """
/// Translation in en :
/// This is the english translation
///
/// Comment :
/// No comment
static var definition_name: String {
NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "This is the english translation", comment: "")
}
"""
let expectEnUs = """
/// Translation in en-us :
/// This is the english us translation
///
/// Comment :
/// No comment
static var definition_name: String { static var definition_name: String {
NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "This is the english us translation", comment: "") NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "This is the english us translation", comment: "")
} }
@ -188,12 +426,18 @@ final class DefinitionTests: XCTestCase {
let expectFr = """ let expectFr = """
/// Translation in fr : /// Translation in fr :
/// Welcome "%@" ! /// Welcome "%@" !
///
/// Comment :
/// This is a comment
var definition_name: String { var definition_name: String {
NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "Welcome \"%@\" !", comment: "") NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "Welcome \"%@\" !", comment: "This is a comment")
} }
/// Translation in fr : /// Translation in fr :
/// Welcome "%@" ! /// Welcome "%@" !
///
/// Comment :
/// This is a comment
func definition_name(arg0: String) -> String { func definition_name(arg0: String) -> String {
String(format: self.definition_name, arg0) String(format: self.definition_name, arg0)
} }
@ -218,12 +462,18 @@ final class DefinitionTests: XCTestCase {
let expectFr = """ let expectFr = """
/// Translation in fr : /// Translation in fr :
/// Welcome "%@" ! Your age is %d :) Your weight is %f ;-) /// Welcome "%@" ! Your age is %d :) Your weight is %f ;-)
///
/// Comment :
/// This is a comment
var definition_name: String { var definition_name: String {
NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "Welcome \"%@\" ! Your age is %d :) Your weight is %f ;-)", comment: "") NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "Welcome \"%@\" ! Your age is %d :) Your weight is %f ;-)", comment: "This is a comment")
} }
/// Translation in fr : /// Translation in fr :
/// Welcome "%@" ! Your age is %d :) Your weight is %f ;-) /// Welcome "%@" ! Your age is %d :) Your weight is %f ;-)
///
/// Comment :
/// This is a comment
func definition_name(arg0: String, arg1: Int, arg2: Double) -> String { func definition_name(arg0: String, arg1: Int, arg2: Double) -> String {
String(format: self.definition_name, arg0, arg1, arg2) String(format: self.definition_name, arg0, arg1, arg2)
} }
@ -249,12 +499,18 @@ final class DefinitionTests: XCTestCase {
let expectFr = """ let expectFr = """
/// Translation in fr : /// Translation in fr :
/// Vous %%: %1$@ %2$@ Age: %3$d /// Vous %%: %1$@ %2$@ Age: %3$d
///
/// Comment :
/// This is a comment
var definition_name: String { var definition_name: String {
NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "Vous %%: %1$@ %2$@ Age: %3$d", comment: "") NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "Vous %%: %1$@ %2$@ Age: %3$d", comment: "This is a comment")
} }
/// Translation in fr : /// Translation in fr :
/// Vous %%: %1$@ %2$@ Age: %3$d /// Vous %%: %1$@ %2$@ Age: %3$d
///
/// Comment :
/// This is a comment
func definition_name(arg0: String, arg1: String, arg2: Int) -> String { func definition_name(arg0: String, arg1: String, arg2: Int) -> String {
String(format: self.definition_name, arg0, arg1, arg2) String(format: self.definition_name, arg0, arg1, arg2)
} }
@ -263,12 +519,18 @@ final class DefinitionTests: XCTestCase {
let expectEn = """ let expectEn = """
/// Translation in en : /// Translation in en :
/// You %%: %2$@ %1$@ Age: %3$d /// You %%: %2$@ %1$@ Age: %3$d
///
/// Comment :
/// This is a comment
var definition_name: String { var definition_name: String {
NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "You %%: %2$@ %1$@ Age: %3$d", comment: "") NSLocalizedString("definition_name", tableName: kStringsFileName, bundle: Bundle.main, value: "You %%: %2$@ %1$@ Age: %3$d", comment: "This is a comment")
} }
/// Translation in en : /// Translation in en :
/// You %%: %2$@ %1$@ Age: %3$d /// You %%: %2$@ %1$@ Age: %3$d
///
/// Comment :
/// This is a comment
func definition_name(arg0: String, arg1: String, arg2: Int) -> String { func definition_name(arg0: String, arg1: String, arg2: Int) -> String {
String(format: self.definition_name, arg0, arg1, arg2) String(format: self.definition_name, arg0, arg1, arg2)
} }
@ -300,6 +562,9 @@ final class DefinitionTests: XCTestCase {
let expectFr = """ let expectFr = """
/// Translation in fr : /// Translation in fr :
/// C'est la traduction francaise /// C'est la traduction francaise
///
/// Comment :
/// This is a comment
var definition_name: String { var definition_name: String {
"C'est la traduction francaise" "C'est la traduction francaise"
} }
@ -308,6 +573,9 @@ final class DefinitionTests: XCTestCase {
let expectEn = """ let expectEn = """
/// Translation in en : /// Translation in en :
/// This is the english translation /// This is the english translation
///
/// Comment :
/// This is a comment
var definition_name: String { var definition_name: String {
"This is the english translation" "This is the english translation"
} }
@ -316,6 +584,9 @@ final class DefinitionTests: XCTestCase {
let expectEnUs = """ let expectEnUs = """
/// Translation in en-us : /// Translation in en-us :
/// This is the english us translation /// This is the english us translation
///
/// Comment :
/// This is a comment
var definition_name: String { var definition_name: String {
"This is the english us translation" "This is the english us translation"
} }
@ -326,6 +597,117 @@ final class DefinitionTests: XCTestCase {
XCTAssertEqual(propertyEnUs.adaptForXCTest(), expectEnUs.adaptForXCTest()) XCTAssertEqual(propertyEnUs.adaptForXCTest(), expectEnUs.adaptForXCTest())
} }
func testGeneratedRawPropertyWithEmptyComment() {
// Given
let definition = Definition(name: "definition_name")
definition.tags = ["ios","iosonly","notranslation"]
definition.comment = ""
definition.translations = [
"fr": "C'est la traduction francaise",
"en": "This is the english translation",
"en-us": "This is the english us translation"
]
// When
let propertyFr = definition.getProperty(forLang: "fr")
let propertyEn = definition.getProperty(forLang: "en")
let propertyEnUs = definition.getProperty(forLang: "en-us")
// Expect
let expectFr = """
/// Translation in fr :
/// C'est la traduction francaise
///
/// Comment :
/// No comment
var definition_name: String {
"C'est la traduction francaise"
}
"""
let expectEn = """
/// Translation in en :
/// This is the english translation
///
/// Comment :
/// No comment
var definition_name: String {
"This is the english translation"
}
"""
let expectEnUs = """
/// Translation in en-us :
/// This is the english us translation
///
/// Comment :
/// No comment
var definition_name: String {
"This is the english us translation"
}
"""
XCTAssertEqual(propertyFr.adaptForXCTest(), expectFr.adaptForXCTest())
XCTAssertEqual(propertyEn.adaptForXCTest(), expectEn.adaptForXCTest())
XCTAssertEqual(propertyEnUs.adaptForXCTest(), expectEnUs.adaptForXCTest())
}
func testGeneratedRawPropertyWithNoComment() {
// Given
let definition = Definition(name: "definition_name")
definition.tags = ["ios","iosonly","notranslation"]
definition.translations = [
"fr": "C'est la traduction francaise",
"en": "This is the english translation",
"en-us": "This is the english us translation"
]
// When
let propertyFr = definition.getProperty(forLang: "fr")
let propertyEn = definition.getProperty(forLang: "en")
let propertyEnUs = definition.getProperty(forLang: "en-us")
// Expect
let expectFr = """
/// Translation in fr :
/// C'est la traduction francaise
///
/// Comment :
/// No comment
var definition_name: String {
"C'est la traduction francaise"
}
"""
let expectEn = """
/// Translation in en :
/// This is the english translation
///
/// Comment :
/// No comment
var definition_name: String {
"This is the english translation"
}
"""
let expectEnUs = """
/// Translation in en-us :
/// This is the english us translation
///
/// Comment :
/// No comment
var definition_name: String {
"This is the english us translation"
}
"""
XCTAssertEqual(propertyFr.adaptForXCTest(), expectFr.adaptForXCTest())
XCTAssertEqual(propertyEn.adaptForXCTest(), expectEn.adaptForXCTest())
XCTAssertEqual(propertyEnUs.adaptForXCTest(), expectEnUs.adaptForXCTest())
}
// MARK: - Raw static properties
func testGeneratedRawStaticProperty() { func testGeneratedRawStaticProperty() {
// Given // Given
let definition = Definition(name: "definition_name") let definition = Definition(name: "definition_name")
@ -346,6 +728,9 @@ final class DefinitionTests: XCTestCase {
let expectFr = """ let expectFr = """
/// Translation in fr : /// Translation in fr :
/// C'est la traduction francaise /// C'est la traduction francaise
///
/// Comment :
/// This is a comment
static var definition_name: String { static var definition_name: String {
"C'est la traduction francaise" "C'est la traduction francaise"
} }
@ -354,7 +739,10 @@ final class DefinitionTests: XCTestCase {
let expectEn = """ let expectEn = """
/// Translation in en : /// Translation in en :
/// This is the english translation /// This is the english translation
static var definition_name: String { ///
/// Comment :
/// This is a comment
static var definition_name: String {
"This is the english translation" "This is the english translation"
} }
""" """
@ -362,6 +750,118 @@ final class DefinitionTests: XCTestCase {
let expectEnUs = """ let expectEnUs = """
/// Translation in en-us : /// Translation in en-us :
/// This is the english us translation /// This is the english us translation
///
/// Comment :
/// This is a comment
static var definition_name: String {
"This is the english us translation"
}
"""
XCTAssertEqual(propertyFr.adaptForXCTest(), expectFr.adaptForXCTest())
XCTAssertEqual(propertyEn.adaptForXCTest(), expectEn.adaptForXCTest())
XCTAssertEqual(propertyEnUs.adaptForXCTest(), expectEnUs.adaptForXCTest())
}
func testGeneratedRawStaticPropertyWithEmptyComment() {
// Given
let definition = Definition(name: "definition_name")
definition.tags = ["ios","iosonly","notranslation"]
definition.comment = ""
definition.translations = [
"fr": "C'est la traduction francaise",
"en": "This is the english translation",
"en-us": "This is the english us translation"
]
// When
let propertyFr = definition.getStaticProperty(forLang: "fr")
let propertyEn = definition.getStaticProperty(forLang: "en")
let propertyEnUs = definition.getStaticProperty(forLang: "en-us")
// Expect
let expectFr = """
/// Translation in fr :
/// C'est la traduction francaise
///
/// Comment :
/// No comment
static var definition_name: String {
"C'est la traduction francaise"
}
"""
let expectEn = """
/// Translation in en :
/// This is the english translation
///
/// Comment :
/// No comment
static var definition_name: String {
"This is the english translation"
}
"""
let expectEnUs = """
/// Translation in en-us :
/// This is the english us translation
///
/// Comment :
/// No comment
static var definition_name: String {
"This is the english us translation"
}
"""
XCTAssertEqual(propertyFr.adaptForXCTest(), expectFr.adaptForXCTest())
XCTAssertEqual(propertyEn.adaptForXCTest(), expectEn.adaptForXCTest())
XCTAssertEqual(propertyEnUs.adaptForXCTest(), expectEnUs.adaptForXCTest())
}
func testGeneratedRawStaticPropertyWithNoComment() {
// Given
let definition = Definition(name: "definition_name")
definition.tags = ["ios","iosonly","notranslation"]
definition.translations = [
"fr": "C'est la traduction francaise",
"en": "This is the english translation",
"en-us": "This is the english us translation"
]
// When
let propertyFr = definition.getStaticProperty(forLang: "fr")
let propertyEn = definition.getStaticProperty(forLang: "en")
let propertyEnUs = definition.getStaticProperty(forLang: "en-us")
// Expect
let expectFr = """
/// Translation in fr :
/// C'est la traduction francaise
///
/// Comment :
/// No comment
static var definition_name: String {
"C'est la traduction francaise"
}
"""
let expectEn = """
/// Translation in en :
/// This is the english translation
///
/// Comment :
/// No comment
static var definition_name: String {
"This is the english translation"
}
"""
let expectEnUs = """
/// Translation in en-us :
/// This is the english us translation
///
/// Comment :
/// No comment
static var definition_name: String { static var definition_name: String {
"This is the english us translation" "This is the english us translation"
} }

File diff suppressed because it is too large Load Diff