-
-
Notifications
You must be signed in to change notification settings - Fork 4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
New openapi-cli subgenerator for OpenApi client generation #9623
Merged
Merged
Changes from all commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
a6326a1
import swagger cli as sub-generator
ecostanzi 5ce694a
fix openapi-cli index.js to make it work as sub-generator
ecostanzi e44fa1e
use node openapi-generator-cli instead of jar file
ecostanzi d14e955
fix iteration over apis to regenerate
ecostanzi e04e5f5
add openapi-cli command description and USAGE file
ecostanzi e6cfa45
create promts.js and add generatorName property
ecostanzi 05727d9
change module name to 'openapi-client'
ecostanzi 946851c
move writing phases to files.js
ecostanzi 641d631
generates java files only with spring clients
ecostanzi ee30c19
remove package.json openapi-generator, use openapi-generator-cli jar
ecostanzi 68d6a40
add test for openapi-client subgenerator
ecostanzi 0b5c059
fix url composition when reading springfox swagger endpoint list
ecostanzi af1426b
fix supportingFiles generation and fix test
ecostanzi c7d29f5
use openapi jar file in the node_modules of the generated project
ecostanzi 807b7b4
fix --regen option
ecostanzi 1d719c9
update openapi-generator-cli to version 0.0.14-4.0.2
ecostanzi e95a239
test for regeneration and component scan exclusion
ecostanzi 7163192
clean previously generated code before regenerating client
ecostanzi bfb1256
fix file path validation for custom endpoint
ecostanzi f96ecbb
fix how the swagger-resources endpoint is built
ecostanzi 2cc6672
use shelljs and lodash instead of fs-extra and underscore.string
ecostanzi 374f578
update package-lock.json
ecostanzi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
Description: | ||
Generates java client code from an OpenAPI/Swagger definition | ||
|
||
Example: | ||
jhipster openapi-client |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,173 @@ | ||
/** | ||
* Copyright 2013-2019 the original author or authors from the JHipster project. | ||
* | ||
* This file is part of the JHipster project, see https://www.jhipster.tech/ | ||
* for more information. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
const path = require('path'); | ||
const shelljs = require('shelljs'); | ||
const _ = require('lodash'); | ||
const chalk = require('chalk'); | ||
const jhipsterConstants = require('../generator-constants'); | ||
|
||
module.exports = { | ||
writeFiles | ||
}; | ||
|
||
function writeFiles() { | ||
return { | ||
callOpenApiGenerator() { | ||
this.baseName = this.config.get('baseName'); | ||
this.authenticationType = this.config.get('authenticationType'); | ||
this.packageName = this.config.get('packageName'); | ||
this.clientPackageManager = this.config.get('clientPackageManager'); | ||
this.packageFolder = this.config.get('packageFolder'); | ||
this.buildTool = this.config.get('buildTool'); | ||
|
||
this.javaDir = `${jhipsterConstants.SERVER_MAIN_SRC_DIR + this.packageFolder}/`; | ||
|
||
if (Object.keys(this.clientsToGenerate).length === 0) { | ||
this.log('No openapi client configured. Please run "jhipster openapi-client" to generate your first OpenAPI client.'); | ||
return; | ||
} | ||
|
||
Object.keys(this.clientsToGenerate).forEach(cliName => { | ||
const inputSpec = this.clientsToGenerate[cliName].spec; | ||
const generatorName = this.clientsToGenerate[cliName].generatorName; | ||
|
||
// using openapi jar file since so this section can be tested | ||
const jarPath = path.resolve('node_modules', '@openapitools', 'openapi-generator-cli', 'bin', 'openapi-generator.jar'); | ||
let JAVA_OPTS; | ||
let command; | ||
if (generatorName === 'spring') { | ||
this.log(chalk.green(`\n\nGenerating java client code for client ${cliName} (${inputSpec})`)); | ||
const cliPackage = `${this.packageName}.client.${_.snakeCase(cliName)}`; | ||
const clientPackageLocation = path.resolve('src', 'main', 'java', ...cliPackage.split('.')); | ||
if (shelljs.test('-d', clientPackageLocation)) { | ||
this.log(`cleanup generated java code for client ${cliName} in directory ${clientPackageLocation}`); | ||
shelljs.rm('-rf', clientPackageLocation); | ||
} | ||
|
||
JAVA_OPTS = ' -Dmodels -Dapis -DsupportingFiles=ApiKeyRequestInterceptor.java,ClientConfiguration.java '; | ||
|
||
let params = | ||
' generate -g spring ' + | ||
` -t ${path.resolve(__dirname, 'templates/swagger-codegen/libraries/spring-cloud')} ` + | ||
' --library spring-cloud ' + | ||
` -i ${inputSpec} --artifact-id ${_.camelCase(cliName)} --api-package ${cliPackage}.api` + | ||
` --model-package ${cliPackage}.model` + | ||
' --type-mappings DateTime=OffsetDateTime,Date=LocalDate ' + | ||
' --import-mappings OffsetDateTime=java.time.OffsetDateTime,LocalDate=java.time.LocalDate' + | ||
` -DdateLibrary=custom,basePackage=${this.packageName}.client,configPackage=${cliPackage},` + | ||
`title=${_.camelCase(cliName)}`; | ||
|
||
if (this.clientsToGenerate[cliName].useServiceDiscovery) { | ||
params += ' --additional-properties ribbon=true'; | ||
} | ||
|
||
command = `java ${JAVA_OPTS} -jar ${jarPath} ${params}`; | ||
} | ||
this.log(`\n${command}`); | ||
|
||
const done = this.async(); | ||
shelljs.exec(command, { silent: this.silent }, (code, msg, err) => { | ||
if (code === 0) { | ||
this.success(`Succesfully generated ${cliName} ${generatorName} client`); | ||
done(); | ||
} else { | ||
this.error(`Something went wrong while generating ${cliName} ${generatorName} client: ${msg} ${err}`); | ||
done(); | ||
} | ||
}); | ||
}); | ||
}, | ||
|
||
addBackendDependencies() { | ||
if (!_.map(this.clientsToGenerate, 'generatorName').includes('spring')) { | ||
return; | ||
} | ||
|
||
if (this.buildTool === 'maven') { | ||
if (!['microservice', 'gateway', 'uaa'].includes(this.applicationType)) { | ||
let exclusions; | ||
if (this.authenticationType === 'session') { | ||
exclusions = | ||
' <exclusions>\n' + | ||
' <exclusion>\n' + | ||
' <groupId>org.springframework.cloud</groupId>\n' + | ||
' <artifactId>spring-cloud-starter-ribbon</artifactId>\n' + | ||
' </exclusion>\n' + | ||
' </exclusions>'; | ||
} | ||
this.addMavenDependency('org.springframework.cloud', 'spring-cloud-starter-openfeign', null, exclusions); | ||
} | ||
this.addMavenDependency('org.springframework.cloud', 'spring-cloud-starter-oauth2'); | ||
} else if (this.buildTool === 'gradle') { | ||
if (!['microservice', 'gateway', 'uaa'].includes(this.applicationType)) { | ||
if (this.authenticationType === 'session') { | ||
const content = | ||
"compile 'org.springframework.cloud:spring-cloud-starter-openfeign', { exclude group: 'org.springframework.cloud', module: 'spring-cloud-starter-ribbon' }"; | ||
this.rewriteFile('./build.gradle', 'jhipster-needle-gradle-dependency', content); | ||
} else { | ||
this.addGradleDependency('compile', 'org.springframework.cloud', 'spring-cloud-starter-openfeign'); | ||
} | ||
} | ||
this.addGradleDependency('compile', 'org.springframework.cloud', 'spring-cloud-starter-oauth2'); | ||
} | ||
}, | ||
|
||
enableFeignClients() { | ||
if (!_.map(this.clientsToGenerate, 'generatorName').includes('spring')) { | ||
return; | ||
} | ||
|
||
const mainClassFile = `${this.javaDir + this.getMainClassName()}.java`; | ||
|
||
if (this.applicationType !== 'microservice' || !['uaa', 'jwt'].includes(this.authenticationType)) { | ||
this.rewriteFile( | ||
mainClassFile, | ||
'import org.springframework.core.env.Environment;', | ||
'import org.springframework.cloud.openfeign.EnableFeignClients;' | ||
); | ||
this.rewriteFile(mainClassFile, '@SpringBootApplication', '@EnableFeignClients'); | ||
} | ||
}, | ||
|
||
handleComponentScanExclusion() { | ||
if (!_.map(this.clientsToGenerate, 'generatorName').includes('spring')) { | ||
return; | ||
} | ||
|
||
const mainClassFile = `${this.javaDir + this.getMainClassName()}.java`; | ||
|
||
this.rewriteFile( | ||
mainClassFile, | ||
'import org.springframework.core.env.Environment;', | ||
'import org.springframework.context.annotation.ComponentScan;' | ||
); | ||
|
||
const componentScan = | ||
`${'@ComponentScan( excludeFilters = {\n @ComponentScan.Filter('}${this.packageName}` + | ||
'.client.ExcludeFromComponentScan.class)\n})'; | ||
this.rewriteFile(mainClassFile, '@SpringBootApplication', componentScan); | ||
|
||
this.template( | ||
'src/main/java/package/client/_ExcludeFromComponentScan.java', | ||
`${this.javaDir}/client/ExcludeFromComponentScan.java` | ||
); | ||
} | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,94 @@ | ||
/** | ||
* Copyright 2013-2019 the original author or authors from the JHipster project. | ||
* | ||
* This file is part of the JHipster project, see https://www.jhipster.tech/ | ||
* for more information. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
const chalk = require('chalk'); | ||
const BaseGenerator = require('../generator-base'); | ||
const prompts = require('./prompts'); | ||
const writeFiles = require('./files').writeFiles; | ||
|
||
module.exports = class extends BaseGenerator { | ||
constructor(args, opts) { | ||
super(args, opts); | ||
this.option('regen', { | ||
desc: 'Regenerates all saved clients', | ||
type: Boolean, | ||
defaults: false | ||
}); | ||
this.registerPrettierTransform(); | ||
} | ||
|
||
get initializing() { | ||
return { | ||
validateFromCli() { | ||
this.checkInvocationFromCLI(); | ||
}, | ||
sayHello() { | ||
// Have Yeoman greet the user. | ||
this.log(chalk.white('Welcome to the JHipster OpenApi client Sub-Generator')); | ||
}, | ||
getConfig() { | ||
this.openApiClients = this.config.get('openApiClients') || {}; | ||
} | ||
}; | ||
} | ||
|
||
get prompting() { | ||
return { | ||
askActionType: prompts.askActionType, | ||
askExistingAvailableDocs: prompts.askExistingAvailableDocs, | ||
askGenerationInfos: prompts.askGenerationInfos | ||
}; | ||
} | ||
|
||
get configuring() { | ||
return { | ||
determineApisToGenerate() { | ||
this.clientsToGenerate = {}; | ||
if (this.options.regen || this.props.action === 'all') { | ||
this.clientsToGenerate = this.openApiClients; | ||
} else if (this.props.action === 'new' || this.props.action === undefined) { | ||
this.clientsToGenerate[this.props.cliName] = { | ||
spec: this.props.inputSpec, | ||
useServiceDiscovery: this.props.useServiceDiscovery, | ||
generatorName: this.props.generatorName | ||
}; | ||
} else if (this.props.action === 'select') { | ||
this.props.selected.forEach(selection => { | ||
this.clientsToGenerate[selection.cliName] = selection.spec; | ||
}); | ||
} | ||
}, | ||
|
||
saveConfig() { | ||
if (!this.options.regen && this.props.saveConfig) { | ||
this.openApiClients[this.props.cliName] = this.clientsToGenerate[this.props.cliName]; | ||
this.config.set('openApiClients', this.openApiClients); | ||
} | ||
} | ||
}; | ||
} | ||
|
||
get writing() { | ||
return writeFiles(); | ||
} | ||
|
||
end() { | ||
this.log('End of openapi-client generator'); | ||
} | ||
}; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@ecostanzi,
It doesn't look appropriate to include generator sub-module dependency in the generated client application. Can't it be encapsulated in the module?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hi Vishal, what do you mean by saying "encapsulated in the module"?
The documentations suggests:
https://www.npmjs.com/package/@openapitools/openapi-generator-cli#package-mode
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes for me there is no problem to add this as dev dependency. Yes it does add significantly to what you have to download. But as it is useful, I don't see the problem of it being downloaded from npm rather than maven...
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
IMO, it should be added as
generator-jhipster
dependency (not under dev) and not in the client applications dev dependency. Can you check if that works?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ok I'll let you know
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@vishal423 I opened issue #10510 to discuss some changes. In that case I think that the dependency should remain in the package.json of the generated project.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@ecostanzi, I will leave it to other members to decide. For me, I am planning to create a separate module that wouldn't contain it.