简体   繁体   中英

How to not build gradle subproject using docker plugin if docker not available?

I have a small multiproject Gradle build. I first constructed a Maven build structure for it, and that works fine. There are three subprojects. Two of them construct WAR files. The last constructs a Docker image using the other two WAR files.

The top-level Maven aggregator uses profile activation so that the Docker image project is only ever built if the OS is Linux. Eventually, I'll need a better conditional check for that (when Docker becomes a first-class element in Windows). For now, the Maven profile activation check works fine.

I'd like to do something similar in the Gradle build, as presently it tries to build the Docker image on Windows, which doesn't work.

What's the best way to have the Gradle build in the Docker-building subproject to do nothing if Docker isn't available (might as well do it right for the future)? If that's too hard I can settle for only building it on Linux.

I don't think, there is a simple solution for this. Especially if you want it to be platform independent. The only solution I can suggest is to make function to run CLI command gradle -v and parse this command output. Though, to run this command you have to do platform specific calls. Something like this:

import org.apache.tools.ant.taskdefs.condition.Os

//if true then Docker is available locally, otherwise false
ext.isDockerAvailable = { ->
    def commandStdOut = new ByteArrayOutputStream()
    if (Os.isFamily(Os.FAMILY_WINDOWS)) {
        //for Windows OS
        exec {
            commandLine "cmd", "/c", 'gradle', '-v'
            standardOutput = commandStdOut
        }
    } else if (Os.isFamily(Os.FAMILY_UNIX)) {
        //for Unix-family OS
        exec {
            commandLine "sh", "/c", 'gradle', '-v'
            standardOutput = commandStdOut
        }
    } else {
        //if OS is unsupported
        println 'Unsupported OS version'
    }
    commandStdOut = commandStdOut.toString().trim()
    //check command output for predefined words
    return commandStdOut.contains('Build time:') && commandStdOut.contains('Revision:')
}.call()

task buildDockerImage {
    enabled = isDockerAvailable
}

Sure, this works for Windows- and Unix-family OS.

And if you don't care much about whether image will be built or not, why don't you simply set ignoreFailures for docker-tasks and ignore them if they fail on Windows.

Anyway, I suppose, it's much better to use remote build server (with Docker remote API available) for such a task. In that case neither you, nor someone else need local Docker distribution to be installed if you are in the same LAN.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM