Git Product home page Git Product logo

swaggen's Issues

SwageGen No such module 'Result'

When i try to generate the code for my swagger url, It generates a file called APIResult.Swift which looks like this

import Result

public typealias APIResult<T> = Result<T, APIError>

Compiler gives me error that

No such module 'Result'

If i replace import Result with import Alamofire the error changes to

Generic type 'Result' specialized with too many type parameters (got 2, but expected 1)

here is my URL from which i am generating the code

http://relatr-dev.westeurope.cloudapp.azure.com:8080/swagger/v1/swagger.json

additionalProperties support

Needs support for additionalProperties (part of the OpenAPI specification). The official Swagger Codegen for Swift has some support for additionalProperties but would be great to see the same support in this project (as the code generated is so much nicer).

NB additionalProperties need to be supported in many cases:

  1. Classes with no static properties but additionalProperties
  2. Classes with both static and additionalProperties
  3. Classes that are inheriting from classes with additionalProperties and vice versa.

https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#schemaObject

Not generate Path Params if parameters are defined in path dictionary

I noticed that you didn't parse Path parameters in class Endpoint. Below is Instagram API I got from Swagger Editor.

Solution: Should we replace path: String by path: Path where Path is a class/struct?
OTW, I was wonder why do you use class instead of struct. Maybe for creating other generators for other languages by inheritance?

YAML:

paths:
  /users/{user-id}:
    parameters:
      - $ref: '#/parameters/user-id'
    get:
      security:
        - key: []
        - oauth:
          - basic
      tags:
        - Users
      description: Get basic information about a user.
     
  /media/{media-id}:
    parameters:
      - name: media-id
        in: path
        description: The media ID
        type: integer
        required: true
    get:
      tags:
        - Media
      description: |
        Get information about a media object.
        The returned type key will allow you to differentiate between `image`
        and `video` media.

Use StencilSwiftKit instead of Stencil

I use stencils in Sourcery and Swiftgen and I miss some nice additions from StencilSwiftKit.
It would be really cool if SwagGen could use it. This would introduce some nice additions for custom templates like macro, set and some nice string filters.

I saw that you use your own version of Stencil to add some feature to the include node. It may not be feasible but this is at least for your information in case you did not know it existed 😉

Build Error: (aka 'ContiguousArray<Int8>') has no member 'withUnsafeMutableBytes'

Hi yonaskolb,

You do a great job. But I met some build error when I build swagGen

My env is

Mac OS X EI Capitan 10.11.6
Xcode 8.0 (8A218a)
$ swift --version
Apple Swift version 3.0 (swiftlang-800.0.46.2 clang-800.0.38)
Target: x86_64-apple-macosx10.9

The error log is:

$ swift build
Cloning https://github.com/kylef/PathKit.git
HEAD is now at 4597ab8 Release 0.7.0
Resolved version: 0.7.0
Cloning https://github.com/kylef/Spectre
HEAD is now at e46b75c chore: Release 0.7.2
Resolved version: 0.7.2
Cloning https://github.com/kylef/Commander.git
HEAD is now at 9304bbf chore: Release 0.6.0
Resolved version: 0.6.0
Cloning https://github.com/yonaskolb/Stencil.git
HEAD is now at ffd8804 added tests
Resolved version: 0.7.3
Cloning https://github.com/jpsim/Yams.git
HEAD is now at 71e81e9 release 0.2.0
Resolved version: 0.2.0
Cloning https://github.com/lucianomarisi/JSONUtilities.git
HEAD is now at a7aa1d6 Merge pull request #10 from lucianomarisi/chore/prepare-for-3.2.0-release
Resolved version: 3.2.0
Compile CYaml src/writer.c
Compile CYaml src/scanner.c
Compile CYaml src/reader.c
Compile CYaml src/parser.c
Compile CYaml src/loader.c
Compile CYaml src/emitter.c
Compile CYaml src/dumper.c
Compile CYaml src/api.c
Compile Swift Module 'JSONUtilities' (8 sources)
Compile Swift Module 'Spectre' (8 sources)
Linking CYaml
Compile Swift Module 'Yams' (9 sources)
Compile Swift Module 'PathKit' (1 sources)
Compile Swift Module 'Commander' (9 sources)
Compile Swift Module 'Stencil' (19 sources)
/Users/secwit/Code/SwagGen/Packages/Yams-0.2.0/Sources/Yams/Emitter.swift:324:13: error: value of type 'ContiguousArray<CChar>' (aka 'ContiguousArray<Int8>') has no member 'withUnsafeMutableBytes'
        _ = value.withUnsafeMutableBytes { value in
            ^~~~~ ~~~~~~~~~~~~~~~~~~~~~~
/Users/secwit/Code/SwagGen/Packages/Yams-0.2.0/Sources/Yams/Emitter.swift:346:13: error: value of type 'ContiguousArray<CChar>' (aka 'ContiguousArray<Int8>') has no member 'withUnsafeMutableBytes'
        _ = tag.withUnsafeMutableBytes { tag in
            ^~~ ~~~~~~~~~~~~~~~~~~~~~~
/Users/secwit/Code/SwagGen/Packages/Yams-0.2.0/Sources/Yams/Emitter.swift:367:13: error: value of type 'ContiguousArray<CChar>' (aka 'ContiguousArray<Int8>') has no member 'withUnsafeMutableBytes'
        _ = tag.withUnsafeMutableBytes { tag in
            ^~~ ~~~~~~~~~~~~~~~~~~~~~~
/Users/secwit/Code/SwagGen/Packages/Yams-0.2.0/Sources/Yams/Parser.swift:130:9: error: value of type 'ContiguousArray<CChar>' (aka 'ContiguousArray<Int8>') has no member 'withUnsafeBytes'
        utf8CString.withUnsafeBytes { bytes in
        ^~~~~~~~~~~ ~~~~~~~~~~~~~~~
/Users/secwit/Code/SwagGen/Packages/Stencil-0.7.3/Sources/Loader.swift:55:14: warning: no calls to throwing functions occur within 'try' expression
      return try environment.templateClass.init(templateString: content, environment: environment, name: name)
             ^
/Users/secwit/Code/SwagGen/Packages/Stencil-0.7.3/Sources/Loader.swift:68:18: warning: no calls to throwing functions occur within 'try' expression
          return try environment.templateClass.init(templateString: content, environment: environment, name: templateName)
                 ^
<unknown>:0: error: build had 1 command failures
error: exit(1): /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift-build-tool -f /Users/secwit/Code/SwagGen/.build/debug.yaml

Homebrew install fails

Reproducible failure when trying to install via Homebrew.

(install via git clone, make succeeded)

> brew install SwagGen
==> Installing SwagGen from yonaskolb/swaggen
==> Downloading https://github.com/yonaskolb/SwagGen/archive/2.1.0.tar.gz
Already downloaded: /Users/erwin/Library/Caches/Homebrew/SwagGen-2.1.0.tar.gz
==> make install PREFIX=/usr/local/Cellar/SwagGen/2.1.0
Last 15 lines from /Users/erwin/Library/Logs/Homebrew/SwagGen/01.make:
Cloning https://github.com/kylef/PathKit.git
Resolving https://github.com/kylef/PathKit.git at 0.8.0
Cloning https://github.com/onevcat/Rainbow.git
Resolving https://github.com/onevcat/Rainbow.git at 2.1.0
Cloning https://github.com/kylef/Spectre.git
Resolving https://github.com/kylef/Spectre.git at 0.7.2
Cloning https://github.com/jpsim/Yams.git
Resolving https://github.com/jpsim/Yams.git at 0.5.0
Cloning https://github.com/yonaskolb/JSONUtilities.git
Resolving https://github.com/yonaskolb/JSONUtilities.git at 3.3.8
Cloning https://github.com/jakeheis/SwiftCLI
Resolving https://github.com/jakeheis/SwiftCLI at 5.0.0
Cloning https://github.com/yonaskolb/Stencil.git
Resolving https://github.com/yonaskolb/Stencil.git at 0.9.3
make: *** [build] Error 1

If reporting this issue please do so to (not Homebrew/brew or Homebrew/core):
yonaskolb/swaggen

/usr/local/Homebrew/Library/Homebrew/utils/github.rb:220:in `raise_api_error': curl failed!  (GitHub::Error)
curl: (22) The requested URL returned error: 422 Unprocessable Entity
curl: (3) <url> malformed
	from /usr/local/Homebrew/Library/Homebrew/utils/github.rb:178:in `open_api'
	from /usr/local/Homebrew/Library/Homebrew/utils/github.rb:292:in `search'
	from /usr/local/Homebrew/Library/Homebrew/utils/github.rb:225:in `search_issues'
	from /usr/local/Homebrew/Library/Homebrew/utils/github.rb:238:in `issues_for_formula'
	from /usr/local/Homebrew/Library/Homebrew/exceptions.rb:368:in `fetch_issues'
	from /usr/local/Homebrew/Library/Homebrew/exceptions.rb:364:in `issues'
	from /usr/local/Homebrew/Library/Homebrew/exceptions.rb:418:in `dump'
	from /usr/local/Homebrew/Library/Homebrew/brew.rb:133:in `rescue in <main>'
	from /usr/local/Homebrew/Library/Homebrew/brew.rb:25:in `<main>'

Invalid version error

With the latest master source, I get an "Invalid Version" error message even though the code clearly checks for version 2 and my speck is "swagger": "2.0".

File: SwaggerSpec.swift line 84-88

version = String(describing: jsonDictionary["swagger"])
if let swaggerVersion = Double(version),
floor(swaggerVersion) != 2 {
throw SwaggerError.invalidVersion(version)
}

Not return allProperties

Seem that, current generator didn't return all model's properties as expected. When I user allProperties it return parentProperties only:

Expected:

context["allProperties"] = schema.properties.map(getPropertyContext) + schema.parentProperties.map(getPropertyContext)

Actual:

context["allProperties"] = schema.parentProperties.map(getPropertyContext)

Generate Mocks

Generate mocks for models and requests.
Can make use of swagger's example field for this as well

Bundle templates

Bundle the templates when installing and allow those templates as a default template for a language.
So instead of passing --template Templates/Swift/template.yml you can pass --language swift

Switch statement must have at least...

'switch' statement body must have at least one 'case' or 'default' block

ActivateCreate.swift

extension API.Auth { 
....
public enum Response: APIResponseValue, CustomStringConvertible, CustomDebugStringConvertible {
            public typealias SuccessType = Void

            public var success: Void? {
                switch self {
                }
            }

Type name overrides

The template options can provide some dictionaries to override model or request type names

Logo Design: SwagGen

Hey, I examined your project and realized that your project has no logo design yet. What do you think about it? If you interested I can contribute on your project with making logo design. Actually my main aims are supporting open source projects and make my portfolio better. I am waiting your feedback and if you have an idea we can talk about design decisions. Have a nice day! :)

Best Regards,
Baran Pirincal
Visual Communication Designer

Not able to build SwagGen locally

I am trying to build SwagGen locally via command line (I have XCode8 installed).
Build is failing with following errors.

➜ SwagGen git:(master) swift build -c release Linking CYaml Compile Swift Module 'JSONUtilities' (8 sources) Compile Swift Module 'Spectre' (8 sources) Compile Swift Module 'Yams' (9 sources) /Users/sankalas/SwapnilSankla-backup/Delta/SwagGen/Packages/Yams-0.2.0/Sources/Yams/Emitter.swift:324:13: error: value of type 'ContiguousArray<CChar>' (aka 'ContiguousArray<Int8>') has no member 'withUnsafeMutableBytes' _ = value.withUnsafeMutableBytes { value in ^~~~~ ~~~~~~~~~~~~~~~~~~~~~~ /Users/sankalas/SwapnilSankla-backup/Delta/SwagGen/Packages/Yams-0.2.0/Sources/Yams/Emitter.swift:346:13: error: value of type 'ContiguousArray<CChar>' (aka 'ContiguousArray<Int8>') has no member 'withUnsafeMutableBytes' _ = tag.withUnsafeMutableBytes { tag in ^~~ ~~~~~~~~~~~~~~~~~~~~~~ /Users/sankalas/SwapnilSankla-backup/Delta/SwagGen/Packages/Yams-0.2.0/Sources/Yams/Emitter.swift:367:13: error: value of type 'ContiguousArray<CChar>' (aka 'ContiguousArray<Int8>') has no member 'withUnsafeMutableBytes' _ = tag.withUnsafeMutableBytes { tag in ^~~ ~~~~~~~~~~~~~~~~~~~~~~ /Users/sankalas/SwapnilSankla-backup/Delta/SwagGen/Packages/Yams-0.2.0/Sources/Yams/Parser.swift:130:9: error: value of type 'ContiguousArray<CChar>' (aka 'ContiguousArray<Int8>') has no member 'withUnsafeBytes' utf8CString.withUnsafeBytes { bytes in ^~~~~~~~~~~ ~~~~~~~~~~~~~~~ <unknown>:0: error: build had 1 command failures error: exit(1): /Users/sankalas/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift-build-tool -f /Users/sankalas/SwapnilSankla-backup/Delta/SwagGen/.build/release.yaml

Support numbers in references

Hi,

I have a problem with the generator, I get this error message: Fatal error: Reference #/responses/400 is unresolved: file /SwagGen/Sources/Swagger/Reference.swift, line 10

The problem is, that I have some references, which are numbers, so imagine the following:

'/application/{applicationId}/cob':
    post:
      summary: Lets a user to enter his country of birth
      consumes:
        - application/x-www-form-urlencoded
      parameters:
        - $ref: '#/parameters/applicationId_pathParam'
        - name: cob
          in: formData
          description: Country of birth parameter in ISO 3166-1 alpha-2
          type: string
          required: true
      responses:
        '200':
          description: 'Succesfully added country of birth param to {applicationId}'
        '400':
          $ref: '#/responses/400'
        '500':
          $ref: '#/responses/500'

The references are:

responses:
  '400':
    description: Validation error
    schema:
      type: array
      items:
        $ref: '#/definitions/BadRequestResponse'
  '404':
    description: Not found
  '500':
    description: Internal error
  '501':
    description: Not implemented yet
  '503':
    description: Service unavailable

This is not working. If I modify 400 to Code400 for instance, the generation is working as expected.

Ps: I also changed the responses reference name to responseCode reference name as I thought before that the problem is that the responses name is special, but the problem persisted, so the problem is the numbers.

Thanks!!

Question: Specify Api Routes

Hey yonaskolb!

First off, really great project. I love SwagGen and the fact that I can now use a native app generating my models and requests plus using Stencil which I really love.

A quick question: Is it possible to specify only the routes or models which should be generated?
Similar to Swagger Codegens -Dmodels {opts}, -Dapis {opts} flags?

That would be great!
Keep up the good work.

Kind regards

PS: Stencil has been updated and now allow % elif %. Would be great if you could update the dependencies. Perhaps even not constraining them to an exact version but e.g. specifying the major version ;-)

Swift template: remove Alamofire?

Once #32 is complete, it will remove the JSONUtilities dependency.
Is it worth removing the Alamofire dependency as well, which would make the generated code dependency free.

Would anyone miss the Alamofire integration? Is anyone hooking into it, or just using the plain ApiClient?

Support inline schemas for parameters

Support inline schemas in parameters which don't reference a definition.

For Swift these should be generated in the scope of the containing object. ie within the Request

[Question] Group API Endpoints by tags

Hi, first of all, thanks for your great work.

I'm working on creating RxSwift + Moya Swift template for Swagger. It worked perfectly after some modifications in Swift3 Codegen. I can finally make a PR but it is painful with inconsistent Java coding conventions, complex codebase.

Luckily, I found your awesome library while finalizing my code before making a PR (after nearly 2 months pending). I can easily understand your codes and implementing task #8. I will submit a PR after I finished.

But I have a question: It is possible to groups API Endpoints by their tags then put them in one file for example: Fake.swift, Pet.swift, Store.swift, User.swift? I see your suggestion in #5 but couldn't find a solution for my case.

Simple responses

The swift template can have an option for simple responses. This would do away with each request decoding it's own error responses and make the completion handler of the APIClient a simple Result of either success response or APIError

Custom URL Class in APIClient

A custom URL class that completely overrides but does not inherit from the Swift URL class
making line 145 of the APICLient class
let url = URL(string: "\(baseURL)\(path)")!
not compile.

also the isEqual(to:) of the classModelAndView.swift
guard self.modelMap == object.modelMap else { return false }
has an error "Expression type 'Bool' is ambiguous without more context"

is it a setting I forgot?

Unused public struct Options

I have generated the code for my Swagger... In the generated code there are struct Options are generated for header field

that option are nowhere being set in the header anywhere.

to initialise the request those value in option are required which is not being set in header field.

Also i think those value should not be required in creating request

My swagger yml is at http://relatr-dev.westeurope.cloudapp.azure.com:8080/swagger/

You can refer the Signup request in which languageCode: and appVersion are required parameters for creating requesting but those are header parameters

Cannot generate Endpoint if Swagger Spec doesn't have any tag

template.yml

- path: request.swift
  context: tags

If Swagger Spec doesn't define any tag, SwagGen couldn't generate API Endpoint with above configuration.

  • Actual implementation: Return empty dictionary when tags is empty:
    public var opererationsByTag: [String: [Operation]] {
        var dictionary: [String: [Operation]] = [:]

        for tag in tags {
            dictionary[tag] = operations.filter { $0.tags.contains(tag) }
        }
        return dictionary
}
  • Expected: Return Dictionary with all Operations for 1 default key:
    public var opererationsByTag: [String: [Operation]] {
        var dictionary: [String: [Operation]] = [:]

        if tags.isEmpty {
            let defaultEndpointName = info.title.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
            dictionary[defaultEndpointName] = operations
            return dictionary
        }

        for tag in tags {
            dictionary[tag] = operations.filter { $0.tags.contains(tag) }
        }
        return dictionary
}

Cococapods podspec

Hi,

I found an other issue with the podspec, there's a dependency to an other library:
s.dependency 'JSONUtilities', '~> 3.3.8'
The error is: None of your spec sources contain a spec satisfying the dependency: 'JSONUtilities (~> 3.3.8)'.

I tried 3.2.0 and also without locking the version, so it would use 5.0.0 but both of them are breaking the generated code. This is the associated library: https://cocoapods.org/?q=jsonutilities

It seems they never had a version 3.3.8 :/

Question: Generated Code Structure and logic

Hi, after the code is generated, where do I start using it?
There is no clear path to start using the API generated with your tool, could you possibly explain the generated architecture and logic of calls to the back end?

a sample would be greatly appreciated.

Regards.

SwiftFormatter doesn't make use of IntegerItem.format to support Int32 and Int64

Swagger provides the field format for integer types to distinguish between int32 and int64 (https://swagger.io/specification/#dataTypeFormat). This field is parsed in IntegerItem, though the SwiftFormatter ignores it and uses always Int as Swift type.
This can lead to loss of data, e.g. when Swagger specification contains int32 and generated code is running on device with 64-bit architecture. Putting a value bigger than int32 max into the field will result in a wrong value on receivers side.

unknown argument: '--disable-sandbox' in homebrew

Hi there,
I'm getting:
:0: error: unknown argument: '--disable-sandbox'
after running:
brew tap yonaskolb/SwagGen https://github.com/yonaskolb/SwagGen.git
brew install SwagGen

This is due to the command:
swift --disable-sandbox build -c release -Xswiftc -static-stdlib

swift -version output:
Apple Swift version 4.0.3 (swiftlang-900.0.74.1 clang-900.0.39.2)
Target: x86_64-apple-macosx10.9

xcode version 9.2

Any idea why?
Thank you!

Readme examples

Can we get some examples added to readme to kickstart using this? How to make an API request, specify parameters and return a User model perhaps?

Compile Errors in project

I was using Swagger codegen until recently. I had encountered error. I tried to generate files from SwagGen. I downloaded the repo project and created xcodeproj using this command in terminal "swift package generate-xcodeproj".
I opened the project but i had some compile time errors in Sources/SwagGenKit/Utilities.swift

"/Users/next/Downloads/SwagGen-master/Sources/SwagGenKit/Utilities.swift:11:32: Same-type requirement makes generic parameter 'Key' non-generic"

Did i do something wrong in the installation process? I created a script file in folder and tried to run the script file but i got "Swag: command not found". Please guide me

Add downstream changes

Hi @Liquidsoul, I've noticed you've made some useful changes in your fork. Would you be open to submitting some of the general ones back into this repo via one or more PR's?

Malformed operationId

When generating code for https://api.closely.io/v1/location/swagger.json the operationId is generated malformed for several requests.

Example:

PUT request for the resource http://host/v1/location/{project}/devices/{device}"

Expected operationId:
putV1LocationByProjectByDevices

Actual operationId:
putV1LocationByProject}Devices{device

Enum case names

All caps Snakecase enum cases are not properly formatted. An enum with the value of PAYMENT_REQUEST gets generated as:

case paymentrequest = "PAYMENT_REQUEST"

When it should be

case paymentRequest = "PAYMENT_REQUEST"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.