From 99cb9781dd371c78d5a1f9157ea5c1e13dce6a24 Mon Sep 17 00:00:00 2001 From: "conner.panarella" Date: Thu, 16 Jan 2025 12:36:55 -0500 Subject: [PATCH 1/2] Add userDefinedTemplateFiles option to maven generator plugin --- .../openapi-generator-maven-plugin/README.md | 159 ++--- .../codegen/plugin/CodeGenMojo.java | 20 + .../codegen/plugin/CodeGenMojoTest.java | 13 + .../src/test/resources/default/pom.xml | 6 + .../user-defined-templates/_merged_spec.yaml | 37 ++ .../local-repo/petstore/schema/1/schema-1.jar | Bin 0 -> 3503 bytes .../local-repo/petstore/schema/1/schema-1.pom | 9 + .../petstore/schema/maven-metadata-local.xml | 12 + .../resources/user-defined-templates/pom.xml | 62 ++ .../user-defined-templates/settings.xml | 11 + .../src/main/java/com/example/Example.java | 7 + .../src/main/resources/petstore.yaml | 617 ++++++++++++++++++ .../src/main/resources/schemas/Category.yaml | 12 + .../src/main/resources/schemas/Order.yaml | 28 + .../src/main/resources/schemas/Pet.yaml | 38 ++ .../src/main/resources/schemas/Tag.yaml | 11 + .../src/main/resources/schemas/User.yaml | 25 + .../templates/modeltest.mustache | 1 + .../codegen/config/CodegenConfigurator.java | 5 + .../config/CodegenConfiguratorUtils.java | 15 + 20 files changed, 1014 insertions(+), 74 deletions(-) create mode 100644 modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/_merged_spec.yaml create mode 100644 modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/local-repo/petstore/schema/1/schema-1.jar create mode 100644 modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/local-repo/petstore/schema/1/schema-1.pom create mode 100644 modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/local-repo/petstore/schema/maven-metadata-local.xml create mode 100644 modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/pom.xml create mode 100644 modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/settings.xml create mode 100644 modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/src/main/java/com/example/Example.java create mode 100644 modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/src/main/resources/petstore.yaml create mode 100644 modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/src/main/resources/schemas/Category.yaml create mode 100644 modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/src/main/resources/schemas/Order.yaml create mode 100644 modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/src/main/resources/schemas/Pet.yaml create mode 100644 modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/src/main/resources/schemas/Tag.yaml create mode 100644 modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/src/main/resources/schemas/User.yaml create mode 100644 modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/templates/modeltest.mustache diff --git a/modules/openapi-generator-maven-plugin/README.md b/modules/openapi-generator-maven-plugin/README.md index 5c6456e6e94a..ff72680201ab 100644 --- a/modules/openapi-generator-maven-plugin/README.md +++ b/modules/openapi-generator-maven-plugin/README.md @@ -1,4 +1,4 @@ -openapi-generator-maven-plugin + openapi-generator-maven-plugin ============================ A Maven plugin to support the OpenAPI generator project @@ -41,80 +41,81 @@ mvn clean compile :bulb: These **general** configurations should be in the same level -| Option | Property | Description | -|--------|----------|-------------| -| `verbose` | `openapi.generator.maven.plugin.verbose` | verbose mode (`false` by default) -| `inputSpec` | `openapi.generator.maven.plugin.inputSpec` | OpenAPI Spec file path -| `inputSpecRootDirectory` | `openapi.generator.maven.plugin.inputSpecRootDirectory` | Local root folder with spec file(s) -| `mergedFileName` | `openapi.generator.maven.plugin.mergedFileName` | Name of the file that will contain all merged specs -| `language` | `openapi.generator.maven.plugin.language` | target generation language (deprecated, replaced by `generatorName` as values here don't represent only 'language' any longer) -| `generatorName` | `openapi.generator.maven.plugin.generatorName` | target generator name -| `cleanupOutput` | `openapi.generator.maven.plugin.cleanupOutput` | Defines whether the output directory should be cleaned up before generating the output (`false` by default). -| `output` | `openapi.generator.maven.plugin.output` | target output path (default is `${project.build.directory}/generated-sources/openapi`. Can also be set globally through the `openapi.generator.maven.plugin.output` property) -| `gitHost` | `openapi.generator.maven.plugin.gitHost` | The git host, e.g. gitlab.com -| `gitUserId` | `openapi.generator.maven.plugin.gitUserId` | sets git information of the project -| `gitRepoId` | `openapi.generator.maven.plugin.gitRepoId` | sets the repo ID (e.g. openapi-generator) -| `collapsedSpec` | `openapi.generator.maven.plugin.collapsedSpec` | sets the path to the collapsed single-file representation of the OpenAPI spec +| Option | Property | Description | +|-----------------------------------|----------|-------------| +| `verbose` | `openapi.generator.maven.plugin.verbose` | verbose mode (`false` by default) +| `inputSpec` | `openapi.generator.maven.plugin.inputSpec` | OpenAPI Spec file path +| `inputSpecRootDirectory` | `openapi.generator.maven.plugin.inputSpecRootDirectory` | Local root folder with spec file(s) +| `mergedFileName` | `openapi.generator.maven.plugin.mergedFileName` | Name of the file that will contain all merged specs +| `language` | `openapi.generator.maven.plugin.language` | target generation language (deprecated, replaced by `generatorName` as values here don't represent only 'language' any longer) +| `generatorName` | `openapi.generator.maven.plugin.generatorName` | target generator name +| `cleanupOutput` | `openapi.generator.maven.plugin.cleanupOutput` | Defines whether the output directory should be cleaned up before generating the output (`false` by default). +| `output` | `openapi.generator.maven.plugin.output` | target output path (default is `${project.build.directory}/generated-sources/openapi`. Can also be set globally through the `openapi.generator.maven.plugin.output` property) +| `gitHost` | `openapi.generator.maven.plugin.gitHost` | The git host, e.g. gitlab.com +| `gitUserId` | `openapi.generator.maven.plugin.gitUserId` | sets git information of the project +| `gitRepoId` | `openapi.generator.maven.plugin.gitRepoId` | sets the repo ID (e.g. openapi-generator) +| `collapsedSpec` | `openapi.generator.maven.plugin.collapsedSpec` | sets the path to the collapsed single-file representation of the OpenAPI spec | `includeCollapsedSpecInArtifacts` | `openapi.generator.maven.plugin.publishCollapsedSpec` | includes the collapsed spec in the Maven artifacts (`false` by default) -| `templateDirectory` | `openapi.generator.maven.plugin.templateDirectory` | directory with mustache templates -| `templateResourcePath` | `openapi.generator.maven.plugin.templateResourcePath` | directory with mustache templates via resource path. This option will overwrite any option defined in `templateDirectory`. -| `engine` | `openapi.generator.maven.plugin.engine` | The name of templating engine to use, "mustache" (default) or "handlebars" (beta) -| `auth` | `openapi.generator.maven.plugin.auth` | adds authorization headers when fetching the OpenAPI definitions remotely. Pass in a URL-encoded string of `name:header` with a comma separating multiple values -| `configurationFile` | `openapi.generator.maven.plugin.configurationFile` | Path to separate json configuration file. File content should be in a json format {"optionKey":"optionValue", "optionKey1":"optionValue1"...} Supported options can be different for each generator. Run `config-help -g {generator name}` command for generator-specific config options -| `skipOverwrite` | `openapi.generator.maven.plugin.skipOverwrite` | Specifies if the existing files should be overwritten during the generation. (`false` by default) -| `apiPackage` | `openapi.generator.maven.plugin.apiPackage` | the package to use for generated api objects/classes -| `modelPackage` | `openapi.generator.maven.plugin.modelPackage` | the package to use for generated model objects/classes -| `invokerPackage` | `openapi.generator.maven.plugin.invokerPackage` | the package to use for the generated invoker objects -| `packageName` | `openapi.generator.maven.plugin.packageName` | the default package name to use for the generated objects -| `groupId` | `openapi.generator.maven.plugin.groupId` | sets project information in generated pom.xml/build.gradle or other build script. Language-specific conversions occur in non-jvm generators -| `artifactId` | `openapi.generator.maven.plugin.artifactId` | sets project information in generated pom.xml/build.gradle or other build script. Language-specific conversions occur in non-jvm generators -| `artifactVersion` | `openapi.generator.maven.plugin.artifactVersion` | sets project information in generated pom.xml/build.gradle or other build script. Language-specific conversions occur in non-jvm generators -| `library` | `openapi.generator.maven.plugin.library` | library template (sub-template) -| `modelNamePrefix` | `openapi.generator.maven.plugin.modelNamePrefix` | Sets the prefix for model classes and enums -| `modelNameSuffix` | `openapi.generator.maven.plugin.modelNameSuffix` | Sets the suffix for model classes and enums -| `apiNameSuffix` | `openapi.generator.maven.plugin.apiNameSuffix` | Sets the suffix for api classes -| `ignoreFileOverride` | `openapi.generator.maven.plugin.ignoreFileOverride` | specifies the full path to a `.openapi-generator-ignore` used for pattern based overrides of generated outputs -| `httpUserAgent` | `openapi.generator.maven.plugin.httpUserAgent` | Sets custom User-Agent header value -| `removeOperationIdPrefix` | `openapi.generator.maven.plugin.removeOperationIdPrefix` | remove operationId prefix (e.g. user_getName => getName) -| `skipOperationExample` | `openapi.generator.maven.plugin.skipOperationExample` | skip examples defined in the operation -| `logToStderr` | `openapi.generator.maven.plugin.logToStderr` | write all log messages (not just errors) to STDERR -| `enablePostProcessFile` | `openapi.generator.maven.plugin.` | enable file post-processing hook -| `skipValidateSpec` | `openapi.generator.maven.plugin.skipValidateSpec` | Whether or not to skip validating the input spec prior to generation. By default, invalid specifications will result in an error. -| `strictSpec` | `openapi.generator.maven.plugin.strictSpec` | Whether or not to treat an input document strictly against the spec. 'MUST' and 'SHALL' wording in OpenAPI spec is strictly adhered to. e.g. when false, no fixes will be applied to documents which pass validation but don't follow the spec. -| `openapiNormalizer` | `openapi.generator.maven.plugin.openapiNormalizer` | specifies the rules to be enabled in OpenAPI normalizer in the form of RULE_1=true,RULE_2=original. -| `generateAliasAsModel` | `openapi.generator.maven.plugin.generateAliasAsModel` | generate alias (array, map) as model -| `configOptions` | N/A | a **map** of generator-specific parameters. To show a full list of generator-specified parameters (options), please use `configHelp` (explained below) -| `instantiationTypes` | `openapi.generator.maven.plugin.instantiationTypes` | sets instantiation type mappings in the format of type=instantiatedType,type=instantiatedType. For example (in Java): `array=ArrayList,map=HashMap`. In other words array types will get instantiated as ArrayList in generated code. You can also have multiple occurrences of this option -| `importMappings` | `openapi.generator.maven.plugin.importMappings` | specifies mappings between a given class and the import that should be used for that class in the format of type=import,type=import. You can also have multiple occurrences of this option -| `typeMappings` | `openapi.generator.maven.plugin.typeMappings` | sets mappings between OpenAPI spec types and generated code types in the format of OpenAPIType=generatedType,OpenAPIType=generatedType. For example: `array=List,map=Map,string=String`. You can also have multiple occurrences of this option. To map a specified format, use type+format, e.g. string+password=EncryptedString will map `type: string, format: password` to `EncryptedString`. -| `schemaMappings` | `openapi.generator.maven.plugin.schemaMappings` | specifies mappings between the schema and the new name in the format of schema_a=Cat,schema_b=Bird. https://openapi-generator.tech/docs/customization/#schema-mapping -| `nameMappings` | `openapi.generator.maven.plugin.nameMappings` | specifies mappings between the property name and the new name in the format of property_a=firstProperty,property_b=secondProperty. https://openapi-generator.tech/docs/customization/#name-mapping -| `modelNameMappings` | `openapi.generator.maven.plugin.modelNameMappings` | specifies mappings between the model name and the new name in the format of model_a=FirstModel,model_b=SecondModel. https://openapi-generator.tech/docs/customization/#name-mapping -| `parameterNameMappings` | `openapi.generator.maven.plugin.parameterNameMappings` | specifies mappings between the parameter name and the new name in the format of param_a=first_parameter,param_b=second_parameter. https://openapi-generator.tech/docs/customization/#name-mapping -| `inlineSchemaNameMappings` | `openapi.generator.maven.plugin.inlineSchemaNameMappings` | specifies mappings between the inline schema name and the new name in the format of inline_object_2=Cat,inline_object_5=Bird. -| `inlineSchemaOptions` | `openapi.generator.maven.plugin.inlineSchemaOptions` | specifies the options used when naming inline schema in inline model resolver -| `languageSpecificPrimitives` | `openapi.generator.maven.plugin.languageSpecificPrimitives` | specifies additional language specific primitive types in the format of type1,type2,type3,type3. For example: `String,boolean,Boolean,Double`. You can also have multiple occurrences of this option -| `additionalProperties` | `openapi.generator.maven.plugin.additionalProperties` | sets additional properties that can be referenced by the mustache templates in the format of name=value,name=value. You can also have multiple occurrences of this option -| `serverVariableOverrides` | `openapi.generator.maven.plugin.serverVariableOverrides` | A map of server variable overrides for specs that support server URL templating -| `reservedWordsMappings` | `openapi.generator.maven.plugin.reservedWordsMappings` | specifies how a reserved name should be escaped to. Otherwise, the default `_` is used. For example `id=identifier`. You can also have multiple occurrences of this option -| `generateApis` | `openapi.generator.maven.plugin.generateApis` | generate the apis (`true` by default). Specific apis may be defined as a CSV via `apisToGenerate`. -| `apisToGenerate` | `openapi.generator.maven.plugin.apisToGenerate` | A comma separated list of apis to generate. All apis is the default. -| `generateModels` | `openapi.generator.maven.plugin.generateModels` | generate the models (`true` by default). Specific models may be defined as a CSV via `modelsToGenerate`. -| `modelsToGenerate` | `openapi.generator.maven.plugin.modelsToGenerate` | A comma separated list of models to generate. All models is the default. -| `generateSupportingFiles` | `openapi.generator.maven.plugin.generateSupportingFiles` | generate the supporting files (`true` by default) -| `supportingFilesToGenerate` | `openapi.generator.maven.plugin.supportingFilesToGenerate` | A comma separated list of supporting files to generate. All files is the default. -| `generateModelTests` | `openapi.generator.maven.plugin.generateModelTests` | generate the model tests (`true` by default. Only available if `generateModels` is `true`) -| `generateModelDocumentation` | `openapi.generator.maven.plugin.generateModelDocumentation` | generate the model documentation (`true` by default. Only available if `generateModels` is `true`) -| `generateApiTests` | `openapi.generator.maven.plugin.generateApiTests` | generate the api tests (`true` by default. Only available if `generateApis` is `true`) -| `generateApiDocumentation` | `openapi.generator.maven.plugin.generateApiDocumentation` | generate the api documentation (`true` by default. Only available if `generateApis` is `true`) -| `skip` | `codegen.skip` | skip code generation (`false` by default. Can also be set globally through the `codegen.skip` property) -| `skipIfSpecIsUnchanged` | `codegen.skipIfSpecIsUnchanged` | Skip the execution if the source file is older than the output folder (`false` by default. Can also be set globally through the `codegen.skipIfSpecIsUnchanged` property) -| `addCompileSourceRoot` | `openapi.generator.maven.plugin.addCompileSourceRoot` | Add the output directory to the project as a source root, so that the generated java types are compiled and included in the project artifact (`true` by default). Mutually exclusive with `addTestCompileSourceRoot`. -| `addTestCompileSourceRoot` | `openapi.generator.maven.plugin.addTestCompileSourceRoot` | Add the output directory to the project as a test source root, so that the generated java types are compiled only for the test classpath of the project (`false` by default). Mutually exclusive with `addCompileSourceRoot`. -| `dryRun` | `openapi.generator.maven.plugin.dryRun` | Defines whether the generator should run in dry-run mode. In dry-run mode no files are written and a summary about file states is output ( `false` by default). -| `environmentVariables` | N/A | deprecated. Use globalProperties instead. -| `globalProperties` | N/A | A **map** of items conceptually similar to "environment variables" or "system properties". These are available to all aspects of the generation flow. See [Global Properties](https://openapi-generator.tech/docs/globals/) for list of available properties. -| `configHelp` | `codegen.configHelp` | dumps the configuration help for the specified library (generates no sources) +| `templateDirectory` | `openapi.generator.maven.plugin.templateDirectory` | directory with mustache templates +| `templateResourcePath` | `openapi.generator.maven.plugin.templateResourcePath` | directory with mustache templates via resource path. This option will overwrite any option defined in `templateDirectory`. +| `engine` | `openapi.generator.maven.plugin.engine` | The name of templating engine to use, "mustache" (default) or "handlebars" (beta) +| `auth` | `openapi.generator.maven.plugin.auth` | adds authorization headers when fetching the OpenAPI definitions remotely. Pass in a URL-encoded string of `name:header` with a comma separating multiple values +| `configurationFile` | `openapi.generator.maven.plugin.configurationFile` | Path to separate json configuration file. File content should be in a json format {"optionKey":"optionValue", "optionKey1":"optionValue1"...} Supported options can be different for each generator. Run `config-help -g {generator name}` command for generator-specific config options +| `skipOverwrite` | `openapi.generator.maven.plugin.skipOverwrite` | Specifies if the existing files should be overwritten during the generation. (`false` by default) +| `apiPackage` | `openapi.generator.maven.plugin.apiPackage` | the package to use for generated api objects/classes +| `modelPackage` | `openapi.generator.maven.plugin.modelPackage` | the package to use for generated model objects/classes +| `invokerPackage` | `openapi.generator.maven.plugin.invokerPackage` | the package to use for the generated invoker objects +| `packageName` | `openapi.generator.maven.plugin.packageName` | the default package name to use for the generated objects +| `groupId` | `openapi.generator.maven.plugin.groupId` | sets project information in generated pom.xml/build.gradle or other build script. Language-specific conversions occur in non-jvm generators +| `artifactId` | `openapi.generator.maven.plugin.artifactId` | sets project information in generated pom.xml/build.gradle or other build script. Language-specific conversions occur in non-jvm generators +| `artifactVersion` | `openapi.generator.maven.plugin.artifactVersion` | sets project information in generated pom.xml/build.gradle or other build script. Language-specific conversions occur in non-jvm generators +| `library` | `openapi.generator.maven.plugin.library` | library template (sub-template) +| `modelNamePrefix` | `openapi.generator.maven.plugin.modelNamePrefix` | Sets the prefix for model classes and enums +| `modelNameSuffix` | `openapi.generator.maven.plugin.modelNameSuffix` | Sets the suffix for model classes and enums +| `apiNameSuffix` | `openapi.generator.maven.plugin.apiNameSuffix` | Sets the suffix for api classes +| `ignoreFileOverride` | `openapi.generator.maven.plugin.ignoreFileOverride` | specifies the full path to a `.openapi-generator-ignore` used for pattern based overrides of generated outputs +| `httpUserAgent` | `openapi.generator.maven.plugin.httpUserAgent` | Sets custom User-Agent header value +| `removeOperationIdPrefix` | `openapi.generator.maven.plugin.removeOperationIdPrefix` | remove operationId prefix (e.g. user_getName => getName) +| `skipOperationExample` | `openapi.generator.maven.plugin.skipOperationExample` | skip examples defined in the operation +| `logToStderr` | `openapi.generator.maven.plugin.logToStderr` | write all log messages (not just errors) to STDERR +| `enablePostProcessFile` | `openapi.generator.maven.plugin.` | enable file post-processing hook +| `skipValidateSpec` | `openapi.generator.maven.plugin.skipValidateSpec` | Whether or not to skip validating the input spec prior to generation. By default, invalid specifications will result in an error. +| `strictSpec` | `openapi.generator.maven.plugin.strictSpec` | Whether or not to treat an input document strictly against the spec. 'MUST' and 'SHALL' wording in OpenAPI spec is strictly adhered to. e.g. when false, no fixes will be applied to documents which pass validation but don't follow the spec. +| `openapiNormalizer` | `openapi.generator.maven.plugin.openapiNormalizer` | specifies the rules to be enabled in OpenAPI normalizer in the form of RULE_1=true,RULE_2=original. +| `generateAliasAsModel` | `openapi.generator.maven.plugin.generateAliasAsModel` | generate alias (array, map) as model +| `configOptions` | N/A | a **map** of generator-specific parameters. To show a full list of generator-specified parameters (options), please use `configHelp` (explained below) +| `instantiationTypes` | `openapi.generator.maven.plugin.instantiationTypes` | sets instantiation type mappings in the format of type=instantiatedType,type=instantiatedType. For example (in Java): `array=ArrayList,map=HashMap`. In other words array types will get instantiated as ArrayList in generated code. You can also have multiple occurrences of this option +| `importMappings` | `openapi.generator.maven.plugin.importMappings` | specifies mappings between a given class and the import that should be used for that class in the format of type=import,type=import. You can also have multiple occurrences of this option +| `typeMappings` | `openapi.generator.maven.plugin.typeMappings` | sets mappings between OpenAPI spec types and generated code types in the format of OpenAPIType=generatedType,OpenAPIType=generatedType. For example: `array=List,map=Map,string=String`. You can also have multiple occurrences of this option. To map a specified format, use type+format, e.g. string+password=EncryptedString will map `type: string, format: password` to `EncryptedString`. +| `schemaMappings` | `openapi.generator.maven.plugin.schemaMappings` | specifies mappings between the schema and the new name in the format of schema_a=Cat,schema_b=Bird. https://openapi-generator.tech/docs/customization/#schema-mapping +| `nameMappings` | `openapi.generator.maven.plugin.nameMappings` | specifies mappings between the property name and the new name in the format of property_a=firstProperty,property_b=secondProperty. https://openapi-generator.tech/docs/customization/#name-mapping +| `modelNameMappings` | `openapi.generator.maven.plugin.modelNameMappings` | specifies mappings between the model name and the new name in the format of model_a=FirstModel,model_b=SecondModel. https://openapi-generator.tech/docs/customization/#name-mapping +| `parameterNameMappings` | `openapi.generator.maven.plugin.parameterNameMappings` | specifies mappings between the parameter name and the new name in the format of param_a=first_parameter,param_b=second_parameter. https://openapi-generator.tech/docs/customization/#name-mapping +| `inlineSchemaNameMappings` | `openapi.generator.maven.plugin.inlineSchemaNameMappings` | specifies mappings between the inline schema name and the new name in the format of inline_object_2=Cat,inline_object_5=Bird. +| `inlineSchemaOptions` | `openapi.generator.maven.plugin.inlineSchemaOptions` | specifies the options used when naming inline schema in inline model resolver +| `languageSpecificPrimitives` | `openapi.generator.maven.plugin.languageSpecificPrimitives` | specifies additional language specific primitive types in the format of type1,type2,type3,type3. For example: `String,boolean,Boolean,Double`. You can also have multiple occurrences of this option +| `additionalProperties` | `openapi.generator.maven.plugin.additionalProperties` | sets additional properties that can be referenced by the mustache templates in the format of name=value,name=value. You can also have multiple occurrences of this option +| `serverVariableOverrides` | `openapi.generator.maven.plugin.serverVariableOverrides` | A map of server variable overrides for specs that support server URL templating +| `reservedWordsMappings` | `openapi.generator.maven.plugin.reservedWordsMappings` | specifies how a reserved name should be escaped to. Otherwise, the default `_` is used. For example `id=identifier`. You can also have multiple occurrences of this option +| `generateApis` | `openapi.generator.maven.plugin.generateApis` | generate the apis (`true` by default). Specific apis may be defined as a CSV via `apisToGenerate`. +| `apisToGenerate` | `openapi.generator.maven.plugin.apisToGenerate` | A comma separated list of apis to generate. All apis is the default. +| `generateModels` | `openapi.generator.maven.plugin.generateModels` | generate the models (`true` by default). Specific models may be defined as a CSV via `modelsToGenerate`. +| `modelsToGenerate` | `openapi.generator.maven.plugin.modelsToGenerate` | A comma separated list of models to generate. All models is the default. +| `generateSupportingFiles` | `openapi.generator.maven.plugin.generateSupportingFiles` | generate the supporting files (`true` by default) +| `supportingFilesToGenerate` | `openapi.generator.maven.plugin.supportingFilesToGenerate` | A comma separated list of supporting files to generate. All files is the default. +| `generateModelTests` | `openapi.generator.maven.plugin.generateModelTests` | generate the model tests (`true` by default. Only available if `generateModels` is `true`) +| `generateModelDocumentation` | `openapi.generator.maven.plugin.generateModelDocumentation` | generate the model documentation (`true` by default. Only available if `generateModels` is `true`) +| `generateApiTests` | `openapi.generator.maven.plugin.generateApiTests` | generate the api tests (`true` by default. Only available if `generateApis` is `true`) +| `generateApiDocumentation` | `openapi.generator.maven.plugin.generateApiDocumentation` | generate the api documentation (`true` by default. Only available if `generateApis` is `true`) +| `skip` | `codegen.skip` | skip code generation (`false` by default. Can also be set globally through the `codegen.skip` property) +| `skipIfSpecIsUnchanged` | `codegen.skipIfSpecIsUnchanged` | Skip the execution if the source file is older than the output folder (`false` by default. Can also be set globally through the `codegen.skipIfSpecIsUnchanged` property) +| `addCompileSourceRoot` | `openapi.generator.maven.plugin.addCompileSourceRoot` | Add the output directory to the project as a source root, so that the generated java types are compiled and included in the project artifact (`true` by default). Mutually exclusive with `addTestCompileSourceRoot`. +| `addTestCompileSourceRoot` | `openapi.generator.maven.plugin.addTestCompileSourceRoot` | Add the output directory to the project as a test source root, so that the generated java types are compiled only for the test classpath of the project (`false` by default). Mutually exclusive with `addCompileSourceRoot`. +| `dryRun` | `openapi.generator.maven.plugin.dryRun` | Defines whether the generator should run in dry-run mode. In dry-run mode no files are written and a summary about file states is output ( `false` by default). +| `environmentVariables` | N/A | deprecated. Use globalProperties instead. +| `globalProperties` | N/A | A **map** of items conceptually similar to "environment variables" or "system properties". These are available to all aspects of the generation flow. See [Global Properties](https://openapi-generator.tech/docs/globals/) for list of available properties. +| `userDefinedTemplateFiles` | N/A | Sets custom user defined template files to generate. This is different than overriding existing templates.See [Customization](https://openapi-generator.tech/docs/customization) for information on this functionality. +| `configHelp` | `codegen.configHelp` | dumps the configuration help for the specified library (generates no sources) ### Configuring **map** structures @@ -217,6 +218,16 @@ Specifying a custom generator is a bit different. It doesn't support the classpa ``` +For user defined templates you can add them by specifying `templateFile`, `templateType`, and `destinationFilename`. + +```xml + + + templateFile=modeltest.mustache,templateType=models,destinationFilename=Custom.java + + +``` + ### Sample configuration Please see [an example configuration](examples) for using the plugin. To run these examples, explicitly pass the file to maven. Example: diff --git a/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java b/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java index 792ca0dda2c0..bc7aa0b93310 100644 --- a/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java +++ b/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java @@ -151,6 +151,12 @@ public class CodeGenMojo extends AbstractMojo { @Parameter(name = "templateResourcePath", property = "openapi.generator.maven.plugin.templateResourcePath") private String templateResourcePath; + /** + * Specifies userDefinedTemplates relative to templateDir, see Customizing for more info + */ + @Parameter(name = "userDefinedTemplateFiles") + private List userDefinedTemplateFiles; + /** * The name of templating engine to use, "mustache" (default) or "handlebars" (beta) */ @@ -723,8 +729,11 @@ public void execute() throws MojoExecutionException { configurator.setApiNameSuffix(apiNameSuffix); } + String templateDir = null; + if (null != templateDirectory) { configurator.setTemplateDir(templateDirectory.getAbsolutePath()); + templateDir = templateDirectory.getAbsolutePath(); } if (StringUtils.isNotEmpty(templateResourcePath)) { @@ -732,6 +741,7 @@ public void execute() throws MojoExecutionException { LOGGER.warn("Both templateDirectory and templateResourcePath were configured. templateResourcePath overwrites templateDirectory."); } configurator.setTemplateDir(templateResourcePath); + templateDir = templateResourcePath; } if (null != engine) { @@ -937,6 +947,16 @@ public void execute() throws MojoExecutionException { } } + if(userDefinedTemplateFiles != null && userDefinedTemplateFiles.size() > 0) { + + if(templateDir == null) { + LOGGER.error("User defined templates have been defined, but no template directory has been set."); + throw new MojoExecutionException("User defined templates have been defined, but no template directory has been set. Please configure the template directory."); + } + + applyUserDefinedTemplateFilesKvpList(userDefinedTemplateFiles, configurator); + } + final ClientOptInput input = configurator.toClientOptInput(); final CodegenConfig config = input.getConfig(); diff --git a/modules/openapi-generator-maven-plugin/src/test/java/org/openapitools/codegen/plugin/CodeGenMojoTest.java b/modules/openapi-generator-maven-plugin/src/test/java/org/openapitools/codegen/plugin/CodeGenMojoTest.java index d7fad6c2b6b3..d5b38ca09231 100644 --- a/modules/openapi-generator-maven-plugin/src/test/java/org/openapitools/codegen/plugin/CodeGenMojoTest.java +++ b/modules/openapi-generator-maven-plugin/src/test/java/org/openapitools/codegen/plugin/CodeGenMojoTest.java @@ -33,6 +33,7 @@ import org.eclipse.aether.repository.LocalRepository; import java.io.File; +import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; @@ -255,6 +256,18 @@ public void test_skipIfSpecIsUnchanged_recognizesUpdatesInExternalReferencedFile assertTrue("Src directory should have been regenerated", Files.exists(generatedDir.resolve("src"))); } + public void test_userTemplateFiles() throws Exception { + + final Path tempDir = newTempFolder(); + final CodeGenMojo mojo = loadMojo(tempDir, "src/test/resources/user-defined-templates", null); + + mojo.execute(); + + assertTrue(Files.exists(tempDir.resolve( + "target/generated-sources/common-maven/remote-openapi/src/main/java/remote/org/openapitools/client/model/CategoryCustom.java" + ))); + } + protected CodeGenMojo loadMojo(Path temporaryFolder, String projectRoot, String profile) throws Exception { return loadMojo(temporaryFolder, projectRoot, profile, "default"); } diff --git a/modules/openapi-generator-maven-plugin/src/test/resources/default/pom.xml b/modules/openapi-generator-maven-plugin/src/test/resources/default/pom.xml index 9ef40042d38f..c9b0f6b60fa7 100644 --- a/modules/openapi-generator-maven-plugin/src/test/resources/default/pom.xml +++ b/modules/openapi-generator-maven-plugin/src/test/resources/default/pom.xml @@ -55,6 +55,12 @@ + + user-templates + + ${basedir}/src/main/resources/petstore.yaml + + common-maven diff --git a/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/_merged_spec.yaml b/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/_merged_spec.yaml new file mode 100644 index 000000000000..118c43647265 --- /dev/null +++ b/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/_merged_spec.yaml @@ -0,0 +1,37 @@ +--- +servers: +- url: "http://localhost:8080" +openapi: "3.0.0" +paths: + /pet: + $ref: "./src\\main\\resources\\petstore.yaml#/paths/~1pet" + /user/{username}: + $ref: "./src\\main\\resources\\petstore.yaml#/paths/~1user~1{username}" + /pet/findByStatus: + $ref: "./src\\main\\resources\\petstore.yaml#/paths/~1pet~1findByStatus" + /user/createWithList: + $ref: "./src\\main\\resources\\petstore.yaml#/paths/~1user~1createWithList" + /pet/{petId}/uploadImage: + $ref: "./src\\main\\resources\\petstore.yaml#/paths/~1pet~1{petId}~1uploadImage" + /store/inventory: + $ref: "./src\\main\\resources\\petstore.yaml#/paths/~1store~1inventory" + /user/login: + $ref: "./src\\main\\resources\\petstore.yaml#/paths/~1user~1login" + /user: + $ref: "./src\\main\\resources\\petstore.yaml#/paths/~1user" + /user/createWithArray: + $ref: "./src\\main\\resources\\petstore.yaml#/paths/~1user~1createWithArray" + /pet/findByTags: + $ref: "./src\\main\\resources\\petstore.yaml#/paths/~1pet~1findByTags" + /store/order: + $ref: "./src\\main\\resources\\petstore.yaml#/paths/~1store~1order" + /user/logout: + $ref: "./src\\main\\resources\\petstore.yaml#/paths/~1user~1logout" + /pet/{petId}: + $ref: "./src\\main\\resources\\petstore.yaml#/paths/~1pet~1{petId}" + /store/order/{orderId}: + $ref: "./src\\main\\resources\\petstore.yaml#/paths/~1store~1order~1{orderId}" +info: + title: "merged spec" + description: "merged spec" + version: "1.0.0" diff --git a/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/local-repo/petstore/schema/1/schema-1.jar b/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/local-repo/petstore/schema/1/schema-1.jar new file mode 100644 index 0000000000000000000000000000000000000000..5b4d1c0860f71e8456a2b3dfba7ccb2a5bed0bac GIT binary patch literal 3503 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 q%laGc{NCY;QGQ?Sic$Vn$FJu + + 4.0.0 + petstore + schema + 1 + POM was created from install:install-file + diff --git a/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/local-repo/petstore/schema/maven-metadata-local.xml b/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/local-repo/petstore/schema/maven-metadata-local.xml new file mode 100644 index 000000000000..d66c798366f3 --- /dev/null +++ b/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/local-repo/petstore/schema/maven-metadata-local.xml @@ -0,0 +1,12 @@ + + + petstore + schema + + 1 + + 1 + + 20210724220722 + + diff --git a/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/pom.xml b/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/pom.xml new file mode 100644 index 000000000000..49a6f573cd09 --- /dev/null +++ b/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/pom.xml @@ -0,0 +1,62 @@ + + + + 4.0.0 + common.maven + common-maven + jar + 1.0.0-SNAPSHOT + OpenAPI Generator Configuration Test + https://openapi-generator.tech/ + + common-maven + + + org.openapitools + openapi-generator-maven-plugin + + ${basedir}/src/main/resources/petstore.yaml + java + + joda + + Suffix + jersey2 + ${basedir}/target/generated-sources/common-maven/remote-openapi + remote.org.openapitools.client.api + remote.org.openapitools.client.model + remote.org.openapitools.client + petstore-full-spec + true + ${basedir}/templates + + templateFile=modeltest.mustache,templateType=models,destinationFilename=Custom.java + + + + + executionId + generate-sources + + generate + + + + + + + diff --git a/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/settings.xml b/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/settings.xml new file mode 100644 index 000000000000..96b902ae2208 --- /dev/null +++ b/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/settings.xml @@ -0,0 +1,11 @@ + + + default + + + + default + ${basedir}/local-repo + + + diff --git a/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/src/main/java/com/example/Example.java b/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/src/main/java/com/example/Example.java new file mode 100644 index 000000000000..8447f00216de --- /dev/null +++ b/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/src/main/java/com/example/Example.java @@ -0,0 +1,7 @@ +package com.example; + +public class Example { + public static void main(String[] args) { + System.out.println("You did it!"); + } +} \ No newline at end of file diff --git a/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/src/main/resources/petstore.yaml b/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/src/main/resources/petstore.yaml new file mode 100644 index 000000000000..55cee186ad14 --- /dev/null +++ b/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/src/main/resources/petstore.yaml @@ -0,0 +1,617 @@ +openapi: 3.0.0 +servers: + - url: 'http://petstore.swagger.io/v2' +info: + description: >- + This is a sample server Petstore server. For this sample, you can use the api key + `special-key` to test the authorization filters. + version: 1.0.0 + title: OpenAPI Petstore + license: + name: Apache-2.0 + url: 'https://www.apache.org/licenses/LICENSE-2.0.html' +tags: + - name: pet + description: Everything about your Pets + - name: store + description: Access to Petstore orders + - name: user + description: Operations about user +paths: + /pet: + post: + tags: + - pet + summary: Add a new pet to the store + description: '' + operationId: addPet + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: 'schemas/Pet.yaml' + application/json: + schema: + $ref: 'schemas/Pet.yaml' + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + put: + tags: + - pet + summary: Update an existing pet + description: '' + operationId: updatePet + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: 'schemas/Pet.yaml' + application/json: + schema: + $ref: 'schemas/Pet.yaml' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + '405': + description: Validation exception + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + /pet/findByStatus: + get: + tags: + - pet + summary: Finds Pets by status + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - name: status + in: query + description: Status values that need to be considered for filter + required: true + style: form + explode: false + schema: + type: array + items: + type: string + enum: + - available + - pending + - sold + default: available + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: 'schemas/Pet.yaml' + application/json: + schema: + type: array + items: + $ref: 'schemas/Pet.yaml' + '400': + description: Invalid status value + security: + - petstore_auth: + - 'read:pets' + /pet/findByTags: + get: + tags: + - pet + summary: Finds Pets by tags + description: >- + Multiple tags can be provided with comma separated strings. Use tag1, + tag2, tag3 for testing. + operationId: findPetsByTags + parameters: + - name: tags + in: query + description: Tags to filter by + required: true + style: form + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: 'schemas/Pet.yaml' + application/json: + schema: + type: array + items: + $ref: 'schemas/Pet.yaml' + '400': + description: Invalid tag value + security: + - petstore_auth: + - 'read:pets' + deprecated: true + '/pet/{petId}': + get: + tags: + - pet + summary: Find pet by ID + description: Returns a single pet + operationId: getPetById + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: 'schemas/Pet.yaml' + application/json: + schema: + $ref: 'schemas/Pet.yaml' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + security: + - api_key: [] + post: + tags: + - pet + summary: Updates a pet in the store with form data + description: '' + operationId: updatePetWithForm + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: integer + format: int64 + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + delete: + tags: + - pet + summary: Deletes a pet + description: '' + operationId: deletePet + parameters: + - name: api_key + in: header + required: false + schema: + type: string + - name: petId + in: path + description: Pet id to delete + required: true + schema: + type: integer + format: int64 + responses: + '400': + description: Invalid pet value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + '/pet/{petId}/uploadImage': + post: + tags: + - pet + summary: uploads an image + description: '' + operationId: uploadFile + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + type: string + format: binary + /store/inventory: + get: + tags: + - store + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: getInventory + responses: + '200': + description: successful operation + content: + application/json: + schema: + type: object + additionalProperties: + type: integer + format: int32 + security: + - api_key: [] + /store/order: + post: + tags: + - store + summary: Place an order for a pet + description: '' + operationId: placeOrder + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: 'schemas/Order.yaml' + application/json: + schema: + $ref: 'schemas/Order.yaml' + '400': + description: Invalid Order + requestBody: + content: + application/json: + schema: + $ref: 'schemas/Order.yaml' + description: order placed for purchasing the pet + required: true + '/store/order/{orderId}': + get: + tags: + - store + summary: Find purchase order by ID + description: >- + For valid response try integer IDs with value <= 5 or > 10. Other values + will generate exceptions + operationId: getOrderById + parameters: + - name: orderId + in: path + description: ID of pet that needs to be fetched + required: true + schema: + type: integer + format: int64 + minimum: 1 + maximum: 5 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: 'schemas/Order.yaml' + application/json: + schema: + $ref: 'schemas/Order.yaml' + '400': + description: Invalid ID supplied + '404': + description: Order not found + delete: + tags: + - store + summary: Delete purchase order by ID + description: >- + For valid response try integer IDs with value < 1000. Anything above + 1000 or nonintegers will generate API errors + operationId: deleteOrder + parameters: + - name: orderId + in: path + description: ID of the order that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid ID supplied + '404': + description: Order not found + /user: + post: + tags: + - user + summary: Create user + description: This can only be done by the logged in user. + operationId: createUser + responses: + default: + description: successful operation + security: + - api_key: [] + requestBody: + content: + application/json: + schema: + $ref: 'schemas/User.yaml' + description: Created user object + required: true + /user/createWithArray: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithArrayInput + responses: + default: + description: successful operation + security: + - api_key: [] + requestBody: + $ref: '#/components/requestBodies/UserArray' + /user/createWithList: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithListInput + responses: + default: + description: successful operation + security: + - api_key: [] + requestBody: + $ref: '#/components/requestBodies/UserArray' + /user/login: + get: + tags: + - user + summary: Logs user into the system + description: '' + operationId: loginUser + parameters: + - name: username + in: query + description: The user name for login + required: true + schema: + type: string + pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$' + - name: password + in: query + description: The password for login in clear text + required: true + schema: + type: string + responses: + '200': + description: successful operation + headers: + Set-Cookie: + description: >- + Cookie authentication key for use with the `api_key` + apiKey authentication. + schema: + type: string + example: AUTH_KEY=abcde12345; Path=/; HttpOnly + X-Rate-Limit: + description: calls per hour allowed by the user + schema: + type: integer + format: int32 + X-Expires-After: + description: date in UTC when token expires + schema: + type: string + format: date-time + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + '400': + description: Invalid username/password supplied + /user/logout: + get: + tags: + - user + summary: Logs out current logged in user session + description: '' + operationId: logoutUser + responses: + default: + description: successful operation + security: + - api_key: [] + '/user/{username}': + get: + tags: + - user + summary: Get user by user name + description: '' + operationId: getUserByName + parameters: + - name: username + in: path + description: The name that needs to be fetched. Use user1 for testing. + required: true + schema: + type: string + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: 'schemas/User.yaml' + application/json: + schema: + $ref: 'schemas/User.yaml' + '400': + description: Invalid username supplied + '404': + description: User not found + put: + tags: + - user + summary: Updated user + description: This can only be done by the logged in user. + operationId: updateUser + parameters: + - name: username + in: path + description: name that need to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid user supplied + '404': + description: User not found + security: + - api_key: [] + requestBody: + content: + application/json: + schema: + $ref: 'schemas/User.yaml' + description: Updated user object + required: true + delete: + tags: + - user + summary: Delete user + description: This can only be done by the logged in user. + operationId: deleteUser + parameters: + - name: username + in: path + description: The name that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid username supplied + '404': + description: User not found + security: + - api_key: [] +externalDocs: + description: Find out more about Swagger + url: 'http://swagger.io' +components: + requestBodies: + UserArray: + content: + application/json: + schema: + type: array + items: + $ref: 'schemas/User.yaml' + description: List of user object + required: true + Pet: + content: + application/json: + schema: + $ref: 'schemas/Pet.yaml' + application/xml: + schema: + $ref: 'schemas/Pet.yaml' + description: Pet object that needs to be added to the store + required: true + securitySchemes: + petstore_auth: + type: oauth2 + flows: + implicit: + authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog' + scopes: + 'write:pets': modify pets in your account + 'read:pets': read your pets + api_key: + type: apiKey + name: api_key + in: header + schemas: + ApiResponse: + title: An uploaded response + description: Describes the result of uploading an image resource + type: object + properties: + code: + type: integer + format: int32 + type: + type: string + message: + type: string diff --git a/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/src/main/resources/schemas/Category.yaml b/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/src/main/resources/schemas/Category.yaml new file mode 100644 index 000000000000..7c746a435f00 --- /dev/null +++ b/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/src/main/resources/schemas/Category.yaml @@ -0,0 +1,12 @@ +title: Pet category +description: A category for a pet +type: object +properties: + id: + type: integer + format: int64 + name: + type: string + pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$' +xml: + name: Category \ No newline at end of file diff --git a/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/src/main/resources/schemas/Order.yaml b/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/src/main/resources/schemas/Order.yaml new file mode 100644 index 000000000000..fa6d787d4fe3 --- /dev/null +++ b/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/src/main/resources/schemas/Order.yaml @@ -0,0 +1,28 @@ +title: Pet Order +description: An order for a pets from the pet store +type: object +properties: + id: + type: integer + format: int64 + petId: + type: integer + format: int64 + quantity: + type: integer + format: int32 + shipDate: + type: string + format: date-time + status: + type: string + description: Order Status + enum: + - placed + - approved + - delivered + complete: + type: boolean + default: false +xml: + name: Order \ No newline at end of file diff --git a/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/src/main/resources/schemas/Pet.yaml b/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/src/main/resources/schemas/Pet.yaml new file mode 100644 index 000000000000..7cc642a8cca9 --- /dev/null +++ b/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/src/main/resources/schemas/Pet.yaml @@ -0,0 +1,38 @@ +title: a Pet +description: A pet for sale in the pet store +type: object +required: + - name + - photoUrls +properties: + id: + type: integer + format: int64 + category: + $ref: 'Category.yaml' + name: + type: string + example: doggie + photoUrls: + type: array + xml: + name: photoUrl + wrapped: true + items: + type: string + tags: + type: array + xml: + name: tag + wrapped: true + items: + $ref: 'Tag.yaml' + status: + type: string + description: pet status in the store + enum: + - available + - pending + - sold +xml: + name: Pet \ No newline at end of file diff --git a/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/src/main/resources/schemas/Tag.yaml b/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/src/main/resources/schemas/Tag.yaml new file mode 100644 index 000000000000..ff2a87dffcc8 --- /dev/null +++ b/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/src/main/resources/schemas/Tag.yaml @@ -0,0 +1,11 @@ +title: Pet Tag +description: A tag for a pet +type: object +properties: + id: + type: integer + format: int64 + name: + type: string +xml: + name: Tag \ No newline at end of file diff --git a/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/src/main/resources/schemas/User.yaml b/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/src/main/resources/schemas/User.yaml new file mode 100644 index 000000000000..90bdee3fb1f3 --- /dev/null +++ b/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/src/main/resources/schemas/User.yaml @@ -0,0 +1,25 @@ +title: a User +description: A User who is purchasing from the pet store +type: object +properties: + id: + type: integer + format: int64 + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + type: integer + format: int32 + description: User Status +xml: + name: User \ No newline at end of file diff --git a/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/templates/modeltest.mustache b/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/templates/modeltest.mustache new file mode 100644 index 000000000000..9e26dfeeb6e6 --- /dev/null +++ b/modules/openapi-generator-maven-plugin/src/test/resources/user-defined-templates/templates/modeltest.mustache @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java index 90a35cd5641c..389c8d18c398 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java @@ -532,6 +532,11 @@ public CodegenConfigurator setLogToStderr(boolean logToStderr) { return this; } + public CodegenConfigurator addUserDefinedTemplate(TemplateDefinition userDefinedTemplate) { + this.userDefinedTemplates.add(userDefinedTemplate); + return this; + } + public CodegenConfigurator setApiNameSuffix(String suffix) { if (StringUtils.isNotEmpty(suffix)) { addAdditionalProperty(CodegenConstants.API_NAME_SUFFIX, suffix); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfiguratorUtils.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfiguratorUtils.java index 42f423984060..d1a621722da6 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfiguratorUtils.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfiguratorUtils.java @@ -18,6 +18,8 @@ package org.openapitools.codegen.config; import org.apache.commons.lang3.tuple.Pair; +import org.openapitools.codegen.api.TemplateDefinition; +import org.openapitools.codegen.api.TemplateFileType; import org.openapitools.codegen.utils.OptionUtils; import java.util.*; @@ -133,6 +135,19 @@ public static void applyNameMappingsKvp(String nameMappings, CodegenConfigurator } } + public static void applyUserDefinedTemplateFilesKvpList(List userDefinedTemplateFiles, CodegenConfigurator configurator) { + for (String propString : userDefinedTemplateFiles) { + applyUserDefinedTemplateFilesKvp(propString, configurator); + } + } + + public static void applyUserDefinedTemplateFilesKvp(String userDefinedTemplateFileOption, CodegenConfigurator configurator) { + final Map map = createMapFromKeyValuePairs(userDefinedTemplateFileOption); + TemplateDefinition templateDefinition = new TemplateDefinition(map.getOrDefault("templateFile", ""), map.getOrDefault("destinationFilename", "")); + templateDefinition.setTemplateType(TemplateFileType.forTemplateType(map.getOrDefault("templateType", TemplateFileType.SupportingFiles.value()))); + configurator.addUserDefinedTemplate(templateDefinition); + } + public static void applyParameterNameMappingsKvpList(List parameterNameMappings, CodegenConfigurator configurator) { for (String propString : parameterNameMappings) { applyParameterNameMappingsKvp(propString, configurator); From 87195a5499f86fc3685c0ef16a0d223eeba8f48b Mon Sep 17 00:00:00 2001 From: "conner.panarella" Date: Thu, 16 Jan 2025 13:43:47 -0500 Subject: [PATCH 2/2] Drop templateDir check --- .../org/openapitools/codegen/plugin/CodeGenMojo.java | 9 --------- 1 file changed, 9 deletions(-) diff --git a/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java b/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java index bc7aa0b93310..57a83fc150d3 100644 --- a/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java +++ b/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java @@ -729,11 +729,9 @@ public void execute() throws MojoExecutionException { configurator.setApiNameSuffix(apiNameSuffix); } - String templateDir = null; if (null != templateDirectory) { configurator.setTemplateDir(templateDirectory.getAbsolutePath()); - templateDir = templateDirectory.getAbsolutePath(); } if (StringUtils.isNotEmpty(templateResourcePath)) { @@ -741,7 +739,6 @@ public void execute() throws MojoExecutionException { LOGGER.warn("Both templateDirectory and templateResourcePath were configured. templateResourcePath overwrites templateDirectory."); } configurator.setTemplateDir(templateResourcePath); - templateDir = templateResourcePath; } if (null != engine) { @@ -948,12 +945,6 @@ public void execute() throws MojoExecutionException { } if(userDefinedTemplateFiles != null && userDefinedTemplateFiles.size() > 0) { - - if(templateDir == null) { - LOGGER.error("User defined templates have been defined, but no template directory has been set."); - throw new MojoExecutionException("User defined templates have been defined, but no template directory has been set. Please configure the template directory."); - } - applyUserDefinedTemplateFilesKvpList(userDefinedTemplateFiles, configurator); }