vendor files

This commit is contained in:
Serguei Bezverkhi
2018-01-09 13:57:14 -05:00
parent 558bc6c02a
commit 7b24313bd6
16547 changed files with 4527373 additions and 0 deletions

View File

@ -0,0 +1,11 @@
all:
swift build
cp .build/debug/gnostic-swift-generator gnostic-swift-generator
rm -f gnostic-swift-client gnostic-swift-server
ln -s gnostic-swift-generator gnostic-swift-client
ln -s gnostic-swift-generator gnostic-swift-server
clean:
rm -rf .build Packages
rm -rf gnostic-swift-client gnostic-swift-server gnostic-swift-generator

View File

@ -0,0 +1,26 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import PackageDescription
let package = Package(
name: "SwiftOpenAPIPlugin",
targets: [
Target(name: "gnostic-swift-generator", dependencies: ["Gnostic"]),
Target(name: "Gnostic")
],
dependencies: [
.Package(url: "https://github.com/apple/swift-protobuf.git", Version(0,9,904)),
]
)

View File

@ -0,0 +1,15 @@
# OpenAPI Swift Generator Plugin
This directory contains an `openapic` plugin that can be used to generate a Swift client library and scaffolding for a Swift server for an API with an OpenAPI description.
The plugin can be invoked like this:
openapic bookstore.json --swift_generator_out=Bookstore
Where `Bookstore` is the name of a directory where the generated code will be written.
Both client and server code will be generated.
For example usage, see the [examples/bookstore](examples/bookstore) directory.
HTTP services are provided by the Kitura library.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,499 @@
// DO NOT EDIT.
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: github.com/googleapis/gnostic/plugins/plugin.proto
//
// For information on using the generated types, please see the documenation:
// https://github.com/apple/swift-protobuf/
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// gnostic can be extended with plugins.
// A plugin is uset a program that reads a Request from stdin
// and writes a Response to stdout.
//
// A plugin executable needs only to be placed somewhere in the path. The
// plugin should be named "gnostic_$NAME", and will then be used when the
// flag "--${NAME}_out" is passed to gnostic.
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that your are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
/// The version number of gnostic.
public struct Gnostic_Plugin_V1_Version: SwiftProtobuf.Message {
public static let protoMessageName: String = _protobuf_package + ".Version"
public var major: Int32 = 0
public var minor: Int32 = 0
public var patch: Int32 = 0
/// A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should
/// be empty for mainline stable releases.
public var suffix: String = String()
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
/// Used by the decoding initializers in the SwiftProtobuf library, not generally
/// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding
/// initializers are defined in the SwiftProtobuf library. See the Message and
/// Message+*Additions` files.
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularInt32Field(value: &self.major)
case 2: try decoder.decodeSingularInt32Field(value: &self.minor)
case 3: try decoder.decodeSingularInt32Field(value: &self.patch)
case 4: try decoder.decodeSingularStringField(value: &self.suffix)
default: break
}
}
}
/// Used by the encoding methods of the SwiftProtobuf library, not generally
/// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and
/// other serializer methods are defined in the SwiftProtobuf library. See the
/// `Message` and `Message+*Additions` files.
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if self.major != 0 {
try visitor.visitSingularInt32Field(value: self.major, fieldNumber: 1)
}
if self.minor != 0 {
try visitor.visitSingularInt32Field(value: self.minor, fieldNumber: 2)
}
if self.patch != 0 {
try visitor.visitSingularInt32Field(value: self.patch, fieldNumber: 3)
}
if !self.suffix.isEmpty {
try visitor.visitSingularStringField(value: self.suffix, fieldNumber: 4)
}
try unknownFields.traverse(visitor: &visitor)
}
}
/// A parameter passed to the plugin from (or through) gnostic.
public struct Gnostic_Plugin_V1_Parameter: SwiftProtobuf.Message {
public static let protoMessageName: String = _protobuf_package + ".Parameter"
/// The name of the parameter as specified in the option string
public var name: String = String()
/// The parameter value as specified in the option string
public var value: String = String()
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
/// Used by the decoding initializers in the SwiftProtobuf library, not generally
/// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding
/// initializers are defined in the SwiftProtobuf library. See the Message and
/// Message+*Additions` files.
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularStringField(value: &self.name)
case 2: try decoder.decodeSingularStringField(value: &self.value)
default: break
}
}
}
/// Used by the encoding methods of the SwiftProtobuf library, not generally
/// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and
/// other serializer methods are defined in the SwiftProtobuf library. See the
/// `Message` and `Message+*Additions` files.
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.name.isEmpty {
try visitor.visitSingularStringField(value: self.name, fieldNumber: 1)
}
if !self.value.isEmpty {
try visitor.visitSingularStringField(value: self.value, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
}
/// An encoded Request is written to the plugin's stdin.
public struct Gnostic_Plugin_V1_Request: SwiftProtobuf.Message {
public static let protoMessageName: String = _protobuf_package + ".Request"
/// filename or URL of the original source document
public var sourceName: String {
get {return _storage._sourceName}
set {_uniqueStorage()._sourceName = newValue}
}
/// Output path specified in the plugin invocation.
public var outputPath: String {
get {return _storage._outputPath}
set {_uniqueStorage()._outputPath = newValue}
}
/// Plugin parameters parsed from the invocation string.
public var parameters: [Gnostic_Plugin_V1_Parameter] {
get {return _storage._parameters}
set {_uniqueStorage()._parameters = newValue}
}
/// The version number of gnostic.
public var compilerVersion: Gnostic_Plugin_V1_Version {
get {return _storage._compilerVersion ?? Gnostic_Plugin_V1_Version()}
set {_uniqueStorage()._compilerVersion = newValue}
}
/// Returns true if `compilerVersion` has been explicitly set.
public var hasCompilerVersion: Bool {return _storage._compilerVersion != nil}
/// Clears the value of `compilerVersion`. Subsequent reads from it will return its default value.
public mutating func clearCompilerVersion() {_storage._compilerVersion = nil}
/// OpenAPI v2 API representation
public var openapi2: Openapi_V2_Document {
get {return _storage._openapi2 ?? Openapi_V2_Document()}
set {_uniqueStorage()._openapi2 = newValue}
}
/// Returns true if `openapi2` has been explicitly set.
public var hasOpenapi2: Bool {return _storage._openapi2 != nil}
/// Clears the value of `openapi2`. Subsequent reads from it will return its default value.
public mutating func clearOpenapi2() {_storage._openapi2 = nil}
/// OpenAPI v3 API representation
public var openapi3: Openapi_V3_Document {
get {return _storage._openapi3 ?? Openapi_V3_Document()}
set {_uniqueStorage()._openapi3 = newValue}
}
/// Returns true if `openapi3` has been explicitly set.
public var hasOpenapi3: Bool {return _storage._openapi3 != nil}
/// Clears the value of `openapi3`. Subsequent reads from it will return its default value.
public mutating func clearOpenapi3() {_storage._openapi3 = nil}
/// Discovery API representation
public var discovery: Discovery_V1_Document {
get {return _storage._discovery ?? Discovery_V1_Document()}
set {_uniqueStorage()._discovery = newValue}
}
/// Returns true if `discovery` has been explicitly set.
public var hasDiscovery: Bool {return _storage._discovery != nil}
/// Clears the value of `discovery`. Subsequent reads from it will return its default value.
public mutating func clearDiscovery() {_storage._discovery = nil}
/// generated code surface representation
public var surface: Surface_V1_Model {
get {return _storage._surface ?? Surface_V1_Model()}
set {_uniqueStorage()._surface = newValue}
}
/// Returns true if `surface` has been explicitly set.
public var hasSurface: Bool {return _storage._surface != nil}
/// Clears the value of `surface`. Subsequent reads from it will return its default value.
public mutating func clearSurface() {_storage._surface = nil}
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
/// Used by the decoding initializers in the SwiftProtobuf library, not generally
/// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding
/// initializers are defined in the SwiftProtobuf library. See the Message and
/// Message+*Additions` files.
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
_ = _uniqueStorage()
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularStringField(value: &_storage._sourceName)
case 2: try decoder.decodeSingularStringField(value: &_storage._outputPath)
case 3: try decoder.decodeRepeatedMessageField(value: &_storage._parameters)
case 4: try decoder.decodeSingularMessageField(value: &_storage._compilerVersion)
case 5: try decoder.decodeSingularMessageField(value: &_storage._openapi2)
case 6: try decoder.decodeSingularMessageField(value: &_storage._openapi3)
case 7: try decoder.decodeSingularMessageField(value: &_storage._discovery)
case 8: try decoder.decodeSingularMessageField(value: &_storage._surface)
default: break
}
}
}
}
/// Used by the encoding methods of the SwiftProtobuf library, not generally
/// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and
/// other serializer methods are defined in the SwiftProtobuf library. See the
/// `Message` and `Message+*Additions` files.
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if !_storage._sourceName.isEmpty {
try visitor.visitSingularStringField(value: _storage._sourceName, fieldNumber: 1)
}
if !_storage._outputPath.isEmpty {
try visitor.visitSingularStringField(value: _storage._outputPath, fieldNumber: 2)
}
if !_storage._parameters.isEmpty {
try visitor.visitRepeatedMessageField(value: _storage._parameters, fieldNumber: 3)
}
if let v = _storage._compilerVersion {
try visitor.visitSingularMessageField(value: v, fieldNumber: 4)
}
if let v = _storage._openapi2 {
try visitor.visitSingularMessageField(value: v, fieldNumber: 5)
}
if let v = _storage._openapi3 {
try visitor.visitSingularMessageField(value: v, fieldNumber: 6)
}
if let v = _storage._discovery {
try visitor.visitSingularMessageField(value: v, fieldNumber: 7)
}
if let v = _storage._surface {
try visitor.visitSingularMessageField(value: v, fieldNumber: 8)
}
}
try unknownFields.traverse(visitor: &visitor)
}
fileprivate var _storage = _StorageClass.defaultInstance
}
/// The plugin writes an encoded Response to stdout.
public struct Gnostic_Plugin_V1_Response: SwiftProtobuf.Message {
public static let protoMessageName: String = _protobuf_package + ".Response"
/// Error message. If non-empty, the plugin failed.
/// The plugin process should exit with status code zero
/// even if it reports an error in this way.
///
/// This should be used to indicate errors which prevent the plugin from
/// operating as intended. Errors which indicate a problem in openapic
/// itself -- such as the input Document being unparseable -- should be
/// reported by writing a message to stderr and exiting with a non-zero
/// status code.
public var errors: [String] = []
/// file output, each file will be written by openapic to an appropriate location.
public var files: [Gnostic_Plugin_V1_File] = []
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
/// Used by the decoding initializers in the SwiftProtobuf library, not generally
/// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding
/// initializers are defined in the SwiftProtobuf library. See the Message and
/// Message+*Additions` files.
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeRepeatedStringField(value: &self.errors)
case 2: try decoder.decodeRepeatedMessageField(value: &self.files)
default: break
}
}
}
/// Used by the encoding methods of the SwiftProtobuf library, not generally
/// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and
/// other serializer methods are defined in the SwiftProtobuf library. See the
/// `Message` and `Message+*Additions` files.
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.errors.isEmpty {
try visitor.visitRepeatedStringField(value: self.errors, fieldNumber: 1)
}
if !self.files.isEmpty {
try visitor.visitRepeatedMessageField(value: self.files, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
}
/// File describes a file generated by a plugin.
public struct Gnostic_Plugin_V1_File: SwiftProtobuf.Message {
public static let protoMessageName: String = _protobuf_package + ".File"
/// name of the file
public var name: String = String()
/// data to be written to the file
public var data: Data = SwiftProtobuf.Internal.emptyData
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
/// Used by the decoding initializers in the SwiftProtobuf library, not generally
/// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding
/// initializers are defined in the SwiftProtobuf library. See the Message and
/// Message+*Additions` files.
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularStringField(value: &self.name)
case 2: try decoder.decodeSingularBytesField(value: &self.data)
default: break
}
}
}
/// Used by the encoding methods of the SwiftProtobuf library, not generally
/// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and
/// other serializer methods are defined in the SwiftProtobuf library. See the
/// `Message` and `Message+*Additions` files.
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.name.isEmpty {
try visitor.visitSingularStringField(value: self.name, fieldNumber: 1)
}
if !self.data.isEmpty {
try visitor.visitSingularBytesField(value: self.data, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "gnostic.plugin.v1"
extension Gnostic_Plugin_V1_Version: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "major"),
2: .same(proto: "minor"),
3: .same(proto: "patch"),
4: .same(proto: "suffix"),
]
public func _protobuf_generated_isEqualTo(other: Gnostic_Plugin_V1_Version) -> Bool {
if self.major != other.major {return false}
if self.minor != other.minor {return false}
if self.patch != other.patch {return false}
if self.suffix != other.suffix {return false}
if unknownFields != other.unknownFields {return false}
return true
}
}
extension Gnostic_Plugin_V1_Parameter: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "name"),
2: .same(proto: "value"),
]
public func _protobuf_generated_isEqualTo(other: Gnostic_Plugin_V1_Parameter) -> Bool {
if self.name != other.name {return false}
if self.value != other.value {return false}
if unknownFields != other.unknownFields {return false}
return true
}
}
extension Gnostic_Plugin_V1_Request: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "source_name"),
2: .standard(proto: "output_path"),
3: .same(proto: "parameters"),
4: .standard(proto: "compiler_version"),
5: .same(proto: "openapi2"),
6: .same(proto: "openapi3"),
7: .same(proto: "discovery"),
8: .same(proto: "surface"),
]
fileprivate class _StorageClass {
var _sourceName: String = String()
var _outputPath: String = String()
var _parameters: [Gnostic_Plugin_V1_Parameter] = []
var _compilerVersion: Gnostic_Plugin_V1_Version? = nil
var _openapi2: Openapi_V2_Document? = nil
var _openapi3: Openapi_V3_Document? = nil
var _discovery: Discovery_V1_Document? = nil
var _surface: Surface_V1_Model? = nil
static let defaultInstance = _StorageClass()
private init() {}
init(copying source: _StorageClass) {
_sourceName = source._sourceName
_outputPath = source._outputPath
_parameters = source._parameters
_compilerVersion = source._compilerVersion
_openapi2 = source._openapi2
_openapi3 = source._openapi3
_discovery = source._discovery
_surface = source._surface
}
}
fileprivate mutating func _uniqueStorage() -> _StorageClass {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _StorageClass(copying: _storage)
}
return _storage
}
public func _protobuf_generated_isEqualTo(other: Gnostic_Plugin_V1_Request) -> Bool {
if _storage !== other._storage {
let storagesAreEqual: Bool = withExtendedLifetime((_storage, other._storage)) { (_storage, other_storage) in
if _storage._sourceName != other_storage._sourceName {return false}
if _storage._outputPath != other_storage._outputPath {return false}
if _storage._parameters != other_storage._parameters {return false}
if _storage._compilerVersion != other_storage._compilerVersion {return false}
if _storage._openapi2 != other_storage._openapi2 {return false}
if _storage._openapi3 != other_storage._openapi3 {return false}
if _storage._discovery != other_storage._discovery {return false}
if _storage._surface != other_storage._surface {return false}
return true
}
if !storagesAreEqual {return false}
}
if unknownFields != other.unknownFields {return false}
return true
}
}
extension Gnostic_Plugin_V1_Response: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "errors"),
2: .same(proto: "files"),
]
public func _protobuf_generated_isEqualTo(other: Gnostic_Plugin_V1_Response) -> Bool {
if self.errors != other.errors {return false}
if self.files != other.files {return false}
if unknownFields != other.unknownFields {return false}
return true
}
}
extension Gnostic_Plugin_V1_File: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "name"),
2: .same(proto: "data"),
]
public func _protobuf_generated_isEqualTo(other: Gnostic_Plugin_V1_File) -> Bool {
if self.name != other.name {return false}
if self.data != other.data {return false}
if unknownFields != other.unknownFields {return false}
return true
}
}

View File

@ -0,0 +1,579 @@
// DO NOT EDIT.
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: github.com/googleapis/gnostic/surface/surface.proto
//
// For information on using the generated types, please see the documenation:
// https://github.com/apple/swift-protobuf/
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Model an API surface for code generation.
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that your are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
public enum Surface_V1_FieldKind: SwiftProtobuf.Enum {
public typealias RawValue = Int
case scalar // = 0
case map // = 1
case array // = 2
case reference // = 3
case UNRECOGNIZED(Int)
public init() {
self = .scalar
}
public init?(rawValue: Int) {
switch rawValue {
case 0: self = .scalar
case 1: self = .map
case 2: self = .array
case 3: self = .reference
default: self = .UNRECOGNIZED(rawValue)
}
}
public var rawValue: Int {
switch self {
case .scalar: return 0
case .map: return 1
case .array: return 2
case .reference: return 3
case .UNRECOGNIZED(let i): return i
}
}
}
public enum Surface_V1_TypeKind: SwiftProtobuf.Enum {
public typealias RawValue = Int
/// implement with named fields
case `struct` // = 0
/// implement with a map
case object // = 1
case UNRECOGNIZED(Int)
public init() {
self = .struct
}
public init?(rawValue: Int) {
switch rawValue {
case 0: self = .struct
case 1: self = .object
default: self = .UNRECOGNIZED(rawValue)
}
}
public var rawValue: Int {
switch self {
case .struct: return 0
case .object: return 1
case .UNRECOGNIZED(let i): return i
}
}
}
public enum Surface_V1_Position: SwiftProtobuf.Enum {
public typealias RawValue = Int
case body // = 0
case header // = 1
case formdata // = 2
case query // = 3
case path // = 4
case UNRECOGNIZED(Int)
public init() {
self = .body
}
public init?(rawValue: Int) {
switch rawValue {
case 0: self = .body
case 1: self = .header
case 2: self = .formdata
case 3: self = .query
case 4: self = .path
default: self = .UNRECOGNIZED(rawValue)
}
}
public var rawValue: Int {
switch self {
case .body: return 0
case .header: return 1
case .formdata: return 2
case .query: return 3
case .path: return 4
case .UNRECOGNIZED(let i): return i
}
}
}
/// Field is a field in a definition and can be associated with
/// a position in a request structure.
public struct Surface_V1_Field: SwiftProtobuf.Message {
public static let protoMessageName: String = _protobuf_package + ".Field"
/// the name as specified in the API description
public var name: String = String()
/// the specified content type of the field
public var type: String = String()
/// what kind of thing is this field? scalar, reference, array, map of strings to the specified type
public var kind: Surface_V1_FieldKind = .scalar
/// the specified format of the field
public var format: String = String()
/// "body", "header", "formdata", "query", or "path"
public var position: Surface_V1_Position = .body
/// the programming-language native type of the field
public var nativeType: String = String()
/// the name to use for a data structure field
public var fieldName: String = String()
/// the name to use for a function parameter
public var parameterName: String = String()
/// true if this field should be serialized (to JSON, etc)
public var serialize: Bool = false
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
/// Used by the decoding initializers in the SwiftProtobuf library, not generally
/// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding
/// initializers are defined in the SwiftProtobuf library. See the Message and
/// Message+*Additions` files.
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularStringField(value: &self.name)
case 2: try decoder.decodeSingularStringField(value: &self.type)
case 3: try decoder.decodeSingularEnumField(value: &self.kind)
case 4: try decoder.decodeSingularStringField(value: &self.format)
case 5: try decoder.decodeSingularEnumField(value: &self.position)
case 6: try decoder.decodeSingularStringField(value: &self.nativeType)
case 7: try decoder.decodeSingularStringField(value: &self.fieldName)
case 8: try decoder.decodeSingularStringField(value: &self.parameterName)
case 9: try decoder.decodeSingularBoolField(value: &self.serialize)
default: break
}
}
}
/// Used by the encoding methods of the SwiftProtobuf library, not generally
/// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and
/// other serializer methods are defined in the SwiftProtobuf library. See the
/// `Message` and `Message+*Additions` files.
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.name.isEmpty {
try visitor.visitSingularStringField(value: self.name, fieldNumber: 1)
}
if !self.type.isEmpty {
try visitor.visitSingularStringField(value: self.type, fieldNumber: 2)
}
if self.kind != .scalar {
try visitor.visitSingularEnumField(value: self.kind, fieldNumber: 3)
}
if !self.format.isEmpty {
try visitor.visitSingularStringField(value: self.format, fieldNumber: 4)
}
if self.position != .body {
try visitor.visitSingularEnumField(value: self.position, fieldNumber: 5)
}
if !self.nativeType.isEmpty {
try visitor.visitSingularStringField(value: self.nativeType, fieldNumber: 6)
}
if !self.fieldName.isEmpty {
try visitor.visitSingularStringField(value: self.fieldName, fieldNumber: 7)
}
if !self.parameterName.isEmpty {
try visitor.visitSingularStringField(value: self.parameterName, fieldNumber: 8)
}
if self.serialize != false {
try visitor.visitSingularBoolField(value: self.serialize, fieldNumber: 9)
}
try unknownFields.traverse(visitor: &visitor)
}
}
/// Type typically corresponds to a definition, parameter, or response
/// in an API and is represented by a type in generated code.
public struct Surface_V1_Type: SwiftProtobuf.Message {
public static let protoMessageName: String = _protobuf_package + ".Type"
/// the name to use for the type
public var name: String = String()
/// a meta-description of the type (struct, map, etc)
public var kind: Surface_V1_TypeKind = .struct
/// a comment describing the type
public var description_p: String = String()
/// if the type is a map, this is its content type
public var contentType: String = String()
/// the fields of the type
public var fields: [Surface_V1_Field] = []
/// language-specific type name
public var typeName: String = String()
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
/// Used by the decoding initializers in the SwiftProtobuf library, not generally
/// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding
/// initializers are defined in the SwiftProtobuf library. See the Message and
/// Message+*Additions` files.
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularStringField(value: &self.name)
case 2: try decoder.decodeSingularEnumField(value: &self.kind)
case 3: try decoder.decodeSingularStringField(value: &self.description_p)
case 4: try decoder.decodeSingularStringField(value: &self.contentType)
case 5: try decoder.decodeRepeatedMessageField(value: &self.fields)
case 6: try decoder.decodeSingularStringField(value: &self.typeName)
default: break
}
}
}
/// Used by the encoding methods of the SwiftProtobuf library, not generally
/// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and
/// other serializer methods are defined in the SwiftProtobuf library. See the
/// `Message` and `Message+*Additions` files.
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.name.isEmpty {
try visitor.visitSingularStringField(value: self.name, fieldNumber: 1)
}
if self.kind != .struct {
try visitor.visitSingularEnumField(value: self.kind, fieldNumber: 2)
}
if !self.description_p.isEmpty {
try visitor.visitSingularStringField(value: self.description_p, fieldNumber: 3)
}
if !self.contentType.isEmpty {
try visitor.visitSingularStringField(value: self.contentType, fieldNumber: 4)
}
if !self.fields.isEmpty {
try visitor.visitRepeatedMessageField(value: self.fields, fieldNumber: 5)
}
if !self.typeName.isEmpty {
try visitor.visitSingularStringField(value: self.typeName, fieldNumber: 6)
}
try unknownFields.traverse(visitor: &visitor)
}
}
/// Method is an operation of an API and typically has associated client and server code.
public struct Surface_V1_Method: SwiftProtobuf.Message {
public static let protoMessageName: String = _protobuf_package + ".Method"
/// Operation ID
public var operation: String = String()
/// HTTP path
public var path: String = String()
/// HTTP method name
public var method: String = String()
/// description of method
public var description_p: String = String()
/// Operation name, possibly generated from method and path
public var name: String = String()
/// name of the generated handler
public var handlerName: String = String()
/// name of the processing function in the service interface
public var processorName: String = String()
/// name of client
public var clientName: String = String()
/// parameters (input), with fields corresponding to input parameters
public var parametersTypeName: String = String()
/// responses (output), with fields corresponding to possible response values
public var responsesTypeName: String = String()
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
/// Used by the decoding initializers in the SwiftProtobuf library, not generally
/// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding
/// initializers are defined in the SwiftProtobuf library. See the Message and
/// Message+*Additions` files.
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularStringField(value: &self.operation)
case 2: try decoder.decodeSingularStringField(value: &self.path)
case 3: try decoder.decodeSingularStringField(value: &self.method)
case 4: try decoder.decodeSingularStringField(value: &self.description_p)
case 5: try decoder.decodeSingularStringField(value: &self.name)
case 6: try decoder.decodeSingularStringField(value: &self.handlerName)
case 7: try decoder.decodeSingularStringField(value: &self.processorName)
case 8: try decoder.decodeSingularStringField(value: &self.clientName)
case 9: try decoder.decodeSingularStringField(value: &self.parametersTypeName)
case 10: try decoder.decodeSingularStringField(value: &self.responsesTypeName)
default: break
}
}
}
/// Used by the encoding methods of the SwiftProtobuf library, not generally
/// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and
/// other serializer methods are defined in the SwiftProtobuf library. See the
/// `Message` and `Message+*Additions` files.
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.operation.isEmpty {
try visitor.visitSingularStringField(value: self.operation, fieldNumber: 1)
}
if !self.path.isEmpty {
try visitor.visitSingularStringField(value: self.path, fieldNumber: 2)
}
if !self.method.isEmpty {
try visitor.visitSingularStringField(value: self.method, fieldNumber: 3)
}
if !self.description_p.isEmpty {
try visitor.visitSingularStringField(value: self.description_p, fieldNumber: 4)
}
if !self.name.isEmpty {
try visitor.visitSingularStringField(value: self.name, fieldNumber: 5)
}
if !self.handlerName.isEmpty {
try visitor.visitSingularStringField(value: self.handlerName, fieldNumber: 6)
}
if !self.processorName.isEmpty {
try visitor.visitSingularStringField(value: self.processorName, fieldNumber: 7)
}
if !self.clientName.isEmpty {
try visitor.visitSingularStringField(value: self.clientName, fieldNumber: 8)
}
if !self.parametersTypeName.isEmpty {
try visitor.visitSingularStringField(value: self.parametersTypeName, fieldNumber: 9)
}
if !self.responsesTypeName.isEmpty {
try visitor.visitSingularStringField(value: self.responsesTypeName, fieldNumber: 10)
}
try unknownFields.traverse(visitor: &visitor)
}
}
/// Model represents an API for code generation.
public struct Surface_V1_Model: SwiftProtobuf.Message {
public static let protoMessageName: String = _protobuf_package + ".Model"
/// a free-form title for the API
public var name: String = String()
/// the types used by the API
public var types: [Surface_V1_Type] = []
/// the methods (functions) of the API
public var methods: [Surface_V1_Method] = []
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
/// Used by the decoding initializers in the SwiftProtobuf library, not generally
/// used directly. `init(serializedData:)`, `init(jsonUTF8Data:)`, and other decoding
/// initializers are defined in the SwiftProtobuf library. See the Message and
/// Message+*Additions` files.
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularStringField(value: &self.name)
case 2: try decoder.decodeRepeatedMessageField(value: &self.types)
case 3: try decoder.decodeRepeatedMessageField(value: &self.methods)
default: break
}
}
}
/// Used by the encoding methods of the SwiftProtobuf library, not generally
/// used directly. `Message.serializedData()`, `Message.jsonUTF8Data()`, and
/// other serializer methods are defined in the SwiftProtobuf library. See the
/// `Message` and `Message+*Additions` files.
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.name.isEmpty {
try visitor.visitSingularStringField(value: self.name, fieldNumber: 1)
}
if !self.types.isEmpty {
try visitor.visitRepeatedMessageField(value: self.types, fieldNumber: 2)
}
if !self.methods.isEmpty {
try visitor.visitRepeatedMessageField(value: self.methods, fieldNumber: 3)
}
try unknownFields.traverse(visitor: &visitor)
}
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "surface.v1"
extension Surface_V1_FieldKind: SwiftProtobuf._ProtoNameProviding {
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
0: .same(proto: "SCALAR"),
1: .same(proto: "MAP"),
2: .same(proto: "ARRAY"),
3: .same(proto: "REFERENCE"),
]
}
extension Surface_V1_TypeKind: SwiftProtobuf._ProtoNameProviding {
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
0: .same(proto: "STRUCT"),
1: .same(proto: "OBJECT"),
]
}
extension Surface_V1_Position: SwiftProtobuf._ProtoNameProviding {
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
0: .same(proto: "BODY"),
1: .same(proto: "HEADER"),
2: .same(proto: "FORMDATA"),
3: .same(proto: "QUERY"),
4: .same(proto: "PATH"),
]
}
extension Surface_V1_Field: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "name"),
2: .same(proto: "type"),
3: .same(proto: "kind"),
4: .same(proto: "format"),
5: .same(proto: "position"),
6: .same(proto: "nativeType"),
7: .same(proto: "fieldName"),
8: .same(proto: "parameterName"),
9: .same(proto: "serialize"),
]
public func _protobuf_generated_isEqualTo(other: Surface_V1_Field) -> Bool {
if self.name != other.name {return false}
if self.type != other.type {return false}
if self.kind != other.kind {return false}
if self.format != other.format {return false}
if self.position != other.position {return false}
if self.nativeType != other.nativeType {return false}
if self.fieldName != other.fieldName {return false}
if self.parameterName != other.parameterName {return false}
if self.serialize != other.serialize {return false}
if unknownFields != other.unknownFields {return false}
return true
}
}
extension Surface_V1_Type: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "name"),
2: .same(proto: "kind"),
3: .same(proto: "description"),
4: .same(proto: "contentType"),
5: .same(proto: "fields"),
6: .same(proto: "typeName"),
]
public func _protobuf_generated_isEqualTo(other: Surface_V1_Type) -> Bool {
if self.name != other.name {return false}
if self.kind != other.kind {return false}
if self.description_p != other.description_p {return false}
if self.contentType != other.contentType {return false}
if self.fields != other.fields {return false}
if self.typeName != other.typeName {return false}
if unknownFields != other.unknownFields {return false}
return true
}
}
extension Surface_V1_Method: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "operation"),
2: .same(proto: "path"),
3: .same(proto: "method"),
4: .same(proto: "description"),
5: .same(proto: "name"),
6: .same(proto: "handlerName"),
7: .same(proto: "processorName"),
8: .same(proto: "clientName"),
9: .same(proto: "parametersTypeName"),
10: .same(proto: "responsesTypeName"),
]
public func _protobuf_generated_isEqualTo(other: Surface_V1_Method) -> Bool {
if self.operation != other.operation {return false}
if self.path != other.path {return false}
if self.method != other.method {return false}
if self.description_p != other.description_p {return false}
if self.name != other.name {return false}
if self.handlerName != other.handlerName {return false}
if self.processorName != other.processorName {return false}
if self.clientName != other.clientName {return false}
if self.parametersTypeName != other.parametersTypeName {return false}
if self.responsesTypeName != other.responsesTypeName {return false}
if unknownFields != other.unknownFields {return false}
return true
}
}
extension Surface_V1_Model: SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "name"),
2: .same(proto: "types"),
3: .same(proto: "methods"),
]
public func _protobuf_generated_isEqualTo(other: Surface_V1_Model) -> Bool {
if self.name != other.name {return false}
if self.types != other.types {return false}
if self.methods != other.methods {return false}
if unknownFields != other.unknownFields {return false}
return true
}
}

View File

@ -0,0 +1,184 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import Gnostic
extension ServiceRenderer {
func renderClient() -> String {
var code = CodePrinter()
code.print(header)
code.print()
code.print("// Client code")
code.print()
code.print("import Foundation")
code.print("import Dispatch")
code.print()
code.print("""
enum ClientError: Swift.Error {
case errorWithCode(Int)
}
""")
code.print()
code.print("public class Client {")
code.indent()
code.print("var service : String")
code.print()
code.print("""
public init(service: String) {
self.service = service
}
""")
for serviceMethod in self.methods {
code.print()
code.print("// " + serviceMethod.description + " Asynchronous.")
code.print("public func " + serviceMethod.name + "(" + asyncClientParametersDeclaration(serviceMethod) + ") throws {")
code.indent()
code.print("var path = self.service")
code.print("path = path + \"" + serviceMethod.path + "\"")
for serviceTypeField in parametersTypeFields(serviceMethod) {
if serviceTypeField.position == "path" {
code.print("path = path.replacingOccurrences(of:\"{" +
serviceTypeField.name +
"}\", with:\"\\(" +
serviceTypeField.name +
")\")")
}
}
code.print("guard let url = URL(string:path) else {")
code.indent()
code.print("throw ClientError.errorWithCode(0)")
code.outdent()
code.print("}")
code.print("var request = URLRequest(url:url)")
code.print("request.httpMethod = \"" + serviceMethod.method + "\"")
for serviceTypeField in parametersTypeFields(serviceMethod) {
if serviceTypeField.position == "body" {
code.print("let jsonObject = " + serviceTypeField.name + ".jsonObject()")
code.print("request.httpBody = try JSONSerialization.data(withJSONObject:jsonObject)")
}
}
if hasResponses(serviceMethod) {
code.print("fetch(request) {(data, response, error) in")
code.indent()
code.print("if error != nil {")
code.indent()
code.print("callback(nil, ClientError.errorWithCode(0))")
code.print("return")
code.outdent()
code.print("}")
code.print("guard let httpResponse = response else {")
code.indent()
code.print("callback(nil, ClientError.errorWithCode(0))")
code.print("return")
code.outdent()
code.print("}")
code.print("if httpResponse.statusCode == 200 {")
code.indent()
code.print("if let data = data {")
code.indent()
code.print("let jsonObject = try! JSONSerialization.jsonObject(with:data)")
code.print("if let value = " + serviceMethod.resultTypeName! + "(jsonObject:jsonObject) {")
code.indent()
code.print("callback(value, nil)")
code.print("return")
code.outdent()
code.print("}")
code.outdent()
code.print("}")
code.print("callback(nil, nil)")
code.outdent()
code.print("} else {")
code.indent()
code.print(" callback(nil, ClientError.errorWithCode(httpResponse.statusCode))")
code.outdent()
code.print("}")
code.outdent()
code.print("}")
} else {
code.print("fetch(request) {(data, response, error) in")
code.print("if error != nil {")
code.indent()
code.print("callback(ClientError.errorWithCode(0))")
code.print("return")
code.outdent()
code.print("}")
code.print("guard let httpResponse = response else {")
code.indent()
code.print("callback(ClientError.errorWithCode(0))")
code.print("return")
code.outdent()
code.print("}")
code.print("if httpResponse.statusCode == 200 {")
code.indent()
code.print("callback(nil)")
code.print("} else {")
code.indent()
code.print("callback(ClientError.errorWithCode(httpResponse.statusCode))")
code.outdent()
code.print("}")
code.outdent()
code.print("}")
}
code.outdent()
code.print("}")
code.print()
code.print("// " + serviceMethod.description + " Synchronous.")
code.print("public func " + serviceMethod.name + "(" + syncClientParametersDeclaration(serviceMethod) + ") throws " + syncClientReturnDeclaration(serviceMethod) + " {")
code.indent()
code.print("let sem = DispatchSemaphore(value: 0)")
if hasResponses(serviceMethod) {
code.print("var response : " + serviceMethod.resultTypeName! + "?")
}
code.print("var error : Swift.Error?")
if hasResponses(serviceMethod) {
code.print("try " + serviceMethod.name + "(" + parameterFieldNames(serviceMethod) + ") {r, e in")
code.indent()
code.print("response = r")
} else {
code.print("try " + serviceMethod.name + "(" + parameterFieldNames(serviceMethod) + ") {e in")
code.indent()
}
code.print("error = e")
code.print("sem.signal()")
code.outdent()
code.print("}")
code.print("sem.wait()")
code.print("if let actualError = error {")
code.indent()
code.print("throw actualError")
code.outdent()
code.print("}")
if hasResponses(serviceMethod) {
code.print("if let actualResponse = response {")
code.indent()
code.print("return actualResponse")
code.outdent()
code.print("} else {")
code.indent()
code.print("throw ClientError.errorWithCode(0)")
code.outdent()
code.print("}")
}
code.outdent()
code.print("}")
code.print()
}
code.outdent()
code.print("}")
return code.content
}
}

View File

@ -0,0 +1,157 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import Gnostic
extension ServiceRenderer {
func renderFetch() -> String {
var code = CodePrinter()
code.print(header)
code.print("""
import Foundation
import Dispatch
import KituraNet
// fetch makes a synchronous request using KituraNet's ClientRequest class
// https://github.com/IBM-Swift/Kitura-net/blob/master/Sources/KituraNet/ClientRequest.swift
public func fetch(_ urlRequest: URLRequest) -> (Data?, HTTPURLResponse?, Error?) {
var data: Data?
var urlResponse: HTTPURLResponse?
let error: Error? = nil // make this mutable when we start using it
let sem = DispatchSemaphore(value: 0)
guard let method = urlRequest.httpMethod else {
return (data, urlResponse, error)
}
guard let url = urlRequest.url else {
return (data, urlResponse, error)
}
guard let scheme = url.scheme else {
return (data, urlResponse, error)
}
guard let host = url.host else {
return (data, urlResponse, error)
}
guard let port = url.port else {
return (data, urlResponse, error)
}
let options : [ClientRequest.Options] = [
.method(method),
.schema(scheme),
.hostname(host),
.port(Int16(port)),
.path(url.path),
// headers, etc
]
let request = HTTP.request(options) { (response) in
guard let response = response else {
sem.signal()
return
}
var responseData = Data()
do {
let code = response.httpStatusCode
try response.readAllData(into: &responseData)
data = responseData
urlResponse = HTTPURLResponse(url:url,
statusCode:code.rawValue,
httpVersion:"HTTP/1.1",
headerFields:[:])
sem.signal()
return
} catch {
sem.signal()
return
}
}
if let requestData = urlRequest.httpBody {
request.write(from:requestData)
}
request.end() // send the request
// now wait on the semaphore for a response
let result = sem.wait(timeout: DispatchTime.distantFuture)
switch result {
case .success:
return (data, urlResponse, error)
default: // includes .timeout
return (data, urlResponse, error)
}
}
// fetch makes an asynchronous request using KituraNet's ClientRequest class
// https://github.com/IBM-Swift/Kitura-net/blob/master/Sources/KituraNet/ClientRequest.swift
public func fetch(_ urlRequest: URLRequest, callback:@escaping (Data?, HTTPURLResponse?, Error?) -> ()) {
var data: Data?
var urlResponse: HTTPURLResponse?
let error: Error? = nil // make this mutable when we start using it
guard let method = urlRequest.httpMethod else {
callback (data, urlResponse, error)
return
}
guard let url = urlRequest.url else {
callback (data, urlResponse, error)
return
}
guard let scheme = url.scheme else {
callback (data, urlResponse, error)
return
}
guard let host = url.host else {
callback (data, urlResponse, error)
return
}
guard let port = url.port else {
callback (data, urlResponse, error)
return
}
let options : [ClientRequest.Options] = [
.method(method),
.schema(scheme),
.hostname(host),
.port(Int16(port)),
.path(url.path),
// headers, etc
]
let request = HTTP.request(options) { (response) in
guard let response = response else {
callback (data, urlResponse, nil)
return
}
var responseData = Data()
do {
let code = response.httpStatusCode
try response.readAllData(into: &responseData)
data = responseData
urlResponse = HTTPURLResponse(url:url,
statusCode:code.rawValue,
httpVersion:"HTTP/1.1",
headerFields:[:])
callback (data, urlResponse, nil)
return
} catch {
callback (data, urlResponse, nil)
return
}
}
if let requestData = urlRequest.httpBody {
request.write(from:requestData)
}
request.end() // send the request
}
""")
return code.content
}
}

View File

@ -0,0 +1,166 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import Gnostic
extension ServiceRenderer {
func renderServer() -> String {
var code = CodePrinter()
code.print(header)
code.print()
code.print("// Service code")
code.print("import Kitura")
code.print("import KituraNet")
code.print("import Foundation")
code.print("// A server requires an instance of an implementation of this protocol.")
code.print("public protocol Service {")
code.indent()
for serviceMethod in self.methods {
code.print("// " + serviceMethod.description)
code.print("func " + serviceMethod.name + " (" +
protocolParametersDeclaration(serviceMethod) + ") throws " +
protocolReturnDeclaration(serviceMethod))
}
code.outdent()
code.print("}")
code.print("func intValue(_ s:String?) -> Int64 {")
code.indent()
code.print("guard let s = s else {")
code.indent()
code.print("return 0")
code.outdent()
code.print("}")
code.print("guard let value = Int64(s) else {")
code.indent()
code.print("return 0")
code.outdent()
code.print("}")
code.print("return value")
code.outdent()
code.print("}")
code.print("public func server(service : Service) -> Router {")
code.indent()
code.print("// Create a new router")
code.print("let router = Router()")
for serviceMethod in self.methods {
code.print("// " + serviceMethod.description)
code.print("router." + lowercase(serviceMethod.method) + "(\"" + kituraPath(serviceMethod) + "\") { req, res, next in")
code.indent()
if hasParameters(serviceMethod) {
code.print("// instantiate the parameters structure")
code.print("let parameters = " + serviceMethod.parametersTypeName! + "()")
for serviceTypeField in parametersTypeFields(serviceMethod) {
if serviceTypeField.position == "path" {
code.print("parameters." + serviceTypeField.name +
" = intValue(req.parameters[\"" +
serviceTypeField.name + "\"])")
}
}
if serviceMethod.method == "POST" {
code.print("// deserialize request from post data")
code.print("let bodyString = try req.readString() ?? \"\"")
code.print("guard let bodyData = bodyString.data(using:.utf8) else {")
code.indent()
code.print("try res.send(status:.badRequest).end()")
code.print("return")
code.outdent()
code.print("}")
code.print("var jsonObject : Any? = nil")
code.print("do {")
code.indent()
code.print("jsonObject = try JSONSerialization.jsonObject(with:bodyData)")
code.outdent()
code.print("} catch {")
code.indent()
code.print("try res.send(status:.badRequest).end()")
code.print("return")
code.outdent()
code.print("}")
code.print("guard let bodyObject = " + serviceMethod.resultTypeName! + "(jsonObject:jsonObject) else {")
code.print("try res.send(status:.badRequest).end()")
code.indent()
code.print("return")
code.outdent()
code.print("}")
code.print("parameters." + bodyParameterFieldName(serviceMethod) + " = bodyObject")
}
}
if hasParameters(serviceMethod) {
if hasResponses(serviceMethod) {
code.print("let responses = try service." + serviceMethod.name + "(parameters)")
} else {
code.print("try service." + serviceMethod.name + "(parameters)")
}
} else {
if hasResponses(serviceMethod) {
code.print("let responses = try service." + serviceMethod.name + "()")
} else {
code.print("try service." + serviceMethod.name + "()")
}
}
if hasResponses(serviceMethod) {
if responsesHasFieldNamedOK(serviceMethod) {
code.print("if let ok = responses.ok {")
code.indent()
code.print("let jsonObject = ok.jsonObject()")
code.print("let responseData = try JSONSerialization.data(withJSONObject:jsonObject)")
code.print("try res.send(data:responseData).end()")
code.print("return")
code.outdent()
code.print("}")
}
if responsesHasFieldNamedError(serviceMethod) {
code.print("if let errorResponse = responses.error {")
code.indent()
code.print("guard let statusCode = HTTPStatusCode(rawValue:Int(errorResponse.code)) else {")
code.indent()
code.print("try res.send(status:.unknown).end()")
code.print("return")
code.outdent()
code.print("}")
code.print("try res.send(status:statusCode).end()")
code.print("return")
code.outdent()
code.print("}")
}
code.print("try res.send(status:.internalServerError).end()")
} else {
code.print("try res.send(status:.OK).end()")
}
code.outdent()
code.print("}")
}
code.print("return router")
code.outdent()
code.print("}")
code.print("public func initialize(service: Service, port:Int) {")
code.indent()
code.print("// Create a new router")
code.print("let router = server(service:service)")
code.print("// Add an HTTP server and connect it to the router")
code.print("Kitura.addHTTPServer(onPort:port, with: router)")
code.outdent()
code.print("}")
code.print("public func run() {")
code.indent()
code.print("// Start the Kitura runloop (this call never returns)")
code.print("Kitura.run()")
code.outdent()
code.print("}")
return code.content
}
}

View File

@ -0,0 +1,112 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import Gnostic
extension ServiceRenderer {
func renderTypes() -> String {
var code = CodePrinter()
code.print(header)
code.print()
code.print("// Common type declarations")
for serviceType in self.types {
code.print()
code.print("public class " + serviceType.name + " : CustomStringConvertible {")
code.indent()
for serviceTypeField in serviceType.fields {
code.print("public var " + serviceTypeField.name + " : " + serviceTypeField.typeName + " = " + serviceTypeField.initialValue)
}
code.print()
code.print("public init() {}")
code.print()
if serviceType.isInterfaceType {
code.print("public init?(jsonObject: Any?) {")
code.indent()
code.print("if let jsonDictionary = jsonObject as? [String:Any] {")
code.indent()
for serviceTypeField in serviceType.fields {
code.print("if let value : Any = jsonDictionary[\"" + serviceTypeField.jsonName + "\"] {")
code.indent()
if serviceTypeField.isArrayType {
code.print("var outArray : [" + serviceTypeField.elementType + "] = []")
code.print("let array = value as! [Any]")
code.print("for arrayValue in array {")
code.indent()
code.print("if let element = " + serviceTypeField.elementType + "(jsonObject:arrayValue) {")
code.indent()
code.print("outArray.append(element)")
code.outdent()
code.print("}")
code.outdent()
code.print("}")
code.print("self." + serviceTypeField.name + " = outArray")
} else if serviceTypeField.isCastableType {
code.print("self." + serviceTypeField.name + " = value as! " + serviceTypeField.typeName)
} else if serviceTypeField.isConvertibleType {
code.print("self." + serviceTypeField.name + " = " + serviceTypeField.typeName + "(value)")
}
code.outdent()
code.print("}")
}
code.outdent()
code.print("} else {")
code.indent()
code.print("return nil")
code.outdent()
code.print("}")
code.outdent()
code.print("}")
code.print()
code.print("public func jsonObject() -> Any {")
code.indent()
code.print("var result : [String:Any] = [:]")
for serviceTypeField in serviceType.fields {
if serviceTypeField.isArrayType {
code.print("var outArray : [Any] = []")
code.print("for arrayValue in self." + serviceTypeField.name + " {")
code.indent()
code.print("outArray.append(arrayValue.jsonObject())")
code.outdent()
code.print("}")
code.print("result[\"" + serviceTypeField.jsonName + "\"] = outArray")
}
if serviceTypeField.isCastableType {
code.print("result[\"" + serviceTypeField.jsonName + "\"] = self." + serviceTypeField.name)
}
if serviceTypeField.isConvertibleType {
code.print("result[\"" + serviceTypeField.jsonName + "\"] = self." + serviceTypeField.name + ".jsonObject()")
}
}
code.print("return result")
code.outdent()
code.print("}")
code.print()
}
code.print("public var description : String {")
code.indent()
code.print("return \"[" + serviceType.name + "\" + ")
for serviceTypeField in serviceType.fields {
code.print(" \" " + serviceTypeField.name + ": \" + String(describing:self." + serviceTypeField.name + ") + ")
}
code.print("\"]\"")
code.outdent()
code.print("}")
code.outdent()
code.print("}")
}
return code.content
}
}

View File

@ -0,0 +1,336 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import Gnostic
extension String {
func capitalizingFirstLetter() -> String {
let first = String(characters.prefix(1)).capitalized
let other = String(characters.dropFirst())
return first + other
}
mutating func capitalizeFirstLetter() {
self = self.capitalizingFirstLetter()
}
}
class ServiceType {
var name : String = ""
var fields : [ServiceTypeField] = []
var isInterfaceType : Bool = false
}
class ServiceTypeField {
var name : String = ""
var typeName : String = ""
var isArrayType : Bool = false
var isCastableType : Bool = false
var isConvertibleType : Bool = false
var elementType : String = ""
var jsonName : String = ""
var position: String = "" // "body", "header", "formdata", "query", or "path"
var initialValue : String = ""
func setTypeForName(_ name : String, _ format : String) {
switch name {
case "integer":
if format == "int32" {
self.typeName = "Int32"
} else if format == "int64" {
self.typeName = "Int64"
} else {
self.typeName = "Int"
}
self.initialValue = "0"
self.isCastableType = true
default:
self.typeName = name.capitalizingFirstLetter()
self.initialValue = self.typeName + "()"
self.isConvertibleType = true
}
}
func setTypeForSchema(_ schema : Openapi_V2_Schema, optional : Bool = false) {
let ref = schema.ref
if ref != "" {
self.typeName = typeForRef(ref)
self.isConvertibleType = true
self.initialValue = self.typeName + "()"
}
if schema.hasType {
let types = schema.type.value
let format = schema.format
if types.count == 1 && types[0] == "string" {
self.typeName = "String"
self.isCastableType = true
self.initialValue = "\"\""
}
if types.count == 1 && types[0] == "integer" && format == "int32" {
self.typeName = "Int32"
self.isCastableType = true
self.initialValue = "0"
}
if types.count == 1 && types[0] == "array" && schema.hasItems {
// we have an array.., but of what?
let items = schema.items.schema
if items.count == 1 && items[0].ref != "" {
self.isArrayType = true
self.elementType = typeForRef(items[0].ref)
self.typeName = "[" + self.elementType + "]"
self.initialValue = "[]"
}
}
}
// this function is incomplete... so return a string representing anything that we don't handle
if self.typeName == "" {
self.typeName = "\(schema)"
}
if optional {
self.typeName += "?"
self.initialValue = "nil"
}
}
}
class ServiceMethod {
var name : String = ""
var path : String = ""
var method : String = ""
var description : String = ""
var handlerName : String = ""
var processorName : String = ""
var clientName : String = ""
var resultTypeName : String?
var parametersTypeName : String?
var responsesTypeName : String?
var parametersType : ServiceType?
var responsesType : ServiceType?
}
func propertyNameForResponseCode(_ code:String) -> String {
switch code {
case "200":
return "ok"
case "default":
return "error"
default:
return code
}
}
func typeForRef(_ ref : String) -> String {
let parts = ref.components(separatedBy:"/")
return parts.last!.capitalizingFirstLetter()
}
class ServiceRenderer {
internal var name : String = ""
internal var package: String = ""
internal var types : [ServiceType] = []
internal var methods : [ServiceMethod] = []
internal var surface : Surface_V1_Model
public init(surface : Surface_V1_Model, document : Openapi_V2_Document) {
self.surface = surface
loadService(document:document)
}
private func loadServiceTypeFromParameters(_ name:String,
_ parameters:[Openapi_V2_ParametersItem])
-> ServiceType? {
let t = ServiceType()
t.name = name.capitalizingFirstLetter() + "Parameters"
for parametersItem in parameters {
let f = ServiceTypeField()
f.typeName = "\(parametersItem)"
switch parametersItem.oneof! {
case .parameter(let parameter):
switch parameter.oneof! {
case .bodyParameter(let bodyParameter):
f.name = bodyParameter.name
if bodyParameter.hasSchema {
f.setTypeForSchema(bodyParameter.schema)
f.position = "body"
}
case .nonBodyParameter(let nonBodyParameter):
switch (nonBodyParameter.oneof!) {
case .headerParameterSubSchema(let headerParameter):
f.name = headerParameter.name
f.position = "header"
case .formDataParameterSubSchema(let formDataParameter):
f.name = formDataParameter.name
f.position = "formdata"
case .queryParameterSubSchema(let queryParameter):
f.name = queryParameter.name
f.position = "query"
case .pathParameterSubSchema(let pathParameter):
f.name = pathParameter.name
f.jsonName = pathParameter.name
f.position = "path"
f.setTypeForName(pathParameter.type, pathParameter.format)
}
}
case .jsonReference: // (let reference):
Log("?")
}
t.fields.append(f)
}
if t.fields.count > 0 {
self.types.append(t)
return t
} else {
return nil
}
}
private func loadServiceTypeFromResponses(_ m:ServiceMethod,
_ name:String,
_ responses:Openapi_V2_Responses)
-> ServiceType? {
let t = ServiceType()
t.name = name.capitalizingFirstLetter() + "Responses"
for responseCode in responses.responseCode {
let f = ServiceTypeField()
f.name = propertyNameForResponseCode(responseCode.name)
f.jsonName = ""
if let responseCodeValueOneOf = responseCode.value.oneof {
switch responseCodeValueOneOf {
case .response(let response):
let schema = response.schema
if let schemaOneOf = schema.oneof {
switch schemaOneOf {
case .schema(let schema):
f.setTypeForSchema(schema, optional:true)
t.fields.append(f)
if f.name == "ok" {
m.resultTypeName = f.typeName.replacingOccurrences(of:"?", with:"")
}
default:
break
}
}
default:
break
}
}
}
if t.fields.count > 0 {
self.types.append(t)
return t
} else {
return nil
}
}
private func loadOperation(_ operation : Openapi_V2_Operation,
method : String,
path : String) {
let m = ServiceMethod()
m.name = operation.operationID
m.path = path
m.method = method
m.description = operation.description_p
m.handlerName = "handle" + m.name
m.processorName = "" + m.name
m.clientName = m.name
m.parametersType = loadServiceTypeFromParameters(m.name, operation.parameters)
if m.parametersType != nil {
m.parametersTypeName = m.parametersType!.name
}
m.responsesType = loadServiceTypeFromResponses(m, m.name, operation.responses)
if m.responsesType != nil {
m.responsesTypeName = m.responsesType!.name
}
self.methods.append(m)
}
private func loadService(document : Openapi_V2_Document) {
// collect service type descriptions
for pair in document.definitions.additionalProperties {
let t = ServiceType()
t.isInterfaceType = true
let schema = pair.value
for pair2 in schema.properties.additionalProperties {
let f = ServiceTypeField()
f.name = pair2.name
f.setTypeForSchema(pair2.value)
f.jsonName = pair2.name
t.fields.append(f)
}
t.name = pair.name.capitalizingFirstLetter()
self.types.append(t)
}
// collect service method descriptions
for pair in document.paths.path {
let v = pair.value
if v.hasGet {
loadOperation(v.get, method:"GET", path:pair.name)
}
if v.hasPost {
loadOperation(v.post, method:"POST", path:pair.name)
}
if v.hasPut {
loadOperation(v.put, method:"PUT", path:pair.name)
}
if v.hasDelete {
loadOperation(v.delete, method:"DELETE", path:pair.name)
}
}
}
public func generate(filenames : [String], response : inout Gnostic_Plugin_V1_Response) throws {
for filename in filenames {
var data : Data?
switch filename {
case "types.swift":
data = renderTypes().data(using:.utf8)
case "server.swift":
data = renderServer().data(using:.utf8)
case "client.swift":
data = renderClient().data(using:.utf8)
case "fetch.swift":
data = renderFetch().data(using:.utf8)
default:
print("error: unable to render \(filename)")
}
if let data = data {
var clientfile = Gnostic_Plugin_V1_File()
clientfile.name = filename
clientfile.data = data
response.files.append(clientfile)
}
}
}
}
let header = """
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
"""

View File

@ -0,0 +1,166 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
func hasParameters(_ value : Any?) -> Bool {
let method : ServiceMethod = value as! ServiceMethod
return method.parametersType != nil
}
func hasResponses(_ value : Any?) -> Bool {
let method : ServiceMethod = value as! ServiceMethod
return method.responsesType != nil
}
func syncClientParametersDeclaration(_ value: Any?) -> String {
let method : ServiceMethod = value as! ServiceMethod
var result = ""
if let parametersType = method.parametersType {
for field in parametersType.fields {
if result != "" {
result += ", "
}
result += field.name + " : " + field.typeName
}
}
return result
}
func syncClientReturnDeclaration(_ value : Any?) -> String {
let method : ServiceMethod = value as! ServiceMethod
var result = ""
if let resultTypeName = method.resultTypeName {
result = " -> " + resultTypeName
}
return result
}
func asyncClientParametersDeclaration(_ value : Any?) -> String {
let method : ServiceMethod = value as! ServiceMethod
var result = ""
if let parametersType = method.parametersType {
for field in parametersType.fields {
if result != "" {
result += ", "
}
result += field.name + " : " + field.typeName
}
}
// add callback
if result != "" {
result += ", "
}
if let resultTypeName = method.resultTypeName {
result += "callback : @escaping (" + resultTypeName + "?, Swift.Error?)->()"
} else {
result += "callback : @escaping (Swift.Error?)->()"
}
return result
}
func protocolParametersDeclaration(_ value: Any?) -> String {
let method : ServiceMethod = value as! ServiceMethod
var result = ""
if let parametersTypeName = method.parametersTypeName {
result = "_ parameters : " + parametersTypeName
}
return result
}
func protocolReturnDeclaration(_ value: Any?) -> String {
let method : ServiceMethod = value as! ServiceMethod
var result = ""
if let responsesTypeName = method.responsesTypeName {
result = "-> " + responsesTypeName
}
return result
}
func parameterFieldNames(_ value: Any?) -> String {
let method : ServiceMethod = value as! ServiceMethod
var result = ""
if let parametersType = method.parametersType {
for field in parametersType.fields {
if result != "" {
result += ", "
}
result += field.name + ":" + field.name
}
}
return result
}
func parametersTypeFields(_ value: Any?) -> [ServiceTypeField] {
let method : ServiceMethod = value as! ServiceMethod
if let parametersType = method.parametersType {
return parametersType.fields
} else {
return []
}
}
func kituraPath(_ value: Any?) -> String {
let method : ServiceMethod = value as! ServiceMethod
var path = method.path
if let parametersType = method.parametersType {
for field in parametersType.fields {
if field.position == "path" {
let original = "{" + field.jsonName + "}"
let replacement = ":" + field.jsonName
path = path.replacingOccurrences(of:original, with:replacement)
}
}
}
return path
}
func bodyParameterFieldName(_ value: Any?) -> String {
let method : ServiceMethod = value as! ServiceMethod
if let parametersType = method.parametersType {
for field in parametersType.fields {
if field.position == "body" {
return field.name
}
}
}
return ""
}
func responsesHasFieldNamedOK(_ value: Any?) -> Bool {
let method : ServiceMethod = value as! ServiceMethod
if let responsesType = method.responsesType {
for field in responsesType.fields {
if field.name == "ok" {
return true
}
}
}
return false
}
func responsesHasFieldNamedError(_ value: Any?) -> Bool {
let method : ServiceMethod = value as! ServiceMethod
if let responsesType = method.responsesType {
for field in responsesType.fields {
if field.name == "error" {
return true
}
}
}
return false
}
func lowercase(_ s : String) -> String {
return s.lowercased()
}

View File

@ -0,0 +1,106 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
// The I/O code below is derived from Apple's swift-protobuf project.
// https://github.com/apple/swift-protobuf
// BEGIN swift-protobuf derivation
#if os(Linux)
import Glibc
#else
import Darwin.C
#endif
enum PluginError: Error {
/// Raised for any errors reading the input
case readFailure
}
// Alias clib's write() so Stdout.write(bytes:) can call it.
private let _write = write
class Stdin {
static func readall() throws -> Data {
let fd: Int32 = 0
let buffSize = 32
var buff = [UInt8]()
while true {
var fragment = [UInt8](repeating: 0, count: buffSize)
let count = read(fd, &fragment, buffSize)
if count < 0 {
throw PluginError.readFailure
}
if count < buffSize {
buff += fragment[0..<count]
return Data(bytes: buff)
}
buff += fragment
}
}
}
class Stdout {
static func write(bytes: Data) {
bytes.withUnsafeBytes { (p: UnsafePointer<UInt8>) -> () in
_ = _write(1, p, bytes.count)
}
}
}
struct CodePrinter {
private(set) var content = ""
private var currentIndentDepth = 0
private var currentIndent = ""
private var atLineStart = true
mutating func print() {
print("")
}
mutating func print(_ text: String...) {
for t in text {
for c in t.characters {
if c == "\n" {
content.append(c)
atLineStart = true
} else {
if atLineStart {
content.append(currentIndent)
atLineStart = false
}
content.append(c)
}
}
}
content.append("\n")
atLineStart = true
}
mutating private func resetIndent() {
currentIndent = (0..<currentIndentDepth).map { Int -> String in return " " } .joined(separator:"")
}
mutating func indent() {
currentIndentDepth += 1
resetIndent()
}
mutating func outdent() {
currentIndentDepth -= 1
resetIndent()
}
}
// END swift-protobuf derivation

View File

@ -0,0 +1,57 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import Gnostic
func Log(_ message : String) {
FileHandle.standardError.write((message + "\n").data(using:.utf8)!)
}
func main() throws {
// read the code generation request
let rawRequest = try Stdin.readall()
let request = try Gnostic_Plugin_V1_Request(serializedData:rawRequest)
var response = Gnostic_Plugin_V1_Response()
if request.hasOpenapi2 && request.hasSurface {
let document = request.openapi2
let surface = request.surface
Log("\(request.surface)")
// build the service renderer
let renderer = ServiceRenderer(surface:surface, document:document)
// generate the desired files
var filenames : [String]
switch CommandLine.arguments[0] {
case "openapi_swift_client":
filenames = ["client.swift", "types.swift", "fetch.swift"]
case "openapi_swift_server":
filenames = ["server.swift", "types.swift"]
default:
filenames = ["client.swift", "server.swift", "types.swift", "fetch.swift"]
}
try renderer.generate(filenames:filenames, response:&response)
}
// return the results
let serializedResponse = try response.serializedData()
Stdout.write(bytes: serializedResponse)
}
try main()

View File

@ -0,0 +1,52 @@
#!/bin/sh
#
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Use this script to run protoc and swift-proto to generate
# support code for gnostic protos.
GNOSTIC=$GOPATH/src/github.com/googleapis/gnostic
PROTOS=(
plugins/plugin.proto
OpenAPIv2/OpenAPIv2.proto
OpenAPIv3/OpenAPIv3.proto
surface/surface.proto
discovery/discovery.proto
)
# remove old compiled pb files
rm -rf Sources/Gnostic/*.pb.swift
# remove any prior compilations
rm -rf Sources/Gnostic/github.com
# compile protos
for proto in "${PROTOS[@]}"
do
echo "COMPILING $proto"
protoc $GNOSTIC/$proto \
--swift_opt=Visibility=Public \
--swift_out=Sources/Gnostic \
--proto_path=$GOPATH/src
# relocate compiled protos
find Sources/Gnostic/github.com -name "*.pb.swift" -exec mv {} Sources/Gnostic \;
# remove scaffolding of compilation
rm -rf Sources/Gnostic/github.com
done

View File

@ -0,0 +1,9 @@
all:
rm -f gnostic-swift-generator
ln -s ../../gnostic-swift-generator
gnostic bookstore.json --swift-generator-out=Sources/Bookstore
swift build
test:
swift test

View File

@ -0,0 +1,26 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import PackageDescription
let package = Package(
name: "BookstoreExample",
targets: [
Target(name: "Server", dependencies: ["Bookstore"]),
],
dependencies: [
.Package(url: "https://github.com/IBM-Swift/Kitura.git", majorVersion: 1, minor: 7)
]
)

View File

@ -0,0 +1,22 @@
# Bookstore Example
This directory contains an OpenAPI description of a simple bookstore API.
Use this example to try the `openapi_swift_generator` plugin, which
generates Swift code that implements an API client and server for
an OpenAPI description.
Run `make all` to build and install `openapic` and the Swift plugin.
It will generate both client and server code. The API client and
server code will be in the `Sources/Bookstore` package.
The `Sources/Server` directory contains additional code that completes the server.
To build and run the server, do the following:
swift build
.build/debug/Server &
To test the service with the generated client, run `swift build`.
Tests are in the `Tests` directory and use client
code generated in `Bookstore` to verify the service.

View File

@ -0,0 +1,128 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Bookstore
class Server : Service {
private var shelves : [Int64:Shelf] = [:]
private var books : [Int64:[Int64:Book]] = [:]
private var lastShelfIndex : Int64 = 0
private var lastBookIndex : Int64 = 0
// Return all shelves in the bookstore.
func listShelves () throws -> ListShelvesResponses {
let responses = ListShelvesResponses()
let response = ListShelvesResponse()
var shelves : [Shelf] = []
for pair in self.shelves {
shelves.append(pair.value)
}
response.shelves = shelves
responses.ok = response
return responses
}
// Create a new shelf in the bookstore.
func createShelf (_ parameters : CreateShelfParameters) throws -> CreateShelfResponses {
lastShelfIndex += 1
let shelf = parameters.shelf
shelf.name = "shelves/\(lastShelfIndex)"
shelves[lastShelfIndex] = shelf
let responses = CreateShelfResponses()
responses.ok = shelf
return responses
}
// Delete all shelves.
func deleteShelves () throws {
shelves = [:]
books = [:]
lastShelfIndex = 0
lastBookIndex = 0
}
// Get a single shelf resource with the given ID.
func getShelf (_ parameters : GetShelfParameters) throws -> GetShelfResponses {
let responses = GetShelfResponses()
if let shelf : Shelf = shelves[parameters.shelf] {
responses.ok = shelf
} else {
let err = Error()
err.code = 404
err.message = "not found"
responses.error = err
}
return responses
}
// Delete a single shelf with the given ID.
func deleteShelf (_ parameters : DeleteShelfParameters) throws {
shelves[parameters.shelf] = nil
books[parameters.shelf] = nil
}
// Return all books in a shelf with the given ID.
func listBooks (_ parameters : ListBooksParameters) throws -> ListBooksResponses {
let responses = ListBooksResponses()
let response = ListBooksResponse()
var books : [Book] = []
if let shelfBooks = self.books[parameters.shelf] {
for pair in shelfBooks {
books.append(pair.value)
}
}
response.books = books
responses.ok = response
return responses
}
// Create a new book on the shelf.
func createBook (_ parameters : CreateBookParameters) throws -> CreateBookResponses {
let responses = CreateBookResponses()
lastBookIndex += 1
let shelf = parameters.shelf
let book = parameters.book
book.name = "shelves/\(shelf)/books/\(lastBookIndex)"
if var shelfBooks = self.books[shelf] {
shelfBooks[lastBookIndex] = book
self.books[shelf] = shelfBooks
} else {
var shelfBooks : [Int64:Book] = [:]
shelfBooks[lastBookIndex] = book
self.books[shelf] = shelfBooks
}
responses.ok = book
return responses
}
// Get a single book with a given ID from a shelf.
func getBook (_ parameters : GetBookParameters) throws -> GetBookResponses {
let responses = GetBookResponses()
if let shelfBooks = self.books[parameters.shelf],
let book = shelfBooks[parameters.book] {
responses.ok = book
} else {
let err = Error()
err.code = 404
err.message = "not found"
responses.error = err
}
return responses
}
// Delete a single book with a given ID from a shelf.
func deleteBook (_ parameters : DeleteBookParameters) throws {
if var shelfBooks = self.books[parameters.shelf] {
shelfBooks[parameters.book] = nil
self.books[parameters.shelf] = shelfBooks
}
}
}
initialize(service:Server(), port:8080)
run()

View File

@ -0,0 +1,208 @@
/*
*
* Copyright 2017, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
import XCTest
import Foundation
@testable import Bookstore
func Log(_ message : String) {
FileHandle.standardError.write((message + "\n").data(using:.utf8)!)
}
let service = "http://localhost:8080"
class BookstoreTests: XCTestCase {
func testBasic() {
// create a client
let b = Bookstore.Client(service:service)
Log("// reset the service by deleting all shelves")
do {
try b.deleteShelves()
} catch (let error) {
XCTFail("\(error)")
}
Log("// verify that the service has no shelves")
do {
let response = try b.listShelves()
XCTAssertEqual(response.shelves.count, 0)
} catch (let error) {
XCTFail("\(error)")
}
Log("// attempting to get a shelf should return an error")
do {
let _ = try b.getShelf(shelf:1)
XCTFail("server error")
} catch {
}
Log("// attempting to get a book should return an error")
do {
let _ = try b.getBook(shelf:1, book:2)
} catch {
}
Log("// add a shelf")
do {
let shelf = Shelf()
shelf.theme = "mysteries"
let response = try b.createShelf(shelf:shelf)
if (response.name != "shelves/1") ||
(response.theme != "mysteries") {
XCTFail("mismatch")
}
} catch (let error) {
XCTFail("\(error)")
}
Log("// add another shelf")
do {
let shelf = Shelf()
shelf.theme = "comedies"
let response = try b.createShelf(shelf:shelf)
if (response.name != "shelves/2") ||
(response.theme != "comedies") {
XCTFail("mismatch")
}
} catch (let error) {
XCTFail("\(error)")
}
Log("// get the first shelf that was added")
do {
let response = try b.getShelf(shelf:1)
if (response.name != "shelves/1") ||
(response.theme != "mysteries") {
XCTFail("mismatch")
}
} catch (let error) {
XCTFail("\(error)")
}
Log("// list shelves and verify that there are 2")
do {
let response = try b.listShelves()
XCTAssertEqual(response.shelves.count, 2)
} catch (let error) {
XCTFail("\(error)")
}
Log("// delete a shelf")
do {
try b.deleteShelf(shelf:2)
} catch (let error) {
XCTFail("\(error)")
}
Log("// list shelves and verify that there is only 1")
do {
let response = try b.listShelves()
XCTAssertEqual(response.shelves.count, 1)
} catch (let error) {
XCTFail("\(error)")
}
Log("// list books on a shelf, verify that there are none")
do {
let response = try b.listBooks(shelf:1)
XCTAssertEqual(response.books.count, 0)
} catch (let error) {
XCTFail("\(error)")
}
Log("// create a book")
do {
let book = Book()
book.author = "Agatha Christie"
book.title = "And Then There Were None"
let _ = try b.createBook(shelf:1, book:book)
} catch (let error) {
XCTFail("\(error)")
}
Log("// create another book")
do {
let book = Book()
book.author = "Agatha Christie"
book.title = "Murder on the Orient Express"
let _ = try b.createBook(shelf:1, book:book)
} catch (let error) {
XCTFail("\(error)")
}
Log("// get the first book that was added")
do {
let response = try b.getBook(shelf:1, book:1)
if (response.author != "Agatha Christie") ||
(response.title != "And Then There Were None") {
XCTFail("mismatch")
}
} catch (let error) {
XCTFail("\(error)")
}
Log("// list the books on a shelf and verify that there are 2")
do {
let response = try b.listBooks(shelf:1)
XCTAssertEqual(response.books.count, 2)
} catch (let error) {
XCTFail("\(error)")
}
Log("// delete a book")
do {
try b.deleteBook(shelf:1, book:2)
} catch (let error) {
XCTFail("\(error)")
}
Log("// list the books on a shelf and verify that is only 1")
do {
let response = try b.listBooks(shelf:1)
XCTAssertEqual(response.books.count, 1)
} catch (let error) {
XCTFail("\(error)")
}
Log("// verify the handling of a badly-formed request")
var path = service
path = path + "/shelves"
guard let url = URL(string:path) else {
XCTFail("Failed to construct URL")
return
}
var request = URLRequest(url:url)
request.httpMethod = "POST"
request.httpBody = "".data(using:.utf8)
let (_, response, _) = fetch(request)
// we expect a 400 (Bad Request) code
if let response = response {
XCTAssertEqual(response.statusCode, 400)
} else {
// Failed requests are returning nil responses on Linux. For now we'll say that is OK.
//XCTFail("Null response for bad request")
}
}
}
extension BookstoreTests {
static var allTests : [(String, (BookstoreTests) -> () throws -> Void)] {
return [
("testBasic", testBasic),
]
}
}

View File

@ -0,0 +1,38 @@
/*
*
* Copyright 2017, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
import XCTest
@testable import BookstoreTests
XCTMain([
testCase(BookstoreTests.allTests),
])

View File

@ -0,0 +1,357 @@
{
"swagger": "2.0",
"info": {
"description": "A simple Bookstore API example.",
"title": "Bookstore",
"version": "1.0.0"
},
"host": "generated-bookstore.appspot.com",
"basePath": "/",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"schemes": [
"https"
],
"paths": {
"/shelves": {
"get": {
"description": "Return all shelves in the bookstore.",
"operationId": "listShelves",
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "List of shelves in the bookstore.",
"schema": {
"$ref": "#/definitions/listShelvesResponse"
}
}
},
"security": [
]
},
"post": {
"description": "Create a new shelf in the bookstore.",
"operationId": "createShelf",
"parameters": [
{
"description": "A shelf resource to create.",
"in": "body",
"name": "shelf",
"required": true,
"schema": {
"$ref": "#/definitions/shelf"
}
}
],
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "A newly created shelf resource.",
"schema": {
"$ref": "#/definitions/shelf"
}
}
}
},
"delete": {
"description": "Delete all shelves.",
"operationId": "deleteShelves",
"responses": {
"default": {
"description": "An empty response body."
}
}
}
},
"/shelves/{shelf}": {
"get": {
"description": "Get a single shelf resource with the given ID.",
"operationId": "getShelf",
"parameters": [
{
"description": "ID of the shelf to get.",
"format": "int64",
"in": "path",
"name": "shelf",
"required": true,
"type": "integer"
}
],
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "A shelf resource.",
"schema": {
"$ref": "#/definitions/shelf"
}
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "#/definitions/Error"
}
}
}
},
"delete": {
"description": "Delete a single shelf with the given ID.",
"operationId": "deleteShelf",
"parameters": [
{
"description": "ID of the shelf to delete.",
"format": "int64",
"in": "path",
"name": "shelf",
"required": true,
"type": "integer"
}
],
"responses": {
"default": {
"description": "An empty response body."
}
}
}
},
"/shelves/{shelf}/books": {
"get": {
"description": "Return all books in a shelf with the given ID.",
"operationId": "listBooks",
"parameters": [
{
"description": "ID of the shelf whose books should be returned.",
"format": "int64",
"in": "path",
"name": "shelf",
"required": true,
"type": "integer"
}
],
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "List of books on the specified shelf.",
"schema": {
"$ref": "#/definitions/listBooksResponse"
}
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "#/definitions/Error"
}
}
}
},
"post": {
"description": "Create a new book on the shelf.",
"operationId": "createBook",
"parameters": [
{
"description": "ID of the shelf where the book should be created.",
"format": "int64",
"in": "path",
"name": "shelf",
"required": true,
"type": "integer"
},
{
"description": "Book to create.",
"in": "body",
"name": "book",
"required": true,
"schema": {
"$ref": "#/definitions/book"
}
}
],
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "A newly created book resource.",
"schema": {
"$ref": "#/definitions/book"
}
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "#/definitions/Error"
}
}
}
}
},
"/shelves/{shelf}/books/{book}": {
"get": {
"description": "Get a single book with a given ID from a shelf.",
"operationId": "getBook",
"parameters": [
{
"description": "ID of the shelf from which to get the book.",
"format": "int64",
"in": "path",
"name": "shelf",
"required": true,
"type": "integer"
},
{
"description": "ID of the book to get from the shelf.",
"format": "int64",
"in": "path",
"name": "book",
"required": true,
"type": "integer"
}
],
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "A book resource.",
"schema": {
"$ref": "#/definitions/book"
}
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "#/definitions/Error"
}
}
}
},
"delete": {
"description": "Delete a single book with a given ID from a shelf.",
"operationId": "deleteBook",
"parameters": [
{
"description": "ID of the shelf from which to delete the book.",
"format": "int64",
"in": "path",
"name": "shelf",
"required": true,
"type": "integer"
},
{
"description": "ID of the book to delete from the shelf.",
"format": "int64",
"in": "path",
"name": "book",
"required": true,
"type": "integer"
}
],
"responses": {
"default": {
"description": "An empty response body."
}
}
}
}
},
"definitions": {
"book": {
"properties": {
"author": {
"type": "string"
},
"name": {
"type": "string"
},
"title": {
"type": "string"
}
},
"required": [
"name",
"author",
"title"
]
},
"listBooksResponse": {
"properties": {
"books": {
"items": {
"$ref": "#/definitions/book"
},
"type": "array"
}
},
"required": [
"books"
],
"type": "object"
},
"listShelvesResponse": {
"properties": {
"shelves": {
"items": {
"$ref": "#/definitions/shelf"
},
"type": "array"
}
},
"type": "object"
},
"shelf": {
"properties": {
"name": {
"type": "string"
},
"theme": {
"type": "string"
}
},
"required": [
"name",
"theme"
]
},
"error": {
"required": [
"code",
"message"
],
"properties": {
"code": {
"type": "integer",
"format": "int32"
},
"message": {
"type": "string"
}
}
}
},
"security": [
{
"api_key": [
]
}
],
"securityDefinitions": {
"api_key": {
"in": "query",
"name": "key",
"type": "apiKey"
}
}
}