For the simple task creation, we need to extend DefaultTask:
The second step is the @TaskAction definition. Note, the task will throw Gradle Exception,
so let’s declare it.
The next important thing is Input variables. These fields should be marked as lateinit or
have a default value.
If the file path should be additionally validated before using, use @get:InputFile.
If the main logic throws an exception, it can be caught and omitted by the external plugin parameter.
The logger can be created by a companion object:
Extension and Plugin setting
Firstly, the SwaggerhubPlugin class should implement Plugin<Project>.
For the “caching” of plugin execution, inputs and output can be used.
In this case, I assume that OpenApi json was generated during the test phase,
If tests are not executed, our task will be skipped too.
The plugin must have an “apply” function, which receives Project as a parameter.
In this function, we are defined tasks and set parameters from Extension.
Extension should be open or abstract class:
Gradle Build
In the build.gradle.kts for this plugin, step one is necessary plugin definition.
com.github.johnrengelman.shadow plugin is significant for packing dependencies into resulting jar.
Shadow plugin tasks should be set according to documentation:
For these plugins and dependencies let’s provide repositories:
And last but not least is our plugin registration:
Local testing
Manual local test creation can be done by another module definition in the same project.
Firstly, create the module with a test json file and a build.gradle (let’s use groovy one).
The best way to test is written unit or integration tests, but here is
the easiest way :)
Buildscript defines the path of the plugin jar and sets dependency using classpath.
Next, apply our plugin and set the required parameters..
The test can be run after gradle build command execution in the plugin module and in the test module.
Then use gradle swaggerhubUpload --stacktrace.
stacktrace flag provides complete stacktrace in case of exceptions.
Important note
If you’ve got java.lang.NoClassDefFoundError during plugin building,
try to add the following code to the gradle.properties.
That’s all!
The source code of this example is available on Github.