Generating SDK Mocks through the usage of swift run tools generate-sdk-mocks (#982)

* basic implementation, that works for now only with the local SDK

* replaced a handmade mock with a generated mock
This commit is contained in:
Mauro
2023-05-30 09:48:55 +02:00
committed by GitHub
parent 25e2b05a4a
commit 088ca622a1
39 changed files with 857 additions and 194 deletions
+2 -2
View File
@@ -23,7 +23,7 @@ import {{ import }}
{% endfor -%}
{% endset %}
{% if method.parameters.count == 1 and not hasNonEscapingClosures %}
{% call swiftifyMethodName method.selectorName %}Received{% for param in method.parameters %}{{ param.name|upperFirstLetter }} = {{ param.name }}{% endfor %}
{% call swiftifyMethodName method.selectorName %}Received{% for param in method.parameters %}{{ param.name | replace:"`","" | upperFirstLetter }} = {{ param.name | replace:"`","" }}{% endfor %}
{% call swiftifyMethodName method.selectorName %}ReceivedInvocations.append({% for param in method.parameters %}{{ param.name }}){% endfor %}
{% else %}
{% if not method.parameters.count == 0 and not hasNonEscapingClosures %}
@@ -56,7 +56,7 @@ import {{ import }}
{% endfor -%}
{% endset %}
{% if method.parameters.count == 1 and not hasNonEscapingClosures %}
{% call accessLevel method.accessLevel %}{% call staticSpecifier method %}var {% call swiftifyMethodName method.selectorName %}Received{% for param in method.parameters %}{{ param.name|upperFirstLetter }}: {{ '(' if param.isClosure }}{{ param.typeName.unwrappedTypeName }}{{ ')' if param.isClosure }}?{% endfor %}
{% call accessLevel method.accessLevel %}{% call staticSpecifier method %}var {% call swiftifyMethodName method.selectorName %}Received{% for param in method.parameters %}{{ param.name| replace:"`","" | upperFirstLetter }}: {{ '(' if param.isClosure }}{{ param.typeName.unwrappedTypeName }}{{ ')' if param.isClosure }}?{% endfor %}
{% call accessLevel method.accessLevel %}{% call staticSpecifier method %}var {% call swiftifyMethodName method.selectorName %}ReceivedInvocations{% for param in method.parameters %}: [{{ '(' if param.isClosure }}{{ param.typeName.unwrappedTypeName }}{{ ')' if param.isClosure }}{%if param.typeName.isOptional%}?{%endif%}]{% endfor %} = []
{% elif not method.parameters.count == 0 and not hasNonEscapingClosures %}
{% call accessLevel method.accessLevel %}{% call staticSpecifier method %}var {% call swiftifyMethodName method.selectorName %}ReceivedArguments: ({% for param in method.parameters %}{{ param.name }}: {{ param.unwrappedTypeName if param.typeAttributes.escaping else param.typeName }}{{ ', ' if not forloop.last }}{% endfor %})?
@@ -1,5 +1,8 @@
sources:
- ../../ElementX
include:
- ../../ElementX
exclude:
- ../../ElementX/Sources/Mocks/SDK
templates:
- AutoMockable.stencil
output:
+5 -8
View File
@@ -26,10 +26,7 @@ struct BuildSDK: ParsableCommand {
@Option(help: "The profile to use when building the SDK. Omit this option to build in debug mode.")
var profile: Profile = .debug
private var parentDirectoryURL: URL { Utilities.projectDirectoryURL.deletingLastPathComponent() }
private var sdkDirectoryURL: URL { parentDirectoryURL.appendingPathComponent("matrix-rust-sdk") }
enum Error: LocalizedError {
case rustupOutputFailure
case missingRustTargets([String])
@@ -81,14 +78,14 @@ struct BuildSDK: ParsableCommand {
/// Clones the Rust SDK if a copy isn't found in the parent directory.
func cloneSDKIfNeeded() throws {
guard !FileManager.default.fileExists(atPath: sdkDirectoryURL.path) else { return }
try Utilities.zsh("git clone https://github.com/matrix-org/matrix-rust-sdk", workingDirectoryURL: parentDirectoryURL)
guard !FileManager.default.fileExists(atPath: Utilities.sdkDirectoryURL.path) else { return }
try Utilities.zsh("git clone https://github.com/matrix-org/matrix-rust-sdk", workingDirectoryURL: Utilities.parentDirectoryURL)
}
/// Checkout the specified branch of the SDK if supplied.
func checkoutBranchIfSupplied() throws {
guard let branch else { return }
try Utilities.zsh("git checkout \(branch)", workingDirectoryURL: sdkDirectoryURL)
try Utilities.zsh("git checkout \(branch)", workingDirectoryURL: Utilities.sdkDirectoryURL)
}
/// Build the Rust SDK as an XCFramework with the debug profile.
@@ -98,7 +95,7 @@ struct BuildSDK: ParsableCommand {
if let target {
buildCommand.append(" --only-target \(target.rawValue)")
}
try Utilities.zsh(buildCommand, workingDirectoryURL: sdkDirectoryURL)
try Utilities.zsh(buildCommand, workingDirectoryURL: Utilities.sdkDirectoryURL)
}
/// Update the Xcode project to use the build of the SDK.
+67
View File
@@ -0,0 +1,67 @@
import ArgumentParser
import Foundation
struct GenerateSDKMocks: ParsableCommand {
enum GenerateSDKMocksError: Error {
case invalidFileUrl
}
static var configuration = CommandConfiguration(abstract: "A tool to setup the mocks for the Matrix Rust SDK")
@Argument(help: "The argument to specify a branch of the SDK. Use `local` to use your local version")
var version: String
private var fileURLFormat = "https://raw.githubusercontent.com/matrix-org/matrix-rust-components-swift/%@/Sources/MatrixRustSDK/matrix_sdk_ffi.swift"
func run() throws {
if version == "local" {
try generateSDKMocks(ffiPath: "\(Utilities.sdkDirectoryURL.path)/bindings/apple/generated/swift")
} else {
try downloadSDK(version: version) { path in
try generateSDKMocks(ffiPath: path)
try FileManager.default.removeItem(atPath: path)
}
}
}
/// Generates the SDK mocks using Sourcery.
func generateSDKMocks(ffiPath: String) throws {
try Utilities.zsh("sourcery --sources \(ffiPath) --sources ElementX/Sources/Mocks/SDK --templates Tools/Sourcery --output ElementX/Sources/Mocks/Generated/SDKGeneratedMocks.swift --args autoMockableImports=\"Foundation\",autoMockableImports=\"MatrixRustSDK\"")
}
/// Downloads the specified version of the `matrix_sdk_ffi.swift` file and returns the path to the downloaded file.
func downloadSDK(version: String, completionHandler: @escaping (String) throws -> Void) throws {
var sdkFilePath = ""
let fileURLString = String(format: fileURLFormat, version)
guard let fileURL = URL(string: fileURLString) else {
throw GenerateSDKMocksError.invalidFileUrl
}
let semaphore = DispatchSemaphore(value: 0)
let task = URLSession.shared.downloadTask(with: fileURL) { tempURL, _, error in
guard let tempURL = tempURL else {
if let error = error {
print("Error downloading SDK file: \(error)")
} else {
print("Unknown error occurred while downloading SDK file.")
}
return
}
do {
sdkFilePath = NSTemporaryDirectory().appending("matrix_sdk_ffi.swift")
try FileManager.default.moveItem(at: tempURL, to: URL(fileURLWithPath: sdkFilePath))
try completionHandler(sdkFilePath)
semaphore.signal()
} catch {
print("Error setting up SDK: \(error)")
semaphore.signal()
}
}
task.resume()
_ = semaphore.wait(timeout: .distantFuture)
}
}
+2 -1
View File
@@ -8,5 +8,6 @@ struct Tools: ParsableCommand {
SetupProject.self,
OutdatedPackages.self,
DownloadStrings.self,
Locheck.self])
Locheck.self,
GenerateSDKMocks.self])
}
+2
View File
@@ -14,6 +14,8 @@ enum Utilities {
}
static var projectDirectoryURL: URL { URL(fileURLWithPath: FileManager.default.currentDirectoryPath) }
static var parentDirectoryURL: URL { Utilities.projectDirectoryURL.deletingLastPathComponent() }
static var sdkDirectoryURL: URL { parentDirectoryURL.appendingPathComponent("matrix-rust-sdk") }
/// Runs a command in zsh.
@discardableResult