Skip to content

Commit

Permalink
Initial version of swift generator
Browse files Browse the repository at this point in the history
  • Loading branch information
Nevermole committed Jul 17, 2023
1 parent cea1870 commit 8a688ad
Show file tree
Hide file tree
Showing 29 changed files with 1,587 additions and 1 deletion.
12 changes: 12 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
.DS_Store
/.build
/Packages
/*.xcodeproj
xcuserdata/
DerivedData/
.netrc
.build
.swiftpm
Package.resolved
client.swift
node_modules
20 changes: 20 additions & 0 deletions LICENCE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
Copyright (c) 2019-present https://github.com/webrpc authors

MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
46 changes: 45 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,45 @@
# gen-swift
# gen-swift

This repo contains the templates used by the `webrpc-gen` cli to code-generate
webrpc Swift client code.

This generator, from a webrpc schema/design file will code-generate:

1. Client -- a Swift client to speak to a webrpc server using the
provided schema. This client is compatible with any webrpc server language (ie. Go, nodejs, etc.).

## Dependencies

In order to support `any` type in webrpc, we use [AnyCodable](https://github.com/Flight-School/AnyCodable).
This is a dependency of the generated code, so you must add it to your project.

## Usage

```
webrpc-gen -schema=example.ridl -target=swift -server -client -out=./example.gen.swift
```

or

```
webrpc-gen -schema=example.ridl -target=github.com/webrpc/[email protected] -server -client -out=./example.get.swift
```

or

```
webrpc-gen -schema=example.ridl -target=./local-templates-on-disk -server -client -out=./example.gen.swift
```

As you can see, the `-target` supports default `swift`, any git URI, or a local folder :)

### Set custom template variables
Change any of the following values by passing `-option="Value"` CLI flag to `webrpc-gen`.

| webrpc-gen -option | Description | Default value |
|----------------------|----------------------------|----------------------------|
| `-client` | generate client code | unset (`false`) |

## LICENSE

[MIT LICENSE](./LICENSE)
27 changes: 27 additions & 0 deletions Tests/Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// swift-tools-version: 5.8
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
name: "gen-swift",
platforms: [.macOS(.v13), .iOS(.v15)],
products: [
// Products define the executables and libraries a package produces, making them visible to other packages.
.library(
name: "gen-swift",
targets: ["gen-swift"]),

],
dependencies: [.package(url: "https://github.com/Flight-School/AnyCodable", from: "0.6.7")],
targets: [
// Targets are the basic building blocks of a package, defining a module or a test suite.
// Targets can depend on other targets in this package and products from dependencies.
.target(
name: "gen-swift",
dependencies: ["AnyCodable"]),
.testTarget(
name: "gen-swiftTests",
dependencies: ["gen-swift"]),
]
)
236 changes: 236 additions & 0 deletions Tests/Tests/gen-swiftTests/tests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,236 @@
import XCTest
@testable import gen_swift

final class gen_swiftTests: XCTestCase {

private let client = TestApiClient(hostname: "http://localhost:9988")

func testEmpty() async throws {
await XCTAssertNoThrow(try await client.getEmpty(), "getEmpty() should get empty type successfully")
}

func testError() async throws {
await XCTAssertThrowsError(try await client.getError(), "getError() should throw error")
}

func testOne() async throws {
let response = try await client.getOne()
await XCTAssertNoThrow(try await client.sendOne(one: response),
"getOne() should receive simple type and send it back via sendOne() successfully")

}

func testMulti() async throws {
let (one, two, three) = try await client.getMulti()
await XCTAssertNoThrow(try await client.sendMulti(one: one, two: two, three: three),
"getMulti() should receive simple type and send it back via sendMulti() successfully")
}

func testComplex() async throws {
let response = try await client.getComplex()
await XCTAssertNoThrow(try await client.sendComplex(complex: response),
"getComplex() should receive complex type and send it back via sendComplex() successfully")
}

func testCustomErrors() async throws {
let errors: [WebrpcError] = [
.init(
error: "WebrpcEndpoint",
code: 0,
message: "endpoint error",
cause: "failed to read file: unexpected EOF",
status: 400,
errorKind: .webrpcEndpointError
),
.init(
error: "Unauthorized",
code: 1,
message: "unauthorized",
cause: "failed to verify JWT token",
status: 401,
errorKind: .unauthorizedError
),
.init(
error: "ExpiredToken",
code: 2,
message: "expired token",
cause: nil,
status: 401,
errorKind: .expiredTokenError
),
.init(
error: "InvalidToken",
code: 3,
message: "invalid token",
cause: nil,
status: 401,
errorKind: .invalidTokenError
),
.init(
error: "Deactivated",
code: 4,
message: "account deactivated",
cause: nil,
status: 403,
errorKind: .deactivatedError
),
.init(
error: "ConfirmAccount",
code: 5,
message: "confirm your email",
cause: nil,
status: 403,
errorKind: .confirmAccountError
),
.init(
error: "AccessDenied",
code: 6,
message: "access denied",
cause: nil,
status: 403,
errorKind: .accessDeniedError
),
.init(
error: "MissingArgument",
code: 7,
message: "missing argument",
cause: nil,
status: 400,
errorKind: .missingArgumentError
),
.init(
error: "UnexpectedValue",
code: 8,
message: "unexpected value",
cause: nil,
status: 400,
errorKind: .unexpectedValueError
),
.init(
error: "RateLimited",
code: 100,
message: "too many requests",
cause: "1000 req/min exceeded",
status: 429,
errorKind: .rateLimitedError
),
.init(
error: "DatabaseDown",
code: 101,
message: "service outage",
cause: nil,
status: 503,
errorKind: .databaseDownError
),
.init(
error: "ElasticDown",
code: 102,
message: "search is degraded",
cause: nil,
status: 503,
errorKind: .elasticDownError
),
.init(
error: "NotImplemented",
code: 103,
message: "not implemented",
cause: nil,
status: 501,
errorKind: .notImplementedError
),
.init(
error: "UserNotFound",
code: 200,
message: "user not found",
cause: nil,
status: 400,
errorKind: .userNotFoundError
),
.init(
error: "UserBusy",
code: 201,
message: "user busy",
cause: nil,
status: 400,
errorKind: .userBusyError
),
.init(
error: "InvalidUsername",
code: 202,
message: "invalid username",
cause: nil,
status: 400,
errorKind: .invalidUsernameError
),
.init(
error: "FileTooBig",
code: 300,
message: "file is too big (max 1GB)",
cause: nil,
status: 400,
errorKind: .fileTooBigError
),
.init(
error: "FileInfected",
code: 301,
message: "file is infected",
cause: nil,
status: 400,
errorKind: .fileInfectedError
),
.init(
error: "FileType",
code: 302,
message: "unsupported file type",
cause: ".wav is not supported",
status: 400,
errorKind: .fileTypeError
)
]
for error in errors {
do {
try await client.getSchemaError(code: error.code)
XCTFail("Expected to throw \(error)")
} catch let err as WebrpcError {
XCTAssertEqual(error.code, err.code)
XCTAssertEqual(error.error, err.error)
XCTAssertEqual(error.message, err.message)
XCTAssertEqual(error.status, err.status)
XCTAssertEqual(error.cause, err.cause)
XCTAssertEqual(error.kind, err.kind)
} catch let err {
XCTFail("Expected to throw \(error) but got \(err) instead")
}
}
}
}

extension XCTest {
func XCTAssertThrowsError<T: Sendable>(
_ expression: @autoclosure () async throws -> T,
_ message: @autoclosure () -> String = "",
file: StaticString = #filePath,
line: UInt = #line,
_ errorHandler: (_ error: Error) -> Void = { _ in }
) async {
do {
_ = try await expression()
XCTFail(message(), file: file, line: line)
} catch {
errorHandler(error)
}
}

func XCTAssertNoThrow<T: Sendable>(
_ expression: @autoclosure () async throws -> T,
_ message: @autoclosure () -> String = "",
file: StaticString = #filePath,
line: UInt = #line
) async {
do {
_ = try await expression()
} catch {
XCTFail(message(), file: file, line: line)
}
}
}
20 changes: 20 additions & 0 deletions Tests/download.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#!/bin/bash
set -e

VERSION="${1}"
DIR="${2}"
[[ -z "$VERSION" || -z "$DIR" ]] && { echo "Usage: $0 <webrpc-version> <dir>"; exit 1; }

mkdir -p "$DIR"

# Download webrpc binaries if not available locally
OS="$(basename $(uname -o | tr A-Z a-z))"
ARCH="$(uname -m | sed 's/x86_64/amd64/')"
if [[ ! -f "$DIR/webrpc-gen" ]]; then
curl -o "$DIR/webrpc-gen" -fLJO "https://github.com/webrpc/webrpc/releases/download/$VERSION/webrpc-gen.$OS-$ARCH"
chmod +x "$DIR/webrpc-gen"
fi
if [[ ! -f "$DIR/webrpc-test" ]]; then
curl -o "$DIR/webrpc-test" -fLJO "https://github.com/webrpc/webrpc/releases/download/$VERSION/webrpc-test.$OS-$ARCH"
chmod +x "$DIR/webrpc-test"
fi
Loading

0 comments on commit 8a688ad

Please sign in to comment.