4

I'd find it really useful to invoke Flyway's migrate command automatically each time I run gradle build.

Spring Boot does this under the hood, but can Gradle do this itself? I have a non-Boot app that I'd like to be able to manage the same way.

I'm hoping it is some lifecycle hook. This question is helpful, but how do I execute flyway pre-build?

Community
  • 1
  • 1
ben3000
  • 4,629
  • 6
  • 24
  • 43

1 Answers1

2

Yes you can. You have several options. You can hook into the lifecycle at any point. By default the java gradle plugin has several places you could hook into.

$ ./gradlew clean build
:clean
:compileJava
:processResources UP-TO-DATE
:classes
:jar
:assemble
:compileTestJava
:processTestResources UP-TO-DATE
:testClasses
:test
:check
:build

You can attach to any of these points

Or you if you need to be applied no matter what before anything else then you might want to consider a simple plugin.

Here is an example of both:

build.gradle:

apply plugin: 'java'

repositories {
    jcenter()
}

dependencies {
    testCompile 'junit:junit:4.12'
}

task runFlyAwayCommand << {
    // process is type java.lang.Process
    def process = "printf lifecycle hooked task".execute()
    def processExitValue = process.waitFor()
    def processOutput = process.text
    project.logger.lifecycle("Flyaway{ exitValue: $processExitValue output: $processOutput }")
}

// compileJava could be any lifecycle task
tasks.findByName('compileJava').dependsOn tasks.findByName('runFlyAwayCommand')


// if you need to execute earlier you might want to create a plugin
apply plugin: SamplePlugin

class SamplePlugin implements Plugin<Project> {

    @Override
    void apply(Project project) {
        def process = "printf plugin apply".execute()
        def processExitValue = process.waitFor()
        def processOutput = process.text
        project.logger.lifecycle("Flyaway{ exitValue: $processExitValue output: $processOutput }")
    }
}

Output:

$ ./gradlew clean build
Configuration on demand is an incubating feature.
Flyaway{ exitValue: 1 output: plugin }
:clean
:runFlyAwayCommand
Flyaway{ exitValue: 1 output: lifecycle }
:compileJava
:processResources UP-TO-DATE
:classes
:jar
:assemble
:compileTestJava
:processTestResources UP-TO-DATE
:testClasses
:test
:check
:build

BUILD SUCCESSFUL

Total time: 1.294 secs
JBirdVegas
  • 10,855
  • 2
  • 44
  • 50