Skip to content

Cannot reference other specs in the same directory #400

Closed
sebgl/oapi-codegen
#1

Description

@ifross89

I am trying to split my specs into multiple files in order be able to produce different output files within the same package. As oapi-codegen considers any external file reference to be an "externalRef" I must supply an import mapping for this. As the generated files are in the same package this leads to attempting to import the current package which is not allowed in go.

Here is an example that reproduces the issue:

  • a.yaml:
openapi: 3.0.0
info:
  title: a
  version: 0.0.1
paths: {}
components:
  schemas:
    A:
      properties:
        foo:
          type: string
  • b.yaml
openapi: 3.0.0
info:
  title: b
  version: 0.0.1
paths: {}
components:
  schemas:
    B:
      $ref: a.yaml#/components/schemas/A

Without import mapping supplied:

$ oapi-codegen -package scratch -generate types,skip-prune b.yaml > b.gen.go
error generating code: error generating type definitions: error generating Go types for component schemas: error converting Schema B to Go type: error turning reference (a.yaml#/components/schemas/A) into a Go type: unrecognized external reference 'a.yaml'; please provide the known import for this reference using option --import-mapping

With import mapping supplied:

$ oapi-codegen -import-mapping a.yaml:scratch -package scratch -generate types,skip-prune b.yaml > b.gen.go
$ go build
package scratch
        imports scratch: import cycle not allowed

I was able to get this working modifying codegen/utils.go to check whether a remote component referred to a file within the same directory & treating it as a local ref. I was wondering if you would like me to make a PR to fix this.
Thanks

Activity

  1. duffn commented on Aug 28, 2021

    @duffn

    I'm running into this right now and would personally love to see a PR to fix this.

  2. sebgl commented on Sep 7, 2021

    @sebgl

    I'm experimenting here with an approach where any remote reference with no corresponding import mapping translates to just importing the local Go type (GoType rather than path.GoType): sebgl#1.

    Works well for my use case but I guess it could be dangerous if users mess up their import mapping (or forget to add one)? Happy to open a PR here if folks think it's an acceptable approach.

  3. DominikBasnerSotec commented on Oct 1, 2021

    @DominikBasnerSotec

    Any update on this? I would like to put all schemas from components/schemas into a separate file but also tumble over this issue

  4. ysulyma commented on Jun 20, 2023

    @ysulyma

    Just encountered this—a PR from either @ifross89 or @sebgl would be highly appreciated!

  5. philous commented on Sep 18, 2023

    @philous

    Having the same issue, would be great to be able to reference external files

  6. added 4 commits that reference this issue on Oct 20, 2023
  7. djgilcrease commented on Oct 20, 2023

    @djgilcrease
    Contributor

    from the origional example, to use my fix you would do
    oapi-codegen -import-mapping a.yaml:* -package scratch -generate types,skip-prune b.yaml > b.gen.go

  8. borod108 commented on Mar 14, 2024

    @borod108

    I am trying to split a long yaml as well, I wonder if there is a work around? I currently just generate the "a.yaml" into a separate package, but it does not really make any sense. I saw #1331, is it gonna be merged soon?
    Is there a different way to split the yaml without using external ref?

  9. LinYunling commented on Sep 29, 2024

    @LinYunling

    I use 2.3.0 version, but this problem is also exists.
    image

    The command line:

    oapi-codegen -import-mapping ../../../api/models/basemodel_definition.yaml:* -config ../../../api/metrics_codegen_config.yaml ../../../api/metrics_api_definition.yaml 

    Report the error:
    image

    The basemodel_definition.yaml file:

    openapi: 3.0.0
    info:
      title: Base Model Definition
      version: 1.0.0
    paths: {}
    components:
      schemas:
        errorInfo:
          type: object
          properties:
            retCode: 
              type: integer
            retMessage:
              type: string
            retDetail:
              type: string

    The metrics_api_definition.yaml file:

    openapi: "3.0.0"
    info:
      version: 1.0.0
      title: get metrics
    paths:
      /api/v1/metrics:
        get:
          responses:
            "404":
              content:
                application/json:
                  schema:
                    $ref: "./basemodel_definition.yaml#/components/schemas/errorInfo"

    The metrics_codegen_config.yaml file:

    # yaml-language-server: $schema=./configuration_schema.json
    package: metrics
    output: metrics_gen.go
    generate:
      models: true
      gin-server: true

    The configuration_schema.json file:

    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "description": "Configuration files for oapi-codegen",
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "package": {
          "type": "string",
          "description": "Go package name to generate the code under"
        },
        "generate": {
          "type": "object",
          "additionalProperties": false,
          "description": "Generate specifies which supported output formats to generate",
          "properties": {
            "iris-server": {
              "type": "boolean",
              "description": "IrisServer specifies whether to generate iris server boilerplate"
            },
            "chi-server": {
              "type": "boolean",
              "description": "ChiServer specifies whether to generate chi server boilerplate"
            },
            "fiber-server": {
              "type": "boolean",
              "description": "FiberServer specifies whether to generate fiber server boilerplate"
            },
            "echo-server": {
              "type": "boolean",
              "description": "EchoServer specifies whether to generate echo server boilerplate"
            },
            "gin-server": {
              "type": "boolean",
              "description": "GinServer specifies whether to generate gin server boilerplate"
            },
            "gorilla-server": {
              "type": "boolean",
              "description": "GorillaServer specifies whether to generate Gorilla server boilerplate"
            },
            "std-http-server": {
              "type": "boolean",
              "description": "StdHTTPServer specifies whether to generate stdlib http server boilerplate"
            },
            "strict-server": {
              "type": "boolean",
              "description": "Strict specifies whether to generate strict server wrapper"
            },
            "client": {
              "type": "boolean",
              "description": "Client specifies whether to generate client boilerplate"
            },
            "models": {
              "type": "boolean",
              "description": "Models specifies whether to generate type definitions"
            },
            "embedded-spec": {
              "type": "boolean",
              "description": "EmbeddedSpec indicates whether to embed the swagger spec in the generated code"
            }
          }
        },
        "compatibility": {
          "type": "object",
          "additionalProperties": false,
          "description": "",
          "properties": {
            "old-merge-schemas": {
              "type": "boolean",
              "description": "In the past, we merged schemas for `allOf` by inlining each schema within the schema list. This approach, though, is incorrect because `allOf` merges at the schema definition level, not at the resulting model level. So, new behavior merges OpenAPI specs but generates different code than we have in the past. Set OldMergeSchemas to true for the old behavior. Please see https://github.com/deepmap/oapi-codegen/issues/531"
            },
            "old-enum-conflicts": {
              "type": "boolean",
              "description": "Enum values can generate conflicting typenames, so we've updated the code for enum generation to avoid these conflicts, but it will result in some enum types being renamed in existing code. Set OldEnumConflicts to true to revert to old behavior. Please see: Please see https://github.com/deepmap/oapi-codegen/issues/549"
            },
            "old-aliasing": {
              "type": "boolean",
              "description": "It was a mistake to generate a go type definition for every $ref in the OpenAPI schema. New behavior uses type aliases where possible, but this can generate code which breaks existing builds. Set OldAliasing to true for old behavior. Please see https://github.com/deepmap/oapi-codegen/issues/549"
            },
            "disable-flatten-additional-properties": {
              "type": "boolean",
              "description": "When an object contains no members, and only an additionalProperties specification, it is flattened to a map"
            },
            "disable-required-readonly-as-pointer": {
              "type": "boolean",
              "description": "When an object property is both required and readOnly the go model is generated as a pointer. Set DisableRequiredReadOnlyAsPointer to true to mark them as non pointer. Please see https://github.com/deepmap/oapi-codegen/issues/604"
            },
            "always-prefix-enum-values": {
              "type": "boolean",
              "description": "When set to true, always prefix enum values with their type name instead of only when typenames would be conflicting."
            },
            "apply-chi-middleware-first-to-last": {
              "type": "boolean",
              "description": "Our generated code for Chi has historically inverted the order in which Chi middleware is applied such that the last invoked middleware ends up executing first in the Chi chain This resolves the behavior such that middlewares are chained in the order they are invoked. Please see https://github.com/deepmap/oapi-codegen/issues/786"
            },
            "apply-gorilla-middleware-first-to-last": {
              "type": "boolean",
              "description": "Our generated code for gorilla/mux has historically inverted the order in which gorilla/mux middleware is applied such that the last invoked middleware ends up executing first in the middlewares chain This resolves the behavior such that middlewares are chained in the order they are invoked. Please see https://github.com/deepmap/oapi-codegen/issues/841"
            },
            "circular-reference-limit": {
              "type": "integer",
              "description": "DEPRECATED: No longer used.\nCircularReferenceLimit allows controlling the limit for circular reference checking. In some OpenAPI specifications, we have a higher number of circular references than is allowed out-of-the-box, but can be tuned to allow traversing them."
            },
            "allow-unexported-struct-field-names": {
              "type": "boolean",
              "description": "AllowUnexportedStructFieldNames makes it possible to output structs that have fields that are unexported.\nThis is expected to be used in conjunction with an extension such as `x-go-name` to override the output name, and `x-oapi-codegen-extra-tags` to not produce JSON tags for `encoding/json`.\nNOTE that this can be confusing to users of your OpenAPI specification, who may see a field present and therefore be expecting to see it in the response, without understanding the nuance of how `oapi-codegen` generates the code."
            }
          }
        },
        "output-options": {
          "type": "object",
          "additionalProperties": false,
          "description": "OutputOptions are used to modify the output code in some way",
          "properties": {
            "skip-fmt": {
              "type": "boolean",
              "description": "Whether to skip go imports on the generated code"
            },
            "skip-prune": {
              "type": "boolean",
              "description": "Whether to skip pruning unused components on the generated code"
            },
            "include-tags": {
              "type": "array",
              "description": "Only include operations that have one of these tags. Ignored when empty.",
              "items": {
                "type": "string"
              }
            },
            "exclude-tags": {
              "type": "array",
              "description": "Exclude operations that have one of these tags. Ignored when empty.",
              "items": {
                "type": "string"
              }
            },
            "include-operation-ids": {
              "type": "array",
              "description": "Only include operations that have one of these operation-ids. Ignored when empty.",
              "items": {
                "type": "string"
              }
            },
            "exclude-operation-ids": {
              "type": "array",
              "description": "Exclude operations that have one of these operation-ids. Ignored when empty.",
              "items": {
                "type": "string"
              }
            },
            "user-templates": {
              "type": "object",
              "description": "Override built-in templates from user-provided files",
              "additionalProperties": {
                "type": "string"
              }
            },
            "exclude-schemas": {
              "type": "array",
              "description": "Exclude from generation schemas with given names. Ignored when empty.",
              "items": {
                "type": "string"
              }
            },
            "response-type-suffix": {
              "type": "string",
              "description": "The suffix used for responses types"
            },
            "client-type-name": {
              "type": "string",
              "description": "Override the default generated client type with the value"
            },
            "initialism-overrides": {
              "type": "boolean",
              "description": "Whether to use the initialism overrides"
            },
            "nullable-type": {
              "type": "boolean",
              "description": "Whether to generate nullable type for nullable fields"
            },
            "disable-type-aliases-for-type": {
              "type": "array",
              "description": "DisableTypeAliasesForType allows defining which OpenAPI `type`s will explicitly not use type aliases",
              "items": {
                "type": "string",
                "enum": ["array"]
              }
            },
            "name-normalizer": {
              "type": "string",
              "description": "NameNormalizer is the method used to normalize Go names and types, for instance converting the text `MyApi` to `MyAPI`. Corresponds with the constants defined for `codegen.NameNormalizerFunction`",
              "default": "ToCamelCase",
              "enum": [
                "ToCamelCase",
                "ToCamelCaseWithDigits",
                "ToCamelCaseWithInitialisms"
              ]
            },
            "overlay": {
              "type": "object",
              "description": "Overlay defines configuration for the OpenAPI Overlay (https://github.com/OAI/Overlay-Specification) to manipulate the OpenAPI specification before generation. This allows modifying the specification without needing to apply changes directly to it, making it easier to keep it up-to-date.",
              "properties": {
                "path": {
                  "description": "The path to the Overlay file",
                  "type": "string"
                },
                "strict": {
                  "type": "boolean",
                  "description": "Strict defines whether the Overlay should be applied in a strict way, highlighting any actions that will not take any effect. This can, however, lead to more work when testing new actions in an Overlay, so can be turned off with this setting.",
                  "default": true
                }
              },
              "required": ["path"]
            }
          }
        },
        "import-mapping": {
          "type": "object",
          "additionalProperties": {
            "type": "string",
            "description": "ImportMapping specifies the golang package path for each external reference"
          }
        },
        "additional-imports": {
          "type": "array",
          "items": {
            "type": "object",
            "additionalProperties": false,
            "properties": {
              "alias": {
                "type": "string"
              },
              "package": {
                "type": "string"
              }
            },
            "required": ["package"]
          },
          "description": "AdditionalImports defines any additional Go imports to add to the generated code"
        },
        "output": {
          "type": "string",
          "description": "The filename to output"
        }
      },
      "required": ["package", "output"]
    }
  10. jamietanna commented on Sep 29, 2024

    @jamietanna
    Member
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions