Lerp
Lerp

Reputation: 3127

Task running unnecessarily

I have written a task to run my project using a main class chosen via user input only it is prompting me to choose a main class when I run gradle tasks. Why is this and how do I prevent it?

task run(dependsOn: "classes", type: JavaExec) {
    description "Executes the project using the selected main class"

    def selection = null
    def mainClasses = []

    // Select the java files with main classes in
    sourceSets.main.allJava.each {
        if(it.text.contains("public static void main")) {
            def pkg = relativePath(it) - 'src/main/java/' - '.java'
            pkg = pkg.tr "/", "."

            println "${mainClasses.size()}. $pkg"
            mainClasses << pkg
        }
    }

    // Now prompt the user to choose a main class to use
    while(selection == null) {
        def input = System.console().readLine "#? "

        if(input?.isInteger()) {
            selection = input as int

            if(selection >= 0 && selection < mainClasses.size()) {
                break
            } else {
                selection = null
            }
        } else if(input?.toLowerCase() == "quit") {
            return
        }

        if(selection == null) {
            println "Unknown option."
        }
    }

    main = mainClasses[selection]
    classpath = sourceSets.main.runtimeClasspath
}

Upvotes: 0

Views: 75

Answers (1)

roomsg
roomsg

Reputation: 1857

Gradle has a configuration phase and an execution phase.
The fact that your build logic is actually run when calling "gradle tasks" is because your build logic is in the tasks configuration section. If you want to move it to the execution phase, you should introduce a doFirst or doLast closure
See gradle build script basics for more details or this post

Upvotes: 1

Related Questions